diff --git a/.changes/unreleased/New-20261126-023925.yaml b/.changes/unreleased/New-20261126-023925.yaml new file mode 100644 index 0000000..a67e020 --- /dev/null +++ b/.changes/unreleased/New-20261126-023925.yaml @@ -0,0 +1,3 @@ +kind: New +body: 'Split view, as in Arc: two tabs side by side, made by dragging a tab onto the page, Option+clicking a link or the split button, shown as one row in the sidebar, and pinned or favorited as one item.' +time: 2026-11-26T02:39:25.583442-05:00 diff --git a/docs/native-window.md b/docs/native-window.md index 932b51e..44feddd 100644 --- a/docs/native-window.md +++ b/docs/native-window.md @@ -60,6 +60,7 @@ The `native-quit-confirmation` change's `design.md` (`openspec/changes/archive/2 The `add-pinned-tabs-and-favorites` change's `design.md` (`openspec/changes/add-pinned-tabs-and-favorites/`) has the reasoning (D1–D12). - **The pin store (D1; `add-tab-folders` D1, D3).** `ClairPinStore` keeps every pinned tab, favorite and folder in Local State (`clair.pins`), one record each under `items`: a folder (`"kind": "folder"`) names its Space and its name; a pinned tab (`"kind": "pin"`) its Space and, in a folder, the folder; a favorite its profile, by the ID of `clair.profiles`; a pin also its URL, title and custom name. Each record carries its sort key, `order`, a fractional index from `clair_order_key.{h,mm}` (`OrderKeyBetween`: base-62 keys, "a0" first, between two neighbours or before the first or after the last), and a container's children are sorted by key, then by ID, so a move rewrites only the record that moved; a folder moving to another Space rewrites its pins' `space` too. The store keeps one index of children per container (`ChildrenOf`), rebuilt on load and on each write, and turns the contract's indices into keys between neighbours (`KeyAt`, which gives the whole container new keys only when two share one). Folders hold pinned tabs only, one level deep; on load, a pin whose folder is missing lists at its own Space's top level, and a record whose Space or profile is gone is dropped. Whether a folder is closed is this Mac's, apart from the records: `clair.closed_folders`. Icons are PNG files in `/Clair Pin Icons/`, written and read on a background sequence; at start-up it reads them and deletes those whose pin is gone. It remembers the last 25 pins and folders removed this session for Restore Last Closed Tab: a removed folder is one removal, with its pins and whether it was closed. +- **Pinned and favorited splits (`add-split-view` D10).** A split record (`"kind": "split"`) has the place a pin has, in a Space's pinned section, a folder or a profile's favorites, its sort key and its `ratio`; each of its two pins names it (`"split"`) and its pane (`"index"`, 0 or 1) instead of a place of its own, so moving the split rewrites only its record. A folder holds pins and splits, still one level deep. On load, a split without both its panes is dropped, its pins taking its place (`RepairSplits`). Removing either pin removes the split with both, as one removal for Restore Last Closed Tab; Separate Tabs (`SeparateSplit`) gives the leading pin the split's key and the trailing one the next; closing one pane of a shown pinned split takes its pin out (`TakeOutOfSplit`), the other keeping the split's place. `ClairHost.h` shows a split as a `ClairPinnedSplit` item, folders as lists of items, and the favorites as items too. - **Binding (D2).** A tab showing a pin's page is bound to it: `ClairSpaceTabs::bound_` maps the pin to the tab, and the tab's tag carries the pin. A bound tab, and its Peek, are in no Today list; a pinned tab's Space is its pin's, and a favorite's tab has none, so the window keeps its Space while it shows one (`IntendedSpaceOf`). The pin's title and icon follow its tab only while the tab is at the pinned URL (its committed or originally requested URL, without the query and fragment). A Today tab's custom name is its tag's; a bound tab's is its pin's. The host pushes each Space's pinned items, pins and folders (`pinnedItemsDidChange:inSpace:`, with `ClairPinnedItem` and `ClairFolder` snapshots), and each profile's favorites (`favoritesDidChange:ofProfile:`), after the tab lists, once per run-loop turn. - **The session tags (D2, D3).** `clair_pin` and `clair_name` ride beside `clair_space` and `clair_order` through the same three hooks of `space-session.patch`. A restored or reopened tab binds to its pin if the pin has no tab; otherwise it joins its Space's Today tabs. - **Restore and removed pins (D3, D12).** `always-restore.patch` ends `SessionStartupPref::GetStartupPref` with `clair::ApplyStartupPref`, which makes it "continue where you left off" except in headless mode, and `chrome://settings` has no On startup section. Restore Last Closed Tab (`IDC_RESTORE_TAB`, run first by `ExecuteTabCommand`) puts back the newest removed pin or folder of the window's profile when that's newer than Chromium's newest recently closed entry, at its key, or at the end when its folder is gone or its key taken; a removed pin's tab closing carries `clair_pin`, so restoring that tab brings the pin back first, with its whole folder when the folder was deleted (`RestorePin`, `add-tab-folders` D7). @@ -101,6 +102,18 @@ The archived `add-bookmarks-menu` change's `design.md` (`openspec/changes/archiv - **One list, and the notice (D6).** `ClairBookmarkBarDrain`, one per original profile (the profile's user data), started by `ClairBrowserWindow` for each window, keeps the Bookmarks Bar empty: when the bookmarks load, when a node lands directly in the bar, and when an import's extensive changes end, it moves the bar's children to the top of Other Bookmarks, in order, in a task of its own. The first drain that moves something asks the profile's most recently active normal window, or the first one to open, to show `BookmarksBarNotice`, and sets the Local State pref `clair.bookmarks_bar_notice_shown`, so it shows once for the whole app. - **Suggestions (D8).** `ClairChromiumAutocomplete` runs every omnibox provider, bookmarks included, and shows a match's title first when Chromium marks it `swap_contents_and_description`, as the omnibox does. A row for a bookmarked page that isn't a search or an open tab is `ClairSuggestionKindBookmark`, with no icon, so `SuggestionRow` draws the `bookmark` symbol and VoiceOver reads "Bookmark". +## Split view + +The `add-split-view` change's `design.md` (`openspec/changes/add-split-view/`) has the reasoning (D1–D13). A split is Chromium's own: two adjacent tabs of a `TabStripModel` in a split collection, with its `SplitTabId`, its ratio, and its pane order as the tabs' order. Session restore and tab restore keep splits without help. + +- **`ClairSplits` (D1, D4, D5, D12).** One per native window, beside `ClairPeeks`, in `clair_splits.{h,mm}`. It makes splits from two tabs (`Make`, after `ClairBrowserWindow::BringHere` has brought both into the window), from a tab and a new tab page (`MakeWithNewTab`), replaces a pane (`Replace`: Chromium's `kReplace` closes the replaced tab, so it ends the split and restores it with the same ID), swaps, separates and resizes, and observes `OnSplitTabChanged` to push the change to `ClairSpaceTabs` and `ClairPeeks`. A `FocusWatcher` on each pane activates it when its contents take focus, so a click in the other pane focuses it; the active tab's partner is marked visible with it (`UpdateVisibility`). When a pane closes, the other is activated. A split Chromium makes itself, as Open Link in Split View does, gets the clicked tab back in the leading pane (`LeadWith`), except while a session restores. +- **Rows and commands.** A split is one row: `ClairBrowserWindow::RowOf` maps a pane to the split's row tab, the leading pane in Today, the tab commands (Ctrl+Tab, Cmd+1…9, Close Tabs Below) count it once, and `ActivateRow` shows the pane focused last (`LastFocusedPane`). Cmd+W, a pane's × and a Today split chip's × close one pane (`CloseTab`); a pinned split's − closes both through `ExecuteCloseTabsCommand`, so tab restore records one split entry. A favorite's page in a split loads another site's URL from the command bar in its pane, not in a new Today tab (`clair::LeavesFavorite`). +- **Peeks (D3, D11).** A pane's Peek sits after the whole split in the strip, since a tab inserted inside a split ends it (`ClairPeeks::PeekIndexFor`); focusing the other pane closes it. Open in Split View expands the Peek and splits it with its parent (`OpenPeekInSplit`). +- **Option+click (D6).** `split-on-option-click.patch` makes Option without Shift give `NEW_SPLIT_VIEW` in Blink's `NavigationPolicyFromEventModifiers` and `ui::DispositionFromClick`, so a link isn't downloaded. `clair::MaybeOpenLink` (`clair_window_hooks.mm`, formerly `MaybeOpenPeek`) hands it to `ClairSplits::OpenLink`: a new background tab after the source and a split with it on a single page, the other pane on a split, the Peek itself in a Peek. The page's context menu keeps Chromium's Open Link in Split View. +- **Across windows and Spaces (D7).** `ClairSpaceTabs` keeps a split's tabs together in the Space's list (`KeepSplitsTogether`, run for every changed list), and Move to Space moves both. Taking a split's row from another window moves the split collection whole (`MoveFamilyHere`, with `DetachSplitTabForInsertion` and `InsertDetachedSplitTabAt`), its Peeks with it. +- **Pins (D10).** `clair::PinTab` pins a split as one item (`PinSplit`), and `OpenPin` on either of its pins opens the closed pages and shows them as a split with the saved ratio (`ShowPinnedSplit`). A restored split whose two tabs bind to one pinned split's pins is made again (`JoinPinnedSplit`). A ratio change of a pinned split is saved (`KeepPinnedRatio`). +- **`ClairUI` (D2, D3, D8, D9, D13).** `ClairTab` carries `splitPartnerID`, `isLeadingPane` and `splitRatio`; `TabListLogic.rows` folds the trailing pane into its leading pane's row, and `SplitLogic.shownSplit` gives the model's `shownSplit` (and `paneCount`). `BrowserRootView` lays out two `PageCardView`s with `SplitDividerView` between them, `PageDropView` over the page takes tabs dragged from the sidebar, and the overlays follow the focused pane. `PageToolbar` shows pane headers (`PageHeaderContent.pane`) and the split button (`SplitButton`), the sidebar shows `SplitRow` and the favorites `FavoriteSplitTile`, and `SplitMenu` adds Tabs › Split with Tab › and View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) and Separate Tabs. The link status names a split or a Peek while Option or Shift is held (`SplitLogic.linkStatus`). + ## Where each piece lives | Piece | File | @@ -119,7 +132,8 @@ The archived `add-bookmarks-menu` change's `design.md` (`openspec/changes/archiv | A Peek moving with its tab | `engine/overlay/chrome/browser/clair/window/clair_peeks.{h,mm}` (`Release`, `Adopt`) | | The still in the card | `native/ClairUI/PageCardView.swift` (`StillView`) | | Tabs' Spaces, windows' groups, pins and names in saved sessions, new tab pages left out | `engine/overlay/chrome/browser/clair/window/clair_space_session.{h,mm}`, `engine/patches/clair/space-session.patch` | -| The pin store, folders and icons | `engine/overlay/chrome/browser/clair/clair_pin_store.{h,mm}` | +| The pin store, folders, pinned splits and icons | `engine/overlay/chrome/browser/clair/clair_pin_store.{h,mm}` | +| Split view: making, changing and closing splits, focus and visibility, Option+click | `engine/overlay/chrome/browser/clair/window/clair_splits.{h,mm}`, `engine/patches/clair/split-on-option-click.patch` | | Sort keys | `engine/overlay/chrome/browser/clair/clair_order_key.{h,mm}` | | Binding tabs to pins, pin snapshots, the host's pin calls, Restore Last Closed Tab for pins | `engine/overlay/chrome/browser/clair/clair_space_tabs.{h,mm}` | | The link rule store and the matcher | `engine/overlay/chrome/browser/clair/clair_link_rule_store.{h,mm}` | @@ -146,10 +160,11 @@ The archived `add-bookmarks-menu` change's `design.md` (`openspec/changes/archiv | Spaces: the model, header, switcher, New Space form, icon field, Spaces menu and Manage Spaces | `native/ClairUI/SpacesModel.swift`, `SpacesLogic.swift`, `SpaceHeaderView.swift`, `SpaceSwitcher.swift`, `NewSpaceForm.swift`, `SpaceIconField.swift`, `SpacesMenu.swift`, `ManageSpacesDialog.swift` | | Profiles: the dialogs, Settings › Profiles, the Advanced toggles | `native/ClairUI/ProfileDialogs.swift`, `ProfilesSettingsView.swift`, `SettingsWindow.swift` | | Link rules: Settings › Links' card, the dialog and its checks | `native/ClairUI/SettingsWindow.swift`, `LinkRulesDialog.swift`, `LinkRulesLogic.swift` | +| Split view: panes, divider, drops on the page, split row and tile, split button and menus | `native/ClairUI/SplitLogic.swift`, `SplitViews.swift`, `SplitMenu.swift`, `BrowserWindowController+Split.swift` | | Command bar | `native/ClairUI/CommandBarModel.swift`, `OverlayViews.swift` | | The bookmark dialog, the Bookmarks Bar notice, Manage Bookmarks' title | `native/ClairUI/BookmarkDialog.swift`, `BookmarksBarNotice.swift`, `MainMenuTitles.swift` | | Unit tests against a fake Chromium | `native/ClairUITests/` (`FakeBrowser.swift`, `FakeHost.swift`) | -| Runtime tests on a packaged Clair | `tests/runtime/ClairRuntimeTests/NativeWindowTests.swift`, `SpacesTests.swift`, `SharedTabsTests.swift`, `ProfilesTests.swift`, `PinsTests.swift`, `LinkRulesTests.swift`, `BookmarksTests.swift` | +| Runtime tests on a packaged Clair | `tests/runtime/ClairRuntimeTests/NativeWindowTests.swift`, `SpacesTests.swift`, `SharedTabsTests.swift`, `ProfilesTests.swift`, `PinsTests.swift`, `LinkRulesTests.swift`, `BookmarksTests.swift`, `SplitViewTests.swift` | ## Working on it diff --git a/engine/overlay/chrome/browser/clair/clair_native_layer.mm b/engine/overlay/chrome/browser/clair/clair_native_layer.mm index 5f543d5..7b51096 100644 --- a/engine/overlay/chrome/browser/clair/clair_native_layer.mm +++ b/engine/overlay/chrome/browser/clair/clair_native_layer.mm @@ -285,10 +285,17 @@ - (void)moveTab:(ClairTabID)tabID toSpace:(ClairSpaceID)spaceID { return clair::PinnedItemSnapshots(base::SysNSStringToUTF8(spaceID ?: @"")); } -- (NSArray>*)favoritesOfProfile:(ClairProfileID)profileID { +- (NSArray>*)favoritesOfProfile:(ClairProfileID)profileID { CHECK([NSThread isMainThread]); - return clair::PinSnapshots(clair::PinContainer::OfProfile( - base::SysNSStringToUTF8(profileID ?: @""))); + // add-split-view D10: favorites and favorited splits. + return clair::FavoriteItemSnapshots(base::SysNSStringToUTF8(profileID ?: @"")); +} + +- (void)separatePinnedSplit:(ClairPinnedSplitID)splitID { + CHECK([NSThread isMainThread]); + if (splitID) { + clair::SeparatePinnedSplit(base::SysNSStringToUTF8(splitID)); + } } - (void)pinTab:(ClairTabID)tabID diff --git a/engine/overlay/chrome/browser/clair/clair_pin_store.h b/engine/overlay/chrome/browser/clair/clair_pin_store.h index 9b4a391..f62f9b1 100644 --- a/engine/overlay/chrome/browser/clair/clair_pin_store.h +++ b/engine/overlay/chrome/browser/clair/clair_pin_store.h @@ -85,6 +85,24 @@ struct Pin { std::string title; // The custom name, or empty. std::string name; + // add-split-view D10: the pinned or favorited split holding the pin, or + // empty, and its pane there, 0 for the leading one. A pin in a split takes + // no place of its own: its container is the split's, and `order` is empty. + std::string split; + int split_index = 0; +}; + +// A pinned or favorited split (add-split-view D10): two pins in one place, +// shown side by side when selected. +struct PinnedSplit { + // A lowercase UUID, which never changes. + std::string id; + // Where it shows, as a pin's. + PinContainer container; + // Its sort key in its container. + std::string order; + // The leading pane's share of the width. + double ratio = 0.5; }; // A folder of pinned tabs in a Space's pinned section (add-tab-folders D1). @@ -110,7 +128,12 @@ struct Folder { // "url": "https://…", "title": "…", // "name": "…" }, // "": { "kind": "pin", "profile": "", -// "order": "a0", … } } } +// "order": "a0", … }, +// "": { "kind": "split", "space": "", +// "folder": "", "order": "a1", +// "ratio": 0.5 }, +// "": { "kind": "pin", "split": "", +// "index": 0, "url": "https://…", … } } } // clair.closed_folders ["", …] // this Mac's (D3) // // A folder names its Space; a pinned tab its Space and, in a folder, the @@ -119,8 +142,12 @@ struct Folder { // it, then by ID, so a move rewrites only the record that moved, except a // folder moving to another Space, which rewrites its pins' Space too. A pin // shows in its folder's Space while the folder exists, and at the top level -// of its own Space when it's missing. Folders hold pins only, one level deep; -// the store refuses any other write. On load, a record whose Space or profile +// of its own Space when it's missing. Folders hold pins and splits, one level +// deep; the store refuses any other write. add-split-view D10: a split has +// the place a pin has, and its two pins name it and their pane instead of a +// place of their own, so moving a split rewrites its record only. A split +// that hasn't exactly a pin for each pane on load keeps the pins it has as +// pins in its place. On load, a record whose Space or profile // is missing, or without a valid sort key, is dropped with its icon. // // Each pin's icon is a PNG of at most 64 × 64 pixels in @@ -150,6 +177,11 @@ class ClairPinStore { bool folder_was_closed = false; // The pin, or the folder's pins in order, each with its place and key. std::vector pins; + // add-split-view D10: the split removed with its pins, or the folder's + // splits; or, with `partner`, the split one pane closed out of, whose + // other pin, `partner`, kept its place. + std::vector splits; + std::string partner; base::Time time; }; @@ -170,18 +202,26 @@ class ClairPinStore { const Pin* Find(std::string_view id) const; const Folder* FindFolder(std::string_view id) const; + const PinnedSplit* FindSplit(std::string_view id) const; + // add-split-view D10: a split's pins, leading pane first; empty for an + // unknown split. + std::vector PinsOfSplit(std::string_view id) const; + // The other pin of `pin`'s split, or null. + const Pin* PartnerOf(std::string_view pin) const; // The IDs of a container's children, in order: a Space's pinned section - // lists its top-level pins and its folders, a folder and the favorites - // their pins. + // lists its top-level pins, splits and folders, a folder and the favorites + // their pins and splits. std::vector ChildrenOf(const PinContainer& container) const; - // A container's pins, in order; a Space's section's top-level ones only. + // A container's pins, in order, a split's two in pane order; a Space's + // section's top-level ones only. std::vector PinsIn(const PinContainer& container) const; // Every pinned tab of a Space, its folders' included, in the sidebar's // order (add-tab-folders D9). std::vector AllPinsIn(std::string_view space) const; // A Space's folders, in order. std::vector FoldersIn(std::string_view space) const; - // A pin's or folder's index among its container's children. + // A pin's, split's or folder's index among its container's children; a + // pin in a split has its split's. std::optional IndexOf(std::string_view id) const; // The profile a pin's tab uses: a favorite's own, or its Space's. std::string ProfileOf(const Pin& pin) const; @@ -197,15 +237,40 @@ class ClairPinStore { const GURL& url, std::string_view title, std::string_view name); - // Moves a pin to `index` in `container`, which may be another, or a folder - // to `index` in a Space's section, with its pins. Refuses a folder - // anywhere else and a folder container of another Space. Returns whether - // anything moved. + // Moves a pin or a split to `index` in `container`, which may be another, + // or a folder to `index` in a Space's section, with its pins. A pin of a + // split moves its split. Refuses a folder anywhere else and a folder + // container of another Space. Returns whether anything moved. bool Move(std::string_view id, const PinContainer& container, size_t index); - // Removes the pin. With `remember`, Restore Last Closed Tab can bring it - // back (D3): the caller removes it before closing its tab, so the tab's - // own entry in Chromium's recently closed list is the newer. + // Removes the pin, or the split holding it with both its pins. With + // `remember`, Restore Last Closed Tab can bring it back (D3): the caller + // removes it before closing its tab, so the tab's own entry in Chromium's + // recently closed list is the newer. void Remove(std::string_view id, bool remember); + + // --- Splits (add-split-view D10) --- + struct NewPin { + GURL url; + std::string title; + std::string name; + }; + // Adds a split of two new pins, leading pane first, at `index` in + // `container`, and returns its ID, or an empty string for an invalid URL or + // an unknown container. + std::string CreateSplit(const PinContainer& container, + size_t index, + double ratio, + const NewPin& leading, + const NewPin& trailing); + // Separate Tabs: the split's pins take its place, in pane order. + void SeparateSplit(std::string_view id); + // One pane of the split holding `pin` closed (Arc's behaviour): the other + // pin takes the split's place, and `pin` goes. Restore Last Closed Tab puts + // both back as the split. + void TakeOutOfSplit(std::string_view pin); + void SetSplitRatio(std::string_view id, double ratio); + // Move Left and Move Right on an open pinned split: its pins swap panes. + void SwapSplitPanes(std::string_view id); // An empty name clears it. void SetName(std::string_view id, std::string_view name); void SetTitle(std::string_view id, std::string_view title); @@ -268,6 +333,10 @@ class ClairPinStore { void Notify(const PinContainer& container); // Rebuilds every container's children, sorted by key, then by ID. void Index(); + // add-split-view D10: a split's pins follow its container. + void PlaceSplitPins(const PinnedSplit& split); + // Turns each split that hasn't a pin for each pane into the pins it has. + void RepairSplits(); // Whether `container` exists: its Space or profile, and its folder, which // must be of that Space. bool IsValid(const PinContainer& container) const; @@ -290,6 +359,7 @@ class ClairPinStore { const raw_ptr prefs_; std::map pins_; std::map folders_; + std::map splits_; // The children of each container, in order. std::map> children_; std::set closed_; diff --git a/engine/overlay/chrome/browser/clair/clair_pin_store.mm b/engine/overlay/chrome/browser/clair/clair_pin_store.mm index dbd7bca..94db6a7 100644 --- a/engine/overlay/chrome/browser/clair/clair_pin_store.mm +++ b/engine/overlay/chrome/browser/clair/clair_pin_store.mm @@ -7,6 +7,7 @@ #import #include +#include #include #include #include @@ -40,6 +41,11 @@ constexpr char kKindKey[] = "kind"; constexpr char kPinKind[] = "pin"; constexpr char kFolderKind[] = "folder"; +// add-split-view D10. +constexpr char kSplitKind[] = "split"; +constexpr char kSplitKey[] = "split"; +constexpr char kIndexKey[] = "index"; +constexpr char kRatioKey[] = "ratio"; constexpr char kSpaceKey[] = "space"; constexpr char kFolderKey[] = "folder"; constexpr char kProfileKey[] = "profile"; @@ -63,6 +69,11 @@ bool IsPinID(std::string_view id) { return base::Uuid::ParseLowercase(id).is_valid(); } +// add-split-view D10: a split's ratio, as the divider allows it. +double ClampRatio(double ratio) { + return std::isfinite(ratio) ? std::clamp(ratio, 0.05, 0.95) : 0.5; +} + // D6: the schemes a pinned URL may have. bool IsPinnableURL(const GURL& url) { return url.is_valid() && @@ -281,22 +292,94 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { folders_[id] = std::move(folder); } } + // The place a pin or a split names: a Space's section, a folder of it, + // or a profile's favorites; nullopt when it's gone. + auto place_of = [&](const base::DictValue& item) + -> std::optional { + const std::string* space = item.FindString(kSpaceKey); + const std::string* profile = item.FindString(kProfileKey); + if (space) { + if (!spaces->Contains(*space)) { + return std::nullopt; + } + // D1: in its folder, in the folder's Space, while the folder + // exists; at its own Space's top level otherwise. + const std::string* folder = item.FindString(kFolderKey); + auto found = folder ? folders_.find(*folder) : folders_.end(); + if (found != folders_.end()) { + return PinContainer::OfFolder(found->second.space, found->first); + } + return PinContainer::OfSpace(*space); + } + if (profile) { + // D13: the profile's ID on this Mac. + const std::string directory = + ClairProfiles::Get()->DirectoryOf(*profile); + if (directory.empty()) { + return std::nullopt; + } + return PinContainer::OfProfile(directory); + } + return std::nullopt; + }; + // add-split-view D10: splits next, so their pins can find them. for (const auto [id, value] : *items) { const base::DictValue* item = value.GetIfDict(); const std::string* kind = item ? item->FindString(kKindKey) : nullptr; - const std::string* url = item ? item->FindString(kURLKey) : nullptr; const std::string* order = item ? item->FindString(kOrderKey) : nullptr; - if (!kind || *kind != kPinKind || !IsPinID(id) || !url || !order || + if (!kind || *kind != kSplitKind || !IsPinID(id) || !order || !IsValidOrderKey(*order) || folders_.contains(id)) { continue; } + std::optional place = place_of(*item); + if (!place) { + continue; + } + PinnedSplit split; + split.id = id; + split.container = *place; + split.order = *order; + split.ratio = ClampRatio(item->FindDouble(kRatioKey).value_or(0.5)); + splits_[id] = std::move(split); + } + for (const auto [id, value] : *items) { + const base::DictValue* item = value.GetIfDict(); + const std::string* kind = item ? item->FindString(kKindKey) : nullptr; + const std::string* url = item ? item->FindString(kURLKey) : nullptr; + if (!kind || *kind != kPinKind || !IsPinID(id) || !url || + folders_.contains(id) || splits_.contains(id)) { + continue; + } Pin pin; pin.id = id; - pin.order = *order; pin.url = GURL(*url); if (!IsPinnableURL(pin.url)) { continue; } + if (const std::string* split_id = item->FindString(kSplitKey)) { + // A pin of a split takes its split's place. + auto split = splits_.find(*split_id); + const std::optional index = item->FindInt(kIndexKey); + if (split == splits_.end() || !index || *index < 0 || *index > 1) { + continue; + } + pin.split = split->first; + pin.split_index = *index; + pin.container = split->second.container; + if (const std::string* title = item->FindString(kTitleKey)) { + pin.title = Clean(*title, kMaxTitleLength); + } + if (const std::string* name = item->FindString(kNameKey)) { + pin.name = Clean(*name, kMaxNameLength); + } + pins_[pin.id] = std::move(pin); + continue; + } + const std::string* order = item->FindString(kOrderKey); + if (!order || !IsValidOrderKey(*order)) { + continue; + } + pin.order = *order; const std::string* space = item->FindString(kSpaceKey); const std::string* profile = item->FindString(kProfileKey); if (space) { @@ -338,9 +421,40 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { closed_.insert(*id); } } + RepairSplits(); Index(); } +void ClairPinStore::RepairSplits() { + for (auto it = splits_.begin(); it != splits_.end();) { + std::vector panes; + bool leading = false; + bool trailing = false; + for (auto& [id, pin] : pins_) { + if (pin.split == it->first) { + panes.push_back(&pin); + (pin.split_index == 0 ? leading : trailing) = true; + } + } + if (panes.size() == 2 && leading && trailing) { + ++it; + continue; + } + // The pins it has take its place, in pane order, each with a key of its + // own after the split's. + std::ranges::sort(panes, {}, &Pin::split_index); + std::string order = it->second.order; + for (Pin* pin : panes) { + pin->split.clear(); + pin->split_index = 0; + pin->container = it->second.container; + pin->order = order; + order = OrderKeyBetween(order, std::string()); + } + it = splits_.erase(it); + } +} + void ClairPinStore::Save() { ClairProfiles* profiles = ClairProfiles::Get(); base::DictValue items; @@ -352,19 +466,38 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { item.Set(kNameKey, folder.name); items.Set(id, std::move(item)); } + // The place a pin or a split names. + auto set_place = [&](base::DictValue& item, const PinContainer& container) { + if (container.is_favorites()) { + // D13: the profile's ID, not its directory. + item.Set(kProfileKey, profiles->StoredIDOf(container.profile)); + } else { + item.Set(kSpaceKey, container.space); + if (container.is_folder()) { + item.Set(kFolderKey, container.folder); + } + } + }; + // add-split-view D10. + for (const auto& [id, split] : splits_) { + base::DictValue item; + item.Set(kKindKey, kSplitKind); + set_place(item, split.container); + item.Set(kOrderKey, split.order); + item.Set(kRatioKey, split.ratio); + items.Set(id, std::move(item)); + } for (const auto& [id, pin] : pins_) { base::DictValue item; item.Set(kKindKey, kPinKind); - if (pin.container.is_favorites()) { - // D13: the profile's ID, not its directory. - item.Set(kProfileKey, profiles->StoredIDOf(pin.container.profile)); + if (!pin.split.empty()) { + // A split's pin names its split and pane, not a place. + item.Set(kSplitKey, pin.split); + item.Set(kIndexKey, pin.split_index); } else { - item.Set(kSpaceKey, pin.container.space); - if (pin.container.is_folder()) { - item.Set(kFolderKey, pin.container.folder); - } + set_place(item, pin.container); + item.Set(kOrderKey, pin.order); } - item.Set(kOrderKey, pin.order); item.Set(kURLKey, pin.url.spec()); item.Set(kTitleKey, pin.title); if (!pin.name.empty()) { @@ -393,7 +526,13 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { keyed[PinContainer::OfSpace(folder.space)].emplace_back(folder.order, id); } for (const auto& [id, pin] : pins_) { - keyed[pin.container].emplace_back(pin.order, id); + // A split's pins have its place (add-split-view D10). + if (pin.split.empty()) { + keyed[pin.container].emplace_back(pin.order, id); + } + } + for (const auto& [id, split] : splits_) { + keyed[split.container].emplace_back(split.order, id); } children_.clear(); for (auto& [container, entries] : keyed) { @@ -443,6 +582,47 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { return found == folders_.end() ? nullptr : &found->second; } +const PinnedSplit* ClairPinStore::FindSplit(std::string_view id) const { + auto found = splits_.find(std::string(id)); + return found == splits_.end() ? nullptr : &found->second; +} + +std::vector ClairPinStore::PinsOfSplit(std::string_view id) const { + std::vector result; + if (id.empty() || !FindSplit(id)) { + return result; + } + for (const auto& [pin_id, pin] : pins_) { + if (pin.split == id) { + result.push_back(&pin); + } + } + std::ranges::sort(result, {}, &Pin::split_index); + return result; +} + +const Pin* ClairPinStore::PartnerOf(std::string_view pin) const { + const Pin* record = Find(pin); + if (!record || record->split.empty()) { + return nullptr; + } + for (const Pin* other : PinsOfSplit(record->split)) { + if (other != record) { + return other; + } + } + return nullptr; +} + +void ClairPinStore::PlaceSplitPins(const PinnedSplit& split) { + for (auto& [id, pin] : pins_) { + if (pin.split == split.id) { + pin.container = split.container; + pin.order.clear(); + } + } +} + std::vector ClairPinStore::ChildrenOf( const PinContainer& container) const { auto found = children_.find(container); @@ -456,6 +636,11 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { for (const std::string& id : ChildrenOf(container)) { if (const Pin* pin = Find(id)) { result.push_back(pin); + } else if (FindSplit(id)) { + // add-split-view D10: a split's two, in pane order. + for (const Pin* pane : PinsOfSplit(id)) { + result.push_back(pane); + } } } return result; @@ -466,6 +651,10 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { for (const std::string& id : ChildrenOf(PinContainer::OfSpace(space))) { if (const Pin* pin = Find(id)) { result.push_back(pin); + } else if (FindSplit(id)) { + for (const Pin* pane : PinsOfSplit(id)) { + result.push_back(pane); + } } else if (FindFolder(id)) { for (const Pin* child : PinsIn(PinContainer::OfFolder(space, id))) { result.push_back(child); @@ -488,8 +677,14 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { std::optional ClairPinStore::IndexOf(std::string_view id) const { PinContainer container; + if (const Pin* pin = Find(id); pin && !pin->split.empty()) { + // add-split-view D10: a split's pin has its split's place. + return IndexOf(pin->split); + } if (const Pin* pin = Find(id)) { container = pin->container; + } else if (const PinnedSplit* split = FindSplit(id)) { + container = split->container; } else if (const Folder* folder = FindFolder(id)) { container = PinContainer::OfSpace(folder->space); } else { @@ -529,6 +724,9 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { if (const Folder* folder = FindFolder(id)) { return folder->order; } + if (const PinnedSplit* split = FindSplit(id)) { + return split->order; + } return *none; } @@ -563,6 +761,8 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { pin->second.order = next; } else if (auto folder = folders_.find(id); folder != folders_.end()) { folder->second.order = next; + } else if (auto split = splits_.find(id); split != splits_.end()) { + split->second.order = next; } previous = std::move(next); } @@ -600,6 +800,30 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { if (!IsValid(container)) { return false; } + // add-split-view D10: a split's pin moves its split, which goes where a pin + // goes. + if (const Pin* pin = Find(id); pin && !pin->split.empty()) { + return Move(pin->split, container, index); + } + if (auto found = splits_.find(std::string(id)); found != splits_.end()) { + const PinContainer from = found->second.container; + std::vector others = ChildrenOf(container); + std::erase(others, std::string(id)); + if (from == container && IndexOf(id) == std::min(index, others.size())) { + return false; + } + std::string key = KeyAt(container, index, id); + found = splits_.find(std::string(id)); + found->second.container = container; + found->second.order = std::move(key); + PlaceSplitPins(found->second); + if (from.Section() != container.Section()) { + Index(); + Notify(from); + } + Changed(container); + return true; + } const std::optional old_index = IndexOf(id); if (auto found = pins_.find(std::string(id)); found != pins_.end()) { const PinContainer from = found->second.container; @@ -635,13 +859,19 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { found = folders_.find(std::string(id)); found->second.order = std::move(key); if (from != container) { - // D1: its pins' own Space follows it. + // D1: its pins' own Space follows it, and its splits' (add-split-view + // D10). found->second.space = container.space; for (auto& [pin_id, pin] : pins_) { if (pin.container.folder == id) { pin.container.space = container.space; } } + for (auto& [split_id, split] : splits_) { + if (split.container.folder == id) { + split.container.space = container.space; + } + } Index(); Notify(from); } @@ -677,6 +907,31 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { if (found == pins_.end()) { return; } + // add-split-view D10: a split's pin goes with its split and the other pin. + if (!found->second.split.empty()) { + auto split = splits_.find(found->second.split); + Removal removal; + std::vector ids; + for (const Pin* pane : PinsOfSplit(found->second.split)) { + ids.push_back(pane->id); + } + for (const std::string& pane_id : ids) { + auto pane = pins_.find(pane_id); + removal.pins.push_back(std::move(pane->second)); + pins_.erase(pane); + } + const PinContainer container = split->second.container; + removal.splits.push_back(std::move(split->second)); + splits_.erase(split); + if (remember) { + removal.time = base::Time::Now(); + Remember(std::move(removal)); + } else { + Forget(removal); + } + Changed(container); + return; + } Pin pin = std::move(found->second); pins_.erase(found); const PinContainer container = pin.container; @@ -691,6 +946,137 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { Changed(container); } +// --- Splits (add-split-view D10) --- + +std::string ClairPinStore::CreateSplit(const PinContainer& container, + size_t index, + double ratio, + const NewPin& leading, + const NewPin& trailing) { + if (!IsPinnableURL(leading.url) || !IsPinnableURL(trailing.url) || + !IsValid(container)) { + return std::string(); + } + PinnedSplit split; + split.id = base::Uuid::GenerateRandomV4().AsLowercaseString(); + split.container = container; + split.order = KeyAt(container, index, std::string()); + split.ratio = ClampRatio(ratio); + int pane = 0; + for (const NewPin* source : {&leading, &trailing}) { + Pin pin; + pin.id = base::Uuid::GenerateRandomV4().AsLowercaseString(); + pin.container = container; + pin.url = source->url; + pin.title = Clean(source->title, kMaxTitleLength); + pin.name = Clean(source->name, kMaxNameLength); + pin.split = split.id; + pin.split_index = pane++; + std::string pin_id = pin.id; + pins_[pin_id] = std::move(pin); + } + std::string id = split.id; + splits_[id] = std::move(split); + Changed(container); + return id; +} + +void ClairPinStore::SeparateSplit(std::string_view id) { + auto split = splits_.find(std::string(id)); + if (split == splits_.end()) { + return; + } + const PinContainer container = split->second.container; + const std::string order = split->second.order; + // The leading pin takes the split's key, the trailing one a key between it + // and the next child's. + const std::vector children = ChildrenOf(container); + auto at = std::ranges::find(children, id); + const std::string next = at != children.end() && at + 1 != children.end() + ? OrderOf(*(at + 1)) + : std::string(); + std::vector panes; + for (const Pin* pin : PinsOfSplit(id)) { + panes.push_back(pin->id); + } + splits_.erase(split); + std::string key = order; + for (size_t i = 0; i < panes.size(); ++i) { + Pin& pin = pins_[panes[i]]; + pin.split.clear(); + pin.split_index = 0; + pin.container = container; + pin.order = key; + key = OrderKeyBetween(key, next); + } + Index(); + // Without room between the two keys, the trailing pin goes right after the + // leading one, as KeyAt renumbers. Its empty key puts it first meanwhile, + // so the leading pin's place is counted without it. + if (panes.size() == 2 && pins_[panes[1]].order.empty()) { + std::vector others = ChildrenOf(container); + std::erase(others, panes[1]); + auto leading = std::ranges::find(others, panes[0]); + std::string fallback = KeyAt( + container, + leading != others.end() + ? static_cast(leading - others.begin()) + 1 + : std::numeric_limits::max(), + panes[1]); + pins_[panes[1]].order = std::move(fallback); + } + Changed(container); +} + +void ClairPinStore::TakeOutOfSplit(std::string_view pin_id) { + const Pin* pin = Find(pin_id); + const Pin* partner = PartnerOf(pin_id); + auto split = pin ? splits_.find(pin->split) : splits_.end(); + if (!pin || !partner || split == splits_.end()) { + return; + } + // The other pin takes the split's place and key. + Pin& kept = pins_[partner->id]; + kept.split.clear(); + kept.split_index = 0; + kept.container = split->second.container; + kept.order = split->second.order; + const PinContainer container = split->second.container; + Removal removal; + removal.partner = kept.id; + removal.splits.push_back(split->second); + auto found = pins_.find(std::string(pin_id)); + removal.pins.push_back(std::move(found->second)); + pins_.erase(found); + splits_.erase(split); + removal.time = base::Time::Now(); + Remember(std::move(removal)); + Changed(container); +} + +void ClairPinStore::SetSplitRatio(std::string_view id, double ratio) { + auto split = splits_.find(std::string(id)); + ratio = ClampRatio(ratio); + if (split == splits_.end() || std::abs(split->second.ratio - ratio) < 1e-4) { + return; + } + split->second.ratio = ratio; + Save(); +} + +void ClairPinStore::SwapSplitPanes(std::string_view id) { + const PinnedSplit* split = FindSplit(id); + if (!split) { + return; + } + for (auto& [pin_id, pin] : pins_) { + if (pin.split == id) { + pin.split_index = 1 - pin.split_index; + } + } + Changed(split->container); +} + void ClairPinStore::SetName(std::string_view id, std::string_view name) { auto found = pins_.find(std::string(id)); std::string cleaned = Clean(name, kMaxNameLength); @@ -797,11 +1183,27 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { original->name}; const std::vector pins = PinsIn(PinContainer::OfFolder(original->space, original->id)); + // add-split-view D10: its splits are copied as splits. + std::map split_copies; + std::vector new_splits; + for (const Pin* pin : pins) { + if (pin->split.empty() || split_copies.contains(pin->split)) { + continue; + } + PinnedSplit split = *FindSplit(pin->split); + split.id = base::Uuid::GenerateRandomV4().AsLowercaseString(); + split.container = PinContainer::OfFolder(copy.space, copy.id); + split_copies[pin->split] = split.id; + new_splits.push_back(std::move(split)); + } std::vector copies; for (const Pin* pin : pins) { Pin duplicate = *pin; duplicate.id = base::Uuid::GenerateRandomV4().AsLowercaseString(); duplicate.container = PinContainer::OfFolder(copy.space, copy.id); + if (!duplicate.split.empty()) { + duplicate.split = split_copies[duplicate.split]; + } if (NSImage* icon = IconOf(pin->id)) { icons_[duplicate.id] = icon; if (!icon_dir_.empty()) { @@ -814,6 +1216,10 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { } std::string copy_id = copy.id; folders_[copy_id] = std::move(copy); + for (PinnedSplit& split : new_splits) { + std::string split_id = split.id; + splits_[split_id] = std::move(split); + } for (Pin& duplicate : copies) { std::string pin_id = duplicate.id; pins_[pin_id] = std::move(duplicate); @@ -842,6 +1248,15 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { removal.pins.push_back(std::move(pin->second)); pins_.erase(pin); } + // add-split-view D10: its splits go with it. + for (auto split = splits_.begin(); split != splits_.end();) { + if (split->second.container.folder == id) { + removal.splits.push_back(std::move(split->second)); + split = splits_.erase(split); + } else { + ++split; + } + } folders_.erase(found); if (closed_.erase(std::string(id)) > 0) { SaveClosed(); @@ -869,6 +1284,13 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { ++it; } } + for (auto it = splits_.begin(); it != splits_.end();) { + if (it->second.container.Section() == section) { + it = splits_.erase(it); + } else { + ++it; + } + } bool had_folders = false; if (!section.is_favorites()) { for (auto it = folders_.begin(); it != folders_.end();) { @@ -962,6 +1384,11 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { closed_.insert(id); SaveClosed(); } + for (PinnedSplit& split : removal.splits) { + split.container = PinContainer::OfFolder(section.space, id); + std::string split_id = split.id; + splits_[split_id] = std::move(split); + } for (Pin& pin : removal.pins) { if (pins_.contains(pin.id)) { continue; @@ -970,9 +1397,76 @@ bool SamePinnedURL(const GURL& url, const GURL& pinned) { std::string pin_id = pin.id; pins_[pin_id] = std::move(pin); } + RepairSplits(); Changed(section); return true; } + // add-split-view D10: a split, whole or with the pane closed out of it. + if (!found->splits.empty()) { + PinnedSplit split = found->splits[0]; + if (FindSplit(split.id) || + std::ranges::any_of(found->pins, [&](const Pin& pin) { + return pins_.contains(pin.id); + })) { + return false; + } + Removal removal = std::move(*found); + removals_.erase(found); + if (!removal.partner.empty()) { + // The pin that kept the split's place takes it back into the split, + // where it is now; without it, the closed pin comes back alone there. + auto partner = pins_.find(removal.partner); + Pin pin = std::move(removal.pins[0]); + if (partner == pins_.end() || !partner->second.split.empty()) { + pin.split.clear(); + pin.split_index = 0; + pin.container = IsValid(split.container) ? split.container + : split.container.Section(); + pin.order = KeyAt(pin.container, std::numeric_limits::max(), + std::string()); + const PinContainer container = pin.container; + std::string pin_id = pin.id; + pins_[pin_id] = std::move(pin); + Changed(container); + return true; + } + split.container = partner->second.container; + split.order = partner->second.order; + partner->second.split = split.id; + partner->second.split_index = 1 - pin.split_index; + partner->second.order.clear(); + pin.container = split.container; + const PinContainer container = split.container; + std::string pin_id = pin.id; + pins_[pin_id] = std::move(pin); + std::string split_id = split.id; + splits_[split_id] = std::move(split); + Changed(container); + return true; + } + bool at_end = false; + if (!IsValid(split.container)) { + if (!IsValid(split.container.Section())) { + return false; + } + split.container = split.container.Section(); + at_end = true; + } + if (at_end || KeyTaken(split.container, split.order)) { + split.order = KeyAt(split.container, std::numeric_limits::max(), + std::string()); + } + const PinContainer container = split.container; + for (Pin& pin : removal.pins) { + pin.container = container; + std::string pin_id = pin.id; + pins_[pin_id] = std::move(pin); + } + std::string split_id = split.id; + splits_[split_id] = std::move(split); + Changed(container); + return true; + } if (found->pins.empty() || pins_.contains(found->pins[0].id) || !IsValid(found->pins[0].container.Section())) { return false; diff --git a/engine/overlay/chrome/browser/clair/clair_space_tabs.h b/engine/overlay/chrome/browser/clair/clair_space_tabs.h index b9b4749..ea46c7c 100644 --- a/engine/overlay/chrome/browser/clair/clair_space_tabs.h +++ b/engine/overlay/chrome/browser/clair/clair_space_tabs.h @@ -154,6 +154,13 @@ class ClairSpaceTabs : public base::SupportsUserData::Data, std::string PinTab(tabs::TabInterface* tab, const clair::PinContainer& container, size_t index); + // add-split-view D10: makes a split of the Today rows `lead` and `trail` a + // pinned or favorited split at `index` in `container`, keeping their pages, + // Peeks, names and ratio. Returns the split's ID, or empty. + std::string PinSplit(tabs::TabInterface* lead, + tabs::TabInterface* trail, + const clair::PinContainer& container, + size_t index); // D5: the pin bound to `tab` is going: `tab`, with its Peek, joins // `space`'s Today list at `index`, keeping its name. void UnbindToToday(tabs::TabInterface* tab, @@ -217,6 +224,9 @@ class ClairSpaceTabs : public base::SupportsUserData::Data, // are written again. void AllListsChanged(); void TabChanged(content::WebContents* contents); + // add-split-view D2: `tab` joined or left a split, or its split changed: + // its snapshot, its list and its pin's container are pushed again. + void SplitChanged(tabs::TabInterface* tab); // Pushes now. void Flush(); @@ -275,6 +285,9 @@ class ClairSpaceTabs : public base::SupportsUserData::Data, std::string OwnSpace() const; // `tab` and its Peek, if it has one in the same window. std::vector FamilyOf(tabs::TabInterface* tab) const; + // add-split-view D7: puts each split's tabs in `list` together, the + // leading pane's family first. + void KeepSplitsTogether(std::vector& list); // Takes `tab`'s family out of `list` and returns its handles, in order. std::vector TakeFamily(std::vector& list, tabs::TabInterface* tab) const; @@ -363,9 +376,11 @@ void KeepLastUsedProfileOnASpace(); tabs::TabInterface* BoundTabOf(std::string_view pin); // A container's pins, as snapshots, in order. NSArray>* PinSnapshots(const PinContainer& container); -// add-tab-folders D2: a Space's pinned items, pins and folders, as snapshots, -// in order. +// add-tab-folders D2: a Space's pinned items, pins, splits and folders, as +// snapshots, in order. NSArray>* PinnedItemSnapshots(const std::string& space); +// add-split-view D10: a profile's favorites and favorited splits, in order. +NSArray>* FavoriteItemSnapshots(const std::string& profile); // Pushes a container's pins to the observers at the end of this run-loop // turn, or with the next FlushAll(). void PinsChanged(const PinContainer& container); @@ -374,6 +389,12 @@ void PinTab(tabs::TabInterface* tab, const std::string& folder, size_t index, bool favorite); +// add-split-view D10: the tabs of `pin`'s pinned split, once both are open in +// one window, become a Chromium split with its ratio. +void JoinPinnedSplit(const std::string& pin); +// Separate Tabs on a pinned or favorited split: its pins take its place, and +// a split of their open tabs ends. +void SeparatePinnedSplit(const std::string& split); void MovePin(const std::string& pin, const PinContainer& to, size_t index); // add-tab-folders D7, D8, D11: the host's folder calls that reach tabs. void MoveFolder(const std::string& folder, @@ -411,8 +432,8 @@ bool CanRestoreLastClosed(ClairBrowserWindow* window); // host. bool IsOtherSite(const GURL& url, const GURL& current); // D7: whether a URL the user enters to open in `window`'s current tab opens -// in a new Today tab instead: the tab is a favorite's, and `url` is on -// another site. +// in a new Today tab instead: the tab is a favorite's, not in a split, and +// `url` is on another site. bool LeavesFavorite(ClairBrowserWindow* window, const GURL& url); // D8: every window's title follows its active tab's name. void UpdateWindowTitles(); diff --git a/engine/overlay/chrome/browser/clair/clair_space_tabs.mm b/engine/overlay/chrome/browser/clair/clair_space_tabs.mm index d6eb8ef..d07298f 100644 --- a/engine/overlay/chrome/browser/clair/clair_space_tabs.mm +++ b/engine/overlay/chrome/browser/clair/clair_space_tabs.mm @@ -6,12 +6,14 @@ #include #include +#include #include #include "base/barrier_closure.h" #include "base/check.h" #include "base/functional/bind.h" #include "base/logging.h" +#include "base/memory/ref_counted.h" #include "base/no_destructor.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" @@ -21,6 +23,7 @@ #include "chrome/browser/browser_process.h" #import "chrome/browser/clair/clair_pin_store.h" #include "chrome/browser/clair/clair_profiles.h" +#include "chrome/browser/clair/window/clair_splits.h" #include "chrome/browser/clair/window/clair_browser_window.h" #include "chrome/browser/clair/window/clair_window_group.h" #include "chrome/browser/clair/window/clair_peeks.h" @@ -105,8 +108,16 @@ // What the session holds for the two; nullopt when unknown. std::optional written_pin; std::optional written_name; + // add-split-view D7: when the tab was first listed, by a count; a split's + // row keeps the place of the pane listed first. + uint64_t listed = 0; }; +uint64_t NextListed() { + static uint64_t count = 0; + return ++count; +} + // add-profiles D6: the group of the window holding `contents`, or empty. std::string GroupOf(content::WebContents* contents) { ClairBrowserWindow* window = ClairBrowserWindow::FromWebContents(contents); @@ -218,7 +229,10 @@ - (instancetype)initWithContents:(content::WebContents*)contents spaceID:(NSString*)spaceID browserID:(ClairBrowserID)browserID pinID:(NSString*)pinID - name:(NSString*)name; + name:(NSString*)name + splitPartnerID:(ClairTabID)splitPartnerID + isLeadingPane:(BOOL)isLeadingPane + splitRatio:(double)splitRatio; @end @implementation ClairChromiumTab @@ -245,6 +259,9 @@ @implementation ClairChromiumTab @synthesize browserID = _browserID; @synthesize pinID = _pinID; @synthesize name = _name; +@synthesize splitPartnerID = _splitPartnerID; +@synthesize isLeadingPane = _isLeadingPane; +@synthesize splitRatio = _splitRatio; - (instancetype)initWithContents:(content::WebContents*)contents peekParentID:(ClairTabID)peekParentID @@ -252,8 +269,14 @@ - (instancetype)initWithContents:(content::WebContents*)contents spaceID:(NSString*)spaceID browserID:(ClairBrowserID)browserID pinID:(NSString*)pinID - name:(NSString*)name { + name:(NSString*)name + splitPartnerID:(ClairTabID)splitPartnerID + isLeadingPane:(BOOL)isLeadingPane + splitRatio:(double)splitRatio { if ((self = [super init])) { + _splitPartnerID = splitPartnerID; + _isLeadingPane = isLeadingPane; + _splitRatio = splitRatio; _peekParentID = peekParentID; _peekID = peekID; _spaceID = [spaceID copy]; @@ -333,6 +356,7 @@ @implementation ClairChromiumPin @synthesize tabID = _tabID; @synthesize tabs = _tabs; @synthesize isAtPinnedURL = _isAtPinnedURL; +@synthesize pinnedSplitID = _pinnedSplitID; - (instancetype)initWithPin:(const clair::Pin&)pin tabs:(NSArray>*)tabs @@ -356,6 +380,7 @@ - (instancetype)initWithPin:(const clair::Pin&)pin _tabs = [tabs copy] ?: @[]; _tabID = _tabs.count ? _tabs.firstObject.tabID : ClairTabIDNone; _isAtPinnedURL = isAtPinnedURL; + _pinnedSplitID = pin.split.empty() ? nil : base::SysUTF8ToNSString(pin.split); } return self; } @@ -364,7 +389,7 @@ - (instancetype)initWithPin:(const clair::Pin&)pin // add-tab-folders D2. @interface ClairChromiumFolder : NSObject - (instancetype)initWithFolder:(const clair::Folder&)folder - pins:(NSArray>*)pins; + items:(NSArray>*)items; @end @implementation ClairChromiumFolder @@ -372,32 +397,74 @@ @implementation ClairChromiumFolder @synthesize spaceID = _spaceID; @synthesize name = _name; @synthesize isOpen = _isOpen; -@synthesize pins = _pins; +@synthesize items = _items; - (instancetype)initWithFolder:(const clair::Folder&)folder - pins:(NSArray>*)pins { + items:(NSArray>*)items { if ((self = [super init])) { _folderID = base::SysUTF8ToNSString(folder.id); _spaceID = base::SysUTF8ToNSString(folder.space); _name = base::SysUTF8ToNSString(folder.name); _isOpen = clair::ClairPinStore::Get()->IsOpen(folder.id); + _items = [items copy] ?: @[]; + } + return self; +} +@end + +// add-split-view D10. +@interface ClairChromiumPinnedSplit : NSObject +- (instancetype)initWithSplit:(const clair::PinnedSplit&)split + pins:(NSArray>*)pins; +@end + +@implementation ClairChromiumPinnedSplit +@synthesize pinnedSplitID = _pinnedSplitID; +@synthesize isFavorite = _isFavorite; +@synthesize spaceID = _spaceID; +@synthesize folderID = _folderID; +@synthesize profileID = _profileID; +@synthesize pins = _pins; +@synthesize ratio = _ratio; + +- (instancetype)initWithSplit:(const clair::PinnedSplit&)split + pins:(NSArray>*)pins { + if ((self = [super init])) { + _pinnedSplitID = base::SysUTF8ToNSString(split.id); + _isFavorite = split.container.is_favorites(); + _spaceID = + _isFavorite ? nil : base::SysUTF8ToNSString(split.container.space); + _folderID = split.container.is_folder() + ? base::SysUTF8ToNSString(split.container.folder) + : nil; + _profileID = base::SysUTF8ToNSString( + _isFavorite ? split.container.profile + : clair::ClairSpaceStore::Get()->ProfileOf( + split.container.space)); _pins = [pins copy] ?: @[]; + _ratio = split.ratio; } return self; } @end @interface ClairChromiumPinnedItem : NSObject -- (instancetype)initWithPin:(id)pin folder:(id)folder; +- (instancetype)initWithPin:(id)pin + split:(id)split + folder:(id)folder; @end @implementation ClairChromiumPinnedItem @synthesize pin = _pin; +@synthesize split = _split; @synthesize folder = _folder; -- (instancetype)initWithPin:(id)pin folder:(id)folder { +- (instancetype)initWithPin:(id)pin + split:(id)split + folder:(id)folder { if ((self = [super init])) { _pin = pin; + _split = split; _folder = folder; } return self; @@ -971,6 +1038,8 @@ void BeforeUnloadFired(bool proceed) override { } const std::string pin = PinOf(tab); const std::string name = NameOf(tab); + // add-split-view D2. + tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); return [[ClairChromiumTab alloc] initWithContents:contents peekParentID:peek_parent_id @@ -978,7 +1047,11 @@ void BeforeUnloadFired(bool proceed) override { spaceID:base::SysUTF8ToNSString(SpaceOf(tab)) browserID:browser_id pinID:pin.empty() ? nil : base::SysUTF8ToNSString(pin) - name:name.empty() ? nil : base::SysUTF8ToNSString(name)]; + name:name.empty() ? nil : base::SysUTF8ToNSString(name) + splitPartnerID:partner ? clair::TabIDOf(partner->GetContents()) + : ClairTabIDNone + isLeadingPane:partner && ClairSplits::IsLeading(tab) + splitRatio:ClairSplits::RatioOf(tab)]; } id ClairSpaceTabs::PinSnapshot(const clair::Pin& pin) const { @@ -1053,6 +1126,9 @@ void BeforeUnloadFired(bool proceed) override { tag = EnsureTag(contents); tag->space = space; tag->rank = rank; + if (!tag->listed) { + tag->listed = NextListed(); + } std::vector& list = lists_[space]; size_t at = 0; @@ -1161,6 +1237,12 @@ void BeforeUnloadFired(bool proceed) override { clair::PinsChanged(record->container); TabChanged(contents); PostFlush(); + // add-split-view D10: a pin of a pinned split shows beside the other one's + // page, once both are open in one window. + if (!record->split.empty()) { + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce(&clair::JoinPinnedSplit, pin)); + } return true; } @@ -1226,6 +1308,68 @@ void BeforeUnloadFired(bool proceed) override { return space.empty() ? clair::ClairSpaceStore::Get()->last_space() : space; } +namespace { + +// What a new pin takes from `tab`: its URL, title and custom name. +clair::ClairPinStore::NewPin NewPinFrom(tabs::TabInterface* tab, + const std::string& name) { + content::WebContents* contents = tab->GetContents(); + content::NavigationEntry* entry = + contents->GetController().GetLastCommittedEntry(); + clair::ClairPinStore::NewPin pin; + pin.url = entry && !entry->IsInitialEntry() ? entry->GetURL() + : contents->GetVisibleURL(); + pin.title = base::UTF16ToUTF8(contents->GetTitle()); + pin.name = name; + return pin; +} + +// Keeps `tab`'s favicon as the pin's icon. +void TakeIcon(tabs::TabInterface* tab, const std::string& pin) { + if (auto* favicons = + favicon::ContentFaviconDriver::FromWebContents(tab->GetContents()); + favicons && favicons->FaviconIsValid()) { + gfx::Image image = favicons->GetFavicon(); + if (!image.IsEmpty()) { + clair::ClairPinStore::Get()->SetIcon(pin, image.ToNSImage()); + } + } +} + +} // namespace + +std::string ClairSpaceTabs::PinSplit(tabs::TabInterface* lead, + tabs::TabInterface* trail, + const clair::PinContainer& container, + size_t index) { + // add-split-view D10: a split of two Today tabs, as one item. + for (tabs::TabInterface* tab : {lead, trail}) { + if (!tab || !is_regular() || !PinOf(tab).empty() || SpaceOf(tab).empty() || + PeekParentOf(tab)) { + return std::string(); + } + } + SpaceTag* lead_tag = EnsureTag(lead->GetContents()); + SpaceTag* trail_tag = EnsureTag(trail->GetContents()); + clair::ClairPinStore* store = clair::ClairPinStore::Get(); + const std::string split = store->CreateSplit( + container, index, ClairSplits::RatioOf(lead), + NewPinFrom(lead, lead_tag->name), NewPinFrom(trail, trail_tag->name)); + const std::vector pins = store->PinsOfSplit(split); + if (pins.size() != 2) { + return std::string(); + } + const std::string lead_pin = pins[0]->id; + const std::string trail_pin = pins[1]->id; + TakeIcon(lead, lead_pin); + TakeIcon(trail, trail_pin); + lead_tag->name.clear(); + trail_tag->name.clear(); + Bind(lead, lead_pin); + Bind(trail, trail_pin); + return split; +} + std::string ClairSpaceTabs::PinTab(tabs::TabInterface* tab, const clair::PinContainer& container, size_t index) { @@ -1394,7 +1538,16 @@ void BeforeUnloadFired(bool proceed) override { return; } std::vector& list = lists_[space]; - const std::vector handles = TakeFamily(list, tab); + std::vector handles = TakeFamily(list, tab); + // add-split-view D7: a Today split moves as one block, its leading pane + // first, as the sidebar counts it as one row. + if (tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); + partner && std::ranges::find(list, partner->GetHandle()) != list.end()) { + const std::vector other = TakeFamily(list, partner); + handles.insert(ClairSplits::IsLeading(partner) ? handles.begin() + : handles.end(), + other.begin(), other.end()); + } const size_t at = static_cast( std::clamp(index, 0, static_cast(list.size()))); list.insert(list.begin() + at, handles.begin(), handles.end()); @@ -1575,6 +1728,75 @@ void BeforeUnloadFired(bool proceed) override { PostFlush(); } +void ClairSpaceTabs::SplitChanged(tabs::TabInterface* tab) { + if (!tab) { + return; + } + TabChanged(tab->GetContents()); + ListChanged(SpaceOf(tab)); + BoundChanged(tab); +} + +void ClairSpaceTabs::KeepSplitsTogether(std::vector& list) { + // add-split-view D7: each split whose tabs are both in the list is one row: + // the leading pane and its Peek, then the trailing pane and its, at the + // place of the pane listed first, as a new tab joins the top of the list + // before Chromium makes it a split. + std::set done; + bool moved = true; + while (moved) { + moved = false; + for (const tabs::TabHandle& handle : list) { + tabs::TabInterface* tab = handle.Get(); + tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); + if (!partner || done.contains(handle) || + std::ranges::find(list, partner->GetHandle()) == list.end()) { + continue; + } + done.insert(handle); + done.insert(partner->GetHandle()); + tabs::TabInterface* lead = ClairSplits::IsLeading(tab) ? tab : partner; + tabs::TabInterface* trail = lead == tab ? partner : tab; + SpaceTag* lead_tag = GetTag(lead->GetContents()); + SpaceTag* trail_tag = GetTag(trail->GetContents()); + tabs::TabInterface* anchor = + lead_tag && trail_tag && trail_tag->listed && + (!lead_tag->listed || trail_tag->listed < lead_tag->listed) + ? trail + : lead; + std::vector block; + for (tabs::TabInterface* pane : {lead, trail}) { + for (tabs::TabInterface* member : FamilyOf(pane)) { + if (std::ranges::find(list, member->GetHandle()) != list.end()) { + block.push_back(member->GetHandle()); + } + } + } + const size_t anchor_at = static_cast( + std::ranges::find(list, anchor->GetHandle()) - list.begin()); + size_t before = 0; + for (size_t i = 0; i < anchor_at; ++i) { + if (std::ranges::find(block, list[i]) != block.end()) { + ++before; + } + } + std::vector rest; + for (const tabs::TabHandle& other : list) { + if (std::ranges::find(block, other) == block.end()) { + rest.push_back(other); + } + } + rest.insert(rest.begin() + (anchor_at - before), block.begin(), + block.end()); + if (rest != list) { + list = std::move(rest); + moved = true; + break; + } + } + } +} + void ClairSpaceTabs::PostFlush() { if (flush_posted_) { return; @@ -1597,6 +1819,7 @@ void BeforeUnloadFired(bool proceed) override { std::erase_if(list->second, [](const tabs::TabHandle& handle) { return !handle.Get(); }); + KeepSplitsTogether(list->second); } if (is_regular()) { WriteSessionTags(space); @@ -1896,9 +2119,11 @@ void Flush() { pending_.clear(); for (const PinContainer& container : pending) { if (container.is_favorites()) { - NSArray>* pins = PinSnapshots(container); + // add-split-view D10: favorites and favorited splits. + NSArray>* items = + FavoriteItemSnapshots(container.profile); for (id observer in Observers().allObjects) { - [observer favoritesDidChange:pins + [observer favoritesDidChange:items ofProfile:base::SysUTF8ToNSString(container.profile)]; } continue; @@ -2139,7 +2364,9 @@ void SwapGroupsShowing(const std::string& space) { // add-profiles D9: reopens each of `rows`, in order, as a tab of `space` in // its window group's member for the Space's profile, from `first_rank` on, // and closes the originals. In a window that showed one of them, the tab -// reopened from it becomes active, and the group shows its member. +// reopened from it becomes active, and the group shows its member. Two rows +// that were a split's panes are a split again, with its ratio +// (add-split-view D7). void ReopenInProfile(std::vector rows, const std::string& space, int first_rank) { @@ -2153,6 +2380,24 @@ void ReopenInProfile(std::vector rows, if (!loaded || !ClairSpaceStore::Get()->Contains(space)) { return; } + struct SplitPanes { + tabs::TabHandle lead; + tabs::TabHandle trail; + double ratio; + }; + std::vector splits; + for (const tabs::TabHandle& handle : rows) { + tabs::TabInterface* partner = ClairSplits::PartnerOf(handle.Get()); + if (partner && ClairSplits::IsLeading(handle.Get()) && + std::ranges::find(rows, partner->GetHandle()) != rows.end()) { + splits.push_back({handle, partner->GetHandle(), + ClairSplits::RatioOf(handle.Get())}); + } + } + // Each row's reopened tab. The profile is loaded, so each member + // comes at once and this is complete after the loop. + auto reopened_of = base::MakeRefCounted< + base::RefCountedData>>(); const std::string profile = ClairProfiles::IDOf(loaded); int rank = first_rank; for (const tabs::TabHandle& handle : rows) { @@ -2184,6 +2429,9 @@ void ReopenInProfile(std::vector rows, int rank, bool shown, std::string previous, std::string pin, std::string name, base::WeakPtr holder, + scoped_refptr>> + reopened_of, ClairBrowserWindow* member) { if (!member) { return; @@ -2200,6 +2448,9 @@ void ReopenInProfile(std::vector rows, } tabs::TabInterface* reopened = OpenTabInSpace( member, url, space, rank, pin, name); + if (reopened) { + reopened_of->data[handle] = reopened->GetHandle(); + } if (shown && reopened) { ClairWindowGroup* group = ClairWindowGroup::Of(member); @@ -2219,7 +2470,25 @@ void ReopenInProfile(std::vector rows, CloseReopened(handle); }, handle, url, space, this_rank, shown, previous, pin, - name, holder->GetWeakPtr())); + name, holder->GetWeakPtr(), reopened_of)); + } + for (const SplitPanes& split : splits) { + auto lead = reopened_of->data.find(split.lead); + auto trail = reopened_of->data.find(split.trail); + if (lead == reopened_of->data.end() || + trail == reopened_of->data.end()) { + continue; + } + tabs::TabInterface* lead_tab = lead->second.Get(); + tabs::TabInterface* trail_tab = trail->second.Get(); + ClairBrowserWindow* window = + ClairBrowserWindow::HolderOf(lead_tab); + if (lead_tab && trail_tab && window && window->splits() && + window == ClairBrowserWindow::HolderOf(trail_tab)) { + window->splits()->Make(lead_tab, trail_tab, + /*other_leading=*/false, split.ratio, + /*focus=*/nullptr); + } } }, std::move(rows), space, first_rank)); @@ -2284,10 +2553,21 @@ void MoveTabToSpace(tabs::TabInterface* tab, const std::string& space) { std::numeric_limits::max()); return; } + // add-split-view D7: a Today split moves whole, the other pane after this + // one; a pinned tab's or favorite's pane stays with its pin, and the split + // ends. + tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); + const bool whole_split = partner && lists->PinOf(partner).empty() && + lists->SpaceOf(partner) == lists->SpaceOf(tab); // add-profiles D9: a page can't change profile; it reopens at the top of - // the other Space, in its profile. + // the other Space, in its profile, a Today split as a split. if (store->ProfileOf(space) != ClairProfiles::IDOf(lists->profile())) { - ReopenInProfile({tab->GetHandle()}, space, /*first_rank=*/0); + std::vector rows{tab->GetHandle()}; + if (whole_split) { + rows = {ClairSplits::PanesOf(tab)[0]->GetHandle(), + ClairSplits::PanesOf(tab)[1]->GetHandle()}; + } + ReopenInProfile(std::move(rows), space, /*first_rank=*/0); return; } // Another window with a still of it picks its next tab, as if the tab had @@ -2298,7 +2578,16 @@ void MoveTabToSpace(tabs::TabInterface* tab, const std::string& space) { } } const bool follows = window && window->IsActiveRow(tab); + if (partner && !whole_split) { + if (window && window->splits()) { + window->splits()->Separate(tab); + } + partner = nullptr; + } lists->SetSpace(tab, space); + if (partner) { + lists->SetSpace(partner, space); + } // The window follows its active tab, which stays active (D9, replacing // add-spaces D7's next-tab choice). if (follows) { @@ -2380,29 +2669,58 @@ void SetSpaceProfile(const std::string& space, const std::string& profile) { return pins; } -NSArray>* PinnedItemSnapshots(const std::string& space) { +namespace { + +// A container's items as snapshots, in order: its pins and splits, and in a +// Space's section its folders (add-tab-folders D2, add-split-view D10). +NSArray>* ItemSnapshots(const PinContainer& container) { NSMutableArray>* items = [NSMutableArray array]; ClairPinStore* store = ClairPinStore::Get(); // `id` is Objective-C's type here, so the child's ID is `child`. - for (const std::string& child : - store->ChildrenOf(PinContainer::OfSpace(space))) { + for (const std::string& child : store->ChildrenOf(container)) { if (const Pin* pin = store->Find(child)) { [items addObject:[[ClairChromiumPinnedItem alloc] initWithPin:PinSnapshotOf(*pin) + split:nil folder:nil]]; - } else if (const Folder* folder = store->FindFolder(child)) { - NSArray>* pins = - PinSnapshots(PinContainer::OfFolder(space, folder->id)); + } else if (const PinnedSplit* split = store->FindSplit(child)) { + NSMutableArray>* pins = [NSMutableArray array]; + for (const Pin* pane : store->PinsOfSplit(child)) { + [pins addObject:PinSnapshotOf(*pane)]; + } [items addObject:[[ClairChromiumPinnedItem alloc] initWithPin:nil - folder:[[ClairChromiumFolder alloc] - initWithFolder:*folder - pins:pins]]]; + split:[[ClairChromiumPinnedSplit alloc] + initWithSplit:*split + pins:pins] + folder:nil]]; + } else if (const Folder* folder = store->FindFolder(child); + folder && !container.is_folder()) { + [items + addObject:[[ClairChromiumPinnedItem alloc] + initWithPin:nil + split:nil + folder:[[ClairChromiumFolder alloc] + initWithFolder:*folder + items:ItemSnapshots( + PinContainer::OfFolder( + folder->space, + folder->id))]]]; } } return items; } +} // namespace + +NSArray>* PinnedItemSnapshots(const std::string& space) { + return ItemSnapshots(PinContainer::OfSpace(space)); +} + +NSArray>* FavoriteItemSnapshots(const std::string& profile) { + return ItemSnapshots(PinContainer::OfProfile(profile)); +} + void PinsChanged(const PinContainer& container) { if (container.space.empty() && container.profile.empty()) { return; @@ -2431,12 +2749,58 @@ void PinTab(tabs::TabInterface* tab, } // add-tab-folders D2: into a folder of its Space; the store refuses one of // another Space. - lists->PinTab(tab, - favorite ? PinContainer::OfProfile( - ClairProfiles::IDOf(lists->profile())) - : folder.empty() ? PinContainer::OfSpace(space) - : PinContainer::OfFolder(space, folder), - index); + const PinContainer container = + favorite ? PinContainer::OfProfile(ClairProfiles::IDOf(lists->profile())) + : folder.empty() ? PinContainer::OfSpace(space) + : PinContainer::OfFolder(space, folder); + // add-split-view D10: a split of two Today tabs is pinned as one; a split + // with a pinned tab or favorite isn't. + if (tabs::TabInterface* partner = ClairSplits::PartnerOf(tab)) { + if (!lists->PinOf(partner).empty() || lists->SpaceOf(partner) != space) { + return; + } + tabs::TabInterface* lead = ClairSplits::IsLeading(tab) ? tab : partner; + lists->PinSplit(lead, lead == tab ? partner : tab, container, index); + return; + } + lists->PinTab(tab, container, index); +} + +void JoinPinnedSplit(const std::string& pin) { + ClairPinStore* store = ClairPinStore::Get(); + const Pin* record = store->Find(pin); + const PinnedSplit* split = record ? store->FindSplit(record->split) : nullptr; + const std::vector panes = + split ? store->PinsOfSplit(split->id) : std::vector(); + if (panes.size() != 2) { + return; + } + tabs::TabInterface* lead = BoundTabOf(panes[0]->id); + tabs::TabInterface* trail = BoundTabOf(panes[1]->id); + ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(lead); + if (!lead || !trail || !holder || holder != ClairBrowserWindow::HolderOf(trail) || + !holder->splits() || ClairSplits::PartnerOf(lead) == trail || + lead->IsSplit() || trail->IsSplit()) { + return; + } + holder->splits()->Make(lead, trail, /*other_leading=*/false, split->ratio, + /*focus=*/nullptr); +} + +void SeparatePinnedSplit(const std::string& split) { + ClairPinStore* store = ClairPinStore::Get(); + const std::vector panes = store->PinsOfSplit(split); + if (panes.size() != 2) { + return; + } + tabs::TabInterface* lead = BoundTabOf(panes[0]->id); + tabs::TabInterface* trail = BoundTabOf(panes[1]->id); + store->SeparateSplit(split); + if (lead && ClairSplits::PartnerOf(lead) == trail) { + if (ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(lead)) { + holder->splits()->Separate(lead); + } + } } namespace { @@ -2482,13 +2846,25 @@ void MovePin(const std::string& pin, const PinContainer& to, size_t index) { return; } const std::string old_profile = store->ProfileOf(*record); - tabs::TabInterface* bound = BoundTabOf(pin); - const tabs::TabHandle handle = - bound ? bound->GetHandle() : tabs::TabHandle::Null(); + // add-split-view D10: a pinned split's pins move together. + std::vector> moved; + std::vector ids = {pin}; + if (!record->split.empty()) { + ids.clear(); + for (const Pin* pane : store->PinsOfSplit(record->split)) { + ids.push_back(pane->id); + } + } + for (const std::string& id : ids) { + tabs::TabInterface* bound = BoundTabOf(id); + moved.emplace_back(id, bound ? bound->GetHandle() : tabs::TabHandle::Null()); + } if (!store->Move(pin, to, index)) { return; } - BoundTabMoved(handle, pin, old_profile); + for (const auto& [id, handle] : moved) { + BoundTabMoved(handle, id, old_profile); + } } // --- Folders (add-tab-folders D6 to D8, D11) --- @@ -2605,15 +2981,37 @@ void RemovePin(const std::string& pin) { if (!store->Find(pin)) { return; } - tabs::TabInterface* bound = BoundTabOf(pin); - const tabs::TabHandle handle = - bound ? bound->GetHandle() : tabs::TabHandle::Null(); + // add-split-view D10: a pinned split's pins go together, with their tabs. + std::vector handles; + const Pin* record = store->Find(pin); + std::vector ids = {pin}; + if (!record->split.empty()) { + ids.clear(); + for (const Pin* pane : store->PinsOfSplit(record->split)) { + ids.push_back(pane->id); + } + } + for (const std::string& id : ids) { + if (tabs::TabInterface* bound = BoundTabOf(id)) { + handles.push_back(bound->GetHandle()); + } + } // D3: removed before its tab closes, so the tab's own entry in the // recently closed list is the newer, and brings the pin back with it. store->Remove(pin, /*remember=*/true); - tabs::TabInterface* tab = handle.Get(); - if (ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab)) { - holder->CloseTab(tab); + if (handles.size() == 2 && + ClairSplits::PartnerOf(handles[0].Get()) == handles[1].Get()) { + if (ClairBrowserWindow* holder = + ClairBrowserWindow::HolderOf(handles[0].Get())) { + holder->CloseSplit(handles[0].Get()); + } + return; + } + for (const tabs::TabHandle& handle : handles) { + tabs::TabInterface* tab = handle.Get(); + if (ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab)) { + holder->CloseTab(tab); + } } } @@ -2691,6 +3089,25 @@ void OpenPin(ClairBrowserWindow* window, const std::string& pin) { store->ProfileOf(*record) != ClairProfiles::IDOf(lists->profile())) { return; } + // add-split-view D10: a pinned split opens each page that isn't open, and + // shows both as a split with its ratio. + if (const PinnedSplit* split = store->FindSplit(record->split)) { + std::vector panes; + for (const Pin* pane : store->PinsOfSplit(split->id)) { + tabs::TabInterface* tab = lists->BoundTab(pane->id); + if (!tab) { + tab = OpenTabInSpace(window, pane->url, std::string(), -1, pane->id, + std::string()); + } + if (tab) { + panes.push_back(tab->GetHandle()); + } + } + if (panes.size() == 2) { + window->ShowPinnedSplit(panes[0].Get(), panes[1].Get(), split->ratio); + } + return; + } // D2: one tab per pin. if (tabs::TabInterface* bound = lists->BoundTab(pin)) { window->ActivateRow(bound); @@ -2722,6 +3139,58 @@ void Unpin(ClairBrowserWindow* window, const std::string& pin, int index) { if (!ClairSpaceStore::Get()->Contains(space)) { return; } + // add-split-view D10: a pinned split becomes a Today split, its pages + // opening when they aren't. + if (const PinnedSplit* split = store->FindSplit(record->split)) { + const double ratio = split->ratio; + std::vector panes; + std::vector pins = store->PinsOfSplit(split->id); + // A page that isn't open opens in the window of the one that is, so the + // two can be a split. + ClairBrowserWindow* home = window; + for (const Pin* pane : pins) { + if (ClairBrowserWindow* holder = + ClairBrowserWindow::HolderOf(lists->BoundTab(pane->id))) { + home = holder; + break; + } + } + for (size_t i = 0; i < pins.size(); ++i) { + // The bridge may pass INT_MAX for the end. + const int at = static_cast(std::min( + int64_t{index} + static_cast(i), + std::numeric_limits::max())); + tabs::TabInterface* tab = lists->BoundTab(pins[i]->id); + if (tab) { + lists->UnbindToToday(tab, space, at); + } else { + tab = OpenTabInSpace(home, pins[i]->url, space, at, std::string(), + pins[i]->name); + } + if (tab) { + panes.push_back(tab->GetHandle()); + } + } + store->Remove(pin, /*remember=*/false); + tabs::TabInterface* lead = panes.size() == 2 ? panes[0].Get() : nullptr; + tabs::TabInterface* trail = panes.size() == 2 ? panes[1].Get() : nullptr; + ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(lead); + // Both pages open in two windows come together in this one. + if (lead && trail && holder != ClairBrowserWindow::HolderOf(trail) && + ClairSplits::PartnerOf(lead) != trail) { + window->ShowPinnedSplit(lead, trail, ratio); + return; + } + if (lead && trail && holder && ClairSplits::PartnerOf(lead) != trail && + !lead->IsSplit() && !trail->IsSplit()) { + holder->splits()->Make(lead, trail, /*other_leading=*/false, ratio, + /*focus=*/nullptr); + } + if (holder && lead && holder->IsActiveRow(lead)) { + holder->FollowActiveTab(); + } + return; + } if (tabs::TabInterface* bound = lists->BoundTab(pin)) { lists->UnbindToToday(bound, space, index); store->Remove(pin, /*remember=*/false); @@ -2857,7 +3326,10 @@ bool LeavesFavorite(ClairBrowserWindow* window, const GURL& url) { ClairSpaceTabs* lists = window ? window->space_tabs() : nullptr; tabs::TabInterface* active = window ? window->browser()->tab_strip_model()->GetActiveTab() : nullptr; + // add-split-view: a favorited split's pane loads it in place, as Arc's + // does. return lists && active && lists->IsFavoriteTab(active) && + !active->IsSplit() && IsOtherSite(url, active->GetContents()->GetLastCommittedURL()); } diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm index 2db6fad..0c31dad 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm @@ -22,6 +22,7 @@ #import "chrome/browser/clair/window/clair_autocomplete.h" #import "chrome/browser/clair/window/clair_bookmarks.h" #import "chrome/browser/clair/window/clair_native_window.h" +#include "chrome/browser/clair/window/clair_splits.h" #include "chrome/browser/clair/window/clair_browser_window.h" #include "chrome/browser/clair/window/clair_downloads.h" #include "chrome/browser/clair/window/clair_extensions.h" @@ -773,6 +774,73 @@ - (void)expandPeekOfTab:(ClairTabID)tabID { } } +- (void)openPeekInSplitOfTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self rowTabWithID:tabID]) { + _browserWindow->OpenPeekInSplit(tab); + } +} + +// --- ClairBrowser: split view (add-split-view D2) --- + +- (void)splitTab:(ClairTabID)tabID + withTab:(ClairTabID)otherID + side:(ClairSplitSide)side { + tabs::TabInterface* tab = [self rowTabWithID:tabID]; + tabs::TabInterface* other = [self rowTabWithID:otherID]; + if (tab && other) { + _browserWindow->SplitTabs(tab, other, + /*other_leading=*/side == ClairSplitSideLeading); + } +} + +- (void)splitTabWithNewTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self rowTabWithID:tabID]) { + _browserWindow->SplitWithNewTab(tab); + } +} + +- (void)showSplitOfTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self rowTabWithID:tabID]) { + _browserWindow->ShowSplit(tab); + } +} + +- (void)replacePaneOfTab:(ClairTabID)tabID withTab:(ClairTabID)newTabID { + tabs::TabInterface* pane = [self tabWithID:tabID]; + tabs::TabInterface* replacement = [self rowTabWithID:newTabID]; + if (pane && replacement) { + _browserWindow->ReplacePane(pane, replacement); + } +} + +- (void)swapSplitOfTab:(ClairTabID)tabID { + tabs::TabInterface* tab = [self rowTabWithID:tabID]; + ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab); + if (holder && holder->splits()) { + holder->splits()->Swap(tab); + } +} + +- (void)separateSplitOfTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self rowTabWithID:tabID]) { + _browserWindow->SeparateSplit(tab); + } +} + +- (void)closeSplitOfTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self rowTabWithID:tabID]) { + _browserWindow->CloseSplit(tab); + } +} + +- (void)setSplitRatio:(double)ratio ofTab:(ClairTabID)tabID { + tabs::TabInterface* tab = [self rowTabWithID:tabID]; + ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab); + if (holder && holder->splits()) { + holder->splits()->SetRatio(tab, ratio); + } +} + // --- ClairBrowser: navigation --- - (void)runCommand:(int)command { diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.h b/engine/overlay/chrome/browser/clair/window/clair_browser_window.h index f61ca0d..e7f28f0 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.h +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.h @@ -53,6 +53,7 @@ class SkBitmap; class ClairExtensions; class ClairPeeks; class ClairSpaceTabs; +class ClairSplits; class GURL; namespace autofill { @@ -247,12 +248,18 @@ class ClairStatusBubble : public StatusBubble { void Hide() override; void MouseMoved(bool left_content) override; + // add-split-view D13a: the link under the pointer in `source`, a page the + // window shows, which may be a split's other pane. + void SetURL(const GURL& url, content::WebContents* source); + private: void Update(); const raw_ptr window_; std::u16string status_; std::u16string url_; + // The ClairTabID of the page the link is in, or -1 for the active one. + int64_t url_tab_ = -1; }; // share-tabs-across-windows D1, D2: how a window takes a tab another window @@ -313,6 +320,8 @@ class ClairBrowserWindow : public BrowserWindow { ClairDownloads* downloads() const { return downloads_.get(); } // The window's Peeks (add-peek design D1); null once the window is going. ClairPeeks* peeks() const { return peeks_.get(); } + // The window's splits (add-split-view design D1); null once it's going. + ClairSplits* splits() const { return splits_.get(); } // The tab lists of the window's profile (add-spaces design D2). ClairSpaceTabs* space_tabs() const { return space_tabs_; } @@ -381,6 +390,38 @@ class ClairBrowserWindow : public BrowserWindow { // with the command bar when it's empty. void OpenInShownSpace(const GURL& url); + // --- Split view (add-split-view design D2, D8, D10 to D12) --- + // The pages shown while `active` is the active tab: it, its Peek or + // parent (add-peek D4), and its split's other pane (D5). + std::set PagesShownWith( + content::WebContents* active) const; + // Makes a split of `tab` and `other` here, `other` leading when + // `other_leading` and focused, taking either from another window first. + void SplitTabs(tabs::TabInterface* tab, + tabs::TabInterface* other, + bool other_leading); + // A new tab page as the trailing, focused pane of `tab`'s split, here. + void SplitWithNewTab(tabs::TabInterface* tab); + // Shows `tab`'s split with the pane focused last, taking it from another + // window if need be. + void ShowSplit(tabs::TabInterface* tab); + // D8: `replacement` takes `pane`'s place, focused. + void ReplacePane(tabs::TabInterface* pane, tabs::TabInterface* replacement); + // Separate Tabs, of a pinned or favorited split too (D10). + void SeparateSplit(tabs::TabInterface* tab); + // Closes both panes, each with its leave-page confirmation, first showing + // the next row when the split is the active row. A pinned split keeps its + // pins (Close and Keep Pinned). + void CloseSplit(tabs::TabInterface* tab); + // D10: shows a pinned or favorited split's open tabs as a split with + // `ratio`, taking them from other windows if need be. + void ShowPinnedSplit(tabs::TabInterface* lead, + tabs::TabInterface* trail, + double ratio); + // D11: the Peek of `tab` becomes the trailing, focused pane of a split + // with its parent. + void OpenPeekInSplit(tabs::TabInterface* tab); + // --- Window groups (add-profiles D3 to D6, D8, D13) --- // Whether the window is a member its group has ordered out. bool IsHiddenMember() const; @@ -479,8 +520,9 @@ class ClairBrowserWindow : public BrowserWindow { // The active tab's docked DevTools changed (D5). void UpdateDevTools(); - // The link under the pointer, or an empty URL to hide the status (D8). - void SetStatusURL(const GURL& url); + // The link under the pointer in `source`, a page the window shows, or an + // empty URL to hide the status (D8, add-split-view D13a). + void SetStatusURL(const GURL& url, content::WebContents* source); // Shows a toast in the card (D8). void ShowToast(const std::u16string& text); @@ -666,10 +708,11 @@ class ClairBrowserWindow : public BrowserWindow { // D2: ends the still, closing the placeholder unless it became a tab. void EndStill(); tabs::TabInterface* placeholder() const; - // The pages the card shows while `active` is the active tab: it and its - // Peek or parent (add-peek D4). - std::set PagesShownWith( - content::WebContents* active) const; + // Brings `tab` here with its row, as a take does, then runs `then`. + void BringHere(tabs::TabInterface* tab, base::OnceClosure then); + // Closes the tabs named by `handles` together, each with its leave-page + // confirmation; a split's two make one entry in the recently closed list. + void CloseTabsNow(std::vector handles); const raw_ptr browser_; ClairNativeWindow* __strong ns_window_ = nil; @@ -683,6 +726,7 @@ class ClairBrowserWindow : public BrowserWindow { std::unique_ptr extensions_; std::unique_ptr downloads_; std::unique_ptr peeks_; + std::unique_ptr splits_; // Owned by the profile. raw_ptr space_tabs_ = nullptr; // add-spaces D3: the Space the window shows, and the tab last active in @@ -711,6 +755,10 @@ class ClairBrowserWindow : public BrowserWindow { bool pending_close_for_another_window_ = false; // D4: the active row Clair is closing, while its page is asked; or null. tabs::TabHandle pending_close_; + // add-split-view D12: a pinned split's pane whose page is asked before it + // closes, and its pin, which leaves the split only once the page agrees. + tabs::TabHandle pending_split_close_; + std::string pending_split_pin_; // Owned by the browser's FindBarController once created. raw_ptr find_bar_ = nullptr; base::CallbackListSubscription zoom_subscription_; diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm index 83dc34b..425de71 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm @@ -58,6 +58,7 @@ #include "chrome/browser/ui/browser_window/public/browser_window_features.h" #include "chrome/browser/ui/browser_window/public/browser_window_interface_iterator.h" #include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/clair/window/clair_splits.h" #include "chrome/browser/ui/browser_window_state.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_bubble.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.h" @@ -772,21 +773,40 @@ NSRect ToNSRect(const gfx::Rect& rect) { void ClairStatusBubble::SetURL(const GURL& url) { url_ = url.is_empty() ? std::u16string() : base::UTF8ToUTF16(url.spec()); + url_tab_ = -1; + Update(); +} + +void ClairStatusBubble::SetURL(const GURL& url, content::WebContents* source) { + url_ = url.is_empty() ? std::u16string() : base::UTF8ToUTF16(url.spec()); + url_tab_ = source ? clair::TabIDOf(source) : -1; Update(); } void ClairStatusBubble::Hide() { status_.clear(); url_.clear(); + url_tab_ = -1; Update(); } void ClairStatusBubble::MouseMoved(bool left_content) {} void ClairStatusBubble::Update() { + const bool is_link = status_.empty() && !url_.empty(); const std::u16string& text = status_.empty() ? url_ : status_; + // add-split-view D13a: the page the text is for, which places the capsule + // in its pane. + content::WebContents* active = + window_->browser()->tab_strip_model()->GetActiveWebContents(); + const ClairTabID tab = + is_link && url_tab_ >= 0 + ? static_cast(url_tab_) + : (active ? clair::TabIDOf(active) : ClairTabIDNone); [window_->clair_window() - statusTextDidChange:text.empty() ? nil : base::SysUTF16ToNSString(text)]; + statusTextDidChange:text.empty() ? nil : base::SysUTF16ToNSString(text) + isLink:is_link + tab:tab]; } // --- ClairBrowserWindow ------------------------------------------------------ @@ -832,6 +852,8 @@ NSRect ToNSRect(const gfx::Rect& rect) { downloads_ = std::make_unique(this); // After the bridge, so the bridge hears of tab strip changes first. peeks_ = std::make_unique(this); + // add-split-view D1: after the Peeks, whose placing it relies on. + splits_ = std::make_unique(this); clair::ApplyPasswordAndAutofillOverrides(browser->GetProfile()); // D2: ClairUI returns a window for every browser. A nil window is a bug that @@ -864,6 +886,7 @@ NSRect ToNSRect(const gfx::Rect& rect) { ClairBrowserWindow::~ClairBrowserWindow() { ClairWindowGroup::Leave(this); browser_->GetFeatures().TearDownPreBrowserWindowDestruction(); + splits_.reset(); peeks_.reset(); if (space_tabs_) { space_tabs_->RemoveBrowser(this); @@ -920,11 +943,21 @@ NSRect ToNSRect(const gfx::Rect& rect) { std::set ClairBrowserWindow::PagesShownWith( content::WebContents* active) const { - if (peeks_) { - return peeks_->PagesShownWith(active); + std::set pages = + peeks_ ? peeks_->PagesShownWith(active) + : active ? std::set{active} + : std::set(); + // add-split-view D5: the split's other pane, beside the active one or the + // parent of its Peek. + tabs::TabInterface* tab = + active ? tabs::TabInterface::MaybeGetFromContents(active) : nullptr; + if (tabs::TabInterface* parent = tab && peeks_ ? peeks_->ParentOf(tab) : nullptr) { + tab = parent; } - return active ? std::set{active} - : std::set(); + if (tabs::TabInterface* partner = ClairSplits::PartnerOf(tab)) { + pages.insert(partner->GetContents()); + } + return pages; } // --- Spaces (add-spaces D3, D4, D5) --- @@ -972,12 +1005,25 @@ void PostTakeBack(base::WeakPtr window) { namespace { -// The row `tab` shows in: its parent if it's a Peek, in whichever window. +// The row `tab` shows in: its parent if it's a Peek, in whichever window; +// for a split's pane, the split's row (add-split-view D2): its pane listed in +// Today, or its leading pane when both are pinned tabs' or favorites'. tabs::TabInterface* RowOf(tabs::TabInterface* tab) { ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab); ClairPeeks* peeks = holder ? holder->peeks() : nullptr; tabs::TabInterface* parent = peeks && tab ? peeks->ParentOf(tab) : nullptr; - return parent ? parent : tab; + tabs::TabInterface* row = parent ? parent : tab; + const std::vector panes = ClairSplits::PanesOf(row); + if (panes.empty()) { + return row; + } + ClairSpaceTabs* lists = holder ? holder->space_tabs() : nullptr; + for (tabs::TabInterface* pane : panes) { + if (lists && lists->PinOf(pane).empty() && !lists->SpaceOf(pane).empty()) { + return pane; + } + } + return panes.front(); } // share-tabs-across-windows D2: `row` stopped showing in its window. If no @@ -1048,6 +1094,13 @@ void GiveBackToStill(tabs::TabHandle handle) { pins.push_back(pin); continue; } + // add-split-view D10: a pinned split's two, in pane order. + if (store->FindSplit(id)) { + for (const clair::Pin* pane : store->PinsOfSplit(id)) { + pins.push_back(pane); + } + continue; + } const bool open = store->IsOpen(id); for (const clair::Pin* pin : store->PinsIn(clair::PinContainer::OfFolder(space, id))) { @@ -1065,7 +1118,9 @@ void GiveBackToStill(tabs::TabHandle handle) { // tabs aren't, except the highlighted one. std::vector rows; for (const clair::Pin* pin : RowPins(shown_space_)) { - if (tabs::TabInterface* tab = space_tabs_->BoundTab(pin->id)) { + // add-split-view: a pinned split's row is its leading pane's. + if (tabs::TabInterface* tab = space_tabs_->BoundTab(pin->id); + tab && RowOf(tab) == tab) { rows.push_back(tab); } } @@ -1087,7 +1142,10 @@ void GiveBackToStill(tabs::TabHandle handle) { if (!tab || !active) { return false; } - return active == tab || (peeks_ && peeks_->ParentOf(active) == tab); + tabs::TabInterface* shown = + peeks_ && peeks_->ParentOf(active) ? peeks_->ParentOf(active) : active; + // add-split-view D2: either pane of the shown split. + return active == tab || shown == tab || ClairSplits::PartnerOf(shown) == tab; } tabs::TabInterface* ClairBrowserWindow::HighlightedRow() const { @@ -1098,8 +1156,8 @@ void GiveBackToStill(tabs::TabHandle handle) { if (!active || ClairSpaceTabs::IsPlaceholder(active->GetContents())) { return nullptr; } - tabs::TabInterface* parent = peeks_ ? peeks_->ParentOf(active) : nullptr; - return parent ? parent : active; + // A Peek's parent's row, or a split's (add-split-view D2). + return RowOf(active); } bool ClairBrowserWindow::IsShownElsewhere(const tabs::TabInterface* row) const { @@ -1143,8 +1201,10 @@ void GiveBackToStill(tabs::TabHandle handle) { } ClairBrowserWindow* holder = HolderOf(row); ClairPeeks* peeks = holder ? holder->peeks() : nullptr; - tabs::TabInterface* peek = peeks ? peeks->PeekOf(row) : nullptr; - ActivateTab(peek ? peek : row, std::move(options)); + // add-split-view: a split shows with the pane focused last. + tabs::TabInterface* pane = ClairSplits::LastFocusedPane(row); + tabs::TabInterface* peek = peeks ? peeks->PeekOf(pane) : nullptr; + ActivateTab(peek ? peek : pane, std::move(options)); } void ClairBrowserWindow::ChooseRow(tabs::TabInterface* row, @@ -1216,7 +1276,10 @@ void GiveBackToStill(tabs::TabHandle handle) { } bool ClairBrowserWindow::IsEmptiedSpacePage(tabs::TabInterface* row) const { - if (!row || !space_tabs_ || !space_tabs_->is_regular() || RowOf(row) != row) { + // add-split-view: a split of new tab pages isn't the emptied Space's page; + // closing it leaves one. + if (!row || !space_tabs_ || !space_tabs_->is_regular() || RowOf(row) != row || + ClairSplits::PartnerOf(row)) { return false; } const std::vector rows = Rows(); @@ -1254,6 +1317,36 @@ void GiveBackToStill(tabs::TabHandle handle) { holder->CloseTab(tab); return; } + // add-split-view D12: a pane of the shown split closes alone, and the other + // pane shows by itself in the split's place. A pane of a pinned or + // favorited split takes its pin out of the split, as in Arc (D10), which + // Restore Last Closed Tab brings back. + if (tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); + partner && IsActiveRow(tab)) { + clair::ClairPinStore* store = clair::ClairPinStore::Get(); + const clair::Pin* pin = + space_tabs_ ? store->Find(space_tabs_->PinOf(tab)) : nullptr; + const clair::Pin* other = + space_tabs_ ? store->Find(space_tabs_->PinOf(partner)) : nullptr; + if (pin && other && !pin->split.empty() && pin->split == other->split) { + // A page that asks before leaving may stay, and its pin with it. + if (tab->GetContents()->NeedToFireBeforeUnloadOrUnloadEvents()) { + pending_split_close_ = tab->GetHandle(); + pending_split_pin_ = pin->id; + } else { + store->TakeOutOfSplit(pin->id); + } + } + if (browser_->tab_strip_model()->GetActiveTab() == tab || + (peeks_ && peeks_->ParentOf(browser_->tab_strip_model()->GetActiveTab()) == + tab)) { + ClairTakeOptions options; + options.choosing = true; + ActivateTab(partner, std::move(options)); + } + CloseTabNow(tab->GetHandle()); + return; + } // D4: Clair picks the next tab first; without one in the Space, a new tab // page takes its place (add-profiles D13). if (IsActiveRow(tab)) { @@ -1312,6 +1405,14 @@ void GiveBackToStill(tabs::TabHandle handle) { } } tabs::TabInterface* tab = tabs::TabInterface::MaybeGetFromContents(contents); + if (tab && tab->GetHandle() == pending_split_close_) { + pending_split_close_ = tabs::TabHandle::Null(); + if (proceed) { + clair::ClairPinStore::Get()->TakeOutOfSplit(pending_split_pin_); + } + pending_split_pin_.clear(); + return; + } if (!tab || tab->GetHandle() != pending_close_) { return; } @@ -1335,8 +1436,16 @@ void GiveBackToStill(tabs::TabHandle handle) { // the Space's rows in every window (share-tabs-across-windows D3). ClairBrowserWindow* holder = HolderOf(tab); ClairPeeks* peeks = holder ? holder->peeks() : nullptr; - tabs::TabInterface* last = peeks ? peeks->LastOfFamily(tab) : tab; - const std::string space = space_tabs_->SpaceOf(tab); + // add-split-view: a split is one row, which shows where its Today pane is + // listed when its other pane is a pinned tab or favorite. Neither pane is + // below it. + tabs::TabInterface* row = RowOf(tab); + std::vector panes = ClairSplits::PanesOf(row); + if (panes.empty()) { + panes = {row}; + } + const bool row_pinned = !space_tabs_->PinOf(row).empty(); + const std::string space = space_tabs_->SpaceOf(row); // add-pinned-tabs-and-favorites D4: from a pinned tab, the open pinned tabs // below it and every Today tab; from a Today tab, the Today tabs below it. std::vector tabs; @@ -1353,16 +1462,32 @@ void GiveBackToStill(tabs::TabHandle handle) { } else { tabs = space_tabs_->TabsIn(space, browser_); } - auto it = std::ranges::find(tabs, last); - if (it == tabs.end()) { - it = std::ranges::find(tabs, tab); + std::vector own; + auto cutoff = tabs.end(); + for (tabs::TabInterface* pane : panes) { + own.push_back(pane); + tabs::TabInterface* last = peeks ? peeks->LastOfFamily(pane) : pane; + if (last != pane) { + own.push_back(last); + } + if (space_tabs_->PinOf(pane).empty() == !row_pinned) { + auto at = std::ranges::find(tabs, last); + if (at == tabs.end()) { + at = std::ranges::find(tabs, pane); + } + if (at != tabs.end() && (cutoff == tabs.end() || at > cutoff)) { + cutoff = at; + } + } } - if (it == tabs.end()) { + if (cutoff == tabs.end()) { return; } std::vector below; - for (++it; it != tabs.end(); ++it) { - below.push_back((*it)->GetHandle()); + for (auto it = cutoff + 1; it != tabs.end(); ++it) { + if (std::ranges::find(own, *it) == own.end()) { + below.push_back((*it)->GetHandle()); + } } for (const tabs::TabHandle& handle : below) { CloseTab(handle.Get()); @@ -1393,6 +1518,225 @@ void GiveBackToStill(tabs::TabHandle handle) { Navigate(¶ms); } +// --- Split view (add-split-view D2, D8, D10 to D12) --- + +void ClairBrowserWindow::BringHere(tabs::TabInterface* tab, + base::OnceClosure then) { + if (!tab) { + return; + } + if (HolderOf(tab) == this) { + std::move(then).Run(); + return; + } + // share-tabs-across-windows D1: taken at once, its row with it; the other + // window keeps a still if it showed it. + ClairTakeOptions options; + options.wait_for_copy = false; + options.then = std::move(then); + Take(tab, std::move(options)); +} + +void ClairBrowserWindow::SplitTabs(tabs::TabInterface* tab, + tabs::TabInterface* other, + bool other_leading) { + if (!tab || !other || tab == other || !splits_) { + return; + } + base::OnceClosure make = base::BindOnce( + [](base::WeakPtr window, tabs::TabHandle first, + tabs::TabHandle second, bool second_leading) { + tabs::TabInterface* a = first.Get(); + tabs::TabInterface* b = second.Get(); + if (window && a && b && HolderOf(a) == window.get() && + HolderOf(b) == window.get()) { + window->splits()->Make(a, b, second_leading, 0.5, b); + } + }, + weak_factory_.GetWeakPtr(), tab->GetHandle(), other->GetHandle(), + other_leading); + base::OnceClosure bring_other = base::BindOnce( + [](base::WeakPtr window, tabs::TabHandle handle, + base::OnceClosure then) { + if (window && handle.Get()) { + window->BringHere(handle.Get(), std::move(then)); + } + }, + weak_factory_.GetWeakPtr(), other->GetHandle(), std::move(make)); + BringHere(tab, std::move(bring_other)); +} + +void ClairBrowserWindow::SplitWithNewTab(tabs::TabInterface* tab) { + if (!tab || !splits_) { + return; + } + BringHere(tab, base::BindOnce( + [](base::WeakPtr window, + tabs::TabHandle handle) { + if (window && handle.Get()) { + window->splits()->MakeWithNewTab(handle.Get()); + } + }, + weak_factory_.GetWeakPtr(), tab->GetHandle())); +} + +void ClairBrowserWindow::ShowSplit(tabs::TabInterface* tab) { + if (tab) { + ActivateRow(RowOf(tab)); + } +} + +void ClairBrowserWindow::ReplacePane(tabs::TabInterface* pane, + tabs::TabInterface* replacement) { + if (!pane || !replacement || !splits_ || HolderOf(pane) != this) { + return; + } + BringHere(replacement, + base::BindOnce( + [](base::WeakPtr window, + tabs::TabHandle pane, tabs::TabHandle replacement) { + if (window && pane.Get() && replacement.Get()) { + window->splits()->Replace(pane.Get(), replacement.Get()); + } + }, + weak_factory_.GetWeakPtr(), pane->GetHandle(), + replacement->GetHandle())); +} + +void ClairBrowserWindow::SeparateSplit(tabs::TabInterface* tab) { + tabs::TabInterface* partner = ClairSplits::PartnerOf(tab); + ClairBrowserWindow* holder = HolderOf(tab); + if (!partner || !holder || !holder->splits()) { + return; + } + // D10: a pinned or favorited split's pins take its place. + clair::ClairPinStore* store = clair::ClairPinStore::Get(); + const clair::Pin* pin = + space_tabs_ ? store->Find(space_tabs_->PinOf(tab)) : nullptr; + const clair::Pin* other = + space_tabs_ ? store->Find(space_tabs_->PinOf(partner)) : nullptr; + if (pin && other && !pin->split.empty() && pin->split == other->split) { + clair::SeparatePinnedSplit(pin->split); + return; + } + holder->splits()->Separate(tab); +} + +void ClairBrowserWindow::CloseTabsNow(std::vector handles) { + TabStripModel* strip = browser_->tab_strip_model(); + strip->ExecuteCloseTabsCommand( + base::BindRepeating( + [](TabStripModel* strip, std::vector handles) { + std::vector tabs_to_close; + for (const tabs::TabHandle& handle : handles) { + tabs::TabInterface* tab = handle.Get(); + if (tab && strip->GetIndexOfTab(tab) != TabStripModel::kNoTab) { + tabs_to_close.push_back(tab); + } + } + return tabs_to_close; + }, + base::Unretained(strip), std::move(handles)), + /*delete_groups=*/false); +} + +void ClairBrowserWindow::CloseSplit(tabs::TabInterface* tab) { + const std::vector panes = ClairSplits::PanesOf(tab); + if (panes.empty()) { + CloseTab(tab); + return; + } + // In whichever window holds it, which picks its own next tab. + if (ClairBrowserWindow* holder = HolderOf(tab); holder && holder != this) { + base::AutoReset elsewhere(&holder->closing_for_another_window_, true); + holder->CloseSplit(tab); + return; + } + std::vector handles; + for (tabs::TabInterface* pane : panes) { + handles.push_back(pane->GetHandle()); + } + tabs::TabInterface* row = RowOf(tab); + if (IsActiveRow(row)) { + // D4: the next row first; without one, a new tab page. + base::OnceClosure close = + base::BindOnce(&ClairBrowserWindow::CloseTabsNow, + weak_factory_.GetWeakPtr(), handles); + if (!ShowNextRow(row, &close) && KeepEmptiedSpace(row)) { + return; + } + if (close) { + std::move(close).Run(); + } + return; + } + CloseTabsNow(std::move(handles)); +} + +void ClairBrowserWindow::ShowPinnedSplit(tabs::TabInterface* lead, + tabs::TabInterface* trail, + double ratio) { + if (!lead || !trail || !splits_) { + return; + } + base::OnceClosure show = base::BindOnce( + [](base::WeakPtr window, tabs::TabHandle lead, + tabs::TabHandle trail, double ratio) { + tabs::TabInterface* a = lead.Get(); + tabs::TabInterface* b = trail.Get(); + if (!window || !a || !b || HolderOf(a) != window.get() || + HolderOf(b) != window.get()) { + return; + } + if (ClairSplits::PartnerOf(a) != b) { + // A pane in another split, as when a Today tab replaced its + // partner, leaves it first, keeping both pages. + for (tabs::TabInterface* pane : {a, b}) { + if (pane->IsSplit()) { + window->splits()->Separate(pane); + } + } + if (!window->splits()->Make(a, b, /*other_leading=*/false, ratio, + /*focus=*/nullptr)) { + return; + } + } + window->ActivateRow(a); + }, + weak_factory_.GetWeakPtr(), lead->GetHandle(), trail->GetHandle(), + ratio); + // Its tabs come here first, apart; a split already open moves whole. + if (ClairSplits::PartnerOf(lead) == trail) { + BringHere(lead, std::move(show)); + return; + } + base::OnceClosure bring_trail = base::BindOnce( + [](base::WeakPtr window, tabs::TabHandle handle, + base::OnceClosure then) { + if (window && handle.Get()) { + window->BringHere(handle.Get(), std::move(then)); + } + }, + weak_factory_.GetWeakPtr(), trail->GetHandle(), std::move(show)); + BringHere(lead, std::move(bring_trail)); +} + +void ClairBrowserWindow::OpenPeekInSplit(tabs::TabInterface* tab) { + ClairBrowserWindow* holder = HolderOf(tab); + ClairPeeks* peeks = holder ? holder->peeks() : nullptr; + if (!peeks || !holder->splits()) { + return; + } + tabs::TabInterface* parent = peeks->ParentOf(tab) ? peeks->ParentOf(tab) : tab; + tabs::TabInterface* peek = peeks->PeekOf(parent); + // D11: not while the parent is in a split, which holds two tabs. + if (!peek || ClairSplits::PartnerOf(parent)) { + return; + } + peeks->Expand(parent); + holder->splits()->Make(parent, peek, /*other_leading=*/false, 0.5, peek); +} + // --- Window groups (add-profiles D3 to D6, D8, D13) --- bool ClairBrowserWindow::IsHiddenMember() const { @@ -1707,7 +2051,12 @@ void GiveBackToStill(tabs::TabHandle handle) { std::string pin; }; std::vector slots; + std::set split_slots; for (const clair::Pin* pin : RowPins(shown_space_)) { + // add-split-view: a pinned split is one row. + if (!pin->split.empty() && !split_slots.insert(pin->split).second) { + continue; + } slots.push_back({space_tabs_->BoundTab(pin->id), pin->id}); } for (tabs::TabInterface* row : TodayRows()) { @@ -1736,7 +2085,9 @@ void GiveBackToStill(tabs::TabHandle handle) { return true; } auto it = std::ranges::find_if(slots, [&](const Slot& slot) { - return slot.tab && slot.tab == active_row; + return slot.tab && active_row && + (slot.tab == active_row || + ClairSplits::PartnerOf(slot.tab) == active_row); }); const bool forward = command == IDC_SELECT_NEXT_TAB || command == IDC_CYCLE_TO_NEXT_TAB; @@ -1817,8 +2168,9 @@ void GiveBackToStill(tabs::TabHandle handle) { others.push_back(row->GetHandle()); } } + // add-split-view: a split row closes both its panes. for (const tabs::TabHandle& handle : others) { - CloseTab(handle.Get()); + CloseSplit(handle.Get()); } return true; } @@ -2018,6 +2370,50 @@ void GiveBackToStill(tabs::TabHandle handle) { } TabStripModel* source = from->browser()->tab_strip_model(); TabStripModel* target = browser_->tab_strip_model(); + // add-split-view D7: a split moves whole, as one collection, with its + // panes' Peeks. + if (const std::vector panes = ClairSplits::PanesOf(row); + !panes.empty() && source->GetIndexOfTab(row) != TabStripModel::kNoTab) { + std::vector> peeks; + for (tabs::TabInterface* pane : panes) { + if (tabs::TabInterface* peek = + from->peeks() ? from->peeks()->Release(pane) : nullptr) { + peeks.emplace_back(pane, peek); + } + } + std::vector moving(panes.begin(), panes.end()); + for (const auto& [pane, peek] : peeks) { + moving.push_back(peek); + } + for (tabs::TabInterface* member : moving) { + space_tabs_->BeginMove(member); + } + std::unique_ptr split = + source->DetachSplitTabForInsertion(*row->GetSplit()); + std::vector> peek_models; + for (const auto& [pane, peek] : peeks) { + const int index = source->GetIndexOfTab(peek); + if (index != TabStripModel::kNoTab) { + peek_models.push_back(source->DetachTabAtForInsertion(index)); + } + } + target->InsertDetachedSplitTabAt(std::move(split), target->count(), + /*pinned=*/false); + for (std::unique_ptr& model : peek_models) { + target->InsertDetachedTabAt(target->count(), std::move(model), + AddTabTypes::ADD_NONE); + } + for (tabs::TabInterface* member : moving) { + space_tabs_->EndMove(member); + } + for (const auto& [pane, peek] : peeks) { + if (peeks_ && target->GetIndexOfTab(pane) != TabStripModel::kNoTab && + target->GetIndexOfTab(peek) != TabStripModel::kNoTab) { + peeks_->Adopt(pane, peek); + } + } + return; + } // The pair leaves the Peek table there before the strip hears of it. tabs::TabInterface* peek = from->peeks() ? from->peeks()->Release(row) : nullptr; std::vector family{row}; @@ -2146,15 +2542,15 @@ void GiveBackToStill(tabs::TabHandle handle) { // row last so Chromium picks this window's next tab only once. TabStripModel* strip = browser_->tab_strip_model(); tabs::TabInterface* active = strip->GetActiveTab(); - tabs::TabInterface* active_row = - active && peeks_ && peeks_->ParentOf(active) ? peeks_->ParentOf(active) - : active; + tabs::TabInterface* active_row = active ? RowOf(active) : nullptr; std::vector rows; for (int i = 0; i < strip->count(); ++i) { tabs::TabInterface* tab = strip->GetTabAtIndex(i); + // A Peek, and a split's pane that isn't its row, move with their row + // (add-split-view D7). if (!tab || tab == active_row || tab == except || ClairSpaceTabs::IsPlaceholder(tab->GetContents()) || - (peeks_ && peeks_->ParentOf(tab))) { + RowOf(tab) != tab) { continue; } rows.push_back(tab->GetHandle()); @@ -2619,8 +3015,9 @@ void GiveBackToStill(tabs::TabHandle handle) { return {}; } -void ClairBrowserWindow::SetStatusURL(const GURL& url) { - status_bubble_.SetURL(url); +void ClairBrowserWindow::SetStatusURL(const GURL& url, + content::WebContents* source) { + status_bubble_.SetURL(url, source); } void ClairBrowserWindow::UpdateTitleBar() { @@ -2694,12 +3091,9 @@ void GiveBackToStill(tabs::TabHandle handle) { } else if (choosing_next_ || old_closed) { came_from_ = tabs::TabHandle::Null(); } else if (new_tab) { - tabs::TabInterface* row = - peeks_ && peeks_->ParentOf(old_tab) ? peeks_->ParentOf(old_tab) - : old_tab; - const bool same_family = - row == new_tab || (peeks_ && peeks_->ParentOf(new_tab) == row); - if (!same_family) { + // A tab and its Peek, or a split's panes (add-split-view), are one row. + tabs::TabInterface* row = RowOf(old_tab); + if (RowOf(new_tab) != row) { came_from_ = row->GetHandle(); } } diff --git a/engine/overlay/chrome/browser/clair/window/clair_peeks.h b/engine/overlay/chrome/browser/clair/window/clair_peeks.h index 9330aca..7c8c0cb 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_peeks.h +++ b/engine/overlay/chrome/browser/clair/window/clair_peeks.h @@ -108,6 +108,10 @@ class ClairPeeks : public TabStripModelObserver { // The tab Close Tabs Below counts from: `tab`'s Peek, if it has one. tabs::TabInterface* LastOfFamily(tabs::TabInterface* tab) const; + // add-split-view: a split was made, changed or ended; each Peek goes back + // to its place. + void SplitsChanged(); + // D7: runs a tab command for the active Peek. Returns whether it ran; // otherwise the window runs it over its rows (add-spaces D5), or Chromium // as usual. @@ -177,6 +181,13 @@ class ClairPeeks : public TabStripModelObserver { // Moves the tab at `from` to `to` without unlinking anything. void MoveQuietly(int from, int to); + // Where `parent`'s Peek belongs in the strip: right after it, or, for a + // split's pane, after the split, the leading pane's Peek first + // (add-split-view D3), since a tab inside a split would end it. + int PeekIndexFor(const tabs::TabInterface* parent) const; + // Where a new Peek of `parent` is inserted: after the tabs and Peeks of its + // row. + int InsertIndexFor(const tabs::TabInterface* parent) const; // After the tab strip changes: puts each Peek back right after its parent, // closes the Peeks whose parent has gone, and activates the parent of a // Peek that closed while it was active. diff --git a/engine/overlay/chrome/browser/clair/window/clair_peeks.mm b/engine/overlay/chrome/browser/clair/window/clair_peeks.mm index 154db40..c263e38 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_peeks.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_peeks.mm @@ -17,6 +17,7 @@ #import "chrome/browser/clair/window/clair_browser_bridge.h" #include "chrome/browser/clair/window/clair_browser_window.h" #include "chrome/browser/clair/window/clair_peek_session.h" +#include "chrome/browser/clair/window/clair_splits.h" #import "chrome/browser/clair/clair_space_tabs.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -238,8 +239,14 @@ void Unwatch() { model_ ? strip()->GetIndexOfTab(parent) : TabStripModel::kNoTab; const int peek_index = model_ ? strip()->GetIndexOfTab(peek) : TabStripModel::kNoTab; - if (parent_index == TabStripModel::kNoTab || - peek_index != parent_index + 1 || FindByParent(parent) != pairs_.end() || + // add-split-view: a split's pane's Peek lands after the split and any + // Peek of its other pane; Repair then orders them. + const bool in_place = + peek_index == parent_index + 1 || + (!ClairSplits::PanesOf(parent).empty() && + peek_index > parent_index && peek_index <= InsertIndexFor(parent)); + if (parent_index == TabStripModel::kNoTab || !in_place || + FindByParent(parent) != pairs_.end() || FindByPeek(parent) != pairs_.end() || FindByPeek(peek) != pairs_.end()) { ActivateTab(peek); return; @@ -360,7 +367,7 @@ void Unwatch() { // A new Peek, inserted in the background right after its parent and linked // before it becomes active, so ClairUI never sees it as a tab of its own. nav_params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; - nav_params.tabstrip_index = strip()->GetIndexOfTab(source_tab) + 1; + nav_params.tabstrip_index = InsertIndexFor(source_tab); nav_params.tabstrip_add_types = AddTabTypes::ADD_FORCE_INDEX | AddTabTypes::ADD_INHERIT_OPENER; nav_params.window_action = NavigateParams::WindowAction::kNoAction; @@ -409,7 +416,7 @@ void Unwatch() { return nav_params.navigated_or_inserted_contents; } nav_params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; - nav_params.tabstrip_index = strip()->GetIndexOfTab(source_tab) + 1; + nav_params.tabstrip_index = InsertIndexFor(source_tab); nav_params.tabstrip_add_types = AddTabTypes::ADD_FORCE_INDEX | AddTabTypes::ADD_INHERIT_OPENER; nav_params.window_action = NavigateParams::WindowAction::kNoAction; @@ -517,6 +524,41 @@ void Unwatch() { // --- Tab commands (D7, D8) --- +int ClairPeeks::PeekIndexFor(const tabs::TabInterface* parent) const { + const int parent_index = + model_ && parent ? strip()->GetIndexOfTab(parent) : TabStripModel::kNoTab; + const std::vector panes = ClairSplits::PanesOf(parent); + if (parent_index == TabStripModel::kNoTab || panes.empty()) { + return parent_index == TabStripModel::kNoTab ? parent_index + : parent_index + 1; + } + int index = strip()->GetIndexOfTab(panes.back()) + 1; + // The trailing pane's Peek follows the leading pane's. + if (parent == panes.back() && PeekOf(panes.front())) { + ++index; + } + return index; +} + +int ClairPeeks::InsertIndexFor(const tabs::TabInterface* parent) const { + const std::vector panes = ClairSplits::PanesOf(parent); + if (!model_ || !parent || panes.empty()) { + return model_ && parent ? strip()->GetIndexOfTab(parent) + 1 + : TabStripModel::kNoTab; + } + int index = strip()->GetIndexOfTab(panes.back()) + 1; + for (tabs::TabInterface* pane : panes) { + if (PeekOf(pane)) { + ++index; + } + } + return index; +} + +void ClairPeeks::SplitsChanged() { + ScheduleRepair(); +} + void ClairPeeks::MoveQuietly(int from, int to) { if (from == TabStripModel::kNoTab || from == to) { return; @@ -809,6 +851,12 @@ void Unwatch() { for (const Pair& pair : pairs_) { pairs.emplace_back(pair.parent, pair.peek); } + // In their parents' order, so a split's leading pane's Peek is in place + // before the trailing pane's place after it is worked out. + std::ranges::stable_sort(pairs, {}, [this](const auto& pair) { + tabs::TabInterface* parent = pair.first.Get(); + return parent ? strip()->GetIndexOfTab(parent) : TabStripModel::kNoTab; + }); for (const auto& [parent_handle, peek_handle] : pairs) { tabs::TabInterface* parent = parent_handle.Get(); tabs::TabInterface* peek = peek_handle.Get(); @@ -817,12 +865,14 @@ void Unwatch() { } const int parent_index = strip()->GetIndexOfTab(parent); const int peek_index = strip()->GetIndexOfTab(peek); + // add-split-view: after a split's panes, not between them. + const int target = PeekIndexFor(parent); if (parent_index == TabStripModel::kNoTab || - peek_index == TabStripModel::kNoTab || peek_index == parent_index + 1) { + peek_index == TabStripModel::kNoTab || peek_index == target) { continue; } - MoveQuietly(peek_index, - peek_index < parent_index ? parent_index : parent_index + 1); + // Moving it from before its place takes it out from there first. + MoveQuietly(peek_index, peek_index < target ? target - 1 : target); } // Parents whose Peek left on their own, unless shown. std::vector to_hide = std::move(parents_to_hide_); diff --git a/engine/overlay/chrome/browser/clair/window/clair_splits.h b/engine/overlay/chrome/browser/clair/window/clair_splits.h new file mode 100644 index 0000000..9cf0ae1 --- /dev/null +++ b/engine/overlay/chrome/browser/clair/window/clair_splits.h @@ -0,0 +1,138 @@ +// Copyright 2026 The Clair Authors +// Use of this source code is governed by the GNU General Public License, +// version 3, found in the LICENSE file at the root of Clair's repository. + +#ifndef CHROME_BROWSER_CLAIR_WINDOW_CLAIR_SPLITS_H_ +#define CHROME_BROWSER_CLAIR_WINDOW_CLAIR_SPLITS_H_ + +#include +#include +#include +#include + +#include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/tabs/tab_strip_model_observer.h" +#include "components/split_tabs/split_tab_id.h" +#include "components/tabs/public/tab_interface.h" +#include "ui/base/window_open_disposition.h" + +class ClairBrowserWindow; +class GURL; +class TabStripModel; + +namespace content { +class NavigationHandle; +class WebContents; +struct OpenURLParams; +} // namespace content + +// One native window's split view (add-split-view design D1). A Clair split +// is a Chromium split of two adjacent tabs in the window's strip: its ID is +// the SplitTabId, its ratio the split's ratio, and its pane order the strip's +// order. The active tab is the focused pane. This makes, changes and ends +// splits, focuses the pane the user clicks in (D4), opens Option+clicked +// links (D6) and keeps a pinned split's ratio in its record (D10). +class ClairSplits : public TabStripModelObserver { + public: + explicit ClairSplits(ClairBrowserWindow* window); + ClairSplits(const ClairSplits&) = delete; + ClairSplits& operator=(const ClairSplits&) = delete; + ~ClairSplits() override; + + // --- Any tab of a native window --- + // The other tab of `tab`'s split, or null outside a split. + static tabs::TabInterface* PartnerOf(const tabs::TabInterface* tab); + // The split's two tabs, leading pane first; empty outside a split. + static std::vector PanesOf(const tabs::TabInterface* tab); + // Whether `tab` is a split's leading pane. + static bool IsLeading(const tabs::TabInterface* tab); + // The leading pane's share of the width; 0.5 outside a split. + static double RatioOf(const tabs::TabInterface* tab); + // The pane of `tab`'s split the user looked at last, or `tab` outside a + // split (spec "Selecting the split row"). + static tabs::TabInterface* LastFocusedPane(tabs::TabInterface* tab); + + // --- This window's tabs --- + // D2: makes a split of `tab` and `other`, `other` leading when + // `other_leading`, with `ratio`. `focus`, one of them or null, becomes + // active. Both must be in this window's strip, and neither a Peek or in a + // split. Returns whether it made the split. + bool Make(tabs::TabInterface* tab, + tabs::TabInterface* other, + bool other_leading, + double ratio, + tabs::TabInterface* focus); + // D2, D13b: a new tab page as the trailing, focused pane of `tab`'s split. + void MakeWithNewTab(tabs::TabInterface* tab); + // D8: `replacement` takes `pane`'s place in its split, focused; `pane` + // leaves the split with its page. + void Replace(tabs::TabInterface* pane, tabs::TabInterface* replacement); + // Move Left and Move Right: swaps the panes, the focused one staying + // focused. + void Swap(tabs::TabInterface* tab); + // Separate Tabs: ends `tab`'s split, both tabs keeping their pages, and + // shows the focused pane's tab alone. + void Separate(tabs::TabInterface* tab); + void SetRatio(tabs::TabInterface* tab, double ratio); + + // D6: a link Option+clicked in `source`, a page of this window, which + // reached the browser as NEW_SPLIT_VIEW: in a Peek it loads there, as a + // plain click; in a split's pane it loads in the other pane, as a new + // navigation, and focuses it; otherwise it opens in a new tab beside the + // page, the trailing, focused pane of a split with it. Returns false when + // `source` isn't this window's. + bool OpenLink(content::WebContents* source, + const content::OpenURLParams& params, + base::OnceCallback& + navigation_handle_callback, + content::WebContents** result); + // The same for a link with a target, whose contents Chromium made first; + // they go when the link loads in the other pane or the Peek, and become the + // new pane otherwise. + bool OpenLink(content::WebContents* source, + std::unique_ptr& new_contents, + const GURL& target_url, + content::WebContents** result); + + // TabStripModelObserver: + void OnTabStripModelChanged(TabStripModel* model, + const TabStripModelChange& change, + const TabStripSelectionChange& selection) override; + void OnSplitTabChanged(const SplitTabChange& change) override; + void OnTabStripModelDestroyed(TabStripModel* model) override; + + private: + class FocusWatcher; + + TabStripModel* strip() const { return model_; } + int IndexOf(const tabs::TabInterface* tab) const; + // D6: the page `contents` a link opened beside `source` becomes the + // trailing, focused pane of a split with it. + void SplitWithNewPage(tabs::TabInterface* source, + content::WebContents* contents); + // D4: a pane's page took keyboard focus, as from a click in it. + void PaneFocused(content::WebContents* contents); + void Watch(tabs::TabInterface* tab); + void Unwatch(const tabs::TabInterface* tab); + // D6: a split Chromium made puts the tab that was active, the one the link + // was clicked in, in the leading pane. + void LeadWith(split_tabs::SplitTabId split, tabs::TabHandle leading); + // D5: both panes of the shown split are visible, and a page leaving it + // isn't unless the window shows it otherwise. + void UpdateVisibility(const std::vector& panes); + // D10: a pinned or favorited split's ratio follows its open tabs'. + void KeepPinnedRatio(split_tabs::SplitTabId split); + void Changed(const std::vector& panes); + void ActivateTab(tabs::TabInterface* tab); + + const raw_ptr window_; + raw_ptr model_; + std::map> watchers_; + // While this changes splits itself. + bool changing_ = false; + base::WeakPtrFactory weak_factory_{this}; +}; + +#endif // CHROME_BROWSER_CLAIR_WINDOW_CLAIR_SPLITS_H_ diff --git a/engine/overlay/chrome/browser/clair/window/clair_splits.mm b/engine/overlay/chrome/browser/clair/window/clair_splits.mm new file mode 100644 index 0000000..870c844 --- /dev/null +++ b/engine/overlay/chrome/browser/clair/window/clair_splits.mm @@ -0,0 +1,680 @@ +// Copyright 2026 The Clair Authors +// Use of this source code is governed by the GNU General Public License, +// version 3, found in the LICENSE file at the root of Clair's repository. + +#include "chrome/browser/clair/window/clair_splits.h" + +#include +#include +#include +#include +#include + +#include "base/auto_reset.h" +#include "base/functional/bind.h" +#include "base/task/single_thread_task_runner.h" +#import "chrome/browser/clair/clair_pin_store.h" +#import "chrome/browser/clair/clair_space_tabs.h" +#include "chrome/browser/clair/window/clair_browser_window.h" +#include "chrome/browser/clair/window/clair_peeks.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sessions/session_restore.h" +#include "chrome/browser/sessions/tab_restore_service_factory.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_window/public/browser_window_interface.h" +#include "chrome/browser/ui/navigator/browser_navigator.h" +#include "chrome/browser/ui/navigator/browser_navigator_params.h" +#include "chrome/browser/ui/tabs/split_tab_metrics.h" +#include "chrome/browser/ui/tabs/tab_enums.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/tabs/tab_strip_user_gesture_details.h" +#include "chrome/common/webui_url_constants.h" +#include "components/sessions/core/tab_restore_service.h" +#include "components/split_tabs/split_tab_visual_data.h" +#include "components/tabs/public/split_tab_data.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/navigation_handle.h" +#include "content/public/browser/page_navigator.h" +#include "content/public/browser/visibility.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/common/referrer.h" +#include "ui/base/page_transition_types.h" +#include "url/gurl.h" + +namespace { + +// The strip of the native window holding `tab`, or null. +TabStripModel* StripOf(const tabs::TabInterface* tab) { + ClairBrowserWindow* holder = ClairBrowserWindow::HolderOf(tab); + return holder ? holder->browser()->tab_strip_model() : nullptr; +} + +// The ratio the divider allows (ClairHost.h, -setSplitRatio:ofTab:). +double ClampRatio(double ratio) { + return std::isfinite(ratio) ? std::clamp(ratio, 0.05, 0.95) : 0.5; +} + +split_tabs::SplitTabVisualData SideBySide(double ratio) { + return split_tabs::SplitTabVisualData(split_tabs::SplitTabLayout::kSideBySide, + ClampRatio(ratio)); +} + +} // namespace + +// D4: tells the splits when a pane's page takes keyboard focus, as when the +// user clicks in it, as Chromium's MultiContentsView does. +class ClairSplits::FocusWatcher : public content::WebContentsObserver { + public: + FocusWatcher(ClairSplits* owner, content::WebContents* contents) + : content::WebContentsObserver(contents), owner_(owner) {} + + void OnWebContentsFocused( + content::RenderWidgetHost* render_widget_host) override { + owner_->PaneFocused(web_contents()); + } + + private: + const raw_ptr owner_; +}; + +ClairSplits::ClairSplits(ClairBrowserWindow* window) + : window_(window), model_(window->browser()->tab_strip_model()) { + model_->AddObserver(this); + // A window that session restore filled before this existed watches its + // splits' panes. + for (const split_tabs::SplitTabId& split : model_->ListSplits()) { + for (tabs::TabInterface* tab : model_->GetSplitData(split)->ListTabs()) { + Watch(tab); + } + } +} + +ClairSplits::~ClairSplits() { + if (model_) { + model_->RemoveObserver(this); + } +} + +// --- Queries --- + +// static +std::vector ClairSplits::PanesOf( + const tabs::TabInterface* tab) { + TabStripModel* strip = StripOf(tab); + if (!strip || !tab->IsSplit()) { + return {}; + } + const std::optional split = tab->GetSplit(); + if (!split || !strip->ContainsSplit(*split)) { + return {}; + } + std::vector panes = + strip->GetSplitData(*split)->ListTabs(); + return panes.size() == 2 ? panes : std::vector(); +} + +// static +tabs::TabInterface* ClairSplits::PartnerOf(const tabs::TabInterface* tab) { + for (tabs::TabInterface* pane : PanesOf(tab)) { + if (pane != tab) { + return pane; + } + } + return nullptr; +} + +// static +bool ClairSplits::IsLeading(const tabs::TabInterface* tab) { + const std::vector panes = PanesOf(tab); + return !panes.empty() && panes.front() == tab; +} + +// static +double ClairSplits::RatioOf(const tabs::TabInterface* tab) { + TabStripModel* strip = StripOf(tab); + if (!strip || PanesOf(tab).empty()) { + return 0.5; + } + return strip->GetSplitData(*tab->GetSplit())->visual_data()->split_ratio(); +} + +// static +tabs::TabInterface* ClairSplits::LastFocusedPane(tabs::TabInterface* tab) { + tabs::TabInterface* last = tab; + for (tabs::TabInterface* pane : PanesOf(tab)) { + if (pane->IsActivated()) { + return pane; + } + if (pane->GetLastActiveTime() > last->GetLastActiveTime()) { + last = pane; + } + } + return last; +} + +int ClairSplits::IndexOf(const tabs::TabInterface* tab) const { + return model_ && tab ? model_->GetIndexOfTab(tab) : TabStripModel::kNoTab; +} + +// --- Commands --- + +bool ClairSplits::Make(tabs::TabInterface* tab, + tabs::TabInterface* other, + bool other_leading, + double ratio, + tabs::TabInterface* focus) { + const int tab_index = IndexOf(tab); + const int other_index = IndexOf(other); + ClairPeeks* peeks = window_->peeks(); + if (tab_index == TabStripModel::kNoTab || + other_index == TabStripModel::kNoTab || tab == other || tab->IsSplit() || + other->IsSplit() || + (peeks && (peeks->ParentOf(tab) || peeks->ParentOf(other)))) { + return false; + } + std::vector panes; + { + base::AutoReset changing(&changing_, true); + const split_tabs::SplitTabId split = strip()->AddToNewSplit( + {tab_index, other_index}, SideBySide(ratio), + split_tabs::SplitTabCreatedSource::kTabContextMenu); + // AddToNewSplit keeps the strip's order; the leading pane is the one + // asked for. + tabs::TabInterface* leading = other_leading ? other : tab; + if (strip()->GetSplitData(split)->ListTabs().front() != leading) { + strip()->ReverseTabsInSplit(split); + } + panes = strip()->GetSplitData(split)->ListTabs(); + } + if (focus) { + ActivateTab(focus); + } + UpdateVisibility(panes); + Changed(panes); + return true; +} + +void ClairSplits::MakeWithNewTab(tabs::TabInterface* tab) { + const int index = IndexOf(tab); + ClairPeeks* peeks = window_->peeks(); + if (index == TabStripModel::kNoTab || tab->IsSplit() || + (peeks && peeks->ParentOf(tab))) { + return; + } + // A new tab page right after the tab, in the background until the split + // shows it. + NavigateParams params(window_->browser(), GURL(chrome::kChromeUINewTabURL), + ui::PAGE_TRANSITION_TYPED); + params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; + params.tabstrip_index = index + 1; + params.tabstrip_add_types = AddTabTypes::ADD_FORCE_INDEX; + params.window_action = NavigateParams::WindowAction::kNoAction; + Navigate(¶ms); + content::WebContents* contents = params.navigated_or_inserted_contents; + tabs::TabInterface* new_tab = + contents ? tabs::TabInterface::MaybeGetFromContents(contents) : nullptr; + if (!new_tab) { + return; + } + // Its row is the split's: after the tab's in Today, or at the top when the + // tab is a pinned tab's or a favorite's. + if (ClairSpaceTabs* lists = window_->space_tabs()) { + if (!lists->SpaceOf(tab).empty() && lists->PinOf(tab).empty()) { + lists->MoveTabBeside(new_tab, tab, /*after=*/true); + } + } + Make(tab, new_tab, /*other_leading=*/false, 0.5, new_tab); +} + +void ClairSplits::Replace(tabs::TabInterface* pane, + tabs::TabInterface* replacement) { + tabs::TabInterface* partner = PartnerOf(pane); + ClairPeeks* peeks = window_->peeks(); + if (!partner || !replacement || replacement == pane || + replacement == partner || replacement->IsSplit() || + IndexOf(replacement) == TabStripModel::kNoTab || + (peeks && peeks->ParentOf(replacement))) { + return; + } + const bool pane_leading = IsLeading(pane); + const split_tabs::SplitTabId split = *pane->GetSplit(); + const double ratio = RatioOf(pane); + std::vector panes; + { + base::AutoReset changing(&changing_, true); + // Chromium's kReplace closes the replaced tab; Clair keeps it, so the + // split ends and comes back, with its ID and ratio, around the other + // pane and the replacement. + strip()->RemoveSplit(split); + std::vector indices = {IndexOf(partner), IndexOf(replacement)}; + std::ranges::sort(indices); + strip()->RestoreSplit(split, indices, SideBySide(ratio)); + tabs::TabInterface* leading = pane_leading ? replacement : partner; + if (strip()->GetSplitData(split)->ListTabs().front() != leading) { + strip()->ReverseTabsInSplit(split); + } + panes = strip()->GetSplitData(split)->ListTabs(); + } + ActivateTab(replacement); + // D8: the replaced tab is the row right below the split's. + if (ClairSpaceTabs* lists = window_->space_tabs(); + lists && !lists->SpaceOf(pane).empty() && lists->PinOf(pane).empty()) { + tabs::TabInterface* anchor = panes.back(); + if (!lists->SpaceOf(anchor).empty() && lists->PinOf(anchor).empty()) { + lists->MoveTabBeside(pane, anchor, /*after=*/true); + } + } + panes.push_back(pane); + UpdateVisibility(panes); + Changed(panes); +} + +void ClairSplits::Swap(tabs::TabInterface* tab) { + const std::vector panes = PanesOf(tab); + if (panes.empty() || IndexOf(tab) == TabStripModel::kNoTab) { + return; + } + { + base::AutoReset changing(&changing_, true); + strip()->ReverseTabsInSplit(*tab->GetSplit()); + } + // D10: a pinned or favorited split's pins follow their panes. + if (ClairSpaceTabs* lists = window_->space_tabs()) { + clair::ClairPinStore* store = clair::ClairPinStore::Get(); + const clair::Pin* leading = store->Find(lists->PinOf(panes[0])); + const clair::Pin* trailing = store->Find(lists->PinOf(panes[1])); + if (leading && trailing && !leading->split.empty() && + leading->split == trailing->split) { + store->SwapSplitPanes(leading->split); + } + } + Changed(panes); +} + +void ClairSplits::Separate(tabs::TabInterface* tab) { + const std::vector panes = PanesOf(tab); + if (panes.empty() || IndexOf(tab) == TabStripModel::kNoTab) { + return; + } + { + base::AutoReset changing(&changing_, true); + strip()->RemoveSplit(*tab->GetSplit()); + } + UpdateVisibility(panes); + Changed(panes); +} + +void ClairSplits::SetRatio(tabs::TabInterface* tab, double ratio) { + if (PanesOf(tab).empty() || IndexOf(tab) == TabStripModel::kNoTab) { + return; + } + strip()->UpdateSplitRatio(*tab->GetSplit(), ClampRatio(ratio)); +} + +// --- Links (D6) --- + +bool ClairSplits::OpenLink(content::WebContents* source, + const content::OpenURLParams& params, + base::OnceCallback& + navigation_handle_callback, + content::WebContents** result) { + tabs::TabInterface* source_tab = + source ? tabs::TabInterface::MaybeGetFromContents(source) : nullptr; + if (IndexOf(source_tab) == TabStripModel::kNoTab) { + return false; + } + ClairPeeks* peeks = window_->peeks(); + content::WebContents* target = nullptr; + if (peeks && peeks->ParentOf(source_tab)) { + // In a Peek, Option+click is a plain click. + target = source; + } else if (tabs::TabInterface* partner = PartnerOf(source_tab)) { + // In a split, the link loads in the other pane, which Back returns from. + target = partner->GetContents(); + } else { + // A new tab right after the page, in the background, then the trailing, + // focused pane of a split with it. Its row keeps the page's place. + NavigateParams nav_params(window_->browser(), params.url, params.transition); + nav_params.FillNavigateParamsFromOpenURLParams(params); + nav_params.source_contents = source; + nav_params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; + nav_params.tabstrip_index = IndexOf(source_tab) + 1; + nav_params.tabstrip_add_types = + AddTabTypes::ADD_FORCE_INDEX | AddTabTypes::ADD_INHERIT_OPENER; + nav_params.window_action = NavigateParams::WindowAction::kNoAction; + base::WeakPtr handle = Navigate(&nav_params); + if (navigation_handle_callback && handle) { + std::move(navigation_handle_callback).Run(*handle); + } + *result = nav_params.navigated_or_inserted_contents; + SplitWithNewPage(source_tab, *result); + return true; + } + content::NavigationController::LoadURLParams load_params(params); + base::WeakPtr handle = + target->GetController().LoadURLWithParams(load_params); + if (navigation_handle_callback && handle) { + std::move(navigation_handle_callback).Run(*handle); + } + if (target != source) { + ActivateTab(tabs::TabInterface::MaybeGetFromContents(target)); + } + // The source, so WebContentsImpl::OpenURL() takes no new contents, as + // Chromium's own split-pane navigation returns. + *result = source; + return true; +} + +bool ClairSplits::OpenLink(content::WebContents* source, + std::unique_ptr& new_contents, + const GURL& target_url, + content::WebContents** result) { + tabs::TabInterface* source_tab = + source ? tabs::TabInterface::MaybeGetFromContents(source) : nullptr; + if (IndexOf(source_tab) == TabStripModel::kNoTab) { + return false; + } + ClairPeeks* peeks = window_->peeks(); + content::WebContents* target = nullptr; + if (peeks && peeks->ParentOf(source_tab)) { + target = source; + } else if (tabs::TabInterface* partner = PartnerOf(source_tab)) { + target = partner->GetContents(); + } else if (new_contents) { + // As for a link without a target: its contents, right after the page. + NavigateParams nav_params(window_->browser(), std::move(new_contents)); + nav_params.source_contents = source; + nav_params.url = target_url; + // Already past the popup blocker, as chrome::AddWebContents says. + nav_params.user_gesture = true; + nav_params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; + nav_params.tabstrip_index = IndexOf(source_tab) + 1; + nav_params.tabstrip_add_types = + AddTabTypes::ADD_FORCE_INDEX | AddTabTypes::ADD_INHERIT_OPENER; + nav_params.window_action = NavigateParams::WindowAction::kNoAction; + Navigate(&nav_params); + *result = nav_params.navigated_or_inserted_contents; + SplitWithNewPage(source_tab, *result); + return true; + } else { + return false; + } + if (target_url.is_valid()) { + target->GetController().LoadURL(target_url, content::Referrer(), + ui::PAGE_TRANSITION_LINK, std::string()); + } + if (target != source) { + ActivateTab(tabs::TabInterface::MaybeGetFromContents(target)); + } + *result = nullptr; + return true; +} + +void ClairSplits::SplitWithNewPage(tabs::TabInterface* source, + content::WebContents* contents) { + tabs::TabInterface* tab = + contents ? tabs::TabInterface::MaybeGetFromContents(contents) : nullptr; + if (!tab || IndexOf(tab) == TabStripModel::kNoTab) { + return; + } + // From a pinned tab or favorite, whose row isn't in Today, the split's row + // is the new tab's, at the top. + if (ClairSpaceTabs* lists = window_->space_tabs(); + lists && (!lists->PinOf(source).empty() || lists->SpaceOf(source).empty())) { + lists->MoveTab(tab, 0); + } + Make(source, tab, /*other_leading=*/false, 0.5, tab); +} + +// --- Focus and visibility (D4, D5) --- + +void ClairSplits::PaneFocused(content::WebContents* contents) { + tabs::TabInterface* tab = + contents ? tabs::TabInterface::MaybeGetFromContents(contents) : nullptr; + if (!tab || !tab->IsSplit() || tab->IsActivated() || + IndexOf(tab) == TabStripModel::kNoTab) { + return; + } + // Not from inside the page's focus notification, and not once the user + // has chosen another tab meanwhile. + tabs::TabInterface* active = model_->GetActiveTab(); + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, + base::BindOnce( + [](base::WeakPtr splits, tabs::TabHandle handle, + tabs::TabHandle was_active) { + tabs::TabInterface* pane = handle.Get(); + tabs::TabInterface* now_active = + splits ? splits->model_->GetActiveTab() : nullptr; + if (splits && pane && pane->IsSplit() && !pane->IsActivated() && + (now_active ? now_active->GetHandle() + : tabs::TabHandle::Null()) == was_active) { + splits->ActivateTab(pane); + } + }, + weak_factory_.GetWeakPtr(), tab->GetHandle(), + active ? active->GetHandle() : tabs::TabHandle::Null())); +} + +void ClairSplits::Watch(tabs::TabInterface* tab) { + if (!tab || watchers_.contains(tab->GetHandle())) { + return; + } + watchers_[tab->GetHandle()] = + std::make_unique(this, tab->GetContents()); +} + +void ClairSplits::Unwatch(const tabs::TabInterface* tab) { + if (tab) { + watchers_.erase(tab->GetHandle()); + } +} + +void ClairSplits::UpdateVisibility( + const std::vector& panes) { + content::WebContents* active = model_ ? model_->GetActiveWebContents() : nullptr; + if (!active) { + return; + } + const std::set shown = window_->PagesShownWith(active); + for (tabs::TabInterface* tab : panes) { + if (!tab || IndexOf(tab) == TabStripModel::kNoTab) { + continue; + } + content::WebContents* contents = tab->GetContents(); + contents->UpdateWebContentsVisibility( + shown.contains(contents) && window_->IsVisible() + ? content::Visibility::VISIBLE + : content::Visibility::HIDDEN); + } +} + +void ClairSplits::LeadWith(split_tabs::SplitTabId split, + tabs::TabHandle leading) { + tabs::TabInterface* tab = leading.Get(); + if (!model_ || !tab || !model_->ContainsSplit(split) || + tab->GetSplit() != split || IsLeading(tab)) { + return; + } + base::AutoReset changing(&changing_, true); + model_->ReverseTabsInSplit(split); + Changed(PanesOf(tab)); +} + +void ClairSplits::KeepPinnedRatio(split_tabs::SplitTabId split) { + ClairSpaceTabs* lists = window_->space_tabs(); + if (!lists || !model_ || !model_->ContainsSplit(split)) { + return; + } + const std::vector panes = + model_->GetSplitData(split)->ListTabs(); + if (panes.size() != 2) { + return; + } + clair::ClairPinStore* store = clair::ClairPinStore::Get(); + const clair::Pin* leading = store->Find(lists->PinOf(panes[0])); + const clair::Pin* trailing = store->Find(lists->PinOf(panes[1])); + if (leading && trailing && !leading->split.empty() && + leading->split == trailing->split) { + store->SetSplitRatio( + leading->split, + model_->GetSplitData(split)->visual_data()->split_ratio()); + } +} + +void ClairSplits::Changed(const std::vector& panes) { + if (ClairSpaceTabs* lists = window_->space_tabs()) { + for (tabs::TabInterface* tab : panes) { + if (tab) { + lists->SplitChanged(tab); + } + } + } +} + +void ClairSplits::ActivateTab(tabs::TabInterface* tab) { + const int index = IndexOf(tab); + if (index != TabStripModel::kNoTab) { + model_->ActivateTabAt(index, + TabStripUserGestureDetails( + TabStripUserGestureDetails::GestureType::kOther)); + } +} + +// --- TabStripModelObserver --- + +void ClairSplits::OnTabStripModelChanged( + TabStripModel* model, + const TabStripModelChange& change, + const TabStripSelectionChange& selection) { + if (change.type() == TabStripModelChange::kRemoved) { + for (const auto& removed : change.GetRemove()->contents) { + Unwatch(removed.tab); + } + } + // A pane whose page Chromium replaces keeps its handle; its new page is + // watched instead. + if (change.type() == TabStripModelChange::kReplaced) { + const TabStripModelChange::Replace* replace = change.GetReplace(); + if (replace->tab && watchers_.contains(replace->tab->GetHandle())) { + watchers_[replace->tab->GetHandle()] = + std::make_unique(this, replace->new_contents); + } + } + if (!selection.active_tab_changed() || !selection.old_tab || + !selection.new_tab) { + return; + } + // Arc: focusing the other pane closes the Peek open over a pane + // (arc-reference, "A Peek in a split"). + ClairPeeks* peeks = window_->peeks(); + tabs::TabInterface* parent = + peeks ? peeks->ParentOf(selection.old_tab.get()) : nullptr; + if (parent && PartnerOf(parent) == selection.new_tab.get()) { + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce( + [](base::WeakPtr window, + tabs::TabHandle peek) { + if (window && window->peeks() && peek.Get()) { + window->peeks()->Close(peek.Get()); + } + }, + window_->GetWeakPtr(), selection.old_tab->GetHandle())); + } +} + +void ClairSplits::OnSplitTabChanged(const SplitTabChange& change) { + if (change.model != model_) { + return; + } + std::vector changed; + switch (change.type) { + case SplitTabChange::Type::kAdded: { + const SplitTabChange::AddedChange* added = change.GetAddedChange(); + for (const auto& [tab, index] : added->tabs()) { + changed.push_back(tab); + Watch(tab); + } + // D6: a split Chromium made, from Option+click or the link's context + // menu, puts the page the link was clicked in, the active tab then, + // in the leading pane. Session restore, Reopen Closed Tab and Reopen + // Closed Window keep the order they saved. + tabs::TabInterface* active = model_->GetActiveTab(); + Profile* profile = window_->browser()->GetProfile(); + sessions::TabRestoreService* tab_restore = + TabRestoreServiceFactory::GetForProfile(profile); + if (!changing_ && + added->reason() == + SplitTabChange::SplitTabAddReason::kNewSplitTabAdded && + !SessionRestore::IsRestoring(profile) && + !(tab_restore && tab_restore->IsRestoring()) && + active && std::ranges::find(changed, active) != changed.end() && + changed.front() != active) { + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, + base::BindOnce(&ClairSplits::LeadWith, weak_factory_.GetWeakPtr(), + change.split_id, active->GetHandle())); + } + break; + } + case SplitTabChange::Type::kRemoved: + for (const auto& [tab, index] : change.GetRemovedChange()->tabs()) { + changed.push_back(tab); + Unwatch(tab); + } + break; + case SplitTabChange::Type::kContentsChanged: + for (const auto& [tab, index] : + change.GetContentsChange()->prev_tabs()) { + changed.push_back(tab); + Unwatch(tab); + } + for (const auto& [tab, index] : change.GetContentsChange()->new_tabs()) { + changed.push_back(tab); + Watch(tab); + } + break; + case SplitTabChange::Type::kVisualsChanged: + if (model_->ContainsSplit(change.split_id)) { + changed = model_->GetSplitData(change.split_id)->ListTabs(); + if (!change.GetVisualsChange()->is_intermediate()) { + KeepPinnedRatio(change.split_id); + } + } + break; + } + // Not from inside the strip's notification: its pages' visibility and the + // lists' pushes follow once it's done. + std::vector handles; + for (tabs::TabInterface* tab : changed) { + if (tab) { + handles.push_back(tab->GetHandle()); + } + } + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce( + [](base::WeakPtr splits, + std::vector handles) { + if (!splits) { + return; + } + std::vector panes; + for (const tabs::TabHandle& handle : handles) { + if (tabs::TabInterface* tab = handle.Get()) { + panes.push_back(tab); + } + } + splits->UpdateVisibility(panes); + splits->Changed(panes); + if (ClairPeeks* peeks = splits->window_->peeks()) { + peeks->SplitsChanged(); + } + }, + weak_factory_.GetWeakPtr(), std::move(handles))); +} + +void ClairSplits::OnTabStripModelDestroyed(TabStripModel* model) { + watchers_.clear(); + model_ = nullptr; +} diff --git a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.h b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.h index 2161135..d7ef8b5 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.h +++ b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.h @@ -100,17 +100,23 @@ bool ContentsMouseEvent(content::WebContents* source, bool exited); // browser_web_contents_delegate.cc, at the start of OpenURLFromTab and // AddNewContents: a link Shift+clicked in a native window's page opens in a // Peek of its tab (add-peek D2), or, from a Peek, in a new tab at the top. -// False when that doesn't apply, and Chromium goes on: another window, another -// disposition than NEW_WINDOW, no user gesture or not from the page (the -// context menu), or the preference off. True when it handled the link, with -// `*result` the contents it opened or navigated, or null. -bool MaybeOpenPeek(BrowserWindowInterface* browser, +// A link Option+clicked there (NEW_SPLIT_VIEW) loads in a Peek it was clicked +// in, or in the other pane of a split, or becomes the trailing pane of a new +// split with the page (add-split-view D6). +// False when that doesn't apply, and Chromium goes on: +// - Shift+click (NEW_WINDOW): another window, no user gesture, not from the +// page (the context menu), or the preference off. +// - Option+click (NEW_SPLIT_VIEW): another window, and for AddNewContents no +// user gesture. OpenURLFromTab takes it from the context menu too. +// True when it handled the link, with `*result` the contents it opened or +// navigated, or null. +bool MaybeOpenLink(BrowserWindowInterface* browser, content::WebContents* source, const content::OpenURLParams& params, base::OnceCallback& navigation_handle_callback, content::WebContents** result); -bool MaybeOpenPeek(BrowserWindowInterface* browser, +bool MaybeOpenLink(BrowserWindowInterface* browser, content::WebContents* source, std::unique_ptr& new_contents, const GURL& target_url, @@ -178,8 +184,9 @@ void RegisterLocalStatePrefs(PrefRegistrySimple* registry); bool IsInNativeWindow(gfx::NativeView view); // render_view_context_menu_mac_cocoa.mm: removes the context menu items of -// D9's unavailable features (split view, reading mode, QR code, send tab to -// self, Lens, translate) and the separators that leaves doubled or at an end. +// D9's unavailable features (reading mode, QR code, send tab to self, Lens, +// translate) and the separators that leaves doubled or at an end. Open Link in +// Split View stays (add-split-view D6). void RemoveUnavailableContextMenuItems(ui::SimpleMenuModel* model); // Not a hook: called once ClairUI has started. Applies D10's menu changes: diff --git a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm index 29cc382..a2c3e3a 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm @@ -24,6 +24,7 @@ #include "chrome/browser/clair/window/clair_browser_window.h" #import "chrome/browser/clair/window/clair_native_window.h" #include "chrome/browser/clair/window/clair_peeks.h" +#include "chrome/browser/clair/window/clair_splits.h" #include "chrome/browser/headless/headless_mode_util.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" @@ -105,7 +106,6 @@ bool IsInNativeWindow(gfx::NativeView view) { void RemoveUnavailableContextMenuItems(ui::SimpleMenuModel* model) { for (size_t i = model->GetItemCount(); i > 0; --i) { switch (model->GetCommandIdAt(i - 1)) { - case IDC_CONTENT_CONTEXT_OPENLINKSPLITVIEW: case IDC_CONTENT_CONTEXT_OPEN_IN_READING_MODE: case IDC_CONTENT_CONTEXT_LISTEN_TO_THIS_PAGE: case IDC_CONTENT_CONTEXT_GENERATE_QR_CODE: @@ -216,8 +216,12 @@ bool UpdateTargetURL(content::WebContents* source, const GURL& url) { if (!window) { return false; } - if (window->browser()->tab_strip_model()->GetActiveWebContents() == source) { - window->SetStatusURL(url); + // The active page's links, or a split's other pane's (add-split-view + // D13a). + content::WebContents* active = + window->browser()->tab_strip_model()->GetActiveWebContents(); + if (active && window->PagesShownWith(active).contains(source)) { + window->SetStatusURL(url, source); } return true; } @@ -228,7 +232,7 @@ bool ContentsMouseEvent(content::WebContents* source, bool exited) { return false; } if (exited) { - window->SetStatusURL(GURL()); + window->SetStatusURL(GURL(), source); } return true; } @@ -251,12 +255,37 @@ bool ContentsMouseEvent(content::WebContents* source, bool exited) { } // namespace -bool MaybeOpenPeek(BrowserWindowInterface* browser, +namespace { + +// The native window whose page `source` is, for a link Option+clicked in it +// (add-split-view D6). +ClairBrowserWindow* SplitWindowFor(BrowserWindowInterface* browser, + content::WebContents* source) { + ClairBrowserWindow* window = ClairBrowserWindow::FromBrowser(browser); + if (!window || !window->splits() || !source || + window->browser()->tab_strip_model()->GetIndexOfWebContents(source) == + TabStripModel::kNoTab) { + return nullptr; + } + return window; +} + +} // namespace + +bool MaybeOpenLink(BrowserWindowInterface* browser, content::WebContents* source, const content::OpenURLParams& params, base::OnceCallback& navigation_handle_callback, content::WebContents** result) { + // add-split-view D6: Option+click (split-on-option-click.patch). From a + // Peek or a split's pane it loads there or in the other pane; otherwise + // Chromium makes the split. + if (params.disposition == WindowOpenDisposition::NEW_SPLIT_VIEW) { + ClairBrowserWindow* window = SplitWindowFor(browser, source); + return window && window->splits()->OpenLink( + source, params, navigation_handle_callback, result); + } // Shift+click is NEW_WINDOW on macOS; the context menu's Open Link in New // Window isn't renderer-initiated, and window.open() without a click has // no user gesture. @@ -273,13 +302,18 @@ bool MaybeOpenPeek(BrowserWindowInterface* browser, return true; } -bool MaybeOpenPeek(BrowserWindowInterface* browser, +bool MaybeOpenLink(BrowserWindowInterface* browser, content::WebContents* source, std::unique_ptr& new_contents, const GURL& target_url, WindowOpenDisposition disposition, bool user_gesture, content::WebContents** result) { + if (disposition == WindowOpenDisposition::NEW_SPLIT_VIEW && user_gesture) { + ClairBrowserWindow* window = SplitWindowFor(browser, source); + return window && + window->splits()->OpenLink(source, new_contents, target_url, result); + } // A link with a target, such as target="_blank", creates its contents // first and arrives here. if (disposition != WindowOpenDisposition::NEW_WINDOW || !user_gesture || diff --git a/engine/patches/clair/native-window-hook.patch b/engine/patches/clair/native-window-hook.patch index 1169b16..e4e5ebb 100644 --- a/engine/patches/clair/native-window-hook.patch +++ b/engine/patches/clair/native-window-hook.patch @@ -280,35 +280,36 @@ #include "chrome/browser/background/background_contents_service_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/page_specific_content_settings_delegate.h" -@@ -541,6 +542,13 @@ +@@ -541,6 +542,14 @@ DCHECK(params.Valid()); #endif -+ // Clair: a link Shift+clicked in a native window opens in a Peek. -+ content::WebContents* clair_peek_result = nullptr; -+ if (clair::MaybeOpenPeek(&*browser_, source, params, -+ navigation_handle_callback, &clair_peek_result)) { -+ return clair_peek_result; ++ // Clair: a link Shift+clicked in a native window opens in a Peek, and one ++ // Option+clicked in a split. ++ content::WebContents* clair_link_result = nullptr; ++ if (clair::MaybeOpenLink(&*browser_, source, params, ++ navigation_handle_callback, &clair_link_result)) { ++ return clair_link_result; + } + if ((browser_->GetType() == BrowserWindowInterface::Type::TYPE_DEVTOOLS)) { DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source); DCHECK(window); -@@ -672,6 +680,13 @@ +@@ -672,6 +681,13 @@ const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) { + // Clair: a link with a target Shift+clicked in a native window opens in -+ // a Peek. -+ content::WebContents* clair_peek_result = nullptr; -+ if (clair::MaybeOpenPeek(&*browser_, source, new_contents, target_url, -+ disposition, user_gesture, &clair_peek_result)) { -+ return clair_peek_result; ++ // a Peek, and one Option+clicked in a split. ++ content::WebContents* clair_link_result = nullptr; ++ if (clair::MaybeOpenLink(&*browser_, source, new_contents, target_url, ++ disposition, user_gesture, &clair_link_result)) { ++ return clair_link_result; + } FullscreenController* fullscreen_controller = exclusive_access_manager_->fullscreen_controller(); #if BUILDFLAG(IS_MAC) -@@ -796,6 +811,10 @@ +@@ -796,6 +812,10 @@ void BrowserWebContentsDelegate::UpdateTargetURL(content::WebContents* source, const GURL& url) { @@ -319,7 +320,7 @@ std::vector status_bubbles = browser_ui_controller_->GetStatusBubbles(); for (StatusBubble* status_bubble : status_bubbles) { -@@ -822,6 +841,11 @@ +@@ -822,6 +842,11 @@ exclusive_access_manager_->OnUserInput(); } @@ -467,7 +468,7 @@ ":global_keyboard_shortcuts_mac", "//chrome/browser/apps/app_shim", "//chrome/browser/mac", -@@ -5257,6 +5258,73 @@ +@@ -5257,6 +5258,75 @@ # is easy to catch in review. sources = [] } @@ -524,6 +525,8 @@ + "clair/window/clair_pinned_link_throttle.mm", + "clair/window/clair_space_session.h", + "clair/window/clair_space_session.mm", ++ "clair/window/clair_splits.h", ++ "clair/window/clair_splits.mm", + "clair/window/clair_window_group.h", + "clair/window/clair_window_group.mm", + "clair/window/clair_window_hooks.h", diff --git a/engine/patches/clair/split-on-option-click.patch b/engine/patches/clair/split-on-option-click.patch new file mode 100644 index 0000000..29130d5 --- /dev/null +++ b/engine/patches/clair/split-on-option-click.patch @@ -0,0 +1,40 @@ +# Option+click on a link opens it in a split on macOS, as in Dia +# (add-split-view design D6), instead of downloading it. Chromium already maps +# Cmd+Option+click to split view; plain Option+click now does the same, in the +# renderer's click policy and in the browser's click disposition. The link +# then reaches the browser as WindowOpenDisposition::NEW_SPLIT_VIEW, which the +# native window handles (clair_window_hooks.mm). Option+click no longer +# downloads; Save Link As… in the context menu still does. + +--- a/ui/base/window_open_disposition_utils.cc ++++ b/ui/base/window_open_disposition_utils.cc +@@ -27,6 +27,13 @@ + if (split_view_modifier && alt_key && !shift_key) { + return WindowOpenDisposition::NEW_SPLIT_VIEW; + } ++#if BUILDFLAG(IS_MAC) ++ // Clair: Option+click opens a link in a split, as in Dia, instead of ++ // downloading it. ++ if (alt_key && !shift_key && !new_tab_modifier) { ++ return WindowOpenDisposition::NEW_SPLIT_VIEW; ++ } ++#endif + if (new_tab_modifier) { + return shift_key ? WindowOpenDisposition::NEW_FOREGROUND_TAB + : WindowOpenDisposition::NEW_BACKGROUND_TAB; +--- a/third_party/blink/renderer/core/loader/navigation_policy.cc ++++ b/third_party/blink/renderer/core/loader/navigation_policy.cc +@@ -61,6 +61,13 @@ + if (new_tab_modifier && alt && !shift) { + return kNavigationPolicySplitView; + } ++#if BUILDFLAG(IS_MAC) ++ // Clair: Option+click opens a link in a split, as in Dia, instead of ++ // downloading it. ++ if (alt && !shift && !new_tab_modifier) { ++ return kNavigationPolicySplitView; ++ } ++#endif + if (!new_tab_modifier && !shift && !alt) { + return kNavigationPolicyCurrentTab; + } else if (new_tab_modifier) { diff --git a/engine/patches/series b/engine/patches/series index 27d6177..370d89e 100644 --- a/engine/patches/series +++ b/engine/patches/series @@ -49,3 +49,4 @@ clair/pinned-link-peek.patch clair/quit-confirmation.patch clair/link-rules.patch clair/bookmarks-menu-root.patch +clair/split-on-option-click.patch diff --git a/native/ClairHost.h b/native/ClairHost.h index 51cddb1..6d2f03d 100644 --- a/native/ClairHost.h +++ b/native/ClairHost.h @@ -93,6 +93,10 @@ typedef NSString *ClairPinID NS_SWIFT_BRIDGED_TYPEDEF NS_SWIFT_NAME(PinID); // which never changes (add-tab-folders design D1). typedef NSString *ClairFolderID NS_SWIFT_BRIDGED_TYPEDEF NS_SWIFT_NAME(FolderID); +// A pinned or favorited split's ID: the UUID string of its record, which never +// changes (add-split-view design D10). +typedef NSString *ClairPinnedSplitID NS_SWIFT_BRIDGED_TYPEDEF NS_SWIFT_NAME(PinnedSplitID); + // A bookmark's ID and a bookmark folder's: Chromium's bookmark node IDs, // stable while Clair runs (add-bookmarks-menu design D3). typedef int64_t ClairBookmarkID NS_SWIFT_NAME(BookmarkID); @@ -104,6 +108,7 @@ static const ClairBookmarkFolderID ClairBookmarkFolderIDNone = -1; @protocol ClairLinkRule; @protocol ClairPin; @protocol ClairPinnedItem; +@protocol ClairPinnedSplit; @protocol ClairProfile; @protocol ClairSpace; @protocol ClairSpacesObserver; @@ -150,7 +155,8 @@ NS_SWIFT_NAME(ClairHost) // The Today tabs of a Space, in its order, across every browser window of the // profile: every window showing the Space lists all of them, whichever window // holds each (share-tabs-across-windows design D1). A Peek directly follows its -// parent. The tabs of pinned tabs and favorites aren't among them: they reach +// parent, and the trailing pane of a split directly follows the leading pane +// and its Peek (add-split-view design D2, D7). The tabs of pinned tabs and favorites aren't among them: they reach // ClairUI through their pins (-pinnedItemsInSpace:, -favoritesOfProfile:). An // incognito or guest window's Space (-[ClairBrowser shownSpaceID]) lists that // window's tabs alone, whose `browserID` is its own. Empty for an unknown @@ -182,7 +188,9 @@ NS_SWIFT_NAME(ClairHost) - (void)deleteSpace:(ClairSpaceID)spaceID NS_SWIFT_NAME(deleteSpace(_:)); // Moves a tab, with its Peek, to the top of another Space's list, or a pinned // tab's bound tab, with its pin, to the end of that Space's pinned section, -// outside any folder (add-pinned-tabs-and-favorites design D5). Within a +// outside any folder (add-pinned-tabs-and-favorites design D5). A tab of a +// split moves with the other, as one split, and a pinned split's with its +// item (add-split-view design D7). Within a // profile it keeps its // page and its window. To a Space of another profile it // reopens at its URL in that profile, without its Peek and without asking @@ -193,12 +201,16 @@ NS_SWIFT_NAME(ClairHost) - (void)moveTab:(ClairTabID)tabID toSpace:(ClairSpaceID)spaceID NS_SWIFT_NAME(move(tab:toSpace:)); // --- Pinned tabs, folders and favorites (add-pinned-tabs-and-favorites -// design D1 to D6, D10; add-tab-folders design D1 to D3, D7, D8, D11) --- +// design D1 to D6, D10; add-tab-folders design D1 to D3, D7, D8, D11; +// add-split-view design D10) --- // A pin is a saved item, kept in Chromium's Local State whether or not a page // is open: a pinned tab belongs to a Space, a favorite to a profile. While its // page is open, one tab is bound to it. A Space's pinned section lists items, -// each a pinned tab or a folder; a folder holds pinned tabs only, one level -// deep. Changes reach every observer through +// each a pinned tab, a pinned split or a folder; a folder holds pinned tabs +// and pinned splits, one level deep. A profile's favorites are favorites and +// favorited splits. A pinned or favorited split holds two pins, in pane order, +// and takes one place: a call naming either of its pins moves, unpins or +// removes the whole split, and opening either opens both pages as a split. Changes reach every observer through // -[ClairSpacesObserver pinnedItemsDidChange:inSpace:] and // -favoritesDidChange:ofProfile:. A place in a Space's pinned section is an // index among its items, pins and folders alike, or, with a folder, an index @@ -210,14 +222,17 @@ NS_SWIFT_NAME(ClairHost) // A Space's pinned items, in its order. Empty for an unknown Space. - (NSArray> *)pinnedItemsInSpace:(ClairSpaceID)spaceID NS_SWIFT_NAME(pinnedItems(inSpace:)); -// A profile's favorites, in its order. Empty for an unknown profile. -- (NSArray> *)favoritesOfProfile:(ClairProfileID)profileID +// A profile's favorites, in its order: each a favorite or a favorited split. +// Empty for an unknown profile. +- (NSArray> *)favoritesOfProfile:(ClairProfileID)profileID NS_SWIFT_NAME(favorites(ofProfile:)); // Pins a Today tab at `index` in its Space's pinned section, or in // `folderID`, a folder of that Space (D5): the pin takes the tab's URL as its // pinned URL, its title, icon and custom name, and the tab, with its Peek, -// stays open and bound to it. A folder of another Space is ignored. +// stays open and bound to it. A folder of another Space is ignored. A tab of a +// split of two Today tabs pins the split, as one pinned split with its ratio; +// a tab of a split with a pinned tab or favorite is ignored. - (void)pinTab:(ClairTabID)tabID inFolder:(nullable ClairFolderID)folderID atIndex:(NSInteger)index NS_SWIFT_NAME(pin(tab:inFolder:at:)); @@ -242,6 +257,10 @@ NS_SWIFT_NAME(ClairHost) // leave-page confirmation. Restore Last Closed Tab brings it back in place, // in its folder while the folder exists (D3, add-tab-folders design D7). - (void)removePin:(ClairPinID)pinID NS_SWIFT_NAME(removePin(_:)); +// Separate Tabs on a pinned or favorited split: its two pins take its place, +// in pane order, each keeping its pinned URL, name and bound tab, and a split +// of their open tabs ends (add-split-view design D10). +- (void)separatePinnedSplit:(ClairPinnedSplitID)splitID NS_SWIFT_NAME(separatePinnedSplit(_:)); // Loads the pinned URL in the bound tab as a new navigation, so Back returns // (D6). - (void)returnToPinnedURL:(ClairPinID)pinID NS_SWIFT_NAME(returnToPinnedURL(_:)); @@ -284,7 +303,7 @@ NS_SWIFT_NAME(ClairHost) // Adds a copy of the folder right after it, open, with a copy of each of its // pins in order: their pinned URLs, titles, names and icons, none open (D11). - (void)duplicateFolder:(ClairFolderID)folderID NS_SWIFT_NAME(duplicateFolder(_:)); -// Removes a folder and its pins, then closes their bound tabs, each with its +// Removes a folder and its items, then closes their bound tabs, each with its // leave-page confirmation. Restore Last Closed Tab brings the folder back with // its pins, in place (D7). ClairUI asks the user first when it has pins. - (void)deleteFolder:(ClairFolderID)folderID NS_SWIFT_NAME(deleteFolder(_:)); @@ -412,6 +431,12 @@ typedef NS_OPTIONS(NSUInteger, ClairTabIndicators) { ClairTabIndicatorsBlockedPermission = 1 << 4, } NS_SWIFT_NAME(TabIndicators); +// The side of a split a tab goes to. +typedef NS_ENUM(NSInteger, ClairSplitSide) { + ClairSplitSideLeading = 0, + ClairSplitSideTrailing = 1, +} NS_SWIFT_NAME(SplitSide); + // Where something chosen in the window opens. typedef NS_ENUM(NSInteger, ClairOpenDisposition) { // Navigates the active tab. @@ -627,6 +652,16 @@ NS_SWIFT_NAME(ClairTab) // The tab's custom name, which rows and the window's title show in place of // `title`, or nil (design D8). A bound tab's is its pin's. @property(nonatomic, readonly, copy, nullable) NSString *name; +// The other tab of the tab's split, or ClairTabIDNone outside a split +// (add-split-view design D1, D2). A split holds two tabs of one window, shown +// side by side; the active tab is the focused pane. Its tabs may be two Today +// tabs, a pinned split's, or a Today tab and a pinned tab's or favorite's. +@property(nonatomic, readonly) ClairTabID splitPartnerID; +// Whether the tab is a split's leading pane. NO outside a split. +@property(nonatomic, readonly) BOOL isLeadingPane; +// The leading pane's share of the page area's width, from 0 to 1, the same for +// both tabs of a split: 0.5 for a new split. 0.5 outside a split. +@property(nonatomic, readonly) double splitRatio; @end // A pinned tab or favorite, as a snapshot (add-pinned-tabs-and-favorites design @@ -665,6 +700,29 @@ NS_SWIFT_NAME(ClairPin) // first requested before redirects, is the pinned URL, ignoring the fragment // (design D2). YES while unbound. @property(nonatomic, readonly) BOOL isAtPinnedURL; +// The pinned or favorited split holding the pin, or nil (add-split-view design +// D10). Its folder and place are the split's. +@property(nonatomic, readonly, copy, nullable) ClairPinnedSplitID pinnedSplitID; +@end + +// A pinned or favorited split, as a snapshot (add-split-view design D10). +// Chromium implements it. +NS_SWIFT_UI_ACTOR +NS_SWIFT_NAME(ClairPinnedSplit) +@protocol ClairPinnedSplit +@property(nonatomic, readonly, copy) ClairPinnedSplitID pinnedSplitID; +// Whether it is a favorited split rather than a pinned one. +@property(nonatomic, readonly) BOOL isFavorite; +// As a pin's: the Space, or nil for a favorited split; the folder holding it, +// or nil; and the profile. +@property(nonatomic, readonly, copy, nullable) ClairSpaceID spaceID; +@property(nonatomic, readonly, copy, nullable) ClairFolderID folderID; +@property(nonatomic, readonly, copy) ClairProfileID profileID; +// Its two pins, leading pane first. +@property(nonatomic, readonly, copy) NSArray> *pins; +// The leading pane's share of the width, from 0 to 1, as -[ClairTab +// splitRatio]. +@property(nonatomic, readonly) double ratio; @end // A folder in a Space's pinned section, as a snapshot (add-tab-folders design @@ -678,16 +736,20 @@ NS_SWIFT_NAME(ClairFolder) @property(nonatomic, readonly, copy) NSString *name; // Whether it's open on this Mac (D3). A new folder is. @property(nonatomic, readonly) BOOL isOpen; -// Its pinned tabs, in its order. -@property(nonatomic, readonly, copy) NSArray> *pins; +// Its pinned tabs and pinned splits, in its order; never a folder +// (add-split-view design D10). +@property(nonatomic, readonly, copy) NSArray> *items; @end -// One item of a Space's pinned section: a pinned tab or a folder; exactly one -// of the two is set (add-tab-folders design D2). Chromium implements it. +// One item of a Space's pinned section, a folder or the favorites: a pinned +// tab or favorite, a pinned or favorited split, or, in a pinned section, a +// folder; exactly one of them is set (add-tab-folders design D2, +// add-split-view design D10). Chromium implements it. NS_SWIFT_UI_ACTOR NS_SWIFT_NAME(ClairPinnedItem) @protocol ClairPinnedItem @property(nonatomic, readonly, nullable) id pin; +@property(nonatomic, readonly, nullable) id split; @property(nonatomic, readonly, nullable) id folder; @end @@ -792,8 +854,9 @@ NS_SWIFT_NAME(ClairSpacesObserver) // -[ClairHost pinnedItemsInSpace:] returns it. - (void)pinnedItemsDidChange:(NSArray> *)items inSpace:(ClairSpaceID)spaceID NS_SWIFT_NAME(pinnedItemsDidChange(_:inSpace:)); -// The same for a profile's favorites. -- (void)favoritesDidChange:(NSArray> *)favorites ofProfile:(ClairProfileID)profileID +// The same for a profile's favorites, as -[ClairHost favoritesOfProfile:] +// returns them. +- (void)favoritesDidChange:(NSArray> *)favorites ofProfile:(ClairProfileID)profileID NS_SWIFT_NAME(favoritesDidChange(_:ofProfile:)); @end @@ -1133,6 +1196,9 @@ NS_SWIFT_NAME(ClairBrowser) // selected it from, the row above or the row below in the window's Space // (add-spaces design D4), taking it from another window if need be. A bound // tab's pin stays, unbound (add-pinned-tabs-and-favorites design D2, D4). +// Closing a pane of a split shows the other pane alone, in the split's place +// (add-split-view design D12); a pane of a pinned or favorited split takes its +// pin out of the split, which Restore Last Closed Tab brings back (D10). - (void)closeTab:(ClairTabID)tabID NS_SWIFT_NAME(close(tab:)); // Closes every row below it in its Space, in whichever window holds each, each // with its leave-page confirmation. @@ -1155,6 +1221,8 @@ NS_SWIFT_NAME(ClairBrowser) // Unpins a pinned tab or favorite: the pin goes, and its bound tab, or a new // one opened at its pinned URL in this window, joins the Today tabs of its // Space (the shown Space for a favorite) at `index`, keeping the custom name. +// A pin of a pinned or favorited split unpins the split: both pages join the +// Today tabs at `index`, as a split with its ratio. - (void)unpin:(ClairPinID)pinID toIndex:(NSInteger)index NS_SWIFT_NAME(unpin(_:to:)); // --- Peek (add-peek design D3); `tabID` names the parent or its Peek --- @@ -1163,6 +1231,49 @@ NS_SWIFT_NAME(ClairBrowser) - (void)closePeekOfTab:(ClairTabID)tabID NS_SWIFT_NAME(closePeek(of:)); // Turns the tab's Peek into a normal, active tab directly below its parent. - (void)expandPeekOfTab:(ClairTabID)tabID NS_SWIFT_NAME(expandPeek(of:)); +// Turns the tab's Peek into a normal tab, as -expandPeekOfTab: does, as the +// trailing, focused pane of a split with its parent (add-split-view design +// D11). Ignored while the parent is in a split. +- (void)openPeekInSplitOfTab:(ClairTabID)tabID NS_SWIFT_NAME(openPeekInSplit(of:)); + +// --- Split view (add-split-view design D1, D2, D4, D8, D12) --- +// Every call naming a tab works on any tab of the window's rows, whichever +// window holds it, and the split it makes or changes is shown here. Focusing +// a pane is -activateTab:. +// Makes a split of `tabID` and `otherID`, `otherID` on `side`, focused, with +// equal panes. Either may be a Today tab, a pinned tab's or a favorite's. +// Ignored when they're the same tab, either is a Peek, or either is in a +// split. +- (void)splitTab:(ClairTabID)tabID + withTab:(ClairTabID)otherID + side:(ClairSplitSide)side NS_SWIFT_NAME(split(tab:with:side:)); +// Makes a split of the tab and a new tab page, the new tab trailing and +// focused, for Add Split View and the menus' New Tab. The command bar doesn't +// open: ClairUI opens it. Ignored for a tab in a split or a Peek. +- (void)splitTabWithNewTab:(ClairTabID)tabID NS_SWIFT_NAME(splitWithNewTab(_:)); +// Shows the tab's split, focusing the pane focused last (add-split-view spec +// "Selecting the split row"). A tab outside a split is activated as +// -activateTab: does. +- (void)showSplitOfTab:(ClairTabID)tabID NS_SWIFT_NAME(showSplit(of:)); +// Puts `newTabID` in the pane of `tabID`, focused. The tab it replaces leaves +// the split with its page, as a row directly below the split's. Ignored when +// `tabID` isn't in a split, or `newTabID` is in one or is a Peek. +- (void)replacePaneOfTab:(ClairTabID)tabID + withTab:(ClairTabID)newTabID NS_SWIFT_NAME(replacePane(of:with:)); +// Swaps the panes of the tab's split, keeping the focused pane focused (Move +// Left and Move Right). +- (void)swapSplitOfTab:(ClairTabID)tabID NS_SWIFT_NAME(swapSplit(of:)); +// Separate Tabs: ends the tab's split, both tabs keeping their pages, as two +// rows in its place, in pane order, and shows the focused pane's tab alone. A +// pinned or favorited split's pins take its place, as +// -[ClairHost separatePinnedSplit:] does. +- (void)separateSplitOfTab:(ClairTabID)tabID NS_SWIFT_NAME(separateSplit(of:)); +// Closes both tabs of the split, each with its leave-page confirmation, as the +// split row's × and a pinned split's − (Close and Keep Pinned) do: a pinned or +// favorited split keeps both pins. Closing one pane is -closeTab:. +- (void)closeSplitOfTab:(ClairTabID)tabID NS_SWIFT_NAME(closeSplit(of:)); +// Sets the leading pane's share of the width, clamped to 0.05 to 0.95. +- (void)setSplitRatio:(double)ratio ofTab:(ClairTabID)tabID NS_SWIFT_NAME(setSplitRatio(_:of:)); // --- Navigation of the active tab: back, forward, reload (which also // reloads a crashed page) and stop --- @@ -1361,8 +1472,13 @@ NS_SWIFT_NAME(ClairWindow) // The window started or stopped showing a still, or its image changed // (-[ClairBrowser stillTabID] and -stillImage). - (void)stillDidChange; -// The URL of the link under the pointer, or nil to hide the status capsule. -- (void)statusTextDidChange:(nullable NSString *)text NS_SWIFT_NAME(statusTextDidChange(_:)); +// The link status (add-split-view design D13a): the URL of the link under the +// pointer, or a status text the page set, or nil to hide the capsule. `isLink` +// says it is a link's URL, which ClairUI words with the modifier keys held. +// `tabID` is the page's tab, a pane of a split or the active tab. +- (void)statusTextDidChange:(nullable NSString *)text + isLink:(BOOL)isLink + tab:(ClairTabID)tabID NS_SWIFT_NAME(statusTextDidChange(_:isLink:tab:)); // Shows a short confirmation at the bottom of the card, such as "Copied Link". - (void)showToast:(NSString *)message NS_SWIFT_NAME(showToast(_:)); // The page asked for full screen, or left it: the card shows the page alone, diff --git a/native/ClairUI/BrowserRootView.swift b/native/ClairUI/BrowserRootView.swift index 1798df8..7985d70 100644 --- a/native/ClairUI/BrowserRootView.swift +++ b/native/ClairUI/BrowserRootView.swift @@ -33,6 +33,9 @@ final class FittingHostingView: NSHostingView { class SelfSizingHostingView: NSHostingView { /// A margin around the content, kept for its shadow, that takes no clicks. var hitInset: CGFloat = 0 + /// Whether a change in the content's width lays the window out again too, + /// for a view sized to its content both ways, such as the link status. + var tracksWidth = false required init(rootView: Content) { super.init(rootView: rootView) @@ -60,7 +63,8 @@ class SelfSizingHostingView: NSHostingView { // in the same pass. override func layout() { super.layout() - if abs(fittingSize.height - bounds.height) > 0.5 { + let size = fittingSize + if abs(size.height - bounds.height) > 0.5 || (tracksWidth && abs(size.width - bounds.width) > 0.5) { superview?.needsLayout = true } } @@ -108,6 +112,13 @@ final class BrowserRootView: NSView { /// The inset above the card, which acts as the window's title bar. let topInset = TitleBarAreaView() let card = PageCardView() + /// A split's trailing pane (add-split-view D3); hidden outside a split. The + /// first card is the leading pane, or the single page. + let secondCard = PageCardView() + /// The gap between the panes, with its grabber. + let splitDivider = SplitDividerView() + /// Takes tabs dragged onto the page (D8). + let pageDrop = PageDropView() /// Arc's loading capsule in the inset above the card (arc-navigation-feedback D4). let loadingIndicator = LoadingIndicatorView() let sidebar: NSView @@ -184,7 +195,18 @@ final class BrowserRootView: NSView { // Above the materials, not inside them, where they'd blend it. addSubview(backgroundTint) addSubview(topInset) + // Below both panes, so the leading pane's Peek can draw over the trailing + // pane without rising above the window's overlays (add-split-view D11). + for view in [background, backgroundTint, topInset] as [NSView] { + view.wantsLayer = true + view.layer?.zPosition = -2 + } addSubview(card) + secondCard.isHidden = true + addSubview(secondCard) + splitDivider.isHidden = true + addSubview(splitDivider) + addSubview(pageDrop) addSubview(loadingIndicator) addSubview(sidebarBackdrop) addSubview(backdropTint) @@ -256,6 +278,9 @@ final class BrowserRootView: NSView { _ = model.commandBar _ = model.isSidebarPopoverOpen _ = model.showsPageHeader + _ = model.shownSplit + _ = model.liveSplitRatio + _ = model.pageDrop } onChange: { [weak self] in Task { @MainActor in guard let self else { return } @@ -349,7 +374,7 @@ final class BrowserRootView: NSView { backdropTint.color = backgroundTint.color backgroundTint.frame = bounds let layout = currentLayout - card.frame = layout.card + layoutPanes(area: layout.card) topInset.frame = layout.topInset(windowWidth: bounds.width) topInset.isHidden = topInset.frame.isEmpty // The floating sidebar while it's revealed or sliding away; the one in @@ -373,12 +398,16 @@ final class BrowserRootView: NSView { roundedRect: revealedPanel.bounds, cornerWidth: 10, cornerHeight: 10, transform: nil) revealedBackground.frame = revealedPanel.bounds revealedTint.frame = revealedBackground.bounds - card.isBare = model.isPageFullscreen - card.showsToolbar = model.showsPageHeader - // Centred on the card, 3 pt below the window's top with the card 10 pt in. + for pane in [card, secondCard] { + pane.isBare = model.isPageFullscreen + pane.showsToolbar = model.showsPageHeader + } + // Centred on the card, or the focused pane, 3 pt below the window's top + // with the card 10 pt in. + let activePane = focusedCard.frame loadingIndicator.isHidden = model.isPageFullscreen loadingIndicator.frame = CGRect( - x: layout.card.midX - LoadingIndicatorModel.trackWidth / 2 - 4, + x: (split == nil ? layout.card : activePane).midX - LoadingIndicatorModel.trackWidth / 2 - 4, y: layout.card.minY - WindowLayout.shownInset + LoadingIndicatorModel.topOffset, width: LoadingIndicatorModel.trackWidth + 8, height: LoadingIndicatorModel.height) resizeHandle.isHidden = model.sidebar.isHidden || model.isPageFullscreen @@ -391,22 +420,144 @@ final class BrowserRootView: NSView { updateRevealTracking() } + // MARK: Split view (add-split-view design D3, D8) + + /// The split the window lays out, if any. + private var split: ShownSplit? { + model.isPageFullscreen ? nil : model.shownSplit + } + + /// The card of the focused pane, or the single page's. In page full + /// screen the focused pane's page fills the window from its own card. + var focusedCard: PageCardView { + model.shownSplit?.focusedIndex == 1 ? secondCard : card + } + + /// The card showing `tabID`: a pane's while split, its Peek's parent's for + /// a Peek, or the single page's. + func card(showing tabID: TabID) -> PageCardView { + guard let split = model.shownSplit else { return card } + let paneID = model.allTabs.first { $0.tabID == tabID }.map { $0.peekParentID != ClairTabIDNone ? $0.peekParentID : $0.tabID } + return split.index(of: paneID ?? tabID) == 1 ? secondCard : card + } + + /// The page area the panes share, as the last layout placed it. + private(set) var pageArea: CGRect = .zero + + private func layoutPanes(area: CGRect) { + pageArea = area + pageDrop.frame = area + if let split { + let ratio = model.liveRatio(of: split) ?? split.ratio + let panes = SplitLogic.paneFrames(in: area, ratio: ratio) + card.frame = panes[0] + secondCard.frame = panes[1] + card.isHidden = false + secondCard.isHidden = false + // A Peek covers the divider with the page area. + splitDivider.isHidden = card.isPeeking || secondCard.isPeeking + splitDivider.frame = SplitLogic.dividerFrame(in: area, ratio: ratio) + splitDivider.areaMinX = area.minX + card.showsFocusRing = split.focusedIndex == 0 + secondCard.showsFocusRing = split.focusedIndex == 1 + card.peekButtonCount = 2 + secondCard.peekButtonCount = 2 + card.paneIndex = 0 + secondCard.paneIndex = 1 + // A Peek covers the page area, over the other pane (D11): the leading + // pane's goes over the trailing pane, which is above it otherwise. Both + // stay below the find field, the notice and the command bar. + for pane in [card, secondCard] { + pane.peekArea = pane.isPeeking ? area.offsetBy(dx: -pane.frame.minX, dy: -pane.frame.minY) : nil + } + card.layer?.zPosition = 0 + secondCard.layer?.zPosition = card.isPeeking ? -1 : 0 + } else if model.isPageFullscreen, model.shownSplit?.focusedIndex == 1 { + // The trailing pane's page in page full screen fills the window from + // its card; the leading pane's hides. + secondCard.frame = area + secondCard.isHidden = false + card.isHidden = true + splitDivider.isHidden = true + for pane in [card, secondCard] { + pane.showsFocusRing = false + pane.peekButtonCount = 3 + pane.paneIndex = nil + pane.peekArea = nil + pane.layer?.zPosition = 0 + } + } else { + // A tab dragged over a single page slides it to the other half (D8). + let frame: CGRect = + if case .half(let side) = model.pageDrop { + SplitLogic.slidFrame(in: area, dropSide: side) + } else { + area + } + if card.frame != frame, !card.frame.isEmpty, model.pageDrop != nil || slidForDrop { + NSAnimationContext.runAnimationGroup { context in + context.duration = SplitLogic.slideDuration + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + card.animator().frame = frame + } + } else { + card.frame = frame + } + slidForDrop = model.pageDrop != nil + card.isHidden = false + secondCard.isHidden = true + splitDivider.isHidden = true + card.showsFocusRing = false + card.peekButtonCount = 3 + card.paneIndex = nil + card.peekArea = nil + card.layer?.zPosition = 0 + secondCard.layer?.zPosition = 0 + } + } + + /// Whether the page was last slid aside for a drag, so it slides back. + private var slidForDrop = false + + /// A Peek of either pane takes clicks over the page area, above the other + /// pane (D11). + override func hitTest(_ point: NSPoint) -> NSView? { + if split != nil, commandBarHost == nil { + for pane in [card, secondCard] where pane.isPeeking { + if let hit = pane.hitTest(point), hit !== pane { + return hit + } + } + } + return super.hitTest(point) + } + private func layoutOverlays(card: CGRect) { func fit(_ view: NSView?, maxWidth: CGFloat) -> CGSize { guard let view else { return .zero } let size = view.fittingSize return CGSize(width: min(size.width, maxWidth), height: size.height) } + // add-split-view D3: find, the notice and the command bar follow the + // focused pane; the toasts the page area. + let focused = focusedCard + let pane = split == nil ? card : focused.frame if let findHost { - let size = fit(findHost, maxWidth: card.width - 20) + let size = fit(findHost, maxWidth: pane.width - 20) // Below the toolbar while it shows (add-page-toolbar D7). findHost.frame = CGRect( - x: card.maxX - size.width - 10, y: card.minY + self.card.contentTop + 10, width: size.width, + x: pane.maxX - size.width - 10, y: pane.minY + focused.contentTop + 10, width: size.width, height: size.height) } if let statusHost { - // At the Peek's corner while a Peek shows (add-peek design D11). - let page = self.card.isPeeking ? convert(self.card.activePageFrame, from: self.card) : card + // At the Peek's corner while a Peek shows (add-peek design D11), or at + // the corner of the pane holding the link (add-split-view D13a). + let holder = self.card(showing: model.statusTabID) + let holderFrame = split == nil ? card : holder.frame + let inPeek = holder.isPeeking && model.allTabs.contains { + $0.tabID == model.statusTabID && $0.peekParentID != ClairTabIDNone + } + let page = holder.isPeeking && (split == nil || inPeek) ? convert(holder.activePageFrame, from: holder) : holderFrame let size = fit(statusHost, maxWidth: page.width / 2) statusHost.frame = CGRect(x: page.minX + 8, y: page.maxY - size.height - 8, width: size.width, height: size.height) } @@ -420,7 +571,7 @@ final class BrowserRootView: NSView { let size = noticeHost.fittingSize let margin = NoticePopupView.margin noticeHost.frame = CGRect( - x: card.maxX - 8 + margin - size.width, y: card.minY + self.card.contentTop + 8 - margin, width: size.width, + x: pane.maxX - 8 + margin - size.width, y: pane.minY + focused.contentTop + 8 - margin, width: size.width, height: size.height) if noticeHost !== subviews.last { addSubview(noticeHost) @@ -432,8 +583,10 @@ final class BrowserRootView: NSView { commandBarHost.frame.size.width = width let height = commandBarHost.fittingSize.height // Whole points, so its hairline border stays one crisp pixel. + // Centred on the focused pane while split, inside the window (D13b). + let minX = SplitLogic.commandBarMinX(width: width, pane: split == nil ? nil : pane, bounds: bounds) commandBarHost.frame = CGRect( - x: (bounds.midX - width / 2).rounded(), y: CommandBarView.top(inWindowHeight: bounds.height), + x: minX.rounded(), y: CommandBarView.top(inWindowHeight: bounds.height), width: width.rounded(), height: height) } } diff --git a/native/ClairUI/BrowserWindowController+Pins.swift b/native/ClairUI/BrowserWindowController+Pins.swift index 58fc61a..e7e6a58 100644 --- a/native/ClairUI/BrowserWindowController+Pins.swift +++ b/native/ClairUI/BrowserWindowController+Pins.swift @@ -62,11 +62,15 @@ extension BrowserWindowController { /// What the Tabs and View menus' Clair items act on. var pinMenuState: PinsLogic.MenuState { guard model.showsPins else { return PinsLogic.MenuState(showsPins: false) } + // The row's highlight stays on a split's leading pane; the commands are + // the focused pane's. let highlighted = model.highlightedTab - let pin = model.pin(ofTab: highlighted) + let commandTab = model.commandTab + let pin = model.pin(ofTab: commandTab) + let rows = TabListLogic.rows(model.tabs) return PinsLogic.MenuState( showsPins: true, - activeIsToday: pin == nil && TabListLogic.rows(model.tabs).contains { $0.tabID == highlighted }, + activeIsToday: pin == nil && rows.contains { $0.tabID == highlighted || $0.tabID == commandTab }, activePinIsFavorite: pin?.isFavorite, activePinIsNavigatedAway: pin.map(PinsLogic.isNavigatedAway) ?? false, todayRowCount: TabListLogic.rowCount(model.tabs), @@ -75,7 +79,7 @@ extension BrowserWindowController { /// One of the main menu's Clair items. func perform(_ command: PinsLogic.MainMenuCommand) { - let highlighted = model.highlightedTab + let highlighted = model.commandTab switch command { case .togglePin: if let pin = model.pin(ofTab: highlighted) { @@ -261,8 +265,11 @@ extension BrowserWindowController { browser?.unpin(pinID, to: index) case (.pin(let pinID), .favorites(var index)): // A favorite moved within the grid lands where it was dropped, the - // others closing up behind it. - if let from = model.favorites.firstIndex(where: { $0.pinID == pinID }), from < index { + // others closing up behind it. The slot counts tiles, a split one, as + // the engine's index does. + if let from = model.favoriteItems.firstIndex(where: { item in + PinsLogic.allPins([item]).contains { $0.pinID == pinID } + }), from < index { index -= 1 } model.spaces.movePin(pinID, toFavoritesAt: index) @@ -332,7 +339,7 @@ extension BrowserWindowController { func moveFolder(_ folderID: FolderID, toSpace spaceID: SpaceID) { guard let space = model.spaces.space(spaceID), let folder = model.spaces.folder(folderID) else { return } let highlighted = model.highlightedTab - let holdsActive = highlighted != ClairTabIDNone && folder.pins.contains { $0.tabID == highlighted } + let holdsActive = highlighted != ClairTabIDNone && PinsLogic.pins(of: folder).contains { $0.tabID == highlighted } model.spaces.moveFolder(folderID, toSpace: spaceID, at: Int.max) if !holdsActive { model.notice.show( diff --git a/native/ClairUI/BrowserWindowController+Split.swift b/native/ClairUI/BrowserWindowController+Split.swift new file mode 100644 index 0000000..e7950c3 --- /dev/null +++ b/native/ClairUI/BrowserWindowController+Split.swift @@ -0,0 +1,288 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// The window's split view (add-split-view design D2, D3, D8, D9, D13). +extension BrowserWindowController: SplitActions { + /// Wires the divider, the panes' hover, drops on the page and the + /// modifier keys the link status reads. + func setUpSplitView() { + rootView.splitDivider.onDrag = { [weak self] x, done in + self?.dividerMoved(to: x, done: done) + } + for (index, card) in [rootView.card, rootView.secondCard].enumerated() { + card.onHover = { [weak model] inside in + guard let model else { return } + if inside { + model.hoveredPane = index + } else if model.hoveredPane == index { + model.hoveredPane = nil + } + } + } + let drop = rootView.pageDrop + // The drop view keeps these, so they take it weakly. + drop.zone = { [weak self, weak drop] item, point in + guard let self, let drop else { return nil } + let tab = self.tab(of: item) + let isPinnedSplit = item.pinID.flatMap { self.model.spaces.pin($0)?.pinnedSplitID } != nil + guard item.isTabOrPin, tab != nil || item.pinID != nil, + SplitLogic.acceptsDrop( + of: tab, isPinnedSplit: isPinnedSplit, shown: self.model.shownSplit, activeTabID: self.shownRowTabID) + else { return nil } + return SplitLogic.dropZone(at: point, in: drop.bounds, split: self.model.shownSplit) + } + drop.zoneFrame = { [weak self, weak drop] zone in + guard let self, let drop else { return .zero } + let area = drop.bounds + switch zone { + case .half(let side): + let panes = SplitLogic.paneFrames(in: area, ratio: 0.5) + return side == .leading ? panes[0] : panes[1] + case .pane(let index): + let ratio = self.model.shownSplit?.ratio ?? 0.5 + return SplitLogic.paneFrames(in: area, ratio: ratio)[index] + } + } + drop.describe = { [weak self] item in + guard let self else { return (nil, "") } + if let tab = self.tab(of: item) { + return (tab.favicon, SplitLogic.title(of: tab)) + } + if case .pin(let pinID) = item, let pin = self.model.spaces.pin(pinID) { + return (pin.icon, PinsLogic.title(of: pin, tab: nil)) + } + return (nil, "") + } + drop.onTarget = { [weak model] zone in + model?.pageDrop = zone + } + drop.onDrop = { [weak self] item, zone in + self?.dropped(item, on: zone) + } + // D13a: the link status follows Option and Shift as they're pressed. + flagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event in + MainActor.assumeIsolated { + guard let self, event.window === self.window, self.model.statusText != nil else { return } + self.model.statusModifiers = event.modifierFlags + } + return event + } + } + + /// The tab whose row the window shows: the active tab, or the active + /// Peek's parent. + var shownRowTabID: TabID { + model.shownPeek?.parentID ?? model.activeTabID + } + + /// The focused pane's tab while split, or the shown row's tab. + var focusedPaneTabID: TabID { + model.shownSplit.map { $0.paneIDs[$0.focusedIndex] } ?? shownRowTabID + } + + /// The tab a dragged row or tile stands for, while open. + private func tab(of item: SidebarDragItem) -> (any ClairTab)? { + switch item { + case .tab(let tabID): return model.allTabs.first { $0.tabID == tabID } + case .pin(let pinID): + guard let pin = model.spaces.pin(pinID), pin.tabID != ClairTabIDNone else { return nil } + return model.tab(ofPin: pin) ?? PinsLogic.tab(of: pin) + case .folder: return nil + } + } + + // MARK: The divider (D3) + + /// The divider snaps to equal panes near the centre as it moves, with + /// the trackpad's alignment feedback, and the ratio it's let go at sticks. + private func dividerMoved(to x: CGFloat, done: Bool) { + guard let split = model.shownSplit else { return } + let width = rootView.pageArea.width + let current = model.liveRatio(of: split) ?? split.ratio + let ratio = SplitLogic.snappedRatio(forDividerAt: x, width: width, current: current) + if ratio == 0.5, current != 0.5 { + NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) + } + model.liveSplitPanes = split.paneIDs + model.liveSplitRatio = ratio + if done { + browser?.setSplitRatio(ratio, of: split.leadingID) + } + } + + /// Lets go of the dragged ratio once the engine reports it, or once + /// the window shows another split or none. + func settleSplitRatio() { + guard let live = model.liveSplitRatio else { return } + guard let split = model.shownSplit, split.paneIDs == model.liveSplitPanes else { + model.liveSplitRatio = nil + model.liveSplitPanes = nil + return + } + if abs(split.ratio - live) < 0.001 { + model.liveSplitRatio = nil + model.liveSplitPanes = nil + } + } + + // MARK: Drops on the page (D8) + + private func dropped(_ item: SidebarDragItem, on zone: SplitLogic.DropZone) { + model.pageDrop = nil + // What it lands on, before a closed pin's page opens and becomes active. + let shown = shownRowTabID + let pane: TabID? = + if case .pane(let index) = zone, let split = model.shownSplit { split.paneIDs[index] } else { nil } + guard let tabID = tab(of: item)?.tabID else { + // A pinned tab or favorite whose page isn't open opens first. + if case .pin(let pinID) = item { + whenPinOpens(pinID) { [weak self] tabID in + self?.split(dropping: tabID, on: zone, shown: shown, pane: pane) + } + } + return + } + split(dropping: tabID, on: zone, shown: shown, pane: pane) + } + + /// Opens a pin whose page is closed, then runs `then` with its tab. + private func whenPinOpens(_ pinID: PinID, then: @escaping (TabID) -> Void) { + pendingPinSplit = (pinID, then) + browser?.openPin(pinID) + finishPendingPinSplit() + } + + private func split(dropping tabID: TabID, on zone: SplitLogic.DropZone, shown: TabID, pane: TabID?) { + switch zone { + case .half(let side): + browser?.split(tab: shown, with: tabID, side: side) + case .pane: + guard let pane else { return } + browser?.replacePane(of: pane, with: tabID) + } + } + + /// A pin dropped on the page while closed has opened. + func finishPendingPinSplit() { + guard let pending = pendingPinSplit, let pin = model.spaces.pin(pending.pinID), pin.tabID != ClairTabIDNone + else { return } + pendingPinSplit = nil + pending.then(pin.tabID) + } + + func splitWithTabItems(tab tabID: TabID?, pin pinID: PinID?) -> [RowClickCatcher.Item] { + let ownTab = tabID ?? pinID.flatMap { model.spaces.pin($0) }?.tabID ?? ClairTabIDNone + let favicons = Dictionary(model.allTabs.map { ($0.tabID, $0.favicon) }, uniquingKeysWith: { first, _ in first }) + // Runs `action` on the menu's tab, opening a closed pin's page first. + let onOwnTab: (@escaping (TabID) -> Void) -> Void = { [weak self] action in + guard let self else { return } + if let tabID { + action(tabID) + } else if let pinID, let pin = self.model.spaces.pin(pinID) { + if pin.tabID != ClairTabIDNone { action(pin.tabID) } else { self.whenPinOpens(pinID, then: action) } + } + } + return SplitLogic.splitWithTabSubmenu(for: ownTab, today: model.tabs).compactMap { entry in + switch entry { + case .tab(let other, let title): + return .icon(title, favicons[other] ?? nil) { [weak self] in + onOwnTab { self?.split(tab: $0, with: other, side: .trailing) } + } + case .newTab: + return .action(entry.title) { [weak self] in onOwnTab { self?.splitWithNewTab($0) } } + case .separator: + return .separator + default: + return nil + } + } + } + + // MARK: Menus (D9) + + /// View › Add Split View, and the menus' New Tab: a new tab page as the + /// trailing pane, with the command bar; "Cannot Add New Pane" while split. + func addSplitView() { + guard model.shownSplit == nil else { + showToast(Self.cannotAddPane) + return + } + splitWithNewTab(shownRowTabID) + } + + static let cannotAddPane = "Cannot Add New Pane" + + /// View › Close Split Pane: the focused pane's tab. + func closeSplitPane() { + guard model.shownSplit != nil else { return } + browser?.close(tab: focusedPaneTabID) + } + + // MARK: SplitActions + + func showSplit(of tabID: TabID) { + browser?.showSplit(of: tabID) + } + + func split(tab tabID: TabID, with otherID: TabID, side: SplitSide) { + browser?.split(tab: tabID, with: otherID, side: side) + } + + func splitWithNewTab(_ tabID: TabID) { + // D13b: the command bar opens on the new pane once it's active. + opensCommandBarOnNewPane = true + browser?.splitWithNewTab(tabID) + } + + func swapSplit(of tabID: TabID) { + browser?.swapSplit(of: tabID) + } + + func separateSplit(of tabID: TabID) { + browser?.separateSplit(of: tabID) + } + + func closeSplit(of tabID: TabID) { + browser?.closeSplit(of: tabID) + } + + func replacePane(of tabID: TabID, with newTabID: TabID) { + browser?.replacePane(of: tabID, with: newTabID) + } + + func setSplitRatio(_ ratio: Double, of tabID: TabID) { + browser?.setSplitRatio(ratio, of: tabID) + } + + func separatePinnedSplit(_ splitID: PinnedSplitID) { + model.spaces.separatePinnedSplit(splitID) + } + + func focusPane(_ tabID: TabID) { + guard tabID != model.activeTabID, model.shownPeek?.parentID != tabID else { return } + browser?.activate(tab: tabID) + } + + /// Peek's Open in Split View (D11). + func openPeekInSplit() { + guard let peek = model.shownPeek else { return } + browser?.openPeekInSplit(of: peek.parentID) + } +} + +extension SidebarDragItem { + /// Whether it's a tab or a pin, which can join a split. + var isTabOrPin: Bool { + if case .folder = self { return false } + return true + } + + var pinID: PinID? { + if case .pin(let pinID) = self { return pinID } + return nil + } +} diff --git a/native/ClairUI/BrowserWindowController.swift b/native/ClairUI/BrowserWindowController.swift index 1e3dba5..d221d18 100644 --- a/native/ClairUI/BrowserWindowController.swift +++ b/native/ClairUI/BrowserWindowController.swift @@ -30,8 +30,11 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over let model: BrowserWindowModel let rootView: BrowserRootView private let sidebarHost: NSHostingView - /// The toolbar above the page, and the Peek's (add-page-toolbar D2, D3). + /// The toolbar above the page, and the Peek's (add-page-toolbar D2, D3); + /// the first is the leading pane's header while split, the second the + /// trailing pane's (add-split-view D9). private let toolbarHost: NSHostingView + private let secondToolbarHost: NSHostingView private let peekToolbarHost: NSHostingView private let preferences: SidebarPreferences /// The sidebar's controls, in its hosting view's coordinates. @@ -39,6 +42,8 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over /// The toolbar's controls, in its hosting view's coordinates, apart from /// the sidebar's, whose stale frames mustn't win (add-page-toolbar D6). private var toolbarFrames: [AnchorControl: CGRect] = [:] + /// The pane whose header reported `toolbarFrames`. + private var toolbarFramesPane = 0 private var extensionPopup: ExtensionPopupWindow? /// The window's dialogs (add-clair-dialogs D1), for every dialog on it. private(set) lazy var dialogs = ClairDialogPresenter(window: window) @@ -65,6 +70,14 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over private var commandBarKeyMonitor: Any? /// When the link status capsule shows and hides. private var statusState = StatusCapsuleState() + // Split view (add-split-view design D8, D13a, D13b). + /// Watches Option and Shift for the link status. + nonisolated(unsafe) var flagsMonitor: Any? + /// A closed pin dropped on the page, which splits once its page opens. + var pendingPinSplit: (pinID: PinID, then: (TabID) -> Void)? + /// Add Split View and New Tab open the command bar on the new pane once + /// it's active. + var opensCommandBarOnNewPane = false private var statusTimer: Task? /// `spaces` is the app's model of Spaces, and `updateBanner` its update @@ -91,19 +104,22 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over showsToolbar: toolbarPreference.isOn) self.model = model sidebarHost = NSHostingView.edgeToEdge(rootView: SidebarView(model: model, actions: nil)) - toolbarHost = NSHostingView.edgeToEdge(rootView: PageToolbar(model: model, content: .tab, actions: nil)) - peekToolbarHost = NSHostingView.edgeToEdge(rootView: PageToolbar(model: model, content: .peek, actions: nil)) + toolbarHost = NSHostingView.edgeToEdge(rootView: PageToolbar(model: model, slot: .pane(0), actions: nil)) + secondToolbarHost = NSHostingView.edgeToEdge(rootView: PageToolbar(model: model, slot: .pane(1), actions: nil)) + peekToolbarHost = NSHostingView.edgeToEdge(rootView: PageToolbar(model: model, slot: .peek, actions: nil)) rootView = BrowserRootView(model: model, sidebar: sidebarHost) super.init() Self.all.add(self) sidebarHost.rootView = SidebarView(model: model, actions: self) - for host in [toolbarHost, peekToolbarHost] { - host.rootView = PageToolbar(model: model, content: host.rootView.content, actions: self) + for host in [toolbarHost, secondToolbarHost, peekToolbarHost] { + host.rootView = PageToolbar(model: model, slot: host.rootView.slot, actions: self) // The toolbar is laid out by the card, not sized by its content. host.sizingOptions = [] } rootView.card.toolbar = toolbarHost + rootView.secondCard.toolbar = secondToolbarHost rootView.card.peekToolbar = peekToolbarHost + setUpSplitView() rootView.onScrimClick = { [weak self] in self?.model.commandBar?.cancel() } rootView.onCopyURL = { [weak self] in self?.copyURL() } rootView.canCopyURL = { [weak self] in @@ -126,15 +142,17 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } // The Peek's buttons, and a click beside it, close or expand it // (add-peek design D4). - let peekControls = NSHostingView(rootView: PeekControlsView(confirm: model.peekConfirm, actions: self)) + let peekControls = NSHostingView(rootView: PeekControlsView(confirm: model.peekConfirm, model: model, actions: self)) // Near the window's top edge the title bar's safe area pushed the // buttons about 10 pt down from Arc's place. peekControls.safeAreaRegions = [] peekControls.sizingOptions = [] rootView.card.peekControls = peekControls - rootView.card.peekClickCatcher.onClick = { [weak self] in self?.closePeek() } - rootView.card.onConfirmDirectionChange = { [weak model] towardPeek in - model?.peekConfirm.growsTowardPeek = towardPeek + for card in [rootView.card, rootView.secondCard] { + card.peekClickCatcher.onClick = { [weak self] in self?.closePeek() } + card.onConfirmDirectionChange = { [weak model] towardPeek in + model?.peekConfirm.growsTowardPeek = towardPeek + } } WindowStyle.apply(to: window, profileKind: browser.profileKind) window.contentView = rootView @@ -249,8 +267,10 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } else if rootView.findHost != nil { rootView.findHost = nil } - // The link status. - reportStatus(model.commandBar == nil ? model.statusText : nil, commandBarOpen: model.commandBar != nil) + settleSplitRatio() + // The link status, worded with the modifier keys held (add-split-view + // D13a). + reportStatus(model.commandBar == nil ? model.wordedStatus : nil, commandBarOpen: model.commandBar != nil) // Toasts. if let toast = model.toast { rootView.toastHost = NSHostingView( @@ -258,19 +278,33 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } else if rootView.toastHost != nil { rootView.toastHost = nil } - // The active tab's infobars and crashed page. - let tab = model.activeTab - if let tab, !tab.infobars.isEmpty { - rootView.card.infobarView = NSHostingView.edgeToEdge(rootView: InfobarsView(tab: tab, actions: self)) - } else if rootView.card.infobarView != nil { - rootView.card.infobarView = nil - } - if tab?.isCrashed == true { - if rootView.card.crashedView == nil { - rootView.card.crashedView = NSHostingView.edgeToEdge(rootView: CrashedPageView(actions: self)) + // The active tab's infobars and crashed page, or each pane's while + // split (add-split-view D3). + let split = model.shownSplit + let paneTabs: [(PageCardView, (any ClairTab)?)] = + split.map { split in + [rootView.card, rootView.secondCard].enumerated().map { index, card in + let paneID = split.paneIDs[index] + let shown = model.shownPeek?.parentID == paneID ? model.peekTab : model.allTabs.first { $0.tabID == paneID } + return (card, shown) + } + } ?? [(rootView.card, model.activeTab), (rootView.secondCard, nil)] + for (card, tab) in paneTabs { + if let tab, !tab.infobars.isEmpty { + card.infobarView = NSHostingView.edgeToEdge(rootView: InfobarsView(tab: tab, actions: self)) + } else if card.infobarView != nil { + card.infobarView = nil + } + if let tab, tab.isCrashed { + let crashed = CrashedPageView(tabID: tab.tabID, actions: self) + if let host = card.crashedView as? NSHostingView { + if host.rootView.tabID != tab.tabID { host.rootView = crashed } + } else { + card.crashedView = NSHostingView.edgeToEdge(rootView: crashed) + } + } else if card.crashedView != nil { + card.crashedView = nil } - } else if rootView.card.crashedView != nil { - rootView.card.crashedView = nil } } @@ -296,9 +330,13 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over let capsule = CapsuleText(text: text, identifier: "clair.status") if let host = rootView.statusHost as? SelfSizingHostingView { host.rootView = capsule + // New text, such as the words Option or Shift add, takes a new width, + // and the pane holding the link may have changed. + rootView.needsLayout = true fade(host, to: 1) } else { let host = SelfSizingHostingView(rootView: capsule) + host.tracksWidth = true host.alphaValue = 0 rootView.statusHost = host fade(host, to: 1) @@ -337,6 +375,9 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over for observer in observers { NotificationCenter.default.removeObserver(observer) } + if let flagsMonitor { + NSEvent.removeMonitor(flagsMonitor) + } } // MARK: Dragging the window from the top of the page @@ -546,25 +587,34 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over guard spaceID == model.shownSpaceID, model.showsPins else { return } pinsChanged() tabsChanged() + finishPendingPinSplit() } func favoritesDidChange(_ profileID: ProfileID) { guard profileID == model.profileID, model.showsPins else { return } pinsChanged() tabsChanged() + finishPendingPinSplit() } /// The window's rows were added, closed or moved, or it shows another /// Space. private func tabsChanged() { - // A Peek opened, closed or expanded. + // A Peek opened, closed or expanded, or a split changed. showPages() + devToolsDidChange() model.reloadStop.loadingChanged(model.activeTab?.isLoading == true) rootView.loadingIndicator.loadingChanged(model.activeTab?.isLoading == true) } private func tabChanged(_ tab: any ClairTab) { + let split = model.shownSplit model.updateTab(tab) + // A split made, changed or ended shows its panes (add-split-view D3). + if model.shownSplit != split { + showPages() + devToolsDidChange() + } if tab.tabID == model.activeTabID { model.reloadStop.loadingChanged(tab.isLoading) rootView.loadingIndicator.loadingChanged(tab.isLoading) @@ -625,7 +675,12 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } showPages() devToolsDidChange() - offerCommandBarIfNew() + if opensCommandBarOnNewPane, switched, model.activeTab?.isNewTabPage != false { + opensCommandBarOnNewPane = false + showCommandBar(mode: .currentTab) + } else { + offerCommandBarIfNew() + } } /// What the card shows: the active tab's page, or a Peek over its parent's @@ -639,10 +694,44 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over if model.shownPeek != shown { model.shownPeek = shown } - if let shown { - rootView.card.show(page: browser?.pageView(for: shown.peekID), behind: browser?.pageView(for: shown.parentID)) + if let split = model.shownSplit { + // add-split-view D3: each pane its tab's page, a Peek over its + // parent's. The card losing a page goes first, so the one taking it + // keeps it. + let cards = [rootView.card, rootView.secondCard] + let pages = split.paneIDs.map { paneID -> (NSView?, NSView?) in + if let shown, shown.parentID == paneID { + return (browser?.pageView(for: shown.peekID), browser?.pageView(for: paneID)) + } + return (browser?.pageView(for: paneID), nil) + } + // A card taking a page the other card holds goes first, so the page + // moves once, rather than leaving its card and coming back. + let takes = cards.indices.map { index in + [pages[index].0, pages[index].1].contains { $0?.isDescendant(of: cards[1 - index]) == true } + } + for index in takes[1] && !takes[0] ? [1, 0] : [0, 1] { + cards[index].show(page: pages[index].0, behind: pages[index].1) + } + // The Peek's buttons go with its card. + let peeking = cards.first { $0.isPeeking } ?? rootView.card + if let controls = rootView.card.peekControls ?? rootView.secondCard.peekControls, controls.superview !== peeking { + cards.forEach { if $0 !== peeking { $0.peekControls = nil } } + peeking.peekControls = controls + peeking.peekToolbar = peekToolbarHost + } } else { - rootView.card.show(page: browser?.pageView(for: model.activeTabID), behind: nil) + rootView.secondCard.show(page: nil) + if let controls = rootView.secondCard.peekControls { + rootView.secondCard.peekControls = nil + rootView.card.peekControls = controls + rootView.card.peekToolbar = peekToolbarHost + } + if let shown { + rootView.card.show(page: browser?.pageView(for: shown.peekID), behind: browser?.pageView(for: shown.parentID)) + } else { + rootView.card.show(page: browser?.pageView(for: model.activeTabID), behind: nil) + } } rootView.needsLayout = true } @@ -664,7 +753,11 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over func devToolsDidChange() { guard let browser else { return } - rootView.card.show(devTools: browser.devToolsView, layout: browser.devToolsLayout) + // The active tab's DevTools docks in its pane (add-split-view D3). + let holder = rootView.card(showing: model.activeTabID) + let other = holder === rootView.card ? rootView.secondCard : rootView.card + other.show(devTools: nil, layout: DevToolsLayout(dockSide: .none, pageBounds: .zero, hidesPage: false)) + holder.show(devTools: browser.devToolsView, layout: browser.devToolsLayout) } func showCommandBar(mode: CommandBarMode) { @@ -731,8 +824,12 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over model.find?.result = result } - func statusTextDidChange(_ text: String?) { + func statusTextDidChange(_ text: String?, isLink: Bool, tab tabID: TabID) { + model.opensPeekOnShiftClick = peekPreference.isEnabled model.statusText = text + model.statusIsLink = isLink && text != nil + model.statusTabID = tabID + model.statusModifiers = NSEvent.modifierFlags } /// Waits out a toast's time; tests replace it so they don't depend on the @@ -792,8 +889,9 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over controls[control] = sidebarHost.convert(frame, to: nil) } var toolbarControls: [AnchorControl: CGRect] = [:] + let reportingHost = toolbarFramesPane == 1 ? secondToolbarHost : toolbarHost for (control, frame) in toolbarFrames { - toolbarControls[control] = toolbarHost.convert(frame, to: nil) + toolbarControls[control] = reportingHost.convert(frame, to: nil) } return AnchorResolver( sidebarInPlace: model.sidebar.isShownInPlace && !model.isPageFullscreen && !isWindowFullscreen, @@ -869,6 +967,7 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over closeExtensionPopup() dialogs.cancelAll() rootView.card.show(page: nil) + rootView.secondCard.show(page: nil) rootView.card.showStill(false, image: nil) removeSafetyNet() stopCommandBarKeyMonitor() @@ -971,6 +1070,14 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } } + func reloadOrStop(pane tabID: TabID) { + // An unfocused pane's button follows its own page; the engine's active + // tab is the pane at once, before the window hears of it. + let isLoading = model.allTabs.first { $0.tabID == tabID }?.isLoading == true + focusPane(tabID) + if isLoading { browser?.stop() } else { browser?.reload() } + } + func reloadButtonHovered(_ hovering: Bool) { if hovering { model.reloadStop.pointerEntered() @@ -984,7 +1091,12 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } func copyURL() { - guard let tab = model.activeTab, !tab.isNewTabPage, let link = TabListLogic.link(of: tab) else { return } + copyURL(of: model.activeTabID) + } + + func copyURL(of tabID: TabID) { + let tab = tabID == model.activeTabID ? model.activeTab : model.allTabs.first { $0.tabID == tabID } + guard let tab, !tab.isNewTabPage, let link = TabListLogic.link(of: tab) else { return } copyToPasteboard(link) // Arc's popup, with a share button for the page. model.notice.show( @@ -1055,7 +1167,11 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over controlFrames = frames } - func toolbarControlFramesChanged(_ frames: [AnchorControl: CGRect]) { + func toolbarControlFramesChanged(_ frames: [AnchorControl: CGRect], pane: Int) { + // The focused pane's header holds the bubbles' controls. + let focused = model.shownSplit?.focusedIndex ?? 0 + guard pane == focused else { return } + toolbarFramesPane = pane toolbarFrames = frames } @@ -1254,11 +1370,13 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over browser?.stopFinding() } - func infobar(_ infobarID: Int, didChoose action: InfobarAction) { - browser?.infobar(infobarID, tab: model.activeTabID, didChoose: action) + func infobar(_ infobarID: Int, of tabID: TabID, didChoose action: InfobarAction) { + browser?.infobar(infobarID, tab: tabID, didChoose: action) } - func reloadCrashedPage() { + func reloadCrashedPage(of tabID: TabID) { + // The engine reloads its active tab, which the pane becomes at once. + focusPane(tabID) browser?.reload() } } diff --git a/native/ClairUI/BrowserWindowModel.swift b/native/ClairUI/BrowserWindowModel.swift index c0646c3..62c8add 100644 --- a/native/ClairUI/BrowserWindowModel.swift +++ b/native/ClairUI/BrowserWindowModel.swift @@ -36,6 +36,10 @@ final class BrowserWindowModel { private(set) var pinnedItems: [any ClairPinnedItem] = [] /// Every pinned tab of the shown Space, its folders' included, in order. private(set) var pins: [any ClairPin] = [] + /// The profile's favorites and favorited splits, as the grid's tiles + /// (add-split-view D10). + private(set) var favoriteItems: [any ClairPinnedItem] = [] + /// Every favorite, a favorited split's two included. private(set) var favorites: [any ClairPin] = [] /// The latest snapshot of each open pin's tab and its Peek, by tab ID. private(set) var pinTabs: [TabID: any ClairTab] = [:] @@ -70,6 +74,26 @@ final class BrowserWindowModel { } } + /// The icons of a dragged row or tile: both pages' for a split, in pane + /// order, as its favorite tile shows them. + func icons(of item: SidebarDragItem) -> [NSImage?] { + switch item { + case .tab(let tabID): + if let tab = allTabs.first(where: { $0.tabID == tabID }), + let (leading, trailing) = TabListLogic.panes(of: tab, in: allTabs) + { + return [leading.favicon, trailing.favicon] + } + case .pin(let pinID): + if let split = PinsLogic.split(containing: pinID, in: pinnedItems + favoriteItems) { + return split.pins.map { PinsLogic.icon(of: $0, tab: tab(ofPin: $0)) } + } + case .folder: + break + } + return [icon(of: item)] + } + /// The pin `tabID` is bound to, among the window's. func pin(ofTab tabID: TabID) -> (any ClairPin)? { guard tabID != ClairTabIDNone else { return nil } @@ -120,6 +144,15 @@ final class BrowserWindowModel { /// The row or tile highlighted among every tab the window lists. var highlightedTab: TabID { highlightedRow(in: allTabs) } + /// The tab the main menu's pin commands act on: the still's, or the + /// active tab, or its parent while a Peek shows. A split's trailing pane + /// is itself, not its row's leading pane, as it has a pin of its own. + var commandTab: TabID { + if isShowingStill { return stillTabID } + if let active = activeTab, active.peekParentID != ClairTabIDNone { return active.peekParentID } + return activeTabID + } + /// The pin or favorite whose row or tile is highlighted, if one is. var activePin: (any ClairPin)? { pin(ofTab: highlightedTab) } @@ -136,8 +169,47 @@ final class BrowserWindowModel { // --- where the browser controls show (add-page-toolbar D1) --- /// The toolbar preference, as the window last read it. var showsToolbar = true - /// The panes the card shows: always one until split view. - var paneCount = 1 + /// The panes the card shows: two while the active tab, or the active + /// Peek's parent, is in a split (add-split-view D3). + var paneCount: Int { shownSplit == nil ? 1 : 2 } + + /// The split the window shows, if any (add-split-view D2). + var shownSplit: ShownSplit? { + isShowingStill ? nil : SplitLogic.shownSplit(activeTabID: activeTabID, in: allTabs) + } + /// The pane under the pointer, whose header shows all its controls + /// (add-split-view spec, "Controls of the other pane"). + var hoveredPane: Int? + /// The ratio while the divider is dragged, before the engine has it, and + /// the panes of the split it's dragged in. + var liveSplitRatio: Double? + var liveSplitPanes: [TabID]? + /// The dragged ratio of `split`, only while it's the split dragged. + func liveRatio(of split: ShownSplit) -> Double? { + liveSplitPanes == split.paneIDs ? liveSplitRatio : nil + } + /// The modifier keys held while the link status shows (D13a). + var statusModifiers: NSEvent.ModifierFlags = [] + /// A tab dragged over the page, and the zone under it (D8). + var pageDrop: SplitLogic.DropZone? + + /// The tab a pane shows: a split's pane's, or the toolbar's tab outside a + /// split. + func paneTab(_ index: Int) -> (any ClairTab)? { + guard let split = shownSplit else { return index == 0 ? toolbarTab : nil } + return allTabs.first { $0.tabID == split.paneIDs[index] } + } + + /// What the link status reads, worded with the modifier keys held. + var wordedStatus: String? { + guard let statusText else { return nil } + guard statusIsLink else { return statusText } + let inPeek = allTabs.first { $0.tabID == statusTabID }.map(TabListLogic.isPeek) ?? false + return SplitLogic.linkStatus( + url: statusText, modifiers: statusModifiers, opensPeekOnShiftClick: opensPeekOnShiftClick, inPeek: inPeek) + } + /// The Peek preference, as the window last read it. + var opensPeekOnShiftClick = true var headerPolicy: PageHeaderPolicy { PageHeaderPolicy(showsToolbar: showsToolbar, paneCount: paneCount) } /// Whether the page shows its header, the toolbar. Views read this, not /// the preference. @@ -212,6 +284,10 @@ final class BrowserWindowModel { /// Bumped when Cmd+F asks for the find field again while it shows. var findFocusRequest = 0 var statusText: String? + /// Whether `statusText` is a link's URL, which the capsule words with the + /// modifier keys held, and the page it's in (add-split-view D13a). + var statusIsLink = false + var statusTabID: TabID = ClairTabIDNone var toast: Toast? var exclusiveAccessNotice: String? /// The popup in the card's top-trailing corner (design D18). @@ -268,13 +344,15 @@ final class BrowserWindowModel { guard showsPins else { pinnedItems = [] pins = [] + favoriteItems = [] favorites = [] pinTabs = [:] return } pinnedItems = spaces.pinnedItems(inSpace: shownSpaceID) pins = PinsLogic.allPins(pinnedItems) - favorites = profileID.map { spaces.favorites(ofProfile: $0) } ?? [] + favoriteItems = profileID.map { spaces.favoriteItems(ofProfile: $0) } ?? [] + favorites = PinsLogic.allPins(favoriteItems) var latest: [TabID: any ClairTab] = [:] for pin in pins + favorites { for tab in pin.tabs { diff --git a/native/ClairUI/FavoritesDropArea.swift b/native/ClairUI/FavoritesDropArea.swift index dc73964..0218c9a 100644 --- a/native/ClairUI/FavoritesDropArea.swift +++ b/native/ClairUI/FavoritesDropArea.swift @@ -15,8 +15,8 @@ struct FavoritesDropArea: NSViewRepresentable { let slot: (CGPoint) -> Int /// The size of a tile in that slot. let tileSize: (Int) -> CGSize - /// The icon of what's dragged. - let icon: (SidebarDragItem) -> NSImage? + /// The icons of what's dragged: a split's pages', in pane order. + let icons: (SidebarDragItem) -> [NSImage?] /// The slot the drag is over, or nil once it leaves or drops. let onTarget: (Int?) -> Void let onDrop: (SidebarDragItem, Int) -> Void @@ -100,7 +100,7 @@ final class FavoritesDropView: NSView { private func tileImage(for item: SidebarDragItem, size: CGSize) -> NSImage? { if let tile, tile.size == size { return tile.image } guard let area, size.width > 0, size.height > 0 else { return nil } - let renderer = ImageRenderer(content: DraggedTile(icon: area.icon(item), size: size, colorScheme: colorScheme)) + let renderer = ImageRenderer(content: DraggedTile(icons: area.icons(item), size: size, colorScheme: colorScheme)) renderer.scale = window?.backingScaleFactor ?? 2 guard let image = renderer.nsImage else { return nil } tile = (size, image) @@ -145,9 +145,10 @@ final class FavoritesDropView: NSView { } /// The tile a dragged row or tile shows over the favorites: a selected tile -/// with its icon, lifted. +/// with its icon, lifted; a split's, a segment per page with a thin line +/// between them, as its tile (add-split-view, "The favorite split tile"). struct DraggedTile: View { - let icon: NSImage? + let icons: [NSImage?] let size: CGSize let colorScheme: ColorScheme @@ -156,7 +157,18 @@ struct DraggedTile: View { RoundedRectangle(cornerRadius: FavoriteTile.cornerRadius, style: .continuous) .fill(PinFill.tile(colorScheme, hovered: false, selected: true)) .shadow(color: .black.opacity(0.18), radius: 3, y: 1) - PinIcon(icon: icon, size: FavoriteTile.iconSize) + HStack(spacing: 0) { + ForEach(Array(icons.enumerated()), id: \.offset) { index, icon in + if index > 0 { + Rectangle() + .fill(PinFill.divider) + .frame(width: 1) + .padding(.vertical, 10) + } + PinIcon(icon: icon, size: FavoriteTile.iconSize) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } } .frame(width: size.width, height: size.height) // Room for the shadow. diff --git a/native/ClairUI/HistoryMenu.swift b/native/ClairUI/HistoryMenu.swift index 55ccb03..91d5e2b 100644 --- a/native/ClairUI/HistoryMenu.swift +++ b/native/ClairUI/HistoryMenu.swift @@ -51,13 +51,15 @@ final class HistoryMenuBuilder: NSObject, ClairHistoryMenuDelegate, NSMenuDelega let item = NSMenuItem(title: page.title, action: #selector(choose(_:)), keyEquivalent: "") item.target = self item.tag = page.itemID - item.image = Self.icon(page.icon) + item.setFavicon(page.icon) item.toolTip = page.url?.absoluteString menu.addItem(item) } } - private static func icon(_ favicon: NSImage?) -> NSImage { + /// A favicon at a menu item's size, or the placeholder; the split menus + /// use it too. + static func icon(_ favicon: NSImage?) -> NSImage { guard let favicon, let copy = favicon.copy() as? NSImage else { return placeholderIcon } copy.size = iconSize return copy @@ -77,7 +79,7 @@ final class HistoryMenuBuilder: NSObject, ClairHistoryMenuDelegate, NSMenuDelega // A favicon arrived: update the open menu in place. for (item, page) in zip(self.menu.items, pages) { item.title = page.title - item.image = Self.icon(page.icon) + item.setFavicon(page.icon) } } else { rebuild(pages) diff --git a/native/ClairUI/NativeLayer.swift b/native/ClairUI/NativeLayer.swift index d8572b2..a9927c6 100644 --- a/native/ClairUI/NativeLayer.swift +++ b/native/ClairUI/NativeLayer.swift @@ -39,6 +39,8 @@ final class NativeLayer { /// Clair's items in the Tab and View menus (add-pinned-tabs-and-favorites /// D11). private(set) var pinsMenu: PinsMenu? + /// Split view's menu bar items (add-split-view D9). + private(set) var splitMenu: SplitMenu? /// View › Hide Toolbar's target (add-page-toolbar D8). let toolbarMenu = ToolbarMenuTarget() @@ -78,6 +80,9 @@ final class NativeLayer { let pinsMenu = PinsMenu() pinsMenu.install(in: NSApp.mainMenu) self.pinsMenu = pinsMenu + let splitMenu = SplitMenu() + splitMenu.install(in: NSApp.mainMenu) + self.splitMenu = splitMenu let updates = UpdateController(host: host, configuration: .current) updates.start() diff --git a/native/ClairUI/OverlayViews.swift b/native/ClairUI/OverlayViews.swift index 04ad4ec..4f460f8 100644 --- a/native/ClairUI/OverlayViews.swift +++ b/native/ClairUI/OverlayViews.swift @@ -11,8 +11,11 @@ import SwiftUI protocol OverlayActions: AnyObject { func find(_ text: String, forward: Bool) func closeFind() - func infobar(_ infobarID: Int, didChoose action: InfobarAction) - func reloadCrashedPage() + /// An infobar's button, for the infobar of `tabID`, which may be an + /// unfocused pane's. + func infobar(_ infobarID: Int, of tabID: TabID, didChoose action: InfobarAction) + /// Reloads `tabID`'s crashed page, which may be an unfocused pane's. + func reloadCrashedPage(of tabID: TabID) } /// The command bar (design D11): a field and up to five rows, floating over @@ -432,18 +435,20 @@ struct InfobarsView: View { } Text(infobar.message).lineLimit(2) if let link = infobar.linkText { - Button(link) { actions?.infobar(infobar.infobarID, didChoose: .link) } + Button(link) { actions?.infobar(infobar.infobarID, of: tab.tabID, didChoose: .link) } .buttonStyle(.link) } Spacer(minLength: 0) if let cancel = infobar.cancelButtonLabel { - Button(cancel) { actions?.infobar(infobar.infobarID, didChoose: .cancel) } + Button(cancel) { actions?.infobar(infobar.infobarID, of: tab.tabID, didChoose: .cancel) } } if let ok = infobar.okButtonLabel { - Button(ok) { actions?.infobar(infobar.infobarID, didChoose: .OK) } + Button(ok) { actions?.infobar(infobar.infobarID, of: tab.tabID, didChoose: .OK) } .keyboardShortcut(.defaultAction) } - Button { actions?.infobar(infobar.infobarID, didChoose: .dismiss) } label: { Image(systemName: "xmark") } + Button { actions?.infobar(infobar.infobarID, of: tab.tabID, didChoose: .dismiss) } label: { + Image(systemName: "xmark") + } .buttonStyle(.plain) .tooltip("Dismiss") .accessibilityLabel("Dismiss") @@ -461,6 +466,8 @@ struct InfobarsView: View { /// The card when the active tab's page crashed (design D5). struct CrashedPageView: View { + /// The tab whose page crashed: the card's pane's. + let tabID: TabID weak var actions: (any OverlayActions)? var body: some View { @@ -470,7 +477,7 @@ struct CrashedPageView: View { .foregroundStyle(.secondary) Text("This page crashed").font(.title2.weight(.semibold)) Text("Something went wrong while showing this page.").foregroundStyle(.secondary) - Button("Reload") { actions?.reloadCrashedPage() } + Button("Reload") { actions?.reloadCrashedPage(of: tabID) } .keyboardShortcut(.defaultAction) .accessibilityIdentifier("clair.crashedReload") } diff --git a/native/ClairUI/PageCardView.swift b/native/ClairUI/PageCardView.swift index d230dcd..307b463 100644 --- a/native/ClairUI/PageCardView.swift +++ b/native/ClairUI/PageCardView.swift @@ -82,6 +82,12 @@ final class PageCardView: NSView { var contentTop: CGFloat { showsToolbar && !isBare ? ToolbarArrangement.height : 0 } /// The Peek's buttons, beside its top-trailing corner. + /// How many buttons the Peek's column holds: Close, Expand and, outside a + /// split, Open in Split View. + var peekButtonCount = 3 { + didSet { if peekButtonCount != oldValue { needsLayout = true } } + } + var peekControls: NSView? { didSet { oldValue?.removeFromSuperview() @@ -101,6 +107,25 @@ final class PageCardView: NSView { /// Whether a Peek shows over its parent. var isPeeking: Bool { parentPageView != nil } + // Split view (add-split-view design D3, D11). + /// Where the Peek is centred, in the card's coordinates: the whole page + /// area while the card is one pane of a split, beyond the card itself. + var peekArea: CGRect? { + didSet { + if peekArea != oldValue { needsLayout = true } + } + } + /// The 2 pt ring of the focused pane, in the accent colour. + var showsFocusRing = false { + didSet { + if showsFocusRing != oldValue { updateFocusRing() } + } + } + /// Called as the pointer enters (true) or leaves the card, for the other + /// pane's header. + var onHover: ((Bool) -> Void)? + private var hoverArea: NSTrackingArea? + /// The view that holds the active page, its DevTools and infobars, and /// where Chromium's tab-modal dialogs centre: the Peek's container while a /// Peek shows. @@ -142,6 +167,16 @@ final class PageCardView: NSView { /// Where the shown Peek grew from, which it shrinks back to. private var peekOrigin: CGPoint? + /// The pane the card shows while split, for its accessibility identifier + /// (add-split-view D13): `clair.pane.N`, or `clair.card` outside a split. + var paneIndex: Int? { + didSet { + if paneIndex != oldValue { + container.setAccessibilityIdentifier(paneIndex.map { "clair.pane.\($0)" } ?? "clair.card") + } + } + } + override init(frame: NSRect) { super.init(frame: frame) wantsLayer = true @@ -201,6 +236,45 @@ final class PageCardView: NSView { override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() updatePeekBacking() + updateFocusRing() + } + + private func updateFocusRing() { + effectiveAppearance.performAsCurrentDrawingAppearance { + container.layer?.borderColor = NSColor.controlAccentColor.cgColor + } + container.layer?.borderWidth = showsFocusRing && !isBare ? 2 : 0 + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let hoverArea { removeTrackingArea(hoverArea) } + let area = NSTrackingArea( + rect: .zero, options: [.mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self) + addTrackingArea(area) + hoverArea = area + } + + override func mouseEntered(with event: NSEvent) { + onHover?(true) + } + + override func mouseExited(with event: NSEvent) { + onHover?(false) + } + + /// The Peek and its buttons take clicks beyond the card while it's a + /// pane of a split, where they show over the page area (D11). + override func hitTest(_ point: NSPoint) -> NSView? { + if isPeeking, peekArea != nil, let superview { + let local = convert(point, from: superview) + for view in [peekControls, peekCard].compactMap({ $0 }) where !view.isHidden { + if view.frame.contains(local), let hit = view.hitTest(convert(local, to: view.superview)) { + return hit + } + } + } + return super.hitTest(point) } /// The Peek's card is the page's background colour under the page, so in @@ -237,6 +311,7 @@ final class PageCardView: NSView { } private func updateAppearance() { + updateFocusRing() container.layer?.cornerRadius = isBare ? 0 : Self.cornerRadius layer?.shadowOpacity = isBare ? 0 : 0.18 layer?.shadowRadius = 6 @@ -276,8 +351,12 @@ final class PageCardView: NSView { .none } - if oldPage !== view, oldPage !== parent { oldPage?.removeFromSuperview() } - if oldParent !== view, oldParent !== parent { oldParent?.removeFromSuperview() } + // A page another card has taken since, as when a split's panes swap, is + // that card's now (add-split-view D3). + if oldPage !== view, oldPage !== parent, oldPage?.isDescendant(of: self) == true { oldPage?.removeFromSuperview() } + if oldParent !== view, oldParent !== parent, oldParent?.isDescendant(of: self) == true { + oldParent?.removeFromSuperview() + } pageView = view parentPageView = parent if let parent, parent.superview !== pageHolder { @@ -350,7 +429,9 @@ final class PageCardView: NSView { /// Shows the active tab's docked DevTools, or none. func show(devTools view: NSView?, layout: DevToolsLayout) { if view !== devToolsView { - devToolsView?.removeFromSuperview() + if devToolsView?.isDescendant(of: self) == true { + devToolsView?.removeFromSuperview() + } devToolsView = view if let view { let surface = activeContainer @@ -382,18 +463,18 @@ final class PageCardView: NSView { } wash.frame = container.bounds peekClickCatcher.frame = container.bounds - let peek = PeekLayout.peekFrame(in: bounds) + let peek = PeekLayout.peekFrame(in: peekArea ?? bounds) peekCard.frame = peek peekContainer.frame = peekCard.bounds peekCard.layer?.shadowPath = CGPath( roundedRect: peekCard.bounds, cornerWidth: PeekLayout.cornerRadius, cornerHeight: PeekLayout.cornerRadius, transform: nil) if let peekControls { - let buttons = PeekLayout.buttonFrames(beside: peek) + let buttons = PeekLayout.buttonFrames(beside: peek, count: peekButtonCount) let first = buttons[0] // Room for the Confirm pill beside the buttons, or, in a window too // narrow for it there, over the Peek. - let room = bounds.maxX - first.minX + let room = (peekArea ?? bounds).maxX - first.minX let towardPeek = room < PeekLayout.confirmWidth let height = buttons[buttons.count - 1].maxY - first.minY peekControls.frame = diff --git a/native/ClairUI/PageToolbar.swift b/native/ClairUI/PageToolbar.swift index de2eda8..e6f3e78 100644 --- a/native/ClairUI/PageToolbar.swift +++ b/native/ClairUI/PageToolbar.swift @@ -6,22 +6,70 @@ import AppKit import ClairHost import SwiftUI -/// Which of the toolbar's groups a page header shows (add-page-toolbar D4). -/// Split view will add its pane variants here. -enum PageHeaderContent { - /// The tab's toolbar: everything. +/// Which of the toolbar's groups a page header shows (add-page-toolbar D4, +/// add-split-view D9). +enum PageHeaderContent: Equatable { + /// The tab's toolbar: everything, with the split button at the trailing + /// end. case tab /// A Peek's: back, forward, reload, the link icon and the host. case peek + /// A split's pane's header: the sidebar toggle in the leading pane, back, + /// forward, the link icon, the host and ×; with `expanded`, while the pane + /// is focused or under the pointer, also reload, the split button, site + /// controls, pinned extensions and indicators. + case pane(leading: Bool, expanded: Bool) /// The leading controls that always show before reload. - var leadingCount: Int { self == .tab ? 3 : 2 } - var showsSidebarToggle: Bool { self == .tab } - var showsSiteControls: Bool { self == .tab } - var showsExtensions: Bool { self == .tab } - var showsIndicators: Bool { self == .tab } + var leadingCount: Int { + switch self { + case .tab: 3 + case .peek: 2 + case .pane(let leading, _): leading ? 3 : 2 + } + } + var showsSidebarToggle: Bool { leadingCount == 3 } + var showsReload: Bool { + if case .pane(_, let expanded) = self { return expanded } + return true + } + private var showsAll: Bool { + switch self { + case .tab: true + case .peek: false + case .pane(_, let expanded): expanded + } + } + var showsSiteControls: Bool { showsAll } + var showsExtensions: Bool { showsAll } + var showsIndicators: Bool { showsAll } + var showsSplitButton: Bool { showsAll } + var showsClose: Bool { + if case .pane = self { return true } + return false + } + /// The trailing controls that always show, from the trailing edge: ×, the + /// split button and the site controls, as each shows. + var trailingFixedCount: Int { + (showsClose ? 1 : 0) + (showsSplitButton ? 1 : 0) + (showsSiteControls ? 1 : 0) + } + + var identifier: String { + switch self { + case .tab: "clair.toolbar" + case .peek: "clair.peekToolbar" + case .pane(let leading, _): "clair.paneToolbar.\(leading ? 0 : 1)" + } + } +} - var identifier: String { self == .tab ? "clair.toolbar" : "clair.peekToolbar" } +/// Which page header a toolbar host shows: a page's, which is a split's pane +/// while split, or a Peek's. +enum PageHeaderSlot: Equatable { + /// The card of a split's pane by its index; the first is the single + /// page's card outside a split. + case pane(Int) + case peek } /// The toolbar's coordinate space, which its hosting view's is. @@ -48,7 +96,7 @@ enum ToolbarFill { /// host, offers Copy URL and Hide Toolbar. struct PageToolbar: View { let model: BrowserWindowModel - let content: PageHeaderContent + let slot: PageHeaderSlot weak var actions: (any SidebarActions)? @State private var width: CGFloat = 0 @@ -56,11 +104,60 @@ struct PageToolbar: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.accessibilityReduceMotion) private var reduceMotion + /// What the toolbar shows: a page's toolbar, a split's pane's header, + /// expanded while focused or under the pointer, or a Peek's. + var content: PageHeaderContent { + switch slot { + case .peek: return .peek + case .pane(let index): + guard let split = model.shownSplit else { return .tab } + return .pane(leading: index == 0, expanded: split.focusedIndex == index || model.hoveredPane == index) + } + } + + /// The pane's tab while split, or nil. + private var paneTabID: TabID? { + guard case .pane(let index) = slot, let split = model.shownSplit else { return nil } + return split.paneIDs[index] + } + + /// Whether the pane isn't the focused one: its controls focus it first. + private var isOtherPane: Bool { + guard case .pane(let index) = slot, let split = model.shownSplit else { return false } + return split.focusedIndex != index + } + + /// Runs `action` on the pane's tab: the pane is focused first. + private func onPane(_ action: @escaping () -> Void) -> () -> Void { + { [weak actions] in + if isOtherPane, let paneTabID { actions?.focusPane(paneTabID) } + action() + } + } + + /// Copies the URL of the pane's tab, or the active tab's. + private func copyURL() { + if let paneTabID { actions?.copyURL(of: paneTabID) } else { actions?.copyURL() } + } + + /// The pane's history menu, which focuses it first so the menu and what + /// it navigates are the pane's. + private func historyMenu(_ direction: HistoryDirection) -> HistoryMenuBuilder? { + onPane {}() + return actions?.historyMenu(direction) + } + /// The tab whose state the toolbar shows: the parent page's behind a Peek, - /// or the Peek's own. - private var tab: (any ClairTab)? { content == .tab ? model.toolbarTab : model.peekTab } + /// or the Peek's own, or the pane's. + private var tab: (any ClairTab)? { + switch slot { + case .peek: return model.peekTab + case .pane(let index): return model.shownSplit == nil ? model.toolbarTab : model.paneTab(index) + } + } var body: some View { + let content = self.content let tab = self.tab let display = URLDisplay.text(for: tab) let hostText = display ?? URLDisplay.placeholder @@ -69,13 +166,18 @@ struct PageToolbar: View { content.showsIndicators ? URLField.indicatorSymbols.filter { tab?.indicators.contains($0.0) == true } : [] let extensions = content.showsExtensions ? model.pinnedExtensionActions : [] let layoutContent = ToolbarArrangement.Content( - leadingCount: content.leadingCount, hasLink: display != nil, hasNotSecure: notSecure, - hostWidth: ToolbarArrangement.hostWidth(for: hostText), - trailingFixedCount: content.showsSiteControls ? 1 : 0, extensionCount: extensions.count, + leadingCount: content.leadingCount, hasReload: content.showsReload, hasLink: display != nil, + hasNotSecure: notSecure, hostWidth: ToolbarArrangement.hostWidth(for: hostText), + trailingFixedCount: content.trailingFixedCount, extensionCount: extensions.count, indicatorCount: indicators.count) let arrangement = ToolbarArrangement(width: width, content: layoutContent) + // The trailing slots, from the edge: ×, then the split button, then the + // site controls (add-split-view D9). + let closeSlot = 0 + let splitSlot = content.showsClose ? 1 : 0 + let siteSlot = splitSlot + (content.showsSplitButton ? 1 : 0) ToolbarLayout(content: layoutContent) { - leadingControls(tab: tab, arrangement: arrangement) + leadingControls(content: content, tab: tab, arrangement: arrangement) if arrangement.notSecure != nil { Image(systemName: "lock.slash.fill") .font(.system(size: 11)) @@ -92,7 +194,7 @@ struct PageToolbar: View { IconButton( systemImage: "link", help: "Copy URL", shortcut: ["⇧", "⌘", "C"], size: 22, height: IconButtonSize.toolbarHeight, glyphSize: IconButtonSize.toolbarLinkGlyph - ) { actions?.copyURL() } + ) { copyURL() } .accessibilityIdentifier("clair.copyURL") .toolbarRole(.link) } @@ -102,25 +204,44 @@ struct PageToolbar: View { systemImage: symbol, help: label, height: IconButtonSize.toolbarHeight, glyphSize: IconButtonSize.toolbarIndicatorGlyph, glyphWeight: .regular, foreground: .red ) { - actions?.showSiteControls(indicator: indicator) + onPane { actions?.showSiteControls(indicator: indicator) }() } .anchorFrame(.indicator(indicator.rawValue)) .toolbarRole(.indicator(index)) + .transition(.opacity) } ForEach(Array(extensions.enumerated()), id: \.element.extensionID) { index, action in if arrangement.extensions.indices.contains(index), arrangement.extensions[index] != nil { ToolbarExtensionButton( action: action, contextMenu: { actions?.contextMenu(forExtension: action.extensionID) } - ) { actions?.runExtension(action.extensionID, pinned: true) } + ) { onPane { actions?.runExtension(action.extensionID, pinned: true) }() } .anchorFrame(.extensionAction(action.extensionID)) .toolbarRole(.pinnedExtension(index)) + .transition(.opacity) } } if content.showsSiteControls { siteControls(enabled: tab != nil) - .toolbarRole(.trailingFixed(0)) + .toolbarRole(.trailingFixed(siteSlot)) + .transition(.opacity) + } + if content.showsSplitButton { + splitButton(tab: tab) + .toolbarRole(.trailingFixed(splitSlot)) + .transition(.opacity) + } + if content.showsClose, let paneTabID { + IconButton( + systemImage: "xmark", help: "Close tab", shortcut: ["⌘", "W"], height: IconButtonSize.toolbarHeight, + glyphSize: IconButtonSize.toolbarGlyph + ) { actions?.close(tab: paneTabID) } + .accessibilityIdentifier("clair.closePane") + .toolbarRole(.trailingFixed(closeSlot)) } } + // The other pane's controls fade in and out as the pointer comes and + // goes, as Arc's do (add-split-view, "Controls of the other pane"). + .animation(reduceMotion ? nil : .easeInOut(duration: 0.15), value: content) .frame(maxWidth: .infinity) .frame(height: ToolbarArrangement.height) .background { background } @@ -130,19 +251,47 @@ struct PageToolbar: View { .coordinateSpace(name: toolbarCoordinateSpace) .onPreferenceChange(AnchorFramesKey.self) { frames in MainActor.assumeIsolated { - if content == .tab { actions?.toolbarControlFramesChanged(frames) } + if case .pane(let index) = slot { + actions?.toolbarControlFramesChanged(frames, pane: index) + } } } .accessibilityElement(children: .contain) - .accessibilityLabel(content == .tab ? "Toolbar" : "Peek toolbar") + .accessibilityLabel(slot == .peek ? "Peek toolbar" : (content == .tab ? "Toolbar" : "Pane toolbar")) .accessibilityIdentifier(content.identifier) } + /// The split button: Split with Tab on a single page, the pane's moves in + /// a split (add-split-view D9). + private func splitButton(tab: (any ClairTab)?) -> some View { + let tabID = paneTabID ?? tab?.tabID ?? ClairTabIDNone + let entries = + paneTabID != nil + ? SplitLogic.paneMenu(isLeading: slot == .pane(0)) + : SplitLogic.singlePageMenu(shown: tabID, today: model.tabs) + let favicons = Dictionary(model.allTabs.map { ($0.tabID, $0) }, uniquingKeysWith: { first, _ in first }) + return SplitButton(entries: entries, icon: { favicons[$0]?.favicon }) { entry in + if isOtherPane { actions?.focusPane(tabID) } + switch entry { + case .tab(let other, _): actions?.split(tab: tabID, with: other, side: .trailing) + case .newTab: actions?.splitWithNewTab(tabID) + case .moveLeft, .moveRight: actions?.swapSplit(of: tabID) + case .separateTabs: actions?.separateSplit(of: tabID) + case .closeThisTab: actions?.close(tab: tabID) + case .heading, .separator: break + } + } + } + /// The sidebar toggle, back, forward and reload, at their slots. @ViewBuilder - private func leadingControls(tab: (any ClairTab)?, arrangement: ToolbarArrangement) -> some View { + private func leadingControls(content: PageHeaderContent, tab: (any ClairTab)?, arrangement: ToolbarArrangement) + -> some View + { + // An unfocused pane's button follows its own page (add-split-view D9). let reloadStop = model.reloadStop.mode - let isLoading = reloadStop.visible == .stop + let isLoading = isOtherPane ? tab?.isLoading == true : reloadStop.visible == .stop + let canReload = tab != nil && (isOtherPane || reloadStop.isEnabled) let canGoBack = tab?.canGoBack ?? false let canGoForward = tab?.canGoForward ?? false let first = content.showsSidebarToggle ? 1 : 0 @@ -160,27 +309,27 @@ struct PageToolbar: View { systemImage: "arrow.left", help: "Go back", shortcut: ["⌘", "["], isEnabled: canGoBack, height: IconButtonSize.toolbarHeight, glyphSize: IconButtonSize.toolbarGlyph ) { - actions?.goBack() + onPane { actions?.goBack() }() } - .overlay(HistoryButtonCatcher(isEnabled: canGoBack, makeMenu: { actions?.historyMenu(.back) })) + .overlay(HistoryButtonCatcher(isEnabled: canGoBack, makeMenu: { historyMenu(.back) })) .accessibilityIdentifier("clair.back") .toolbarRole(.leading(first)) IconButton( systemImage: "arrow.right", help: "Go forward", shortcut: ["⌘", "]"], isEnabled: canGoForward, height: IconButtonSize.toolbarHeight, glyphSize: IconButtonSize.toolbarGlyph ) { - actions?.goForward() + onPane { actions?.goForward() }() } - .overlay(HistoryButtonCatcher(isEnabled: canGoForward, makeMenu: { actions?.historyMenu(.forward) })) + .overlay(HistoryButtonCatcher(isEnabled: canGoForward, makeMenu: { historyMenu(.forward) })) .accessibilityIdentifier("clair.forward") .toolbarRole(.leading(first + 1)) if arrangement.reload != nil { IconButton( help: isLoading ? "Stop loading this page" : "Reload this page", - shortcut: isLoading ? ["esc"] : ["⌘", "R"], isEnabled: tab != nil && reloadStop.isEnabled, + shortcut: isLoading ? ["esc"] : ["⌘", "R"], isEnabled: canReload, height: IconButtonSize.toolbarHeight ) { - actions?.reloadOrStop() + if isOtherPane, let paneTabID { actions?.reloadOrStop(pane: paneTabID) } else { actions?.reloadOrStop() } } label: { ZStack { SymbolGlyph(systemImage: "arrow.clockwise", size: IconButtonSize.toolbarGlyph).opacity(isLoading ? 0 : 1) @@ -188,9 +337,12 @@ struct PageToolbar: View { } .animation(reduceMotion ? nil : .easeInOut(duration: 0.1), value: isLoading) } - .onHover { actions?.reloadButtonHovered($0) } + // The focused pane's Reload/Stop timing; an unfocused pane's follows + // its page. + .onHover { hovering in if !hovering || !isOtherPane { actions?.reloadButtonHovered(hovering) } } .accessibilityIdentifier("clair.reload") .toolbarRole(.reload) + .transition(.opacity) } } @@ -208,7 +360,7 @@ struct PageToolbar: View { ToolbarFill.hostHover(colorScheme).opacity(isHostHovered ? 1 : 0), in: .rect(cornerRadius: 6)) .contentShape(Rectangle()) .onHover { hovering in withAnimation(sidebarHoverFade) { isHostHovered = hovering } } - .onTapGesture { actions?.editURL() } + .onTapGesture { onPane { actions?.editURL() }() } .overlay(RowClickCatcher(onMiddleClick: {}, menuItems: menuItems(canCopy: !isPlaceholder))) .accessibilityElement() .accessibilityLabel(text) @@ -225,12 +377,13 @@ struct PageToolbar: View { height: IconButtonSize.toolbarHeight, glyphSize: IconButtonSize.toolbarSiteControlsGlyph, glyphWeight: .regular ) { - model.isSiteControlCenterOpen = true + onPane { model.isSiteControlCenterOpen = true }() } // A click while the popover is open only closes it (arc-site-control-center // design D2). .allowsHitTesting(!model.isSiteControlCenterOpen) - .popover(isPresented: $model.isSiteControlCenterOpen, arrowEdge: .bottom) { + // Only the focused pane's button holds the popover (add-split-view D9). + .popover(isPresented: isOtherPane ? .constant(false) : $model.isSiteControlCenterOpen, arrowEdge: .bottom) { SiteControlCenter(model: model, actions: actions) { model.isSiteControlCenterOpen = false } } .anchorFrame(.siteControls) @@ -251,7 +404,11 @@ struct PageToolbar: View { private func menuItems(canCopy: Bool) -> [RowClickCatcher.Item] { var items: [RowClickCatcher.Item] = [] if canCopy { - items.append(.action("Copy URL") { [weak actions] in actions?.copyURL() }) + let paneTabID = self.paneTabID + items.append( + .action("Copy URL") { [weak actions] in + if let paneTabID { actions?.copyURL(of: paneTabID) } else { actions?.copyURL() } + }) items.append(.separator) } items.append(.action(ToolbarPreference.menuTitle(isOn: true)) { [weak actions] in actions?.setToolbarShown(false) }) diff --git a/native/ClairUI/PeekViews.swift b/native/ClairUI/PeekViews.swift index 7adce88..ddaa9bd 100644 --- a/native/ClairUI/PeekViews.swift +++ b/native/ClairUI/PeekViews.swift @@ -112,6 +112,8 @@ enum PeekLayout { protocol PeekActions: AnyObject { func closePeek() func expandPeek() + /// The Peek as a tab in a split with its parent (add-split-view D11). + func openPeekInSplit() } /// The column of round buttons beside the Peek (add-peek design D4, D6): @@ -119,6 +121,9 @@ protocol PeekActions: AnyObject { /// arms the next one, and Expand. struct PeekControlsView: View { let confirm: PeekConfirmState + /// The window's, for whether the parent is in a split, where Open in + /// Split View doesn't show (add-split-view D11). + var model: BrowserWindowModel? weak var actions: (any PeekActions)? var body: some View { @@ -137,6 +142,12 @@ struct PeekControlsView: View { label: "Expand Peek into a tab", identifier: "clair.peekExpand" ) { actions?.expandPeek() } + if model?.shownSplit == nil { + PeekRoundButton( + systemImage: "rectangle.split.2x1", glyphSize: PeekLayout.expandGlyphSize, tooltip: "Open in Split View", + label: "Open Peek in Split View", identifier: "clair.peekSplit" + ) { actions?.openPeekInSplit() } + } } .fixedSize() .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: towardPeek ? .topTrailing : .topLeading) diff --git a/native/ClairUI/PinsLogic.swift b/native/ClairUI/PinsLogic.swift index e1313c2..ee8d762 100644 --- a/native/ClairUI/PinsLogic.swift +++ b/native/ClairUI/PinsLogic.swift @@ -88,31 +88,89 @@ enum PinsLogic { // MARK: Folders (add-tab-folders design D4) - /// Every pinned tab of `items`, its folders' included, in order. + /// Every pinned tab of `items`, its folders' and splits' included, in + /// order (add-split-view D10). static func allPins(_ items: [any ClairPinnedItem]) -> [any ClairPin] { items.flatMap { item -> [any ClairPin] in if let pin = item.pin { return [pin] } - return item.folder?.pins ?? [] + if let split = item.split { return split.pins } + return item.folder.map { allPins($0.items) } ?? [] } } + /// The pinned or favorited split of `items`, its folders' included, that + /// holds `pinID`. + static func split(containing pinID: PinID, in items: [any ClairPinnedItem]) -> (any ClairPinnedSplit)? { + for item in items { + if let split = item.split, split.pins.contains(where: { $0.pinID == pinID }) { return split } + if let folder = item.folder, let split = split(containing: pinID, in: folder.items) { return split } + } + return nil + } + + /// A folder's pinned tabs, its splits' two included, in order. + static func pins(of folder: any ClairFolder) -> [any ClairPin] { + allPins(folder.items) + } + /// One row of the pinned section. enum PinnedRow { /// A pinned tab, under `folder` when it's listed in one. case pin(any ClairPin, folder: (any ClairFolder)?) + /// A pinned split, one row for its two pages (add-split-view D10). + case split(any ClairPinnedSplit, folder: (any ClairFolder)?) case folder(any ClairFolder) var id: String { switch self { case .pin(let pin, _): "pin-\(pin.pinID)" + case .split(let split, _): "split-\(split.pinnedSplitID)" case .folder(let folder): "folder-\(folder.folderID)" } } + /// The pinned tab, or a pinned split's leading one, which stands for the + /// split in commands. var pin: (any ClairPin)? { - if case .pin(let pin, _) = self { return pin } - return nil + switch self { + case .pin(let pin, _): pin + case .split(let split, _): split.pins.first + case .folder: nil + } } + + /// The ID of the item the row is: a pin's, a split's or a folder's. + var itemID: String { + switch self { + case .pin(let pin, _): pin.pinID + case .split(let split, _): split.pinnedSplitID + case .folder(let folder): folder.folderID + } + } + + /// The folder a pin's or split's row is listed in. + var parent: (any ClairFolder)? { + switch self { + case .pin(_, let folder), .split(_, let folder): folder + case .folder: nil + } + } + } + + /// The ID of a pinned item: its pin's, split's or folder's. + static func itemID(_ item: any ClairPinnedItem) -> String { + item.pin?.pinID ?? item.split?.pinnedSplitID ?? item.folder?.folderID ?? "" + } + + /// Whether a pinned split's page shows: either pin's bound tab is + /// `highlighted`. + static func isSelected(_ split: any ClairPinnedSplit, highlighted: TabID) -> Bool { + highlighted != ClairTabIDNone && split.pins.contains { $0.tabID == highlighted } + } + + /// Whether any of a split's pages is open. + static func isOpen(_ split: any ClairPinnedSplit) -> Bool { + split.pins.contains { $0.tabID != ClairTabIDNone } } /// The pinned section's rows: each pinned tab; each folder, then its @@ -123,18 +181,34 @@ enum PinsLogic { /// "Folders in a collapsed pinned section"). static func pinnedRows(_ items: [any ClairPinnedItem], collapsed: Bool, highlighted: TabID) -> [PinnedRow] { let isSelected = { (pin: any ClairPin) in pin.tabID != ClairTabIDNone && pin.tabID == highlighted } + // A row of an item at the top level or in `folder`: a pin or a split. + let row = { (item: any ClairPinnedItem, folder: (any ClairFolder)?) -> PinnedRow? in + if let pin = item.pin { return .pin(pin, folder: folder) } + if let split = item.split { return .split(split, folder: folder) } + return nil + } if collapsed { - return allPins(items).filter(isSelected).map { .pin($0, folder: nil) } + let leaves = items.flatMap { item in item.folder?.items ?? [item] } + return leaves.compactMap { item -> PinnedRow? in + if let pin = item.pin, isSelected(pin) { return .pin(pin, folder: nil) } + if let split = item.split, Self.isSelected(split, highlighted: highlighted) { + return .split(split, folder: nil) + } + return nil + } } var rows: [PinnedRow] = [] for item in items { - if let pin = item.pin { - rows.append(.pin(pin, folder: nil)) - } else if let folder = item.folder { + if let folder = item.folder { rows.append(.folder(folder)) - for pin in folder.pins where folder.isOpen || pin.tabID != ClairTabIDNone { - rows.append(.pin(pin, folder: folder)) + for child in folder.items { + let open = child.pin.map { $0.tabID != ClairTabIDNone } ?? child.split.map(isOpen) ?? false + if folder.isOpen || open, let child = row(child, folder) { + rows.append(child) + } } + } else if let item = row(item, nil) { + rows.append(item) } } return rows @@ -149,7 +223,7 @@ enum PinsLogic { } static func hasOpenTabs(_ folder: any ClairFolder) -> Bool { - folder.pins.contains { $0.tabID != ClairTabIDNone } + pins(of: folder).contains { $0.tabID != ClairTabIDNone } } static func folderIcon(_ folder: any ClairFolder) -> FolderIcon { @@ -307,15 +381,15 @@ enum PinsLogic { if let movingTodayRow, movingTodayRow < row { row -= 1 } - // Rows before it, each with its Peek, less the moving row's family. - let moving = movingTodayRow.flatMap { rows.indices.contains($0) ? rows[$0].tabID : nil } + // Rows before it, each with its Peek and a split's other pane, less the + // moving row's family. var others = rows if let movingTodayRow, rows.indices.contains(movingTodayRow) { others.remove(at: movingTodayRow) } let before = others.prefix(row) let index = before.reduce(0) { count, tab in - count + 1 + (TabListLogic.peek(ofRow: tab.tabID, in: today) == nil || tab.tabID == moving ? 0 : 1) + count + TabListLogic.rowFamily(tab.tabID, in: today).count } return .today(index) } @@ -333,67 +407,57 @@ enum PinsLogic { } gap = min(max(gap, 0), others.count) // The items as they are once the lifted row's item is out of the way. - var topItems = items - var liftedPin: PinID? - switch lifted { - case .pin(let pin, _): - liftedPin = pin.pinID - topItems.removeAll { $0.pin?.pinID == pin.pinID } - case .folder(let folder): - topItems.removeAll { $0.folder?.folderID == folder.folderID } - case nil: - break - } + let liftedID = lifted?.itemID + let topItems = items.filter { itemID($0) != liftedID } let topIndex = { (id: String) -> Int? in - topItems.firstIndex { ($0.pin?.pinID ?? $0.folder?.folderID) == id } + topItems.firstIndex { itemID($0) == id } } - let indexInFolder = { (pin: any ClairPin, folder: any ClairFolder) -> Int in - folder.pins.filter { $0.pinID != liftedPin }.firstIndex { $0.pinID == pin.pinID } ?? 0 + let indexInFolder = { (id: String, folder: any ClairFolder) -> Int in + folder.items.filter { itemID($0) != liftedID }.firstIndex { itemID($0) == id } ?? 0 } - /// The place of `pin` itself, in a folder or at the top level. - let placeOf = { (pin: any ClairPin) -> ListDrop in + /// The place of the item of a pin's or split's row itself, in a folder + /// or at the top level. + let placeOf = { (row: PinnedRow) -> ListDrop in for item in topItems { - if let folder = item.folder, folder.pins.contains(where: { $0.pinID == pin.pinID }) { - return .folder(folder.folderID, indexInFolder(pin, folder)) + if let folder = item.folder, folder.items.contains(where: { itemID($0) == row.itemID }) { + return .folder(folder.folderID, indexInFolder(row.itemID, folder)) } } - return .pinned(topIndex(pin.pinID) ?? topItems.count) + return .pinned(topIndex(row.itemID) ?? topItems.count) } if collapsed { // Only the selected tab shows: before it is its own place, after it // the end of the section. - if gap < others.count, let pin = others[gap].pin { - return placeOf(pin) + if gap < others.count, others[gap].pin != nil { + return placeOf(others[gap]) } return .pinned(topItems.count) } let below = gap < others.count ? others[gap] : nil - switch gap > 0 ? others[gap - 1] : nil { - case nil: - return .pinned(0) - case .folder(let folder): + guard gap > 0 else { return .pinned(0) } + let above = others[gap - 1] + if case .folder(let folder) = above { // Under a folder's row: first in it, or before its first listed tab // while it's closed; after it when it's closed and lists nothing. - if case .pin(let pin, let parent)? = below, parent?.folderID == folder.folderID { - return .folder(folder.folderID, indexInFolder(pin, folder)) + if let below, below.parent?.folderID == folder.folderID { + return .folder(folder.folderID, indexInFolder(below.itemID, folder)) } if folder.isOpen { return .folder(folder.folderID, 0) } return .pinned((topIndex(folder.folderID) ?? topItems.count - 1) + 1) - case .pin(let pin, let parent): - guard let parent else { - return .pinned((topIndex(pin.pinID) ?? topItems.count - 1) + 1) - } - if parent.isOpen { - return .folder(parent.folderID, indexInFolder(pin, parent) + 1) - } - // Between two tabs a closed folder lists: in it, before the lower one. - if case .pin(let next, let nextParent)? = below, nextParent?.folderID == parent.folderID { - return .folder(parent.folderID, indexInFolder(next, parent)) - } - return .pinned((topIndex(parent.folderID) ?? topItems.count - 1) + 1) } + guard let parent = above.parent else { + return .pinned((topIndex(above.itemID) ?? topItems.count - 1) + 1) + } + if parent.isOpen { + return .folder(parent.folderID, indexInFolder(above.itemID, parent) + 1) + } + // Between two rows a closed folder lists: in it, before the lower one. + if let below, below.parent?.folderID == parent.folderID { + return .folder(parent.folderID, indexInFolder(below.itemID, parent)) + } + return .pinned((topIndex(parent.folderID) ?? topItems.count - 1) + 1) } // MARK: Menus (sidebar, pinned-tabs and favorites specs) @@ -417,6 +481,9 @@ enum PinsLogic { // A folder's (add-tab-folders). case turnIntoSpace case deleteFolder + // Split view's (add-split-view D9, D10). + case splitWithTab + case separateTabs } struct MenuItem: Equatable { @@ -425,15 +492,21 @@ enum PinsLogic { var isEnabled = true } + static let splitWithTab = MenuItem(title: "Split with Tab", command: .splitWithTab) + static let separateTabs = MenuItem(title: "Separate Tabs", command: .separateTabs) + /// A Today tab's menu: nil entries are separators. Incognito and guest - /// windows have neither pin item. - static func todayMenu(isMuted: Bool, canMoveToSpace: Bool, canPin: Bool) -> [MenuItem?] { + /// windows have neither pin item. A split row's chip (`inSplit`) has no + /// Split with Tab, and Separate Tabs (add-split-view, "The split row's + /// menu"). + static func todayMenu(isMuted: Bool, canMoveToSpace: Bool, canPin: Bool, inSplit: Bool = false) -> [MenuItem?] { var items: [MenuItem?] = [ MenuItem(title: "Copy Link", command: .copyLink), MenuItem(title: "Rename…", command: .rename), MenuItem(title: "Duplicate", command: .duplicate), MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute), ] + items += inSplit ? [nil, separateTabs] : [splitWithTab] if canPin { items += [nil, MenuItem(title: "Pin Tab", command: .pin), MenuItem(title: "Pin to Favorites", command: .pinToFavorites)] } @@ -448,15 +521,19 @@ enum PinsLogic { return items } - /// A pinned tab's menu. - static func pinnedMenu(isOpen: Bool, isMuted: Bool, canMoveToSpace: Bool) -> [MenuItem?] { + /// A pinned tab's menu; a pinned split's chip's has no Edit Pinned Page + /// or Split with Tab, and Separate Tabs. + static func pinnedMenu(isOpen: Bool, isMuted: Bool, canMoveToSpace: Bool, inSplit: Bool = false) -> [MenuItem?] { var items: [MenuItem?] = [ MenuItem(title: "Copy Link", command: .copyLink), MenuItem(title: "Rename…", command: .rename), MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute, isEnabled: isOpen), - MenuItem(title: "Edit Pinned Page", command: .editPinnedPage), - MenuItem(title: "Duplicate", command: .duplicate), ] + if !inSplit { + items.append(MenuItem(title: "Edit Pinned Page", command: .editPinnedPage)) + } + items.append(MenuItem(title: "Duplicate", command: .duplicate)) + items += inSplit ? [nil, separateTabs] : [splitWithTab] if canMoveToSpace { items += [nil, MenuItem(title: "Move to Space", command: .moveToSpace)] } @@ -468,16 +545,21 @@ enum PinsLogic { return items } - /// A favorite's menu; Close Tab only while the window shows its page. - static func favoriteMenu(isShown: Bool, isOpen: Bool, isMuted: Bool) -> [MenuItem?] { + /// A favorite's menu; Close Tab only while the window shows its page. A + /// favorited split's segment's has no Edit Pinned Page or Split with Tab, + /// and Separate Tabs. + static func favoriteMenu(isShown: Bool, isOpen: Bool, isMuted: Bool, inSplit: Bool = false) -> [MenuItem?] { var items: [MenuItem?] = [ MenuItem(title: "Copy Link", command: .copyLink), MenuItem(title: "Rename…", command: .rename), MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute, isEnabled: isOpen), - MenuItem(title: "Edit Pinned Page", command: .editPinnedPage), - MenuItem(title: "Duplicate", command: .duplicate), - nil, ] + if !inSplit { + items.append(MenuItem(title: "Edit Pinned Page", command: .editPinnedPage)) + } + items.append(MenuItem(title: "Duplicate", command: .duplicate)) + items += inSplit ? [nil, separateTabs] : [splitWithTab] + items.append(nil) if isShown { items.append(MenuItem(title: "Close Tab", command: .closeTab)) } @@ -515,7 +597,7 @@ enum PinsLogic { /// Whether Delete asks first: only for a folder with tabs. static func folderDeletionNeedsConfirmation(_ folder: any ClairFolder) -> Bool { - !folder.pins.isEmpty + !folder.items.isEmpty } static func folderDeletionTitle(_ name: String) -> String { diff --git a/native/ClairUI/PinsViews.swift b/native/ClairUI/PinsViews.swift index 546a966..a1b673b 100644 --- a/native/ClairUI/PinsViews.swift +++ b/native/ClairUI/PinsViews.swift @@ -169,19 +169,28 @@ struct FavoritesGrid: View { @State private var dropIndex: Int? var body: some View { - let favorites = model.favorites + // A favorited split is one tile (add-split-view D10). + let favorites = model.favoriteItems let room = dropIndex.map { min($0, favorites.count) } let layout = FavoritesLayout(count: favorites.count + (room == nil ? 0 : 1), width: width) let highlighted = model.highlightedTab ZStack(alignment: .topLeading) { - ForEach(Array(favorites.enumerated()), id: \.element.pinID) { index, pin in + ForEach(Array(favorites.enumerated()), id: \.offset) { index, item in let slot = room.map { index >= $0 ? index + 1 : index } ?? index let frame = layout.frame(of: slot) - FavoriteTile( - pin: pin, tab: model.tab(ofPin: pin), peek: peek(of: pin), - isSelected: pin.tabID != ClairTabIDNone && pin.tabID == highlighted, isWindowKey: model.isWindowKey, - isShown: pin.tabID != ClairTabIDNone && pin.tabID == highlighted, actions: actions - ) + Group { + if let split = item.split { + SplitRows.favorite(split, model: model, actions: actions) + .onDrag { SidebarDragItem.pin(split.pins.first?.pinID ?? "").itemProvider() } + } else if let pin = item.pin { + FavoriteTile( + pin: pin, tab: model.tab(ofPin: pin), peek: peek(of: pin), + isSelected: pin.tabID != ClairTabIDNone && pin.tabID == highlighted, isWindowKey: model.isWindowKey, + isShown: pin.tabID != ClairTabIDNone && pin.tabID == highlighted, actions: actions + ) + } + } + .id(PinsLogic.itemID(item)) .frame(width: frame.width, height: frame.height) .offset(x: frame.minX, y: frame.minY) } @@ -194,7 +203,7 @@ struct FavoritesGrid: View { FavoritesDropArea( slot: { [width] in FavoritesLayout(count: favorites.count, width: width).dropIndex(at: $0) }, tileSize: { [width] in FavoritesLayout(count: favorites.count + 1, width: width).frame(of: $0).size }, - icon: { [model] in model.icon(of: $0) }, + icons: { [model] in model.icons(of: $0) }, onTarget: { [$dropIndex] in $dropIndex.wrappedValue = $0 }, onDrop: { [actions] item, slot in actions?.drop(item, on: .favorites(slot)) }) } @@ -330,7 +339,7 @@ struct FavoritesHintBox: View { FavoritesDropArea( slot: { _ in 0 }, tileSize: { _ in CGSize(width: tileWidth, height: FavoritesLayout.tileHeight) }, - icon: { [model] in model.icon(of: $0) }, + icons: { [model] in model.icons(of: $0) }, onTarget: { [$isTargeted] in $isTargeted.wrappedValue = $0 != nil }, onDrop: { [actions] item, _ in actions?.drop(item, on: .favorites(0)) }) } @@ -499,8 +508,20 @@ struct PinRow: View { } private var menuItems: [RowClickCatcher.Item] { + PinMenus.pinnedItems(pin: pin, tab: tab, moveTargets: moveTargets, actions: actions) + } +} + +extension PinMenus { + /// A pinned tab's menu, with Move to Space's submenu; a pinned split's + /// chip's with `inSplit`. + static func pinnedItems( + pin: any ClairPin, tab: (any ClairTab)?, moveTargets: [any ClairSpace], actions: (any SidebarActions)?, + inSplit: Bool = false + ) -> [RowClickCatcher.Item] { var items = PinMenus.items( - PinsLogic.pinnedMenu(isOpen: tab != nil, isMuted: tab?.isMuted == true, canMoveToSpace: !moveTargets.isEmpty), + PinsLogic.pinnedMenu( + isOpen: tab != nil, isMuted: tab?.isMuted == true, canMoveToSpace: !moveTargets.isEmpty, inSplit: inSplit), pin: pin, actions: actions) // Move to Space's submenu. let pinID = pin.pinID @@ -550,6 +571,21 @@ enum PinMenus { guard let item else { return .separator } guard item.isEnabled else { return .disabled(item.title) } switch item.command { + case .splitWithTab: + // Disabled while the pin's page is in a split (add-split-view D9). + if pin.tabs.contains(where: { $0.splitPartnerID != ClairTabIDNone }) { + return .disabledSubmenu(item.title) + } + return .submenu(item.title, actions?.splitWithTabItems(tab: nil, pin: pinID) ?? []) + case .separateTabs: + // A pinned split's, or a Today split's holding the pin's page. + return .action(item.title) { [weak actions] in + if let splitID = pin.pinnedSplitID { + actions?.separatePinnedSplit(splitID) + } else if pin.tabID != ClairTabIDNone { + actions?.separateSplit(of: pin.tabID) + } + } case .editPinnedPage: return .submenu( item.title, @@ -587,7 +623,7 @@ enum PinMenus { case .closeTab: actions?.closeKeepingPin(pinID) case .removeFavorite: actions?.removePin(pinID) case .pin, .editPinnedPage, .replacePinnedURL, .editPinnedURL, .moveToSpace, .closeTabsBelow, .turnIntoSpace, - .deleteFolder: + .deleteFolder, .splitWithTab, .separateTabs: break } } diff --git a/native/ClairUI/SidebarView.swift b/native/ClairUI/SidebarView.swift index 7a67065..1a743a9 100644 --- a/native/ClairUI/SidebarView.swift +++ b/native/ClairUI/SidebarView.swift @@ -8,7 +8,7 @@ import SwiftUI /// What the sidebar asks the window to do. @MainActor -protocol SidebarActions: SpaceActions, PinActions { +protocol SidebarActions: SpaceActions, PinActions, SplitActions { // Tabs. func activate(tab: TabID) func close(tab: TabID) @@ -25,12 +25,17 @@ protocol SidebarActions: SpaceActions, PinActions { /// that way (arc-navigation-feedback design D3). func historyMenu(_ direction: HistoryDirection) -> HistoryMenuBuilder? func reloadOrStop() + /// Reload or Stop in an unfocused pane's header, for its own page, which + /// it focuses (add-split-view D9). + func reloadOrStop(pane tabID: TabID) func reloadButtonHovered(_ hovering: Bool) func toggleSidebar() /// A double-click on the top row's empty space, as on a title bar. func titleBarDoubleClicked() func editURL() func copyURL() + /// Copies `tabID`'s URL: a pane's, from its header. + func copyURL(of tabID: TabID) func showSiteControls(indicator: TabIndicators) func openInNewTab(_ url: URL) // Extensions and downloads. @@ -49,7 +54,7 @@ protocol SidebarActions: SpaceActions, PinActions { func controlFramesChanged(_ frames: [AnchorControl: CGRect]) /// The toolbar's controls, in its own coordinate space (add-page-toolbar /// D6). - func toolbarControlFramesChanged(_ frames: [AnchorControl: CGRect]) + func toolbarControlFramesChanged(_ frames: [AnchorControl: CGRect], pane: Int) /// Shows or hides the toolbar in every window (add-page-toolbar D8). func setToolbarShown(_ shown: Bool) // The update banner (add-update-banners). @@ -1098,6 +1103,8 @@ struct TabList: View { case .pinned(let row): switch row { case .pin(let pin, _): dragged = .pin(pin.pinID) + // add-split-view D10: a pinned split moves as one. + case .split(let split, _): dragged = .pin(split.pins.first?.pinID ?? "") case .folder(let folder): dragged = .folder(folder.folderID) } drop = PinsLogic.listDrop( @@ -1184,6 +1191,12 @@ struct TabList: View { // add-tab-folders D4: a folder's tabs are indented under it. .padding(.leading, folder == nil ? 0 : FolderRow.indent) .itemProvider { SidebarDragItem.pin(pin.pinID).itemProvider() } + case .pinned(.split(let split, let folder)): + SplitRows.pinned( + split, model: model, highlighted: highlighted, moveTargets: moveTargets, actions: actions + ) + .padding(.leading, folder == nil ? 0 : FolderRow.indent) + .itemProvider { split.pins.first.map { SidebarDragItem.pin($0.pinID).itemProvider() } } case .pinned(.folder(let folder)): FolderRow( folder: folder, moveTargets: moveTargets, @@ -1213,6 +1226,10 @@ struct TabList: View { } } } + case .tab(let tab) where tab.splitPartnerID != ClairTabIDNone: + // add-split-view D2: a split's row, its chips in pane order. + SplitRows.today(tab, model: model, highlighted: highlighted, moveTargets: moveTargets, actions: actions) + .itemProvider { model.showsPins ? SidebarDragItem.tab(tab.tabID).itemProvider() : nil } case .tab(let tab): TabRow( tab: tab, isActive: tab.tabID == highlighted, isWindowKey: model.isWindowKey, @@ -1531,8 +1548,18 @@ extension TabRow { /// The row's context menu (sidebar spec, "Today tab menu"): Rename… and /// the pin items only where the window shows pins. var menuItems: [RowClickCatcher.Item] { + Self.menuItems(tab: tab, canPin: canPin, moveTargets: moveTargets, actions: actions) + } + + /// A Today tab's menu, or a Today split's chip's with `inSplit` + /// (add-split-view, "The split row's menu"). + static func menuItems( + tab: any ClairTab, canPin: Bool, moveTargets: [any ClairSpace], actions: (any SidebarActions)?, + inSplit: Bool = false + ) -> [RowClickCatcher.Item] { let tabID = tab.tabID, isMuted = tab.isMuted - let menu = PinsLogic.todayMenu(isMuted: isMuted, canMoveToSpace: !moveTargets.isEmpty, canPin: canPin) + let menu = PinsLogic.todayMenu( + isMuted: isMuted, canMoveToSpace: !moveTargets.isEmpty, canPin: canPin, inSplit: inSplit) return menu.compactMap { item -> RowClickCatcher.Item? in guard let item else { return .separator } switch item.command { @@ -1556,6 +1583,8 @@ extension TabRow { }) case .closeTab: return .action(item.title) { actions?.close(tab: tabID) } case .closeTabsBelow: return .action(item.title) { actions?.closeTabs(below: tabID) } + case .splitWithTab: return .submenu(item.title, actions?.splitWithTabItems(tab: tabID, pin: nil) ?? []) + case .separateTabs: return .action(item.title) { actions?.separateSplit(of: tabID) } default: return nil } } @@ -1573,12 +1602,18 @@ struct RowClickCatcher: NSViewRepresentable { /// Shown, but can't be chosen. case disabled(String) case submenu(String, [Item]) + /// An action with an icon, as a tab with its favicon (add-split-view D9). + case icon(String, NSImage?, () -> Void) + /// A disabled submenu. + case disabledSubmenu(String) case separator /// The item's title, or nil for a separator. var title: String? { switch self { - case .action(let title, _), .checked(let title, _), .disabled(let title), .submenu(let title, _): title + case .action(let title, _), .checked(let title, _), .disabled(let title), .submenu(let title, _), + .icon(let title, _, _), .disabledSubmenu(let title): + title case .separator: nil } } @@ -1662,6 +1697,17 @@ struct RowClickCatcher: NSViewRepresentable { let menuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") menuItem.isEnabled = false menu.addItem(menuItem) + case .disabledSubmenu(let title): + let menuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") + menuItem.submenu = NSMenu() + menuItem.isEnabled = false + menu.addItem(menuItem) + case .icon(let title, let image, let action): + let menuItem = NSMenuItem(title: title, action: #selector(runItem(_:)), keyEquivalent: "") + menuItem.target = target + menuItem.representedObject = ItemAction(run: action) + menuItem.setFavicon(image) + menu.addItem(menuItem) case .submenu(let title, let items): let menuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") menuItem.submenu = Self.menu(items, target: target) diff --git a/native/ClairUI/SpaceHeaderView.swift b/native/ClairUI/SpaceHeaderView.swift index 20db99e..219cf8e 100644 --- a/native/ClairUI/SpaceHeaderView.swift +++ b/native/ClairUI/SpaceHeaderView.swift @@ -302,6 +302,13 @@ struct RowMenuContent: View { Button(title) {}.disabled(true) case .submenu(let title, let items): Menu(title) { RowMenuContent(items: items) } + case .icon(let title, let image, let run): + Button(action: run) { + Label { Text(title) } icon: { Image(nsImage: SplitRows.menuIcon(image)) } + } + .labelStyle(.titleAndIcon) + case .disabledSubmenu(let title): + Menu(title) {}.disabled(true) case .separator: Divider() } diff --git a/native/ClairUI/SpacesModel.swift b/native/ClairUI/SpacesModel.swift index 0efc405..9517042 100644 --- a/native/ClairUI/SpacesModel.swift +++ b/native/ClairUI/SpacesModel.swift @@ -52,7 +52,7 @@ final class SpacesModel: NSObject, ClairSpacesObserver { /// Each Space's pinned items and each profile's favorites, in order, as /// last reported (add-pinned-tabs-and-favorites D11, add-tab-folders D2). @ObservationIgnored private var itemsBySpace: [SpaceID: [any ClairPinnedItem]] = [:] - @ObservationIgnored private var favoritesByProfile: [ProfileID: [any ClairPin]] = [:] + @ObservationIgnored private var favoritesByProfile: [ProfileID: [any ClairPinnedItem]] = [:] @ObservationIgnored private let listeners = NSHashTable.weakObjects() init(host: (any ClairHost)?) { @@ -107,6 +107,12 @@ final class SpacesModel: NSObject, ClairSpacesObserver { return items } + /// Separate Tabs on a pinned or favorited split whose pages are closed + /// (add-split-view D10). + func separatePinnedSplit(_ splitID: PinnedSplitID) { + host?.separatePinnedSplit(splitID) + } + /// Every pinned tab of a Space, its folders' included, in the sidebar's /// order. func pins(inSpace spaceID: SpaceID) -> [any ClairPin] { @@ -126,8 +132,9 @@ final class SpacesModel: NSObject, ClairSpacesObserver { return nil } - /// A profile's favorites, in its order. - func favorites(ofProfile profileID: ProfileID) -> [any ClairPin] { + /// A profile's favorites and favorited splits, in its order + /// (add-split-view D10). + func favoriteItems(ofProfile profileID: ProfileID) -> [any ClairPinnedItem] { if let favorites = favoritesByProfile[profileID] { return favorites } @@ -136,6 +143,11 @@ final class SpacesModel: NSObject, ClairSpacesObserver { return favorites } + /// A profile's favorites, a favorited split's two included, in its order. + func favorites(ofProfile profileID: ProfileID) -> [any ClairPin] { + PinsLogic.allPins(favoriteItems(ofProfile: profileID)) + } + /// The number of a Space's pinned tabs whose page is open. func openPinCount(inSpace spaceID: SpaceID) -> Int { pins(inSpace: spaceID).count { $0.tabID != ClairTabIDNone } @@ -308,8 +320,8 @@ final class SpacesModel: NSObject, ClairSpacesObserver { for items in itemsBySpace.values { if let pin = PinsLogic.allPins(items).first(where: { $0.pinID == pinID }) { return pin } } - for pins in favoritesByProfile.values { - if let pin = pins.first(where: { $0.pinID == pinID }) { return pin } + for items in favoritesByProfile.values { + if let pin = PinsLogic.allPins(items).first(where: { $0.pinID == pinID }) { return pin } } return nil } @@ -454,7 +466,7 @@ final class SpacesModel: NSObject, ClairSpacesObserver { } } - func favoritesDidChange(_ favorites: [any ClairPin], ofProfile profileID: ProfileID) { + func favoritesDidChange(_ favorites: [any ClairPinnedItem], ofProfile profileID: ProfileID) { favoritesByProfile[profileID] = favorites for listener in allListeners { listener.favoritesDidChange(profileID) diff --git a/native/ClairUI/SplitLogic.swift b/native/ClairUI/SplitLogic.swift new file mode 100644 index 0000000..550457f --- /dev/null +++ b/native/ClairUI/SplitLogic.swift @@ -0,0 +1,243 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// The split the window shows (add-split-view design D2, D3): its two tabs, +/// leading pane first, its ratio, and which pane is focused. +struct ShownSplit: Equatable { + let leadingID: TabID + let trailingID: TabID + let ratio: Double + /// The pane holding the active tab, or the parent of the active Peek. + let focusedIndex: Int + + var paneIDs: [TabID] { [leadingID, trailingID] } + + /// The pane showing `tabID`, or nil. + func index(of tabID: TabID) -> Int? { + paneIDs.firstIndex(of: tabID) + } +} + +/// The rules of split view in the window, kept apart from the views so they +/// can be tested (add-split-view design D2, D3, D8, D9, D13). +enum SplitLogic { + // MARK: The shown split + + /// The split the window shows while `activeTabID` is active: the active + /// tab's, or the active Peek's parent's, while its partner is among `tabs`. + static func shownSplit(activeTabID: TabID, in tabs: [any ClairTab]) -> ShownSplit? { + guard let active = tabs.first(where: { $0.tabID == activeTabID }) else { return nil } + var shown = active + if active.peekParentID != ClairTabIDNone, let parent = tabs.first(where: { $0.tabID == active.peekParentID }) { + shown = parent + } + guard let (leading, trailing) = TabListLogic.panes(of: shown, in: tabs) else { return nil } + return ShownSplit( + leadingID: leading.tabID, trailingID: trailing.tabID, ratio: leading.splitRatio, + focusedIndex: shown.tabID == leading.tabID ? 0 : 1) + } + + // MARK: Panes (D3) + + /// Arc's gap between the panes, where the divider sits. + static let gap: CGFloat = 10 + /// The narrowest a pane's page gets while dragging the divider, as Dia's + /// (dia-reference/README.md). + static let minimumPageWidth: CGFloat = 210 + /// The divider this near the centre makes the panes equal. + static let snapDistance: CGFloat = 20 + + /// The panes' frames in the page area `area`, leading first, the leading + /// pane taking `ratio` of the width left beside the gap. + static func paneFrames(in area: CGRect, ratio: Double) -> [CGRect] { + let room = max(0, area.width - gap) + let leading = (room * CGFloat(min(max(ratio, 0), 1))).rounded() + return [ + CGRect(x: area.minX, y: area.minY, width: leading, height: area.height), + CGRect(x: area.minX + leading + gap, y: area.minY, width: room - leading, height: area.height), + ] + } + + /// The gap's frame between the panes. + static func dividerFrame(in area: CGRect, ratio: Double) -> CGRect { + let panes = paneFrames(in: area, ratio: ratio) + return CGRect(x: panes[0].maxX, y: area.minY, width: gap, height: area.height) + } + + /// The ratio the divider gives with its centre at `x` in a page area + /// `width` wide: each pane's page stays at least `minimumPageWidth` wide, + /// unless the area is too narrow for two such pages, when `current` holds. + static func ratio(forDividerAt x: CGFloat, width: CGFloat, current: Double) -> Double { + let room = width - gap + guard room > 0 else { return current } + guard room >= 2 * minimumPageWidth else { return current } + let leading = min(max(x - gap / 2, minimumPageWidth), room - minimumPageWidth) + return Double(leading / room) + } + + /// The ratio the divider gives while dragged and when let go: equal panes + /// within `snapDistance` of the page area's centre. + static func snappedRatio(forDividerAt x: CGFloat, width: CGFloat, current: Double) -> Double { + if abs(x - width / 2) <= snapDistance, width - gap >= 2 * minimumPageWidth { + return 0.5 + } + return ratio(forDividerAt: x, width: width, current: current) + } + + // MARK: The split button's menus (D9) + + enum MenuEntry: Equatable { + /// A heading, which can't be chosen. + case heading(String) + /// A Today tab to split with. + case tab(TabID, title: String) + case newTab + case moveLeft(isEnabled: Bool) + case moveRight(isEnabled: Bool) + case separateTabs + case closeThisTab + case separator + + var title: String { + switch self { + case .heading(let title), .tab(_, let title): title + case .newTab: "New Tab" + case .moveLeft: "Move Left" + case .moveRight: "Move Right" + case .separateTabs: "Separate Tabs" + case .closeThisTab: "Close This Tab" + case .separator: "" + } + } + } + + static let splitWithTabTitle = "Split with Tab" + + /// The Today tabs a split can be made with, in the sidebar's order: every + /// Today row but `tabID` and the tabs already in a split. + static func candidates(for tabID: TabID, today: [any ClairTab]) -> [any ClairTab] { + TabListLogic.rows(today).filter { $0.tabID != tabID && $0.splitPartnerID == ClairTabIDNone } + } + + /// The split button's menu on a single page: "Split with Tab", the Space's + /// other Today tabs, a divider and New Tab, as in Dia. + static func singlePageMenu(shown tabID: TabID, today: [any ClairTab]) -> [MenuEntry] { + [.heading(splitWithTabTitle)] + candidates(for: tabID, today: today).map { .tab($0.tabID, title: title(of: $0)) } + + [.separator, .newTab] + } + + /// The split button's menu in a pane: Move Left or Move Right, a divider, + /// Separate Tabs and Close This Tab. + static func paneMenu(isLeading: Bool) -> [MenuEntry] { + [.moveLeft(isEnabled: !isLeading), .moveRight(isEnabled: isLeading), .separator, .separateTabs, .closeThisTab] + } + + /// A tab menu's Split with Tab › submenu: the other Today tabs, then New + /// Tab. + static func splitWithTabSubmenu(for tabID: TabID, today: [any ClairTab]) -> [MenuEntry] { + candidates(for: tabID, today: today).map { .tab($0.tabID, title: title(of: $0)) } + [.separator, .newTab] + } + + /// What a row reads: its custom name, or its title. + static func title(of tab: any ClairTab) -> String { + if let name = tab.name, !name.isEmpty { return name } + return tab.title.isEmpty ? (tab.displayHost ?? tab.urlText) : tab.title + } + + // MARK: Dragging a tab onto the page (D8) + + /// Where a dragged tab lands on the page. + enum DropZone: Equatable { + /// A split with the shown page, the dragged tab on this side. + case half(SplitSide) + /// In place of this pane's tab, while the page is split. + case pane(Int) + } + + /// The drop zone under `point` in a page area: the half under it, or, + /// while split, the pane under it, the gap counting as the nearer pane. + static func dropZone(at point: CGPoint, in area: CGRect, split: ShownSplit?) -> DropZone? { + guard area.contains(point) else { return nil } + guard let split else { + return .half(point.x < area.midX ? .leading : .trailing) + } + let divider = dividerFrame(in: area, ratio: split.ratio) + return .pane(point.x < divider.midX ? 0 : 1) + } + + /// Whether a dragged item makes a drop zone over the page: a tab or pin + /// that isn't shown there already and isn't a split row, open or not + /// (`isPinnedSplit`, a pinned split's pin). + static func acceptsDrop( + of tab: (any ClairTab)?, isPinnedSplit: Bool = false, shown split: ShownSplit?, activeTabID: TabID + ) -> Bool { + if isPinnedSplit { return false } + guard let tab else { return true } + if tab.splitPartnerID != ClairTabIDNone { return false } + if let split { return !split.paneIDs.contains(tab.tabID) } + return tab.tabID != activeTabID && tab.peekParentID == ClairTabIDNone + } + + /// Arc's portrait card for a tab dragged over the page. + static let dragCardSize = CGSize(width: 216, height: 250) + /// How long the page takes to slide aside, ease-out, as in Arc. + static let slideDuration: TimeInterval = 0.2 + + /// Where the page's card goes while a tab is dragged over the half + /// `side`: the other half. + static func slidFrame(in area: CGRect, dropSide side: SplitSide) -> CGRect { + let panes = paneFrames(in: area, ratio: 0.5) + return side == .leading ? panes[1] : panes[0] + } + + // MARK: The link status (D13a) + + /// What the link status reads for a link `url`, with `modifiers` held: + /// Option names the split, and Shift the Peek while the Peek preference is + /// on; in a Peek, where neither applies, the URL alone. + static func linkStatus( + url: String, modifiers: NSEvent.ModifierFlags, opensPeekOnShiftClick: Bool, inPeek: Bool + ) -> String { + let flags = modifiers.intersection([.option, .shift, .command, .control]) + guard !inPeek else { return url } + if flags == .option { return "Open \(url) in Split View" } + if flags == .shift && opensPeekOnShiftClick { return "Open \(url) in Peek" } + return url + } + + // MARK: The command bar's place (D13b) + + /// The command bar's horizontal place: centred on `pane` while split, or + /// on the window, and kept inside `bounds`, the window's content. + static func commandBarMinX(width: CGFloat, pane: CGRect?, bounds: CGRect) -> CGFloat { + let centre = pane?.midX ?? bounds.midX + let x = centre - width / 2 + return min(max(x, bounds.minX), max(bounds.minX, bounds.maxX - width)) + } +} + +/// The actions split view takes in the window (add-split-view design D2). +@MainActor +protocol SplitActions: AnyObject { + /// Shows a split with the pane focused last, as its row's click does. + func showSplit(of tabID: TabID) + func split(tab tabID: TabID, with otherID: TabID, side: SplitSide) + /// A new tab page beside `tabID`, with the command bar on it. + func splitWithNewTab(_ tabID: TabID) + func swapSplit(of tabID: TabID) + func separateSplit(of tabID: TabID) + /// Closes both panes, or a pinned split's pages (Close and Keep Pinned). + func closeSplit(of tabID: TabID) + func replacePane(of tabID: TabID, with newTabID: TabID) + func setSplitRatio(_ ratio: Double, of tabID: TabID) + func separatePinnedSplit(_ splitID: PinnedSplitID) + /// Focuses a pane, as a click in it does. + func focusPane(_ tabID: TabID) + /// A tab menu's Split with Tab › items for a Today tab, or a pin + /// (add-split-view D9). + func splitWithTabItems(tab: TabID?, pin: PinID?) -> [RowClickCatcher.Item] +} diff --git a/native/ClairUI/SplitMenu.swift b/native/ClairUI/SplitMenu.swift new file mode 100644 index 0000000..ebb0b68 --- /dev/null +++ b/native/ClairUI/SplitMenu.swift @@ -0,0 +1,156 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// Split view's items in the menu bar (add-split-view design D9): Tabs › +/// Split with Tab ›, and View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) +/// and Separate Tabs. They act on the main window, which enables them. +final class SplitMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { + enum Command: Int, CaseIterable { + case splitWithTab = 1 + case addSplitView + case closeSplitPane + case separateTabs + + var title: String { + switch self { + case .splitWithTab: SplitLogic.splitWithTabTitle + case .addSplitView: "Add Split View" + case .closeSplitPane: "Close Split Pane" + case .separateTabs: "Separate Tabs" + } + } + + /// Whether the item can be chosen: Split with Tab and Add Split View on + /// a single page (Add Split View then shows "Cannot Add New Pane"), the + /// others while split. + func isEnabled(isSplit: Bool) -> Bool { + switch self { + case .splitWithTab: !isSplit + case .addSplitView: true + case .closeSplitPane, .separateTabs: isSplit + } + } + } + + /// Clair's tags for these items, clear of Chromium's and `PinsMenu`'s. + static let baseTag = 0x436C_5100 + + /// The window the items act on. + var currentController: () -> BrowserWindowController? = { BrowserWindowController.main } + + private(set) var items: [Command: NSMenuItem] = [:] + + /// Adds the items, once. + @discardableResult + func install(in mainMenu: NSMenu?) -> Bool { + guard let mainMenu, items.isEmpty else { return false } + let tabMenu = mainMenu.items.first { $0.tag == PinsMenu.tabMenuTag }?.submenu + let viewMenu = mainMenu.items.first { $0.tag == PinsMenu.viewMenuTag }?.submenu + guard let tabMenu else { return false } + // After Clair's pin items in Tabs. + let lastPinItem = tabMenu.items.lastIndex { $0.tag >= PinsMenu.baseTag && $0.tag < Self.baseTag } + tabMenu.insertItem(make(.splitWithTab), at: lastPinItem.map { $0 + 1 } ?? tabMenu.numberOfItems) + if let viewMenu { + // After Collapse Pinned Tabs, if it's there. + var index = viewMenu.items.firstIndex { $0.tag >= PinsMenu.baseTag && $0.tag < Self.baseTag }.map { $0 + 1 } ?? 0 + for command in [Command.addSplitView, .closeSplitPane, .separateTabs] { + viewMenu.insertItem(make(command), at: index) + index += 1 + } + viewMenu.insertItem(.separator(), at: index) + } + return true + } + + private func make(_ command: Command) -> NSMenuItem { + let item: NSMenuItem + switch command { + case .splitWithTab: + // With an action, the menu asks validateMenuItem whether it's on; an + // item with a submenu and none is always on. + item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "") + let submenu = NSMenu(title: command.title) + submenu.delegate = self + item.submenu = submenu + case .addSplitView: + item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "=") + item.keyEquivalentModifierMask = [.control, .shift] + case .closeSplitPane: + item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "-") + item.keyEquivalentModifierMask = [.control, .shift] + case .separateTabs: + item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "") + } + item.target = self + item.tag = Self.baseTag + command.rawValue + items[command] = item + return item + } + + private var isSplit: Bool { currentController()?.model.shownSplit != nil } + + func validateMenuItem(_ item: NSMenuItem) -> Bool { + if item.action == #selector(chooseTab(_:)) || item.action == #selector(chooseNewTab(_:)) { + return currentController() != nil && !isSplit + } + guard let command = Command(rawValue: item.tag - Self.baseTag) else { return false } + return currentController() != nil && command.isEnabled(isSplit: isSplit) + } + + @objc func choose(_ sender: NSMenuItem) { + guard let command = Command(rawValue: sender.tag - Self.baseTag), let controller = currentController(), + command.isEnabled(isSplit: controller.model.shownSplit != nil) + else { return } + switch command { + case .addSplitView: controller.addSplitView() + case .closeSplitPane: controller.closeSplitPane() + case .separateTabs: controller.separateSplit(of: controller.focusedPaneTabID) + case .splitWithTab: break + } + } + + // MARK: Tabs › Split with Tab › + + /// Lists the main window's Today tabs as the split button's menu does, + /// with New Tab, for its shown tab. + func menuNeedsUpdate(_ menu: NSMenu) { + menu.removeAllItems() + guard let controller = currentController(), controller.model.shownSplit == nil else { return } + let shown = controller.shownRowTabID + let entries = SplitLogic.splitWithTabSubmenu(for: shown, today: controller.model.tabs) + let favicons = Dictionary( + controller.model.allTabs.map { ($0.tabID, $0.favicon) }, uniquingKeysWith: { first, _ in first }) + for entry in entries { + switch entry { + case .separator: + menu.addItem(.separator()) + case .tab(let other, let title): + let item = NSMenuItem(title: title, action: #selector(chooseTab(_:)), keyEquivalent: "") + item.target = self + item.tag = Int(truncatingIfNeeded: other) + item.setFavicon(favicons[other] ?? nil) + menu.addItem(item) + case .newTab: + let item = NSMenuItem(title: entry.title, action: #selector(chooseNewTab(_:)), keyEquivalent: "") + item.target = self + menu.addItem(item) + default: + break + } + } + } + + @objc func chooseTab(_ sender: NSMenuItem) { + guard let controller = currentController(), controller.model.shownSplit == nil else { return } + controller.split(tab: controller.shownRowTabID, with: TabID(sender.tag), side: .trailing) + } + + @objc func chooseNewTab(_ sender: NSMenuItem) { + guard let controller = currentController(), controller.model.shownSplit == nil else { return } + controller.splitWithNewTab(controller.shownRowTabID) + } +} diff --git a/native/ClairUI/SplitViews.swift b/native/ClairUI/SplitViews.swift new file mode 100644 index 0000000..b17bdc5 --- /dev/null +++ b/native/ClairUI/SplitViews.swift @@ -0,0 +1,784 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost +import SwiftUI + +// MARK: The divider (add-split-view design D3) + +/// The gap between a split's panes: a grabber, the resize pointer, and a drag +/// that resizes the panes, reporting the divider's centre in the page area. +/// The grabber stays faint until the pointer is over the divider or drags +/// it. +final class SplitDividerView: NSView { + /// The divider moved to `x`, from the page area's leading edge; `done` on + /// the drag's last step. + var onDrag: ((CGFloat, _ done: Bool) -> Void)? + /// The page area's leading edge, in the divider's superview. + var areaMinX: CGFloat = 0 + + private let grabber = DynamicFillView(color: SplitDividerView.grabberColor) + private var dragOffset: CGFloat = 0 + private var isHovered = false + private var isDragging = false + + static let grabberColor = NSColor(name: "clair.splitGrabber") { appearance in + appearance.isDark ? NSColor(white: 1, alpha: 0.28) : NSColor(white: 0, alpha: 0.22) + } + static let grabberSize = CGSize(width: 4, height: 32) + /// The grabber's opacity while the pointer is elsewhere, and under it. + static let restingAlpha: CGFloat = 0.35 + static let activeAlpha: CGFloat = 1 + + override init(frame: NSRect) { + super.init(frame: frame) + wantsLayer = true + grabber.wantsLayer = true + grabber.layer?.cornerRadius = Self.grabberSize.width / 2 + grabber.alphaValue = Self.restingAlpha + addSubview(grabber) + setAccessibilityElement(true) + setAccessibilityRole(.splitter) + setAccessibilityLabel("Split view divider") + setAccessibilityIdentifier("clair.splitDivider") + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override var isFlipped: Bool { true } + + /// The grabber's opacity now, for tests. + var grabberAlpha: CGFloat { grabber.alphaValue } + + override func layout() { + super.layout() + grabber.frame = CGRect( + x: (bounds.width - Self.grabberSize.width) / 2, y: (bounds.height - Self.grabberSize.height) / 2, + width: Self.grabberSize.width, height: Self.grabberSize.height) + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + for area in trackingAreas { removeTrackingArea(area) } + addTrackingArea( + NSTrackingArea( + rect: .zero, options: [.mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)) + } + + override func mouseEntered(with event: NSEvent) { + isHovered = true + updateGrabber() + } + + override func mouseExited(with event: NSEvent) { + isHovered = false + updateGrabber() + } + + override func resetCursorRects() { + addCursorRect(bounds, cursor: .resizeLeftRight) + } + + override func mouseDown(with event: NSEvent) { + let point = convert(event.locationInWindow, from: nil) + dragOffset = point.x - bounds.midX + isDragging = true + updateGrabber() + } + + override func mouseDragged(with event: NSEvent) { + report(event, done: false) + } + + override func mouseUp(with event: NSEvent) { + isDragging = false + report(event, done: true) + isHovered = bounds.contains(convert(event.locationInWindow, from: nil)) + updateGrabber() + } + + private func report(_ event: NSEvent, done: Bool) { + guard let superview else { return } + let x = superview.convert(event.locationInWindow, from: nil).x - dragOffset - areaMinX + onDrag?(x, done) + } + + /// Fades the grabber to its full colour under the pointer or a drag, and + /// back. + private func updateGrabber() { + let alpha = isHovered || isDragging ? Self.activeAlpha : Self.restingAlpha + guard grabber.alphaValue != alpha else { return } + NSAnimationContext.runAnimationGroup { context in + context.duration = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? 0 : 0.15 + grabber.animator().alphaValue = alpha + } + } +} + +// MARK: Dragging a tab onto the page (D8) + +/// Takes a sidebar row or tile dragged over the page: the half or pane under +/// it becomes a drop zone, the drag turns into Arc's portrait card, and a +/// drop makes or changes the split. Clicks go through it to the page. +final class PageDropView: NSView { + /// The zone under `point`, in the view, for `item`, or nil where a drop + /// does nothing. + var zone: ((SidebarDragItem, CGPoint) -> SplitLogic.DropZone?)? + /// The favicon and title of what's dragged. + var describe: ((SidebarDragItem) -> (icon: NSImage?, title: String))? + /// The zone the drag is over, or nil once it leaves or drops. + var onTarget: ((SplitLogic.DropZone?) -> Void)? + var onDrop: ((SidebarDragItem, SplitLogic.DropZone) -> Void)? + + private let zoneView = DropZoneView() + private var item: SidebarDragItem? + private var current: SplitLogic.DropZone? + private var originals: [Int: (offset: CGPoint, size: CGSize, components: [NSDraggingImageComponent])] = [:] + private var card: NSImage? + + /// The zone's frame in the view for a zone, set by the window's layout. + var zoneFrame: ((SplitLogic.DropZone) -> CGRect)? + + override init(frame: NSRect) { + super.init(frame: frame) + registerForDraggedTypes([NSPasteboard.PasteboardType(SidebarDragItem.type.identifier)]) + zoneView.isHidden = true + addSubview(zoneView) + setAccessibilityElement(false) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override var isFlipped: Bool { true } + + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + override func layout() { + super.layout() + if let current, let frame = zoneFrame?(current) { + zoneView.frame = frame + } + } + + override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation { + let payload = sender.draggingPasteboard.string( + forType: NSPasteboard.PasteboardType(SidebarDragItem.type.identifier)) + item = payload.flatMap(SidebarDragItem.init(payload:)) + originals = [:] + card = nil + return update(sender) + } + + override func draggingUpdated(_ sender: any NSDraggingInfo) -> NSDragOperation { + update(sender) + } + + override func draggingExited(_ sender: (any NSDraggingInfo)?) { + if let sender { restore(sender) } + setZone(nil) + } + + override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool { + guard let item, let current else { return false } + setZone(nil) + onDrop?(item, current) + return true + } + + override func draggingEnded(_ sender: any NSDraggingInfo) { + item = nil + originals = [:] + setZone(nil) + } + + private func setZone(_ zone: SplitLogic.DropZone?) { + guard zone != current else { return } + current = zone + onTarget?(zone) + if let zone, let frame = zoneFrame?(zone) { + zoneView.frame = frame + zoneView.isHidden = false + } else { + zoneView.isHidden = true + } + } + + private func update(_ sender: any NSDraggingInfo) -> NSDragOperation { + guard let item else { return [] } + let point = convert(sender.draggingLocation, from: nil) + guard let zone = zone?(item, point) else { + restore(sender) + setZone(nil) + return [] + } + setZone(zone) + morph(sender, at: point) + return sender.draggingSourceOperationMask.contains(.move) ? .move : .generic + } + + /// Arc's portrait card: the favicon above the title, on a white card. + private func cardImage() -> NSImage? { + if let card { return card } + guard let item, let description = describe?(item) else { return nil } + let renderer = ImageRenderer( + content: DraggedPageCard(icon: description.icon, title: description.title) + .environment(\.colorScheme, effectiveAppearance.isDark ? .dark : .light)) + renderer.scale = window?.backingScaleFactor ?? 2 + card = renderer.nsImage + return card + } + + private func morph(_ sender: any NSDraggingInfo, at point: CGPoint) { + guard let image = cardImage() else { return } + sender.enumerateDraggingItems( + options: [], for: self, classes: [NSPasteboardItem.self], searchOptions: [:] + ) { [self] draggingItem, index, _ in + if originals[index] == nil { + let frame = draggingItem.draggingFrame + originals[index] = ( + CGPoint(x: frame.minX - point.x, y: frame.minY - point.y), frame.size, draggingItem.imageComponents ?? [] + ) + } + let size = image.size + draggingItem.setDraggingFrame( + NSRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height), + contents: image) + } + } + + private func restore(_ sender: any NSDraggingInfo) { + guard !originals.isEmpty else { return } + let point = convert(sender.draggingLocation, from: nil) + sender.enumerateDraggingItems( + options: [], for: self, classes: [NSPasteboardItem.self], searchOptions: [:] + ) { [self] draggingItem, index, _ in + guard let original = originals[index] else { return } + let components = original.components + draggingItem.draggingFrame = NSRect( + origin: CGPoint(x: point.x + original.offset.x, y: point.y + original.offset.y), size: original.size) + draggingItem.imageComponentsProvider = { components } + } + originals = [:] + } +} + +/// The drop zone: the accent colour at low opacity with a 2 pt accent +/// border, as Arc's (arc-reference/README.md, "Dragging a tab onto the +/// page"). +final class DropZoneView: NSView { + override init(frame: NSRect) { + super.init(frame: frame) + wantsLayer = true + layer?.cornerRadius = PageCardView.cornerRadius + layer?.cornerCurve = .continuous + layer?.borderWidth = 2 + updateColors() + setAccessibilityElement(true) + setAccessibilityRole(.group) + setAccessibilityIdentifier("clair.splitDropZone") + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + updateColors() + } + + private func updateColors() { + effectiveAppearance.performAsCurrentDrawingAppearance { + layer?.borderColor = NSColor.controlAccentColor.cgColor + layer?.backgroundColor = NSColor.controlAccentColor.withAlphaComponent(0.06).cgColor + } + } +} + +/// A tab dragged over the page, as Arc draws it: a white portrait card with +/// the favicon above the title in bold. +struct DraggedPageCard: View { + let icon: NSImage? + let title: String + + @Environment(\.colorScheme) private var colorScheme + + var body: some View { + VStack(spacing: 14) { + PinIcon(icon: icon, size: 16) + .frame(width: 18, height: 18) + Text(title) + .font(.system(size: 13, weight: .bold)) + .multilineTextAlignment(.center) + .lineLimit(3) + .foregroundStyle(colorScheme == .dark ? Color.white : Color.black) + } + .padding(16) + .frame(width: SplitLogic.dragCardSize.width, height: SplitLogic.dragCardSize.height) + .background( + colorScheme == .dark ? Color(white: 0.2) : Color.white, + in: .rect(cornerRadius: 14, style: .continuous)) + } +} + +// MARK: The split row (add-split-view design D13) + +/// One page of a split row. +struct SplitChipPage { + let title: String + let icon: NSImage? + /// The tab, while the page is open. + let tab: (any ClairTab)? + /// The pin, for a pinned or favorited split's page. + let pin: (any ClairPin)? + /// The row Rename… edits for this chip: its tab's, or its pinned tab's; a + /// favorite's is a dialog. + var renameRow: RowRename.Row? = nil + /// The rename in progress in this chip, or nil. + var rename: RowRename? = nil + + /// `page`'s chip, with its rename while `renaming` is its row's. + static func editable( + title: String, icon: NSImage?, tab: (any ClairTab)?, pin: (any ClairPin)?, renaming: RowRename? + ) -> SplitChipPage { + let row: RowRename.Row? = + if let pin { pin.isFavorite ? nil : .pin(pin.pinID) } else { tab.map { .tab($0.tabID) } } + return SplitChipPage( + title: title, icon: icon, tab: tab, pin: pin, renameRow: row, + rename: row != nil && renaming?.row == row ? renaming : nil) + } +} + +/// A split as one row in the sidebar, as in Arc: a chip per page with its +/// favicon and title, a thin line between them while not selected, a grey +/// pill each while selected. In Today, hovering the row shows a × on each +/// chip, which closes that page; in the pinned section, the row shows − or ×. +struct SplitRow: View { + let pages: [SplitChipPage] + let isActive: Bool + let isWindowKey: Bool + /// The button the row shows on hover. + enum Button: Equatable { + case closeKeepingPins + case removePin + + var help: String { + switch self { + case .closeKeepingPins: "Close and Keep Pinned" + case .removePin: "Remove Pin" + } + } + + var systemImage: String { self == .closeKeepingPins ? "minus" : "xmark" } + var shortcut: [String] { self == .removePin ? [] : ["⌘", "W"] } + var identifier: String { + switch self { + case .closeKeepingPins: "clair.pinClose" + case .removePin: "clair.pinRemove" + } + } + } + + /// The row's button, or nil for a × on each chip. + let button: Button? + let onTap: () -> Void + let onButton: () -> Void + /// Closes a chip's page, by its index: its × and a middle-click. + var onChipClose: ((Int) -> Void)? + /// The chip of the focused pane while the split shows, whose × Cmd+W is. + var focusedIndex: Int? + /// Each chip's context menu, by its index. + let menuItems: (Int) -> [RowClickCatcher.Item] + /// Ends a chip's rename in place. + var onRenameEnd: ((RowRename.Row, PinsLogic.NameChange) -> Void)? + + @State private var isHovered = false + @Environment(\.colorScheme) private var colorScheme + + /// The gap between the chips. + static let chipGap: CGFloat = 3 + /// The row's inset around its chips. + static let inset: CGFloat = 4 + + var body: some View { + HStack(spacing: Self.chipGap) { + ForEach(Array(pages.enumerated()), id: \.offset) { index, page in + if index > 0 { + // Kept, clear, while selected, so the chips don't move, as in Arc. + Rectangle() + .fill(PinFill.divider) + .frame(width: 1, height: 16) + .opacity(isActive ? 0 : 1) + } + chip(page, index: index) + } + if isHovered, let button { + IconButton( + systemImage: button.systemImage, help: button.help, shortcut: button.shortcut, size: TabRow.closeSize, + glyphSize: 12, glyphWeight: .bold, dimsWhenInactive: false, action: onButton + ) + .accessibilityIdentifier(button.identifier) + } + } + .padding(.horizontal, Self.inset) + .frame(height: TabRow.pillHeight) + .background { + if isActive { + RoundedRectangle(cornerRadius: TabRow.cornerRadius, style: .continuous) + .fill(SidebarFill.activePill(colorScheme, isWindowKey: isWindowKey)) + .shadow(color: SidebarFill.activeShadow, radius: 2, y: 1) + } else if isHovered { + RoundedRectangle(cornerRadius: TabRow.cornerRadius, style: .continuous).fill(SidebarFill.hover(colorScheme)) + } + } + .padding(.top, TabRow.pillInset) + .padding(.bottom, TabRow.pillInset + TabRow.spacing) + .contentShape(Rectangle()) + .onTapGesture(perform: onTap) + .onHover { isHovered = $0 } + .accessibilityElement(children: .contain) + .accessibilityLabel(pages.map(\.title).joined(separator: ", ")) + .accessibilityIdentifier("clair.splitRow") + .accessibilityAddTraits(isActive ? .isSelected : []) + } + + private func chip(_ page: SplitChipPage, index: Int) -> some View { + let showsClose = onChipClose != nil && isHovered + return HStack(spacing: 6) { + PinIcon(icon: page.icon, isLoading: page.tab?.isLoading == true && page.icon == nil, size: TabRow.faviconSize) + .frame(width: TabRow.iconSize, height: TabRow.iconSize) + if let rename = page.rename, let row = page.renameRow { + RenameField( + text: page.title, placeholder: page.pin?.title ?? page.tab?.title ?? "", rename: rename, + current: page.pin == nil ? page.tab?.name : nil + ) { change in onRenameEnd?(row, change) } + } else { + Text(page.title).font(TabRow.titleFont).lineLimit(1) + } + Spacer(minLength: 0) + } + .padding(.leading, 6) + // Room for the chip's ×, which then covers the title's end. + .padding(.trailing, showsClose ? TabRow.closeSize : 6) + .frame(maxWidth: .infinity, minHeight: 28, maxHeight: 28) + .background { + if isActive { + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(colorScheme == .dark ? Color.white.opacity(0.1) : Color.black.opacity(0.06)) + } + } + .contentShape(Rectangle()) + .overlay( + RowClickCatcher(onMiddleClick: { onChipClose?(index) }, menuItems: menuItems(index))) + .accessibilityElement(children: .ignore) + .accessibilityLabel(page.title) + .accessibilityIdentifier("clair.splitChip.\(index)") + .overlay(alignment: .trailing) { + if showsClose, let onChipClose { + IconButton( + systemImage: "xmark", help: "Close tab", shortcut: focusedIndex == index ? ["⌘", "W"] : [], + size: TabRow.closeSize, glyphSize: 12, glyphWeight: .bold, dimsWhenInactive: false + ) { onChipClose(index) } + .padding(.trailing, 1) + .accessibilityIdentifier("clair.splitClose.\(index)") + } + } + } +} + +// MARK: The favorite split tile (add-split-view spec, "The favorite split tile") + +/// A favorited split's tile: a segment per page with its icon, a thin line +/// between them, and, while shown, a white or light grey tile with a ring +/// blending from the leading page's icon colour to the trailing page's. +struct FavoriteSplitTile: View { + let icons: [NSImage?] + let isSelected: Bool + let onTap: () -> Void + let menuItems: (Int) -> [RowClickCatcher.Item] + let titles: [String] + + @State private var isHovered = false + @Environment(\.colorScheme) private var colorScheme + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: FavoriteTile.cornerRadius, style: .continuous) + .fill(PinFill.tile(colorScheme, hovered: isHovered, selected: isSelected)) + if isSelected { + RoundedRectangle(cornerRadius: FavoriteTile.cornerRadius, style: .continuous) + .strokeBorder( + LinearGradient( + colors: icons.map { Color(nsColor: IconColor.ring(of: $0)) }, startPoint: .leading, + endPoint: .trailing), + lineWidth: 2) + } + HStack(spacing: 0) { + ForEach(Array(icons.enumerated()), id: \.offset) { index, icon in + if index > 0 { + Rectangle() + .fill(PinFill.divider) + .frame(width: 1) + .padding(.vertical, 10) + } + PinIcon(icon: icon, size: FavoriteTile.iconSize) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .contentShape(Rectangle()) + .overlay(RowClickCatcher(onMiddleClick: {}, menuItems: menuItems(index))) + .accessibilityElement() + .accessibilityLabel(titles.indices.contains(index) ? titles[index] : "") + .accessibilityIdentifier("clair.splitChip.\(index)") + } + } + } + .contentShape(Rectangle()) + .onTapGesture(perform: onTap) + .onHover { hovering in withAnimation(sidebarHoverFade) { isHovered = hovering } } + .accessibilityElement(children: .contain) + .accessibilityLabel(titles.joined(separator: ", ")) + .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton) + .accessibilityIdentifier("clair.favoriteSplitTile") + } +} + +// MARK: The split button (add-split-view design D9) + +/// The split button, as in Arc, with Dia's menu: Split with Tab on a single +/// page, Move Left or Right, Separate Tabs and Close This Tab in a pane. It's +/// the toolbar's icon button, whose click opens the menu below it. +struct SplitButton: View { + let entries: [SplitLogic.MenuEntry] + /// Each Today tab's favicon, by ID. + let icon: (TabID) -> NSImage? + let choose: (SplitLogic.MenuEntry) -> Void + + @State private var anchor = MenuAnchor.Box() + + static let symbol = "square.split.2x1" + + var body: some View { + IconButton( + systemImage: Self.symbol, help: "Split view", height: IconButtonSize.toolbarHeight, + glyphSize: IconButtonSize.toolbarSiteControlsGlyph, glyphWeight: .regular + ) { + anchor.popUp(Self.menu(entries, icon: icon, choose: choose)) + } + .background(MenuAnchor(box: anchor)) + .accessibilityIdentifier("clair.splitButton") + } + + /// The menu for `entries`: a heading as a section header, a tab with its + /// favicon. + static func menu( + _ entries: [SplitLogic.MenuEntry], icon: (TabID) -> NSImage?, choose: @escaping (SplitLogic.MenuEntry) -> Void + ) -> NSMenu { + let menu = NSMenu() + menu.autoenablesItems = false + for entry in entries { + let item: NSMenuItem + switch entry { + case .separator: + menu.addItem(.separator()) + continue + case .heading(let title): + menu.addItem(.sectionHeader(title: title)) + continue + case .tab(let tabID, let title): + item = MenuAnchor.item(title) { choose(entry) } + item.setFavicon(icon(tabID)) + case .moveLeft(let isEnabled), .moveRight(let isEnabled): + item = MenuAnchor.item(entry.title) { choose(entry) } + item.isEnabled = isEnabled + case .newTab, .separateTabs, .closeThisTab: + item = MenuAnchor.item(entry.title) { choose(entry) } + } + menu.addItem(item) + } + return menu + } +} + +/// An invisible view behind a SwiftUI button that a menu pops up from. +struct MenuAnchor: NSViewRepresentable { + /// Holds the view, for the button's action to reach. + @MainActor + final class Box { + weak var view: NSView? + + /// Pops `menu` up below the view, its trailing edge at the view's when + /// it's wider, as the button sits at the toolbar's trailing end. + func popUp(_ menu: NSMenu) { + guard let view else { return } + let x = min(0, view.bounds.width - menu.size.width) + menu.popUp(positioning: nil, at: NSPoint(x: x, y: view.isFlipped ? view.bounds.maxY + 4 : -4), in: view) + } + } + + let box: Box + + func makeNSView(context: Context) -> NSView { + let view = AnchorView() + box.view = view + return view + } + + func updateNSView(_ view: NSView, context: Context) { + box.view = view + } + + private final class AnchorView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + } + + /// A menu item that runs `action`. + static func item(_ title: String, action: @escaping () -> Void) -> NSMenuItem { + let item = NSMenuItem(title: title, action: #selector(ItemTarget.run(_:)), keyEquivalent: "") + item.target = ItemTarget.shared + item.representedObject = RowClickCatcher.ItemAction(run: action) + return item + } + + @MainActor + private final class ItemTarget: NSObject { + static let shared = ItemTarget() + + @objc func run(_ sender: NSMenuItem) { + (sender.representedObject as? RowClickCatcher.ItemAction)?.run() + } + } +} + +// MARK: The sidebar's split rows (add-split-view design D2, D10) + +/// Builds a split's row in Today or the pinned section. +@MainActor +enum SplitRows { + /// A Today split's row, its chips in pane order. A chip holding a pinned + /// tab's or favorite's page has that pin's menu. + static func today( + _ tab: any ClairTab, model: BrowserWindowModel, highlighted: TabID, moveTargets: [any ClairSpace], + actions: (any SidebarActions)? + ) -> some View { + let panes = TabListLogic.panes(of: tab, in: model.allTabs).map { [$0.leading, $0.trailing] } ?? [tab] + let pages = panes.map { pane in + SplitChipPage.editable( + title: SplitLogic.title(of: pane), icon: pane.favicon, tab: pane, pin: model.pin(ofTab: pane.tabID), + renaming: model.renaming) + } + let tabID = tab.tabID + let focusedIndex = model.shownSplit.flatMap { split in + panes.contains { $0.tabID == split.paneIDs[split.focusedIndex] } ? split.focusedIndex : nil + } + return SplitRow( + pages: pages, isActive: panes.contains { $0.tabID == highlighted }, isWindowKey: model.isWindowKey, + button: nil, + onTap: { [weak actions] in actions?.showSplit(of: tabID) }, + onButton: {}, + // Each chip's × closes its page only, as a pane's × does. + onChipClose: { [weak actions] index in actions?.close(tab: panes[index].tabID) }, + focusedIndex: focusedIndex, + menuItems: { [weak actions] index in + let page = pages[index] + guard let pane = page.tab else { return [] } + if let pin = page.pin { + return pin.isFavorite + ? PinMenus.items( + PinsLogic.favoriteMenu(isShown: true, isOpen: true, isMuted: pane.isMuted, inSplit: true), pin: pin, + actions: actions) + : PinMenus.pinnedItems(pin: pin, tab: pane, moveTargets: moveTargets, actions: actions, inSplit: true) + } + return TabRow.menuItems( + tab: pane, canPin: model.showsPins, moveTargets: moveTargets, actions: actions, inSplit: true) + }, + onRenameEnd: { [weak actions] row, change in actions?.endRenaming(row, change: change) }) + } + + /// A pinned split's row: its pages' titles from when they were last open, + /// − while selected and × otherwise (split-view spec, "The pinned split + /// row"). + static func pinned( + _ split: any ClairPinnedSplit, model: BrowserWindowModel, highlighted: TabID, moveTargets: [any ClairSpace], + actions: (any SidebarActions)? + ) -> some View { + let pins = split.pins + let pages = pins.map { pin in + let tab = model.tab(ofPin: pin) + return SplitChipPage.editable( + title: PinsLogic.title(of: pin, tab: tab), icon: PinsLogic.icon(of: pin, tab: tab), tab: tab, pin: pin, + renaming: model.renaming) + } + let isActive = pins.contains { $0.tabID != ClairTabIDNone && $0.tabID == highlighted } + let openTab = pins.first { $0.tabID != ClairTabIDNone }?.tabID + let firstPin = pins.first?.pinID + return SplitRow( + pages: pages, isActive: isActive, isWindowKey: model.isWindowKey, + button: isActive ? .closeKeepingPins : .removePin, + onTap: { [weak actions] in open(openTab: openTab, firstPin: firstPin, actions: actions) }, + onButton: { [weak actions] in + if isActive, let openTab { + actions?.closeSplit(of: openTab) + } else if let firstPin { + actions?.removePin(firstPin) + } + }, + menuItems: { [weak actions] index in + PinMenus.pinnedItems( + pin: pages[index].pin!, tab: pages[index].tab, moveTargets: moveTargets, actions: actions, inSplit: true) + }, + onRenameEnd: { [weak actions] row, change in actions?.endRenaming(row, change: change) }) + } + + /// A favorited split's tile. + static func favorite(_ split: any ClairPinnedSplit, model: BrowserWindowModel, actions: (any SidebarActions)?) + -> some View + { + let pins = split.pins + let tabs = pins.map { model.tab(ofPin: $0) } + let highlighted = model.highlightedTab + let isShown = pins.contains { $0.tabID != ClairTabIDNone && $0.tabID == highlighted } + let openTab = pins.first { $0.tabID != ClairTabIDNone }?.tabID + let firstPin = pins.first?.pinID + return FavoriteSplitTile( + icons: zip(pins, tabs).map { PinsLogic.icon(of: $0, tab: $1) }, isSelected: isShown, + onTap: { [weak actions] in open(openTab: openTab, firstPin: firstPin, actions: actions) }, + menuItems: { [weak actions] index in + PinMenus.items( + PinsLogic.favoriteMenu( + isShown: isShown, isOpen: tabs[index] != nil, isMuted: tabs[index]?.isMuted == true, inSplit: true), + pin: pins[index], actions: actions) + }, + titles: zip(pins, tabs).map { PinsLogic.title(of: $0, tab: $1) }) + } + + /// Shows an open pinned split with the pane focused last, or opens its + /// pages. + private static func open(openTab: TabID?, firstPin: PinID?, actions: (any SidebarActions)?) { + if let openTab { + actions?.showSplit(of: openTab) + } else if let firstPin { + actions?.openPin(firstPin) + } + } + + /// A favicon sized for a menu item, or the globe that stands for a page + /// without one elsewhere, at the same size so titles stay aligned. + static func menuIcon(_ image: NSImage?) -> NSImage { + HistoryMenuBuilder.icon(image) + } +} + +extension NSMenuItem { + /// Shows a page's favicon, or the globe, beside the title: macOS 27 hides + /// menu item images unless they're asked to show. + func setFavicon(_ favicon: NSImage?) { + image = SplitRows.menuIcon(favicon) + if #available(macOS 27, *) { + preferredImageVisibility = .visible + } + } +} diff --git a/native/ClairUI/TabListLogic.swift b/native/ClairUI/TabListLogic.swift index 0c4ba50..7c4861f 100644 --- a/native/ClairUI/TabListLogic.swift +++ b/native/ClairUI/TabListLogic.swift @@ -19,16 +19,49 @@ enum TabListLogic { return target == source ? nil : target } - /// The tabs Close Tabs Below closes: every tab after `tabID` and its Peek, - /// which stays (add-peek design D8). + /// The tabs Close Tabs Below closes: every tab after `tabID`'s row, its + /// Peek and a split's other pane, which stay (add-peek design D8, + /// add-split-view D2). static func tabsBelow(_ tabID: TabID, in tabs: [any ClairTab]) -> [TabID] { - let last = peek(ofRow: tabID, in: tabs)?.tabID ?? tabID - guard let index = tabs.firstIndex(where: { $0.tabID == last }) else { + let family = Set(rowFamily(tabID, in: tabs)) + guard let index = tabs.lastIndex(where: { family.contains($0.tabID) }) else { return [] } return tabs[(index + 1)...].map(\.tabID) } + // MARK: Splits (add-split-view design D2) + + /// Whether `tab` is a split's trailing pane whose leading pane is also in + /// `ids`: the leading pane's row stands for both. + static func isFoldedPane(_ tab: any ClairTab, ids: Set) -> Bool { + tab.splitPartnerID != ClairTabIDNone && !tab.isLeadingPane && ids.contains(tab.splitPartnerID) + } + + /// The tabs a row stands for, in list order: the tab, its Peek, and for a + /// split, the other pane and its Peek. + static func rowFamily(_ row: TabID, in tabs: [any ClairTab]) -> [TabID] { + guard let tab = tabs.first(where: { $0.tabID == row }) else { return [row] } + var members: Set = [row] + if tab.peekID != ClairTabIDNone { members.insert(tab.peekID) } + if tab.splitPartnerID != ClairTabIDNone { + members.insert(tab.splitPartnerID) + if let partner = tabs.first(where: { $0.tabID == tab.splitPartnerID }), partner.peekID != ClairTabIDNone { + members.insert(partner.peekID) + } + } + return tabs.map(\.tabID).filter(members.contains) + } + + /// The split's two tabs, leading pane first, found among `tabs`, or nil + /// outside a split or while the other pane isn't among them. + static func panes(of tab: any ClairTab, in tabs: [any ClairTab]) -> (leading: any ClairTab, trailing: any ClairTab)? { + guard tab.splitPartnerID != ClairTabIDNone, + let partner = tabs.first(where: { $0.tabID == tab.splitPartnerID }) + else { return nil } + return tab.isLeadingPane ? (tab, partner) : (partner, tab) + } + // MARK: Peeks (add-peek design D4) /// Whether `tab` is a Peek, which has no row of its own. @@ -36,18 +69,29 @@ enum TabListLogic { tab.peekParentID != ClairTabIDNone } - /// The tabs with a row in the sidebar: every tab but the Peeks, in order. + /// The tabs with a row in the sidebar: every tab but the Peeks and a + /// split's trailing pane, whose leading pane's row stands for both + /// (add-split-view D2), in order. static func rows(_ tabs: [any ClairTab]) -> [any ClairTab] { - tabs.filter { !isPeek($0) } + let ids = Set(tabs.map(\.tabID)) + return tabs.filter { !isPeek($0) && !isFoldedPane($0, ids: ids) } } /// The row highlighted while `activeTabID` is active: the tab's own, or its - /// parent's while a Peek shows. + /// parent's while a Peek shows, or for a split's trailing pane, the leading + /// pane's row. static func highlightedRow(activeTabID: TabID, in tabs: [any ClairTab]) -> TabID { - guard let active = tabs.first(where: { $0.tabID == activeTabID }), isPeek(active), - tabs.contains(where: { $0.tabID == active.peekParentID }) - else { return activeTabID } - return active.peekParentID + guard let active = tabs.first(where: { $0.tabID == activeTabID }) else { return activeTabID } + var row = active + if isPeek(active), let parent = tabs.first(where: { $0.tabID == active.peekParentID }) { + row = parent + } + if row.splitPartnerID != ClairTabIDNone, !row.isLeadingPane, + tabs.contains(where: { $0.tabID == row.splitPartnerID }) + { + return row.splitPartnerID + } + return row.tabID } /// The tab a click on `row` activates: its Peek, if it has one, so the tab @@ -56,9 +100,9 @@ enum TabListLogic { peek(ofRow: row, in: tabs)?.tabID ?? row } - /// The number of rows: every tab but the Peeks. + /// The number of rows: every tab but the Peeks and folded panes. static func rowCount(_ tabs: [any ClairTab]) -> Int { - tabs.reduce(0) { $0 + (isPeek($1) ? 0 : 1) } + rows(tabs).count } /// Each row's Peek, by the row's tab ID, in one pass over the tabs: the @@ -114,7 +158,7 @@ enum TabListLogic { let moving = rows.remove(at: source) rows.insert(moving, at: target) return rows[.. Int? { - guard let tab = windowTabs.first(where: { $0.tabID == tabID }) else { return nil } - // The tab moves with its Peek. - let family: Set = [tab.tabID, tab.peekID] + guard windowTabs.contains(where: { $0.tabID == tabID }) else { return nil } + // The tab moves with its Peek, and a split's other pane with its own. + let family = Set(rowFamily(tabID, in: windowTabs)) let windowRest = windowTabs.filter { !family.contains($0.tabID) } let spaceRest = spaceTabs.filter { !family.contains($0.tabID) } let target = min(max(index, 0), windowRest.count) diff --git a/native/ClairUITests/ClairHostObjCxxTests.mm b/native/ClairUITests/ClairHostObjCxxTests.mm index 4cdc79c..604e51e 100644 --- a/native/ClairUITests/ClairHostObjCxxTests.mm +++ b/native/ClairUITests/ClairHostObjCxxTests.mm @@ -78,9 +78,11 @@ - (void)openURL:(NSURL*)url inProfile:(ClairProfileID)profileID { - (NSArray>*)pinnedItemsInSpace:(ClairSpaceID)spaceID { return @[]; } -- (NSArray>*)favoritesOfProfile:(ClairProfileID)profileID { +- (NSArray>*)favoritesOfProfile:(ClairProfileID)profileID { return @[]; } +- (void)separatePinnedSplit:(ClairPinnedSplitID)splitID { +} - (void)pinTab:(ClairTabID)tabID inFolder:(ClairFolderID)folderID atIndex:(NSInteger)index { } - (void)favoriteTab:(ClairTabID)tabID atIndex:(NSInteger)index { @@ -208,6 +210,8 @@ - (void)testHostCompilesInObjectiveCxx { [host setFolder:folder_id open:NO]; XCTAssertNil([host turnFolderIntoSpace:folder_id]); [host setPinnedURL:[NSURL URLWithString:@"https://example.com/"] forPin:pin]; + // The pinned split calls (add-split-view design D10). + [host separatePinnedSplit:@(std::string("0e4b2a10-0000-4000-8000-000000000000").c_str())]; // The link rule calls (add-link-rules design D4). XCTAssertEqual(host.linkRules.count, 0u); [host replaceLinkRules:@[ [[ObjCxxLinkRule alloc] init] ]]; @@ -236,6 +240,9 @@ - (void)testWindowContractCompilesInObjectiveCxx { XCTAssertEqual(ClairSuggestionKindBookmark, 4); std::string kinds[] = {"regular", "incognito", "guest"}; XCTAssertEqual(kinds[ClairProfileKindGuest], "guest"); + // add-split-view design D2: the side a split's new tab takes. + std::string sides[] = {"leading", "trailing"}; + XCTAssertEqual(sides[ClairSplitSideTrailing], "trailing"); for (Protocol* protocol in @[ @protocol(ClairBrowser), @protocol(ClairWindow), @protocol(ClairTab), @protocol(ClairAutocomplete), @protocol(ClairAutocompleteDelegate), @@ -243,7 +250,8 @@ - (void)testWindowContractCompilesInObjectiveCxx { @protocol(ClairExtensionAction), @protocol(ClairExtensionPrompt), @protocol(ClairInfobar), @protocol(ClairHistoryMenu), @protocol(ClairHistoryMenuDelegate), @protocol(ClairHistoryItem), @protocol(ClairSpace), @protocol(ClairSpacesObserver), @protocol(ClairProfile), - @protocol(ClairPin), @protocol(ClairLinkRule), @protocol(ClairBookmark), + @protocol(ClairPin), @protocol(ClairPinnedSplit), @protocol(ClairPinnedItem), + @protocol(ClairFolder), @protocol(ClairLinkRule), @protocol(ClairBookmark), @protocol(ClairBookmarkFolder) ]) { XCTAssertTrue(protocol_conformsToProtocol(protocol, @protocol(NSObject))); diff --git a/native/ClairUITests/FakeBrowser.swift b/native/ClairUITests/FakeBrowser.swift index 4b73bfd..0c4c947 100644 --- a/native/ClairUITests/FakeBrowser.swift +++ b/native/ClairUITests/FakeBrowser.swift @@ -33,15 +33,22 @@ final class FakeTab: NSObject, ClairTab { let browserID: BrowserID let pinID: PinID? let name: String? + let splitPartnerID: TabID + let isLeadingPane: Bool + let splitRatio: Double init( id: TabID, title: String = "", url: String? = nil, isLoading: Bool = false, loadProgress: Double = 0, canGoBack: Bool = false, canGoForward: Bool = false, isAudible: Bool = false, isMuted: Bool = false, isCrashed: Bool = false, indicators: TabIndicators = [], infobars: [any ClairInfobar] = [], isNotSecure: Bool = false, peekParentID: TabID = ClairTabIDNone, peekID: TabID = ClairTabIDNone, spaceID: SpaceID = FakeHost.homeID, - browserID: BrowserID = 0, pinID: PinID? = nil, name: String? = nil + browserID: BrowserID = 0, pinID: PinID? = nil, name: String? = nil, splitPartnerID: TabID = ClairTabIDNone, + isLeadingPane: Bool = false, splitRatio: Double = 0.5 ) { tabID = id + self.splitPartnerID = splitPartnerID + self.isLeadingPane = splitPartnerID != ClairTabIDNone && isLeadingPane + self.splitRatio = splitPartnerID != ClairTabIDNone ? splitRatio : 0.5 self.pinID = pinID self.name = name self.peekParentID = peekParentID @@ -71,7 +78,8 @@ final class FakeTab: NSObject, ClairTab { isAudible: Bool? = nil, isMuted: Bool? = nil, canGoBack: Bool? = nil, canGoForward: Bool? = nil, isCrashed: Bool? = nil, indicators: TabIndicators? = nil, isNotSecure: Bool? = nil, peekParentID: TabID? = nil, peekID: TabID? = nil, spaceID: SpaceID? = nil, browserID: BrowserID? = nil, - pinID: PinID?? = nil, name: String?? = nil + pinID: PinID?? = nil, name: String?? = nil, splitPartnerID: TabID? = nil, isLeadingPane: Bool? = nil, + splitRatio: Double? = nil ) -> FakeTab { FakeTab( id: tabID, title: title ?? self.title, url: url ?? (self.url?.absoluteString), @@ -82,7 +90,13 @@ final class FakeTab: NSObject, ClairTab { indicators: indicators ?? self.indicators, infobars: infobars, isNotSecure: isNotSecure ?? self.isNotSecure, peekParentID: peekParentID ?? self.peekParentID, peekID: peekID ?? self.peekID, spaceID: spaceID ?? self.spaceID, browserID: browserID ?? self.browserID, pinID: pinID ?? self.pinID, - name: name ?? self.name) + name: name ?? self.name, splitPartnerID: splitPartnerID ?? self.splitPartnerID, + isLeadingPane: isLeadingPane ?? self.isLeadingPane, splitRatio: splitRatio ?? self.splitRatio) + } + + /// A copy outside any split. + func unsplit() -> FakeTab { + with(splitPartnerID: ClairTabIDNone, isLeadingPane: false, splitRatio: 0.5) } } @@ -100,13 +114,15 @@ final class FakePin: NSObject, ClairPin { let tabs: [any ClairTab] let isAtPinnedURL: Bool let folderID: FolderID? + let pinnedSplitID: PinnedSplitID? init( id: PinID, isFavorite: Bool = false, spaceID: SpaceID? = FakeHost.homeID, profileID: ProfileID = FakeHost.defaultProfileID, url: String, title: String = "", name: String? = nil, - tab: FakeTab? = nil, isAtPinnedURL: Bool = true, folderID: FolderID? = nil + tab: FakeTab? = nil, isAtPinnedURL: Bool = true, folderID: FolderID? = nil, pinnedSplitID: PinnedSplitID? = nil ) { pinID = id + self.pinnedSplitID = pinnedSplitID self.isFavorite = isFavorite self.folderID = isFavorite ? nil : folderID self.spaceID = isFavorite ? nil : spaceID @@ -126,29 +142,71 @@ final class FakeFolder: NSObject, ClairFolder { let spaceID: SpaceID let name: String let isOpen: Bool - let pins: [any ClairPin] + let items: [any ClairPinnedItem] - init(id: FolderID, spaceID: SpaceID = FakeHost.homeID, name: String, isOpen: Bool = true, pins: [any ClairPin] = []) { + init( + id: FolderID, spaceID: SpaceID = FakeHost.homeID, name: String, isOpen: Bool = true, + items: [any ClairPinnedItem] = [] + ) { folderID = id self.spaceID = spaceID self.name = name self.isOpen = isOpen + self.items = items + } + + /// A folder holding pinned tabs only. + convenience init(id: FolderID, spaceID: SpaceID = FakeHost.homeID, name: String, isOpen: Bool = true, pins: [any ClairPin]) { + self.init(id: id, spaceID: spaceID, name: name, isOpen: isOpen, items: pins.map { FakePinnedItem(pin: $0) }) + } +} + +/// A stand-in for a pinned or favorited split snapshot (add-split-view +/// design D10). +final class FakePinnedSplit: NSObject, ClairPinnedSplit { + let pinnedSplitID: PinnedSplitID + let isFavorite: Bool + let spaceID: SpaceID? + let folderID: FolderID? + let profileID: ProfileID + let pins: [any ClairPin] + let ratio: Double + + init( + id: PinnedSplitID, isFavorite: Bool = false, spaceID: SpaceID? = FakeHost.homeID, folderID: FolderID? = nil, + profileID: ProfileID = FakeHost.defaultProfileID, pins: [any ClairPin], ratio: Double = 0.5 + ) { + pinnedSplitID = id + self.isFavorite = isFavorite + self.spaceID = isFavorite ? nil : spaceID + self.folderID = isFavorite ? nil : folderID + self.profileID = profileID self.pins = pins + self.ratio = ratio } } -/// A stand-in for a pinned item snapshot: a pin or a folder. +/// A stand-in for a pinned item snapshot: a pin, a split or a folder. final class FakePinnedItem: NSObject, ClairPinnedItem { let pin: (any ClairPin)? + let split: (any ClairPinnedSplit)? let folder: (any ClairFolder)? init(pin: any ClairPin) { self.pin = pin + split = nil + folder = nil + } + + init(split: any ClairPinnedSplit) { + pin = nil + self.split = split folder = nil } init(folder: any ClairFolder) { pin = nil + split = nil self.folder = folder } } @@ -619,6 +677,10 @@ final class FakeBrowser: NSObject, ClairBrowser { func closeTabNow(_ tabID: TabID) { host.operation { guard let tab = tab(tabID) else { return } + // add-split-view D12: the other pane stays, by itself. + if tab.splitPartnerID != ClairTabIDNone { + host.clearSplit(tabID) + } // A bound tab closing leaves its pin, unbound (D2). if let pinID = tab.pinID, host.boundTab(of: pinID)?.tabID == tabID { host.pageViews[tabID] = nil @@ -793,6 +855,22 @@ final class FakeBrowser: NSObject, ClairBrowser { /// window (add-profiles D13). fileprivate func closeAsClair(_ tabID: TabID, forAnotherWindow: Bool = false) { guard let tab = tab(tabID) else { return } + // add-split-view D12: a pane of the shown split closes alone, and the + // other shows by itself; a pinned split's pane leaves its item (D10). + if let partner = self.tab(tab.splitPartnerID), isShowingSplit(of: tabID) { + if let pinID = tab.pinID, let other = partner.pinID, + let split = host.pinRecord(pinID)?.splitID, host.pinRecord(other)?.splitID == split + { + host.takeOutOfSplit(pinID) + } + if activeTabID == tabID || self.tab(activeTabID)?.peekParentID == tabID { + isChoosingNext = true + setActive(partner.tabID) + isChoosingNext = false + } + closeTabNow(tabID) + return + } if isActiveRow(tabID) { if let next = nextRow(leaving: tabID, avoidingShown: forAnotherWindow) { choose(next) @@ -837,10 +915,15 @@ final class FakeBrowser: NSObject, ClairBrowser { func take(_ tabID: TabID) { guard let tab = rowTab(tabID), tab.browserID != browserID, let holder = holder(of: tab) else { return } let row = tab.peekParentID != ClairTabIDNone ? tab.peekParentID : tab.tabID - if holder.isActiveRow(row) { + // add-split-view: a split comes whole, both panes with their Peeks. + let partner = host.tab(row)?.splitPartnerID ?? ClairTabIDNone + let panes = partner == ClairTabIDNone ? [row] : [row, partner] + if panes.contains(where: holder.isActiveRow) { holder.beginStill(of: row) } - moveFamilyHere(row) + for pane in panes { + moveFamilyHere(pane) + } setActive(tabID) } @@ -1148,12 +1231,204 @@ final class FakeBrowser: NSObject, ClairBrowser { } } + // MARK: Split view (add-split-view D2, D8, D10 to D12) + + /// Whether the window shows `tabID`'s split: the active tab, or the Peek's + /// parent, is one of its panes. + func isShowingSplit(of tabID: TabID) -> Bool { + guard let tab = host.tab(tabID), tab.splitPartnerID != ClairTabIDNone else { return false } + let active = self.tab(activeTabID) + let shown = active.flatMap { $0.peekParentID != ClairTabIDNone ? $0.peekParentID : $0.tabID } + return shown == tabID || shown == tab.splitPartnerID + } + + /// Makes a split of two of the window's tabs, as the engine does once it + /// holds both, `other` focused. + func makeSplit(_ tabID: TabID, with otherID: TabID, otherLeading: Bool = false, ratio: Double = 0.5) { + host.operation { + if otherLeading { + host.setSplit(otherID, tabID, ratio: ratio) + } else { + host.setSplit(tabID, otherID, ratio: ratio) + } + setActive(otherID) + } + } + + func split(tab tabID: TabID, with otherID: TabID, side: SplitSide) { + host.operation { + record("split \(tabID) \(otherID) \(side.rawValue)") + guard tabID != otherID, let tab = rowTab(tabID), let other = rowTab(otherID), + tab.peekParentID == ClairTabIDNone, other.peekParentID == ClairTabIDNone, + tab.splitPartnerID == ClairTabIDNone, other.splitPartnerID == ClairTabIDNone + else { return } + // Both come here first, as a take does. + for row in [tab, other] where row.browserID != browserID { + moveFamilyHere(row.tabID) + } + makeSplit(tabID, with: otherID, otherLeading: side == .leading) + } + } + + func splitWithNewTab(_ tabID: TabID) { + host.operation { + record("splitWithNewTab \(tabID)") + guard let tab = rowTab(tabID), tab.peekParentID == ClairTabIDNone, tab.splitPartnerID == ClairTabIDNone else { + return + } + if tab.browserID != browserID { + moveFamilyHere(tabID) + } + // A new tab page right after the tab's row in Today, or at the top. + let page = FakeTab(id: host.newTabID(), url: "chrome://newtab/", spaceID: shownSpaceID, browserID: browserID) + host.pageViews[page.tabID] = NSView() + mutate(shownSpaceID) { list in + let family = TabListLogic.rowFamily(tabID, in: list) + let at = list.lastIndex { family.contains($0.tabID) }.map { $0 + 1 } ?? 0 + list.insert(page, at: at) + } + makeSplit(tabID, with: page.tabID) + } + } + + func showSplit(of tabID: TabID) { + host.operation { + record("showSplit \(tabID)") + guard let tab = rowTab(tabID) else { return } + guard let partner = host.tab(tab.splitPartnerID) else { + activate(tab: tabID) + return + } + // The pane focused last. + let last = host.lastActive(row: partner.tabID) > host.lastActive(row: tabID) ? partner.tabID : tabID + if self.tab(last) != nil { setActive(last) } else { take(last) } + } + } + + func replacePane(of tabID: TabID, with newTabID: TabID) { + host.operation { + record("replacePane \(tabID) \(newTabID)") + guard let pane = tab(tabID), let partner = host.tab(pane.splitPartnerID), let replacement = rowTab(newTabID), + replacement.splitPartnerID == ClairTabIDNone, replacement.peekParentID == ClairTabIDNone, + newTabID != pane.splitPartnerID + else { return } + if replacement.browserID != browserID { + moveFamilyHere(newTabID) + } + let leading = pane.isLeadingPane + let ratio = pane.splitRatio + host.clearSplit(tabID) + if leading { + host.setSplit(newTabID, partner.tabID, ratio: ratio) + } else { + host.setSplit(partner.tabID, newTabID, ratio: ratio) + } + // The replaced tab is the row right below the split's. + if let moved = host.tab(tabID), host.list(moved.spaceID).contains(where: { $0.tabID == tabID }) { + mutate(moved.spaceID) { list in + list.removeAll { $0.tabID == tabID } + let family = TabListLogic.rowFamily(partner.tabID, in: list) + let at = list.lastIndex { family.contains($0.tabID) }.map { $0 + 1 } ?? list.count + list.insert(moved, at: at) + } + } + setActive(newTabID) + } + } + + func swapSplit(of tabID: TabID) { + host.operation { + record("swapSplit \(tabID)") + guard rowTab(tabID) != nil else { return } + host.swapSplit(of: tabID) + } + } + + func separateSplit(of tabID: TabID) { + host.operation { + record("separateSplit \(tabID)") + guard let tab = rowTab(tabID), let partner = host.tab(tab.splitPartnerID) else { return } + if let pinID = tab.pinID, let split = host.pinRecord(pinID)?.splitID, + partner.pinID.flatMap({ host.pinRecord($0)?.splitID }) == split + { + host.separatePinnedSplit(split) + return + } + host.clearSplit(tabID) + } + } + + func closeSplit(of tabID: TabID) { + host.operation { + record("closeSplit \(tabID)") + guard let tab = rowTab(tabID), let partner = host.tab(tab.splitPartnerID), let holder = holder(of: tab) else { + return + } + holder.closeBothPanes(tab.isLeadingPane ? tab.tabID : partner.tabID, tab.isLeadingPane ? partner.tabID : tab.tabID) + } + } + + /// Closes a split's panes as Clair does: the next row first while it + /// shows, and the pins of a pinned split stay. + fileprivate func closeBothPanes(_ leadID: TabID, _ trailID: TabID) { + if isShowingSplit(of: leadID) { + let rowID = TabListLogic.highlightedRow(activeTabID: leadID, in: tabs + pinnedTabs) + if let next = nextRow(leaving: rowID), next != leadID, next != trailID { + choose(next) + } + } + host.clearSplit(leadID) + closeTabNow(trailID) + closeTabNow(leadID) + } + + func setSplitRatio(_ ratio: Double, of tabID: TabID) { + record("setSplitRatio \(ratio) \(tabID)") + guard rowTab(tabID) != nil else { return } + host.setSplitRatio(min(max(ratio, 0.05), 0.95), of: tabID) + } + + func openPeekInSplit(of tabID: TabID) { + host.operation { + record("openPeekInSplit \(tabID)") + guard let peek = peek(of: tabID), let parent = self.tab(peek.peekParentID), + parent.splitPartnerID == ClairTabIDNone + else { return } + unlinkPeek(peek.tabID) + host.setSplit(parent.tabID, peek.tabID) + setActive(peek.tabID) + } + } + // MARK: Pins (add-pinned-tabs-and-favorites D4, D5) func openPin(_ pinID: PinID) { host.operation { record("openPin \(pinID)") guard profileKind == .regular, let record = host.pinRecord(pinID) else { return } + // add-split-view D10: a pinned split opens each page that isn't open, + // as a split with its ratio. + if let splitID = record.splitID, let split = host.splitRecord(splitID) { + var panes: [TabID] = [] + for pin in host.pinRecords(ofSplit: splitID) { + if let bound = host.boundTab(of: pin.id) { + if bound.browserID != browserID { moveFamilyHere(bound.tabID) } + panes.append(bound.tabID) + } else { + let tab = FakeTab( + id: host.newTabID(), title: pin.title, url: pin.url, spaceID: pin.spaceID ?? "", browserID: browserID, + pinID: pin.id) + host.pageViews[tab.tabID] = NSView() + host.bind(pin.id, to: tab) + panes.append(tab.tabID) + } + } + if panes.count == 2, host.tab(panes[0])?.splitPartnerID != panes[1] { + host.setSplit(panes[0], panes[1], ratio: split.ratio) + } + showSplit(of: panes[0]) + return + } if let bound = host.boundTab(of: pinID) { if bound.browserID == browserID { setActive(bound.tabID) } else { take(bound.tabID) } return @@ -1296,7 +1571,9 @@ final class RecordingWindow: NSObject, ClairWindow { func showFind(text: String) { calls.append("find \(text)") } func hideFind() { calls.append("hideFind") } func findResultDidChange(_ result: FindResult) { calls.append("findResult \(result.activeMatch)/\(result.matchCount)") } - func statusTextDidChange(_ text: String?) { calls.append("status \(text ?? "-")") } + func statusTextDidChange(_ text: String?, isLink: Bool, tab tabID: TabID) { + calls.append("status \(text ?? "-")") + } func showToast(_ message: String) { calls.append("toast \(message)") } func pageFullscreenDidChange(_ fullscreen: Bool) { calls.append("pageFullscreen \(fullscreen)") } func showExclusiveAccessNotice(_ text: String?) { calls.append("notice \(text ?? "-")") } @@ -1352,13 +1629,20 @@ final class RecordingSpacesObserver: NSObject, ClairSpacesObserver { } func pinnedItemsDidChange(_ items: [any ClairPinnedItem], inSpace spaceID: SpaceID) { - let titles = items.map { item in - item.pin?.title ?? item.folder.map { "[\($0.name): \($0.pins.map(\.title).joined(separator: ","))]" } ?? "" - } - calls.append("pins \(spaceID) \(titles.joined(separator: ","))") + calls.append("pins \(spaceID) \(Self.titles(items))") + } + + func favoritesDidChange(_ favorites: [any ClairPinnedItem], ofProfile profileID: ProfileID) { + calls.append("favorites \(profileID) \(Self.titles(favorites))") } - func favoritesDidChange(_ favorites: [any ClairPin], ofProfile profileID: ProfileID) { - calls.append("favorites \(profileID) \(favorites.map(\.title).joined(separator: ","))") + /// Items as a test reads them: a pin's title, "News|Docs" for a split, and + /// "[Folder: …]" for a folder. + static func titles(_ items: [any ClairPinnedItem]) -> String { + items.map { item in + if let pin = item.pin { return pin.title } + if let split = item.split { return split.pins.map(\.title).joined(separator: "|") } + return item.folder.map { "[\($0.name): \(titles($0.items))]" } ?? "" + }.joined(separator: ",") } } diff --git a/native/ClairUITests/FakeBrowserTests.swift b/native/ClairUITests/FakeBrowserTests.swift index 9b5f577..2063ff0 100644 --- a/native/ClairUITests/FakeBrowserTests.swift +++ b/native/ClairUITests/FakeBrowserTests.swift @@ -552,8 +552,8 @@ struct FakeFolderTests { host.addPin(url: "https://plan.example/", title: "Plan", folder: docs) let items = host.pinnedItems(inSpace: FakeHost.homeID) #expect(items.map { $0.pin?.title ?? $0.folder?.name ?? "" } == ["Mail", "Docs"]) - #expect(items[1].folder?.pins.map(\.title) == ["Spec", "Plan"]) - #expect(items[1].folder?.pins.allSatisfy { $0.folderID == docs } == true) + #expect(items[1].folder.map { PinsLogic.pins(of: $0).map(\.title) } == ["Spec", "Plan"]) + #expect(items[1].folder.map { PinsLogic.pins(of: $0) }?.allSatisfy { $0.folderID == docs } == true) #expect(observer.calls.last == "pins \(FakeHost.homeID) Mail,[Docs: Spec,Plan]") // Every pinned tab of the Space, in the sidebar's order. #expect(host.pins(inSpace: FakeHost.homeID).map(\.title) == ["Mail", "Spec", "Plan"]) diff --git a/native/ClairUITests/FakeHost.swift b/native/ClairUITests/FakeHost.swift index cbf124e..ac66ec2 100644 --- a/native/ClairUITests/FakeHost.swift +++ b/native/ClairUITests/FakeHost.swift @@ -318,6 +318,19 @@ final class FakeHost: NSObject, ClairHost { var name: String? /// The folder holding a pinned tab, or nil. var folderID: FolderID? + /// add-split-view D10: the split holding it, and its pane there. A + /// split's pin has the split's place. + var splitID: PinnedSplitID? = nil + var splitIndex = 0 + } + + /// A pinned or favorited split as the engine's store keeps it. + struct SplitRecord { + let id: PinnedSplitID + var spaceID: SpaceID? + var profileID: ProfileID + var folderID: FolderID? + var ratio: Double } /// A folder as the engine's store keeps it. @@ -329,6 +342,8 @@ final class FakeHost: NSObject, ClairHost { private var records: [PinID: PinRecord] = [:] private var folderRecords: [FolderID: FolderRecord] = [:] + private var splitRecords: [PinnedSplitID: SplitRecord] = [:] + private var nextSplit = 1 /// Each Space's items, pins and folders, in order. private var pinOrder: [SpaceID: [String]] = [:] /// Each folder's pins, in order. @@ -350,26 +365,39 @@ final class FakeHost: NSObject, ClairHost { func folderRecord(_ folderID: FolderID) -> FolderRecord? { folderRecords[folderID] } - /// Every pin of a Space, its folders' included, in the sidebar's order. + /// The pins an item of an order list stands for: a pin, a split's two or + /// a folder's. + private func pinRecords(ofItem id: String) -> [PinRecord] { + if let record = records[id] { return [record] } + if splitRecords[id] != nil { return pinRecords(ofSplit: id) } + return (folderOrder[id] ?? []).flatMap { pinRecords(ofItem: $0) } + } + + /// Every pin of a Space, its folders' and splits' included, in the + /// sidebar's order. func pinRecords(inSpace spaceID: SpaceID) -> [PinRecord] { - (pinOrder[spaceID] ?? []).flatMap { id -> [PinRecord] in - if let record = records[id] { return [record] } - return (folderOrder[id] ?? []).compactMap { records[$0] } - } + (pinOrder[spaceID] ?? []).flatMap { pinRecords(ofItem: $0) } } /// A folder's pins, in order. func pinRecords(inFolder folderID: FolderID) -> [PinRecord] { - (folderOrder[folderID] ?? []).compactMap { records[$0] } + (folderOrder[folderID] ?? []).flatMap { pinRecords(ofItem: $0) } + } + + /// A split's pins, leading pane first. + func pinRecords(ofSplit splitID: PinnedSplitID) -> [PinRecord] { + records.values.filter { $0.splitID == splitID }.sorted { $0.splitIndex < $1.splitIndex } } + func splitRecord(_ splitID: PinnedSplitID) -> SplitRecord? { splitRecords[splitID] } + /// A Space's folders, in order. func folderRecords(inSpace spaceID: SpaceID) -> [FolderRecord] { (pinOrder[spaceID] ?? []).compactMap { folderRecords[$0] } } func favoriteRecords(ofProfile profileID: ProfileID) -> [PinRecord] { - (favoriteOrder[profileID] ?? []).compactMap { records[$0] } + (favoriteOrder[profileID] ?? []).flatMap { pinRecords(ofItem: $0) } } func boundTab(of pinID: PinID) -> FakeTab? { bound[pinID] } @@ -414,13 +442,27 @@ final class FakeHost: NSObject, ClairHost { return FakePin( id: record.id, isFavorite: record.spaceID == nil, spaceID: record.spaceID, profileID: record.profileID, url: record.url, title: record.title, name: record.name, tab: tab, isAtPinnedURL: atPinnedURL, - folderID: record.folderID) + folderID: record.folderID, pinnedSplitID: record.splitID) + } + + private func snapshot(_ split: SplitRecord) -> FakePinnedSplit { + FakePinnedSplit( + id: split.id, isFavorite: split.spaceID == nil, spaceID: split.spaceID, folderID: split.folderID, + profileID: split.profileID, pins: pinRecords(ofSplit: split.id).map(snapshot), ratio: split.ratio) + } + + /// The snapshot of an order list's item. + private func itemSnapshot(_ id: String) -> FakePinnedItem? { + if let record = records[id] { return FakePinnedItem(pin: snapshot(record)) } + if let split = splitRecords[id] { return FakePinnedItem(split: snapshot(split)) } + if let folder = folderRecords[id] { return FakePinnedItem(folder: snapshot(folder)) } + return nil } private func snapshot(_ folder: FolderRecord) -> FakeFolder { FakeFolder( id: folder.id, spaceID: folder.spaceID, name: folder.name, isOpen: isFolderOpen(folder.id), - pins: pinRecords(inFolder: folder.id).map(snapshot)) + items: (folderOrder[folder.id] ?? []).compactMap(itemSnapshot)) } private func pinsChanged(of pinID: PinID) { @@ -468,6 +510,36 @@ final class FakeHost: NSObject, ClairHost { /// Space's Today tabs at `index`, with its name. func unpin(_ pinID: PinID, toIndex index: Int, in browser: FakeBrowser) { guard let record = records[pinID] else { return } + // D10: a pinned split becomes a Today split, its pages opening when they + // aren't. + if let splitID = record.splitID, let split = splitRecords.removeValue(forKey: splitID) { + let spaceID = split.spaceID ?? browser.shownSpaceID + let pins = pinRecords(ofSplit: splitID) + let tabs = pins.map { pin in + bound[pin.id]?.with(spaceID: spaceID, pinID: .some(nil), name: .some(pin.name)) + ?? FakeTab( + id: newTabID(), title: pin.title, url: pin.url, spaceID: spaceID, browserID: browser.browserID, + name: pin.name) + } + for tab in tabs where pageViews[tab.tabID] == nil { + pageViews[tab.tabID] = NSView() + } + withOrder(spaceID: split.spaceID, profileID: split.profileID, folderID: split.folderID) { + $0.removeAll { $0 == splitID } + } + for pin in pins { + records[pin.id] = nil + bound[pin.id] = nil + } + var list = self.list(spaceID) + list.insert(contentsOf: tabs, at: max(0, min(index, list.count))) + setList(list, inSpace: spaceID) + if tabs.count == 2 { + setSplit(tabs[0].tabID, tabs[1].tabID, ratio: split.ratio) + } + containerChanged(spaceID: split.spaceID, profileID: split.profileID) + return + } let spaceID = record.spaceID ?? browser.shownSpaceID let tab = bound[pinID]?.with(spaceID: spaceID, pinID: .some(nil), name: .some(record.name)) @@ -558,11 +630,7 @@ final class FakeHost: NSObject, ClairHost { // MARK: ClairHost: pins func pinnedItems(inSpace spaceID: SpaceID) -> [any ClairPinnedItem] { - (pinOrder[spaceID] ?? []).compactMap { id -> FakePinnedItem? in - if let record = records[id] { return FakePinnedItem(pin: snapshot(record)) } - if let folder = folderRecords[id] { return FakePinnedItem(folder: snapshot(folder)) } - return nil - } + (pinOrder[spaceID] ?? []).compactMap(itemSnapshot) } /// Every pinned tab of a Space, its folders' included, as snapshots. @@ -570,10 +638,198 @@ final class FakeHost: NSObject, ClairHost { pinRecords(inSpace: spaceID).map(snapshot) } - func favorites(ofProfile profileID: ProfileID) -> [any ClairPin] { + func favorites(ofProfile profileID: ProfileID) -> [any ClairPinnedItem] { + (favoriteOrder[profileID] ?? []).compactMap(itemSnapshot) + } + + /// Every favorite of a profile, a favorited split's two included. + func favoritePins(ofProfile profileID: ProfileID) -> [any ClairPin] { favoriteRecords(ofProfile: profileID).map(snapshot) } + // MARK: Pinned and favorited splits (add-split-view design D10) + + /// The order list holding a split's or pin's place. + private func withOrder( + spaceID: SpaceID?, profileID: ProfileID, folderID: FolderID?, _ body: (inout [String]) -> Void + ) { + if let folderID { + body(&folderOrder[folderID, default: []]) + } else if let spaceID { + body(&pinOrder[spaceID, default: []]) + } else { + body(&favoriteOrder[profileID, default: []]) + } + } + + /// Adds a pinned or favorited split of two new pins, as the store would, + /// without tabs, and returns its pins' IDs. + @discardableResult + func addSplit( + _ leading: (url: String, title: String), _ trailing: (url: String, title: String), + inSpace spaceID: SpaceID? = FakeHost.homeID, folder folderID: FolderID? = nil, + profile profileID: ProfileID = FakeHost.defaultProfileID, ratio: Double = 0.5, at index: Int = Int.max + ) -> [PinID] { + let splitID = "split-\(nextSplit)" + nextSplit += 1 + let spaceID = folderID.flatMap { folderRecords[$0]?.spaceID } ?? spaceID + splitRecords[splitID] = SplitRecord( + id: splitID, spaceID: spaceID, profileID: profileID, folderID: spaceID == nil ? nil : folderID, ratio: ratio) + var ids: [PinID] = [] + for (pane, page) in [leading, trailing].enumerated() { + let pinID = "pin-\(nextPin)" + nextPin += 1 + records[pinID] = PinRecord( + id: pinID, spaceID: spaceID, profileID: profileID, url: page.url, title: page.title, + folderID: spaceID == nil ? nil : folderID, splitID: splitID, splitIndex: pane) + ids.append(pinID) + } + withOrder(spaceID: spaceID, profileID: profileID, folderID: spaceID == nil ? nil : folderID) { + Self.insert(splitID, into: &$0, at: index) + } + containerChanged(spaceID: spaceID, profileID: profileID) + return ids + } + + /// D10: Separate Tabs on a pinned or favorited split: its pins take its + /// place, in pane order. + func separatePinnedSplit(_ splitID: PinnedSplitID) { + commands.append("separatePinnedSplit \(splitID)") + guard let split = splitRecords.removeValue(forKey: splitID) else { return } + let pins = pinRecords(ofSplit: splitID) + for pin in pins { + records[pin.id]?.splitID = nil + records[pin.id]?.splitIndex = 0 + } + withOrder(spaceID: split.spaceID, profileID: split.profileID, folderID: split.folderID) { order in + guard let at = order.firstIndex(of: splitID) else { return } + order.replaceSubrange(at...at, with: pins.map(\.id)) + } + // Their open tabs leave the split. + if pins.count == 2, let lead = bound[pins[0].id], let trail = bound[pins[1].id], lead.splitPartnerID == trail.tabID { + clearSplit(lead.tabID) + } + containerChanged(spaceID: split.spaceID, profileID: split.profileID) + } + + /// D10, Arc: one pane of a pinned split closed: the other pin takes the + /// split's place, and `pinID` goes. + func takeOutOfSplit(_ pinID: PinID) { + guard let splitID = records[pinID]?.splitID, let split = splitRecords.removeValue(forKey: splitID), + let other = pinRecords(ofSplit: splitID).first(where: { $0.id != pinID }) + else { return } + records[pinID] = nil + records[other.id]?.splitID = nil + records[other.id]?.splitIndex = 0 + withOrder(spaceID: split.spaceID, profileID: split.profileID, folderID: split.folderID) { order in + if let at = order.firstIndex(of: splitID) { order[at] = other.id } + } + containerChanged(spaceID: split.spaceID, profileID: split.profileID) + } + + /// D10: pins a split of two Today tabs as one item. + private func pinSplit(lead: FakeTab, trail: FakeTab, folder folderID: FolderID?, at index: Int, favorite: Bool) { + guard let profileID = profile(ofSpace: lead.spaceID) else { return } + let ids = addSplit( + (lead.url?.absoluteString ?? lead.urlText, lead.title), (trail.url?.absoluteString ?? trail.urlText, trail.title), + inSpace: favorite ? nil : lead.spaceID, folder: favorite ? nil : folderID, profile: profileID, + ratio: lead.splitRatio, at: index) + setList( + list(lead.spaceID).filter { ![lead.tabID, trail.tabID, lead.peekID, trail.peekID].contains($0.tabID) }, + inSpace: lead.spaceID) + bind(ids[0], to: lead) + bind(ids[1], to: trail) + } + + // MARK: Open splits (add-split-view design D1, D2) + + /// Makes `lead` and `trail` a split with `ratio`: their snapshots name + /// each other, and in a Today list the trailing pane and its Peek follow + /// the leading pane and its Peek. + func setSplit(_ leadID: TabID, _ trailID: TabID, ratio: Double = 0.5) { + guard let lead = tab(leadID), let trail = tab(trailID) else { return } + replaceSilently(lead.with(splitPartnerID: trailID, isLeadingPane: true, splitRatio: ratio)) + replaceSilently(trail.with(splitPartnerID: leadID, isLeadingPane: false, splitRatio: ratio)) + keepTogether(leadID, trailID) + } + + /// Ends a tab's split: both tabs stay where they are. + func clearSplit(_ tabID: TabID) { + guard let tab = tab(tabID) else { return } + let partner = self.tab(tab.splitPartnerID) + replaceSilently(tab.unsplit()) + if let partner { + replaceSilently(partner.unsplit()) + } + spaceOrPinsChanged(tab) + if let partner { spaceOrPinsChanged(partner) } + } + + /// Sets a split's ratio. + func setSplitRatio(_ ratio: Double, of tabID: TabID) { + guard let tab = tab(tabID), let partner = self.tab(tab.splitPartnerID) else { return } + replaceSilently(tab.with(splitRatio: ratio)) + replaceSilently(partner.with(splitRatio: ratio)) + // D10: a pinned split keeps its ratio in its record. + if let pinID = tab.pinID, let splitID = records[pinID]?.splitID { + splitRecords[splitID]?.ratio = ratio + } + spaceOrPinsChanged(tab) + spaceOrPinsChanged(partner) + } + + /// Swaps a split's panes. + func swapSplit(of tabID: TabID) { + guard let tab = tab(tabID), let partner = self.tab(tab.splitPartnerID) else { return } + let lead = tab.isLeadingPane ? tab : partner + let trail = tab.isLeadingPane ? partner : tab + // A pinned split's pins follow their panes. + if let a = lead.pinID, let b = trail.pinID, let split = records[a]?.splitID, records[b]?.splitID == split { + records[a]?.splitIndex = 1 + records[b]?.splitIndex = 0 + } + setSplit(trail.tabID, lead.tabID, ratio: lead.splitRatio) + } + + /// Replaces a tab's snapshot in its list or binding without a push. + private func replaceSilently(_ tab: FakeTab) { + if let pinID = tab.pinID, bound[pinID]?.tabID == tab.tabID { + bound[pinID] = tab + return + } + replaceQuietly(tab) + } + + /// Pushes the list or pins showing a tab. + private func spaceOrPinsChanged(_ tab: FakeTab) { + if let pinID = tab.pinID, bound[pinID]?.tabID == tab.tabID { + pinsChanged(of: pinID) + } else { + setList(list(tab.spaceID), inSpace: tab.spaceID) + } + } + + /// D7: a Today split is one row: the trailing pane's family right after + /// the leading pane's. + private func keepTogether(_ leadID: TabID, _ trailID: TabID) { + guard let lead = tab(leadID), let trail = tab(trailID) else { return } + let leadToday = list(lead.spaceID).contains { $0.tabID == leadID } + let trailToday = list(trail.spaceID).contains { $0.tabID == trailID } + if leadToday && trailToday && lead.spaceID == trail.spaceID { + var tabs = list(lead.spaceID) + let family = tabs.filter { $0.tabID == trailID || ($0.peekParentID == trailID && trail.peekID == $0.tabID) } + tabs.removeAll { candidate in family.contains { $0.tabID == candidate.tabID } } + if let at = tabs.firstIndex(where: { $0.tabID == leadID }) { + let after = lead.peekID != ClairTabIDNone && tabs.indices.contains(at + 1) && tabs[at + 1].tabID == lead.peekID + tabs.insert(contentsOf: family, at: at + (after ? 2 : 1)) + } + setList(tabs, inSpace: lead.spaceID) + } else { + spaceOrPinsChanged(lead) + spaceOrPinsChanged(trail) + } + } + /// D5: a Today tab becomes a pin of its Space, in `folderID`, or of its /// profile's favorites, keeping its page and name. private func pin(tab tabID: TabID, inFolder folderID: FolderID?, at index: Int, favorite: Bool) { @@ -582,6 +838,14 @@ final class FakeHost: NSObject, ClairHost { else { return } // A folder of another Space is ignored. if let folderID, folderRecords[folderID]?.spaceID != tab.spaceID || favorite { return } + // add-split-view D10: a split of two Today tabs is pinned as one; a split + // with a pinned tab or favorite isn't. + if let partner = self.tab(tab.splitPartnerID) { + guard partner.pinID == nil, partner.spaceID == tab.spaceID else { return } + let lead = tab.isLeadingPane ? tab : partner + pinSplit(lead: lead, trail: lead === tab ? partner : tab, folder: folderID, at: index, favorite: favorite) + return + } let pinID = "pin-\(nextPin)" nextPin += 1 let record = PinRecord( @@ -607,6 +871,10 @@ final class FakeHost: NSObject, ClairHost { folderID.map { "movePin \(pinID) \(spaceID) \($0) \(index)" } ?? "movePin \(pinID) \(spaceID) \(index)") guard var record = records[pinID], isSpace(spaceID), let profileID = profile(ofSpace: spaceID) else { return } if let folderID, folderRecords[folderID]?.spaceID != spaceID { return } + if let splitID = record.splitID { + moveSplit(splitID, toSpace: spaceID, folder: folderID, profile: profileID, at: index) + return + } let from = (record.spaceID, record.profileID) removeRecord(pinID) record.spaceID = spaceID @@ -630,9 +898,44 @@ final class FakeHost: NSObject, ClairHost { pinsChanged(of: pinID) } + /// D10: a split moves whole, in the same profile. + private func moveSplit( + _ splitID: PinnedSplitID, toSpace spaceID: SpaceID?, folder folderID: FolderID?, profile profileID: ProfileID, + at index: Int + ) { + guard var split = splitRecords[splitID] else { return } + let from = (split.spaceID, split.profileID) + withOrder(spaceID: split.spaceID, profileID: split.profileID, folderID: split.folderID) { + $0.removeAll { $0 == splitID } + } + split.spaceID = spaceID + split.folderID = spaceID == nil ? nil : folderID + split.profileID = profileID + splitRecords[splitID] = split + withOrder(spaceID: split.spaceID, profileID: profileID, folderID: split.folderID) { + Self.insert(splitID, into: &$0, at: index) + } + for pin in pinRecords(ofSplit: splitID) { + records[pin.id]?.spaceID = spaceID + records[pin.id]?.folderID = split.folderID + records[pin.id]?.profileID = profileID + if let tab = bound[pin.id] { + bound[pin.id] = tab.with(spaceID: spaceID ?? "") + } + } + if from.0 != spaceID { + containerChanged(spaceID: from.0, profileID: from.1) + } + containerChanged(spaceID: spaceID, profileID: profileID) + } + func movePin(_ pinID: PinID, toFavoritesAt index: Int) { commands.append("movePinToFavorites \(pinID) \(index)") guard var record = records[pinID] else { return } + if let splitID = record.splitID { + moveSplit(splitID, toSpace: nil, folder: nil, profile: record.profileID, at: index) + return + } let from = (record.spaceID, record.profileID) removeRecord(pinID) record.spaceID = nil @@ -649,6 +952,23 @@ final class FakeHost: NSObject, ClairHost { func removePin(_ pinID: PinID) { commands.append("removePin \(pinID)") + // D10: a split's pin goes with its split and the other pin. + if let splitID = records[pinID]?.splitID, let split = splitRecords.removeValue(forKey: splitID) { + let pins = pinRecords(ofSplit: splitID) + withOrder(spaceID: split.spaceID, profileID: split.profileID, folderID: split.folderID) { + $0.removeAll { $0 == splitID } + } + let tabs = pins.compactMap { bound.removeValue(forKey: $0.id) } + for pin in pins { records[pin.id] = nil } + containerChanged(spaceID: split.spaceID, profileID: split.profileID) + for tab in tabs { + guard let browser = browser(tab.browserID) else { continue } + let today = tab.with(spaceID: split.spaceID ?? browser.shownSpaceID, pinID: .some(nil)) + setList([today] + list(today.spaceID), inSpace: today.spaceID) + browser.close(tab: tab.tabID) + } + return + } guard let record = records[pinID], let index = removeRecord(pinID) else { return } removedPins.insert((record, index), at: 0) let tab = bound.removeValue(forKey: pinID) @@ -705,8 +1025,13 @@ final class FakeHost: NSObject, ClairHost { folder.spaceID = spaceID folderRecords[folderID] = folder Self.insert(folderID, into: &pinOrder[spaceID, default: []], at: index) - // D1, D11: its pins follow it, and their tabs as Move to Space moves them. - for pinID in folderOrder[folderID] ?? [] { + // D1, D11: its pins follow it, a split's two with their split, and their + // tabs as Move to Space moves them. + for id in folderOrder[folderID] ?? [] { + splitRecords[id]?.spaceID = spaceID + splitRecords[id]?.profileID = profileID + } + for pinID in (folderOrder[folderID] ?? []).flatMap({ pinRecords(ofItem: $0).map(\.id) }) { guard var record = records[pinID] else { continue } let changedProfile = record.profileID != profileID record.spaceID = spaceID @@ -756,7 +1081,10 @@ final class FakeHost: NSObject, ClairHost { let index = pinOrder[folder.spaceID]?.firstIndex(of: folderID) else { return } pinOrder[folder.spaceID]?.remove(at: index) - let pins = (folderOrder.removeValue(forKey: folderID) ?? []).compactMap { records.removeValue(forKey: $0) } + // A split's two pins go with their split. + let items = folderOrder.removeValue(forKey: folderID) ?? [] + let pins = items.flatMap { pinRecords(ofItem: $0) }.compactMap { records.removeValue(forKey: $0.id) } + for id in items { splitRecords[id] = nil } removedFolders.insert((folder, pins, index, closedFolders.remove(folderID) != nil), at: 0) let tabs = pins.compactMap { bound.removeValue(forKey: $0.id) } spaceChanged(folder.spaceID) @@ -1008,18 +1336,38 @@ final class FakeHost: NSObject, ClairHost { guard tab.spaceID != spaceID else { return } operation { let wasActive = browser.isActiveRow(tab.tabID) + // add-split-view D7: a Today split moves whole; a pinned tab's or + // favorite's pane stays with its pin, and the split ends. + var partner = self.tab(tab.splitPartnerID) + if let other = partner, other.pinID != nil || other.spaceID != tab.spaceID { + clearSplit(tab.tabID) + tab = self.tab(tab.tabID) ?? tab + partner = nil + } if profile(ofSpace: tab.spaceID) != profile(ofSpace: spaceID) { // add-profiles D9: a page can't change profile; it reopens at its URL - // at the top of the other Space, without its Peek. - let reopened = reopen(tab, inSpace: spaceID, at: 0, by: browser) + // at the top of the other Space, without its Peek, a split as one. + let panes = partner.map { tab.isLeadingPane ? [tab, $0] : [$0, tab] } ?? [tab] + let reopened = panes.enumerated().map { index, pane in reopen(pane, inSpace: spaceID, at: index, by: browser) } + if reopened.count == 2 { + setSplit(reopened[0].tabID, reopened[1].tabID, ratio: tab.splitRatio) + } if wasActive { - browser.setActive(reopened.tabID) + browser.setActive(reopened[panes.firstIndex { $0.tabID == tab.tabID } ?? 0].tabID) + } + for pane in panes { + browser.closeReopened(pane.tabID) } - browser.closeReopened(tab.tabID) } else { - // The tab and its Peek go to the top of the other list (add-spaces D7). + // The tab and its Peek go to the top of the other list (add-spaces + // D7), with its split's other pane and that pane's Peek. let source = tab.spaceID - let family = list(source).filter { $0.tabID == tab.tabID || ($0.peekParentID == tab.tabID && tab.peekID == $0.tabID) } + var members: Set = [tab.tabID] + for member in [tab] + (partner.map { [$0] } ?? []) { + members.insert(member.tabID) + if member.peekID != ClairTabIDNone { members.insert(member.peekID) } + } + let family = list(source).filter { members.contains($0.tabID) } let moved = family.map { $0.with(spaceID: spaceID) } setList(list(source).filter { candidate in !family.contains { $0.tabID == candidate.tabID } }, inSpace: source) setList(moved + list(spaceID), inSpace: spaceID) @@ -1029,6 +1377,7 @@ final class FakeHost: NSObject, ClairHost { browser.followActiveTab() } tabClosed(tab.tabID) + if let partner { tabClosed(partner.tabID) } } } } diff --git a/native/ClairUITests/FoldersTests.swift b/native/ClairUITests/FoldersTests.swift index e50b88c..2c13d50 100644 --- a/native/ClairUITests/FoldersTests.swift +++ b/native/ClairUITests/FoldersTests.swift @@ -26,6 +26,8 @@ struct FolderRowsTests { rows.map { row in switch row { case .pin(let pin, let folder): folder == nil ? pin.title : " \(pin.title)" + case .split(let split, let folder): + (folder == nil ? "" : " ") + split.pins.map(\.title).joined(separator: "|") case .folder(let folder): "[\(folder.name)]" } } @@ -306,12 +308,12 @@ struct FolderWindowTests { let tab = w.browser.addTab(title: "Plan", url: "https://plan.example/") // A Today tab on the folder's row: its first tab. w.controller.drop(.tab(tab.tabID), on: .folder(docs, 0)) - #expect(w.model.pinnedItems.first?.folder?.pins.map(\.title) == ["Plan", "Spec"]) + #expect(w.model.pinnedItems.first?.folder.map { PinsLogic.pins(of: $0).map(\.title) } == ["Plan", "Spec"]) // A favorite on the folder's row leaves the grid. let calendar = w.host.addPin(url: "https://cal.example/", title: "Calendar", inSpace: nil) w.controller.drop(.pin(calendar), on: .folder(docs, 0)) #expect(w.model.favorites.isEmpty) - #expect(w.model.pinnedItems.first?.folder?.pins.first?.title == "Calendar") + #expect(w.model.pinnedItems.first?.folder.flatMap { PinsLogic.pins(of: $0).first }?.title == "Calendar") // A tab dragged out above the folder. let spec = w.model.pins.first { $0.title == "Spec" }?.pinID ?? "" w.controller.drop(.pin(spec), on: .pinned(0)) @@ -348,7 +350,7 @@ struct FolderWindowTests { #expect(w.model.pinnedItems.isEmpty) // Restore Last Closed Tab brings it back with its tab. w.host.restoreRemovedFolder() - #expect(w.model.pinnedItems.first?.folder?.pins.map(\.title) == ["Spec"]) + #expect(w.model.pinnedItems.first?.folder.map { PinsLogic.pins(of: $0).map(\.title) } == ["Spec"]) } @Test func duplicateAddsACopyRightAfter() { @@ -358,7 +360,7 @@ struct FolderWindowTests { w.host.addPin(url: "https://mail.example/", title: "Mail") w.controller.duplicateFolder(docs) #expect(w.model.pinnedItems.map { $0.pin?.title ?? $0.folder?.name ?? "" } == ["Docs", "Docs", "Mail"]) - #expect(w.model.pinnedItems[1].folder?.pins.map(\.title) == ["Spec"]) + #expect(w.model.pinnedItems[1].folder.map { PinsLogic.pins(of: $0).map(\.title) } == ["Spec"]) } @Test func movingAFolderShowsTheNotice() { diff --git a/native/ClairUITests/PinsTests.swift b/native/ClairUITests/PinsTests.swift index 3c0077f..af8703b 100644 --- a/native/ClairUITests/PinsTests.swift +++ b/native/ClairUITests/PinsTests.swift @@ -224,18 +224,44 @@ struct PinsLogicTests { @Test func theMenusListTheirItemsInOrder() { let today = PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true).compactMap { $0?.title } - #expect(today == ["Copy Link", "Rename…", "Duplicate", "Mute", "Pin Tab", "Pin to Favorites", "Close Tab", "Close Tabs Below"]) + #expect( + today == [ + "Copy Link", "Rename…", "Duplicate", "Mute", "Split with Tab", "Pin Tab", "Pin to Favorites", "Close Tab", + "Close Tabs Below", + ]) let pinned = PinsLogic.pinnedMenu(isOpen: true, isMuted: false, canMoveToSpace: true).compactMap { $0?.title } #expect( pinned == [ - "Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Move to Space", "Pin to Favorites", - "Unpin Tab", + "Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Split with Tab", "Move to Space", + "Pin to Favorites", "Unpin Tab", ]) let favorite = PinsLogic.favoriteMenu(isShown: true, isOpen: true, isMuted: false).compactMap { $0?.title } - #expect(favorite == ["Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Close Tab", "Remove Favorite"]) + #expect( + favorite == [ + "Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Split with Tab", "Close Tab", + "Remove Favorite", + ]) #expect(!PinsLogic.favoriteMenu(isShown: false, isOpen: false, isMuted: false).contains { $0?.title == "Close Tab" }) } + /// add-split-view, "The split row's menu": a chip's menu has no Split + /// with Tab or Edit Pinned Page, and Separate Tabs. + @Test func aSplitChipsMenusSeparateTheSplit() { + let today = PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true, inSplit: true) + .compactMap { $0?.title } + #expect( + today == [ + "Copy Link", "Rename…", "Duplicate", "Mute", "Separate Tabs", "Pin Tab", "Pin to Favorites", "Close Tab", + "Close Tabs Below", + ]) + let pinned = PinsLogic.pinnedMenu(isOpen: false, isMuted: false, canMoveToSpace: false, inSplit: true) + .compactMap { $0?.title } + #expect(pinned == ["Copy Link", "Rename…", "Mute", "Duplicate", "Separate Tabs", "Pin to Favorites", "Unpin Tab"]) + let favorite = PinsLogic.favoriteMenu(isShown: false, isOpen: false, isMuted: false, inSplit: true) + .compactMap { $0?.title } + #expect(favorite == ["Copy Link", "Rename…", "Mute", "Duplicate", "Separate Tabs", "Remove Favorite"]) + } + @Test func privateWindowsMenusHaveNoPinItems() { let today = PinsLogic.todayMenu(isMuted: true, canMoveToSpace: false, canPin: false).compactMap { $0?.title } #expect(!today.contains("Pin Tab") && !today.contains("Pin to Favorites")) diff --git a/native/ClairUITests/SpacesTests.swift b/native/ClairUITests/SpacesTests.swift index cd3fe48..a8d9e8a 100644 --- a/native/ClairUITests/SpacesTests.swift +++ b/native/ClairUITests/SpacesTests.swift @@ -149,7 +149,7 @@ struct SpacesLogicTests { @Test func tabRowMenuHasNoMoveToSpaceWithOneSpace() { let row = TabRow(tab: FakeTab(id: 1, title: "One"), isActive: false, isWindowKey: true, moveTargets: []) #expect(!row.menuItems.contains { $0.title == "Move to Space" }) - #expect(row.menuItems.compactMap(\.title) == ["Copy Link", "Duplicate", "Mute", "Close Tab", "Close Tabs Below"]) + #expect(row.menuItems.compactMap(\.title) == ["Copy Link", "Duplicate", "Mute", "Split with Tab", "Close Tab", "Close Tabs Below"]) } // MARK: Names and the form diff --git a/native/ClairUITests/SplitTests.swift b/native/ClairUITests/SplitTests.swift new file mode 100644 index 0000000..2540359 --- /dev/null +++ b/native/ClairUITests/SplitTests.swift @@ -0,0 +1,501 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost +import Testing + +@testable import ClairUI + +/// Split view's rules (add-split-view design D3, D8, D9, D13). +struct SplitLogicTests { + let area = CGRect(x: 10, y: 0, width: 1010, height: 700) + + @Test func thePanesShareTheAreaBesideTheGap() { + let panes = SplitLogic.paneFrames(in: area, ratio: 0.5) + #expect(panes[0] == CGRect(x: 10, y: 0, width: 500, height: 700)) + #expect(panes[1] == CGRect(x: 520, y: 0, width: 500, height: 700)) + #expect(SplitLogic.dividerFrame(in: area, ratio: 0.5) == CGRect(x: 510, y: 0, width: 10, height: 700)) + let uneven = SplitLogic.paneFrames(in: area, ratio: 0.3) + #expect(uneven[0].width == 300 && uneven[1].width == 700) + } + + @Test func theDividerKeepsEachPageWideEnough() { + // 1000 pt beside the gap: each page at least 210 pt. + #expect(SplitLogic.ratio(forDividerAt: 0, width: 1010, current: 0.5) == 0.21) + #expect(SplitLogic.ratio(forDividerAt: 1010, width: 1010, current: 0.5) == 0.79) + #expect(SplitLogic.ratio(forDividerAt: 305, width: 1010, current: 0.5) == 0.3) + // Too narrow for two such pages: the ratio holds. + #expect(SplitLogic.ratio(forDividerAt: 100, width: 400, current: 0.4) == 0.4) + } + + @Test func theDividerSnapsToEqualPanesNearTheCentre() { + #expect(SplitLogic.snappedRatio(forDividerAt: 520, width: 1010, current: 0.5) == 0.5) + #expect(SplitLogic.snappedRatio(forDividerAt: 600, width: 1010, current: 0.5) != 0.5) + } + + @Test func theSingleMenuListsTodaysOtherUnsplitTabs() { + let mail = FakeTab(id: 1, title: "Mail") + let news = FakeTab(id: 2, title: "News", splitPartnerID: 3, isLeadingPane: true) + let docs = FakeTab(id: 3, title: "Docs", splitPartnerID: 2) + let plan = FakeTab(id: 4, title: "Plan") + let menu = SplitLogic.singlePageMenu(shown: 1, today: [mail, news, docs, plan]) + #expect(menu == [.heading("Split with Tab"), .tab(4, title: "Plan"), .separator, .newTab]) + #expect(SplitLogic.splitWithTabSubmenu(for: 4, today: [mail, plan]) == [.tab(1, title: "Mail"), .separator, .newTab]) + } + + @Test func aPanesMenuMovesTheOtherWay() { + #expect( + SplitLogic.paneMenu(isLeading: true) == [ + .moveLeft(isEnabled: false), .moveRight(isEnabled: true), .separator, .separateTabs, .closeThisTab, + ]) + #expect(SplitLogic.paneMenu(isLeading: false).prefix(2) == [.moveLeft(isEnabled: true), .moveRight(isEnabled: false)]) + } + + @Test func aDropLandsOnTheHalfOrThePaneUnderIt() { + let bounds = CGRect(x: 0, y: 0, width: 1010, height: 700) + #expect(SplitLogic.dropZone(at: CGPoint(x: 100, y: 10), in: bounds, split: nil) == .half(.leading)) + #expect(SplitLogic.dropZone(at: CGPoint(x: 900, y: 10), in: bounds, split: nil) == .half(.trailing)) + let split = ShownSplit(leadingID: 1, trailingID: 2, ratio: 0.3, focusedIndex: 0) + #expect(SplitLogic.dropZone(at: CGPoint(x: 400, y: 10), in: bounds, split: split) == .pane(1)) + #expect(SplitLogic.dropZone(at: CGPoint(x: 200, y: 10), in: bounds, split: split) == .pane(0)) + #expect(SplitLogic.dropZone(at: CGPoint(x: 2000, y: 10), in: bounds, split: split) == nil) + // The page slides to the other half. + #expect(SplitLogic.slidFrame(in: bounds, dropSide: .leading).minX == 510) + } + + @Test func shownTabsAndSplitRowsMakeNoDropZone() { + let shown = FakeTab(id: 1, title: "Shown") + let other = FakeTab(id: 2, title: "Other") + let paired = FakeTab(id: 3, title: "Paired", splitPartnerID: 4) + #expect(SplitLogic.acceptsDrop(of: other, shown: nil, activeTabID: 1)) + #expect(!SplitLogic.acceptsDrop(of: shown, shown: nil, activeTabID: 1)) + #expect(!SplitLogic.acceptsDrop(of: paired, shown: nil, activeTabID: 1)) + let split = ShownSplit(leadingID: 1, trailingID: 5, ratio: 0.5, focusedIndex: 0) + #expect(!SplitLogic.acceptsDrop(of: shown, shown: split, activeTabID: 1)) + #expect(SplitLogic.acceptsDrop(of: other, shown: split, activeTabID: 1)) + // A closed pin opens first, unless it's a pinned split's, which is a + // split row. + #expect(SplitLogic.acceptsDrop(of: nil, shown: nil, activeTabID: 1)) + #expect(!SplitLogic.acceptsDrop(of: nil, isPinnedSplit: true, shown: nil, activeTabID: 1)) + } + + @Test func theLinkStatusNamesWhatAClickDoes() { + let url = "https://example.com/" + #expect(SplitLogic.linkStatus(url: url, modifiers: [], opensPeekOnShiftClick: true, inPeek: false) == url) + #expect( + SplitLogic.linkStatus(url: url, modifiers: .option, opensPeekOnShiftClick: true, inPeek: false) + == "Open https://example.com/ in Split View") + #expect( + SplitLogic.linkStatus(url: url, modifiers: .shift, opensPeekOnShiftClick: true, inPeek: false) + == "Open https://example.com/ in Peek") + #expect(SplitLogic.linkStatus(url: url, modifiers: .shift, opensPeekOnShiftClick: false, inPeek: false) == url) + #expect(SplitLogic.linkStatus(url: url, modifiers: .option, opensPeekOnShiftClick: true, inPeek: true) == url) + #expect(SplitLogic.linkStatus(url: url, modifiers: [.option, .command], opensPeekOnShiftClick: true, inPeek: false) == url) + } + + @Test func theCommandBarCentresOnThePaneInsideTheWindow() { + let bounds = CGRect(x: 0, y: 0, width: 1200, height: 800) + #expect(SplitLogic.commandBarMinX(width: 600, pane: nil, bounds: bounds) == 300) + #expect(SplitLogic.commandBarMinX(width: 400, pane: CGRect(x: 700, y: 0, width: 500, height: 800), bounds: bounds) == 750) + // Narrower than the bar: kept inside the window. + #expect(SplitLogic.commandBarMinX(width: 600, pane: CGRect(x: 900, y: 0, width: 300, height: 800), bounds: bounds) == 600) + } + + /// D9: a pinned tab or favorite whose page is in a split can't make + /// another. + @MainActor + @Test func splitWithTabIsDisabledOnASplitPin() { + let split = FakePin( + id: "p", url: "https://mail.example/", title: "Mail", tab: FakeTab(id: 1, title: "Mail", splitPartnerID: 2)) + let lone = FakePin(id: "q", url: "https://news.example/", title: "News", tab: FakeTab(id: 3, title: "News")) + let menu = PinsLogic.pinnedMenu(isOpen: true, isMuted: false, canMoveToSpace: false) + let splitItem = PinMenus.items(menu, pin: split, actions: nil).first { $0.title == "Split with Tab" } + let loneItem = PinMenus.items(menu, pin: lone, actions: nil).first { $0.title == "Split with Tab" } + if case .disabledSubmenu = splitItem {} else { Issue.record("Split with Tab isn't disabled") } + if case .submenu = loneItem {} else { Issue.record("Split with Tab isn't a submenu") } + } + + @Test func paneHeadersExpandWhileFocusedOrHovered() { + let leading = PageHeaderContent.pane(leading: true, expanded: false) + #expect(leading.showsSidebarToggle && !leading.showsReload && !leading.showsSplitButton && leading.showsClose) + #expect(leading.trailingFixedCount == 1) + let trailing = PageHeaderContent.pane(leading: false, expanded: true) + #expect(!trailing.showsSidebarToggle && trailing.showsReload && trailing.showsSplitButton) + #expect(trailing.trailingFixedCount == 3) + #expect(trailing.identifier == "clair.paneToolbar.1") + #expect(PageHeaderContent.tab.showsSplitButton && !PageHeaderContent.tab.showsClose) + #expect(!PageHeaderContent.peek.showsSplitButton) + } +} + +/// One row for a split, its tabs in pane order (add-split-view D2). +struct SplitRowListTests { + @Test func aSplitsTrailingPaneFoldsIntoItsRow() { + let mail = FakeTab(id: 1, title: "Mail") + let news = FakeTab(id: 2, title: "News", splitPartnerID: 3, isLeadingPane: true) + let docs = FakeTab(id: 3, title: "Docs", splitPartnerID: 2) + let tabs: [any ClairTab] = [mail, news, docs] + #expect(TabListLogic.rows(tabs).map(\.title) == ["Mail", "News"]) + #expect(TabListLogic.highlightedRow(activeTabID: 3, in: tabs) == 2) + #expect(TabListLogic.rowFamily(2, in: tabs) == [2, 3]) + #expect(SplitLogic.shownSplit(activeTabID: 3, in: tabs) == ShownSplit(leadingID: 2, trailingID: 3, ratio: 0.5, focusedIndex: 1)) + #expect(SplitLogic.shownSplit(activeTabID: 1, in: tabs) == nil) + } +} + +/// The fake engine's splits, which the window tests rely on (add-split-view +/// tasks 1.3). +@MainActor +struct FakeSplitTests { + let browser = FakeBrowser() + let window = RecordingWindow() + let mail: FakeTab + let news: FakeTab + let docs: FakeTab + + init() { + browser.clairWindow = window + docs = browser.addTab(title: "Docs") + news = browser.addTab(title: "News") + mail = browser.addTab(title: "Mail") + } + + private func tab(_ tab: FakeTab) -> FakeTab { browser.host.tab(tab.tabID)! } + + @Test func splittingMakesTheOtherTabTrailingAndFocused() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + #expect(tab(mail).splitPartnerID == docs.tabID && tab(mail).isLeadingPane) + #expect(tab(docs).splitPartnerID == mail.tabID && !tab(docs).isLeadingPane) + #expect(browser.activeTabID == docs.tabID) + #expect(browser.isShowingSplit(of: mail.tabID)) + // Already in a split: nothing. + browser.split(tab: news.tabID, with: docs.tabID, side: .trailing) + #expect(tab(news).splitPartnerID == ClairTabIDNone) + } + + @Test func aLeadingSideDropPutsTheOtherTabFirst() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .leading) + #expect(tab(docs).isLeadingPane && !tab(mail).isLeadingPane) + } + + @Test func swappingKeepsTheFocus() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.swapSplit(of: docs.tabID) + #expect(tab(docs).isLeadingPane) + #expect(browser.activeTabID == docs.tabID) + } + + @Test func theRatioIsKept() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.setSplitRatio(0.3, of: mail.tabID) + #expect(abs(tab(mail).splitRatio - 0.3) < 0.001 && abs(tab(docs).splitRatio - 0.3) < 0.001) + } + + @Test func separatingKeepsBothTabsInPaneOrder() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.separateSplit(of: mail.tabID) + #expect(tab(mail).splitPartnerID == ClairTabIDNone && tab(docs).splitPartnerID == ClairTabIDNone) + #expect(browser.tabs.contains { $0.tabID == mail.tabID } && browser.tabs.contains { $0.tabID == docs.tabID }) + } + + @Test func closingAPaneLeavesTheOtherAlone() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.close(tab: docs.tabID) + #expect(!browser.tabs.contains { $0.tabID == docs.tabID }) + #expect(tab(mail).splitPartnerID == ClairTabIDNone) + #expect(browser.activeTabID == mail.tabID) + } + + @Test func closingTheSplitClosesBothPanes() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.closeSplit(of: mail.tabID) + #expect(!browser.tabs.contains { $0.tabID == mail.tabID || $0.tabID == docs.tabID }) + #expect(browser.activeTabID == news.tabID) + } + + @Test func replacingAPaneTakesItsPlace() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.replacePane(of: docs.tabID, with: news.tabID) + #expect(tab(mail).splitPartnerID == news.tabID && tab(news).splitPartnerID == mail.tabID) + #expect(tab(docs).splitPartnerID == ClairTabIDNone) + #expect(browser.activeTabID == news.tabID) + } + + @Test func aNewTabSplitAddsANewTabPage() { + browser.splitWithNewTab(mail.tabID) + let page = tab(mail).splitPartnerID + #expect(page != ClairTabIDNone) + #expect(browser.host.tab(page)?.urlText == "chrome://newtab/") + #expect(browser.activeTabID == page) + } + + @Test func aPeekOpensInSplitWithItsParent() { + let peek = browser.openPeek(of: mail.tabID, title: "Peek")! + browser.openPeekInSplit(of: mail.tabID) + #expect(tab(mail).splitPartnerID == peek.tabID) + #expect(tab(peek).peekParentID == ClairTabIDNone) + #expect(browser.activeTabID == peek.tabID) + } + + @Test func showingASplitFocusesThePaneFocusedLast() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + browser.activate(tab: news.tabID) + browser.showSplit(of: mail.tabID) + #expect(browser.activeTabID == docs.tabID) + } +} + +/// Pinned and favorited splits in the fake store (add-split-view D10). +@MainActor +struct FakePinnedSplitTests { + let host = FakeHost() + + @Test func aPinnedSplitIsOneItem() { + host.addPin(url: "https://mail.example/", title: "Mail") + host.addSplit(("https://news.example/", "News"), ("https://docs.example/", "Docs"), ratio: 0.4) + let items = host.pinnedItems(inSpace: FakeHost.homeID) + #expect(items.count == 2) + let split = items[1].split + #expect(split?.pins.map(\.title) == ["News", "Docs"]) + #expect(abs((split?.ratio ?? 0) - 0.4) < 0.001) + #expect(split?.pins.allSatisfy { $0.pinnedSplitID == split?.pinnedSplitID } == true) + let rows = PinsLogic.pinnedRows(items, collapsed: false, highlighted: ClairTabIDNone) + #expect(rows.count == 2) + if case .split = rows[1] {} else { Issue.record("The split isn't one row") } + } + + @Test func separatingPutsItsPinsInItsPlace() { + host.addSplit(("https://news.example/", "News"), ("https://docs.example/", "Docs")) + host.addPin(url: "https://mail.example/", title: "Mail") + let splitID = host.pinnedItems(inSpace: FakeHost.homeID)[0].split!.pinnedSplitID + host.separatePinnedSplit(splitID) + let titles = host.pinnedItems(inSpace: FakeHost.homeID).map { $0.pin?.title ?? "" } + #expect(titles == ["News", "Docs", "Mail"]) + } + + @Test func aFavoritedSplitIsOneTile() { + host.addSplit(("https://news.example/", "News"), ("https://docs.example/", "Docs"), inSpace: nil) + let items = host.favorites(ofProfile: FakeHost.defaultProfileID) + #expect(items.count == 1) + #expect(items[0].split?.isFavorite == true) + #expect(PinsLogic.allPins(items).map(\.title) == ["News", "Docs"]) + } +} + +/// The window's split view (add-split-view D3, D9). +@MainActor +struct SplitWindowTests { + let browser = FakeBrowser() + let controller: BrowserWindowController + let mail: FakeTab + let docs: FakeTab + + init() { + let defaults = UserDefaults(suiteName: "ClairUITests.Split.\(UUID().uuidString)")! + controller = BrowserWindowController( + browser: browser, spaces: browser.spaces, preferences: SidebarPreferences(defaults: defaults), + peekPreference: PeekPreference(defaults: defaults)) + browser.clairWindow = controller + docs = browser.addTab(title: "Docs", url: "https://docs.example/") + mail = browser.addTab(title: "Mail", url: "https://mail.example/") + } + + @Test func eachPaneShowsItsPage() { + let root = controller.rootView + #expect(root.secondCard.isHidden || controller.model.shownSplit == nil) + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + #expect(controller.model.shownSplit == ShownSplit(leadingID: mail.tabID, trailingID: docs.tabID, ratio: 0.5, focusedIndex: 1)) + #expect(root.card.pageView === browser.pageView(for: mail.tabID)) + #expect(root.secondCard.pageView === browser.pageView(for: docs.tabID)) + #expect(root.focusedCard === root.secondCard) + // Swapped: the pages change cards. + browser.swapSplit(of: docs.tabID) + #expect(root.card.pageView === browser.pageView(for: docs.tabID)) + #expect(root.secondCard.pageView === browser.pageView(for: mail.tabID)) + // Separated: the focused tab alone. + browser.separateSplit(of: docs.tabID) + #expect(controller.model.shownSplit == nil) + #expect(root.card.pageView === browser.pageView(for: docs.tabID)) + #expect(root.secondCard.pageView == nil) + } + + @Test func addSplitViewWhileSplitShowsAToast() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + controller.addSplitView() + #expect(controller.model.toast?.message == "Cannot Add New Pane") + } + + @Test func addSplitViewOpensTheCommandBarOnTheNewPane() { + controller.addSplitView() + let split = controller.model.shownSplit + #expect(split?.leadingID == mail.tabID) + #expect(split?.focusedIndex == 1) + #expect(controller.model.commandBar != nil) + } + + @Test func aTabsMenuSplitsItWithTheChosenTab() { + let items = controller.splitWithTabItems(tab: docs.tabID, pin: nil) + #expect(items.compactMap(\.title) == ["Mail", "New Tab"]) + guard case .icon(_, _, let run) = items[0] else { + Issue.record("Mail isn't an item with its favicon") + return + } + run() + #expect(browser.host.tab(docs.tabID)?.splitPartnerID == mail.tabID) + #expect(browser.host.tab(docs.tabID)?.isLeadingPane == true) + #expect(browser.activeTabID == mail.tabID) + } + + @Test func theMenuBarItemsFollowTheSplit() { + let menu = SplitMenu() + menu.currentController = { [controller] in controller } + let main = NSMenu() + for (title, tag) in [("Tab", PinsMenu.tabMenuTag), ("View", PinsMenu.viewMenuTag)] { + let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") + item.tag = tag + item.submenu = NSMenu(title: title) + main.addItem(item) + } + #expect(menu.install(in: main)) + let view = main.items[1].submenu! + #expect(view.items.prefix(3).map(\.title) == ["Add Split View", "Close Split Pane", "Separate Tabs"]) + let close = menu.items[.closeSplitPane]! + #expect(close.keyEquivalent == "-" && close.keyEquivalentModifierMask == [.control, .shift]) + #expect(!menu.validateMenuItem(close)) + #expect(menu.validateMenuItem(menu.items[.splitWithTab]!)) + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + #expect(menu.validateMenuItem(close)) + #expect(!menu.validateMenuItem(menu.items[.splitWithTab]!)) + // Close Split Pane closes the focused pane. + menu.choose(close) + #expect(!browser.tabs.contains { $0.tabID == docs.tabID }) + #expect(controller.model.shownSplit == nil) + } + + @Test func theDividerSnapsToEqualPanesAsItMoves() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + let root = controller.rootView + root.frame = CGRect(x: 0, y: 0, width: 1400, height: 900) + root.layoutSubtreeIfNeeded() + let width = root.pageArea.width + let divider = root.splitDivider + divider.onDrag?(width / 2 - 150, false) + #expect(controller.model.liveSplitRatio != 0.5) + // Within the snap distance, before letting go: equal panes. + divider.onDrag?(width / 2 + 12, false) + #expect(controller.model.liveSplitRatio == 0.5) + divider.onDrag?(width / 2 + 12, true) + #expect(browser.host.tab(mail.tabID)?.splitRatio == 0.5) + // The grabber rests faint until the pointer is over it. + #expect(divider.grabberAlpha == SplitDividerView.restingAlpha) + } + + @Test func theDividerKeepsTheRatioItsLetGoAt() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + let root = controller.rootView + root.frame = CGRect(x: 0, y: 0, width: 1400, height: 900) + root.layoutSubtreeIfNeeded() + let width = root.pageArea.width + root.splitDivider.onDrag?(width / 2 - 150, true) + let ratio = browser.host.tab(mail.tabID)?.splitRatio ?? 0.5 + #expect(ratio < 0.45) + #expect(abs(ratio - (controller.model.liveSplitRatio ?? ratio)) < 0.001) + } + + @Test func aDraggedRatioBelongsToItsSplit() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + guard let split = controller.model.shownSplit else { + Issue.record("No split") + return + } + controller.model.liveSplitPanes = split.paneIDs + controller.model.liveSplitRatio = 0.3 + #expect(controller.model.liveRatio(of: split) == 0.3) + let other = ShownSplit(leadingID: 90, trailingID: 91, ratio: 0.6, focusedIndex: 0) + #expect(controller.model.liveRatio(of: other) == nil) + // Another split shown, or none: the dragged ratio goes. + browser.separateSplit(of: docs.tabID) + controller.settleSplitRatio() + #expect(controller.model.liveSplitRatio == nil) + } + + @Test func theTrailingPanesPageFillsTheWindowInPageFullScreen() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + let root = controller.rootView + root.frame = CGRect(x: 0, y: 0, width: 1400, height: 900) + controller.model.isPageFullscreen = true + root.needsLayout = true + root.layoutSubtreeIfNeeded() + #expect(controller.model.shownSplit?.focusedIndex == 1) + #expect(root.focusedCard === root.secondCard) + #expect(!root.secondCard.isHidden && root.card.isHidden) + #expect(root.secondCard.frame == root.pageArea) + #expect(root.secondCard.pageView === browser.pageView(for: docs.tabID)) + } + + @Test func pinCommandsActOnTheFocusedPane() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + // The row stays highlighted on its leading pane. + #expect(controller.model.highlightedTab == mail.tabID) + #expect(controller.model.commandTab == docs.tabID) + } + + @Test func aFavoriteDroppedInPlaceStaysThereAfterASplit() { + let host = browser.host + host.addSplit(("https://news.example/", "News"), ("https://docs.example/", "Docs"), inSpace: nil) + let c = host.addPin(url: "https://c.example/", title: "C", inSpace: nil) + host.addPin(url: "https://d.example/", title: "D", inSpace: nil) + host.addPin(url: "https://e.example/", title: "E", inSpace: nil) + // Slot 2, just after C's tile: where it is. + controller.drop(.pin(c), on: .favorites(2)) + #expect( + host.favoriteRecords(ofProfile: FakeHost.defaultProfileID).map(\.title) == ["News", "Docs", "C", "D", "E"]) + } + + @Test func aDraggedSplitShowsBothIcons() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + #expect(controller.model.icons(of: .tab(mail.tabID)).count == 2) + let other = browser.addTab(title: "Other", url: "https://other.example/") + #expect(controller.model.icons(of: .tab(other.tabID)).count == 1) + } + + @Test func theSplitButtonsMenuHasAHeadingAndItsTabs() { + var chosen: SplitLogic.MenuEntry? + let entries = SplitLogic.singlePageMenu(shown: docs.tabID, today: browser.tabs) + let menu = SplitButton.menu(entries, icon: { _ in nil }) { chosen = $0 } + #expect(menu.items.map(\.title) == ["Split with Tab", "Mail", "", "New Tab"]) + #expect(menu.items[0].isSectionHeader) + // A page without a favicon shows the globe. + #expect(menu.items[1].image === HistoryMenuBuilder.placeholderIcon) + if #available(macOS 27, *) { + #expect(menu.items[1].preferredImageVisibility == .visible) + } + let mailItem = menu.items[1] + _ = (mailItem.target as? NSObject)?.perform(mailItem.action, with: mailItem) + #expect(chosen == .tab(mail.tabID, title: "Mail")) + let pane = SplitButton.menu(SplitLogic.paneMenu(isLeading: true), icon: { _ in nil }) { _ in } + #expect(!pane.items[0].isEnabled && pane.items[1].isEnabled) + } + + @Test func theLinkStatusLaysTheWindowOutWhenItsWordsChange() { + let superview = NSView(frame: CGRect(x: 0, y: 0, width: 800, height: 600)) + let host = SelfSizingHostingView(rootView: CapsuleText(text: "https://docs.example/", identifier: "clair.status")) + host.tracksWidth = true + superview.addSubview(host) + host.frame = CGRect(origin: .zero, size: host.fittingSize) + superview.layoutSubtreeIfNeeded() + #expect(!superview.needsLayout) + // Option's words make it wider, at the same height. + host.rootView = CapsuleText(text: "Option-click to open in split view: https://docs.example/", identifier: "clair.status") + host.layoutSubtreeIfNeeded() + #expect(superview.needsLayout) + } + + @Test func theSplitRowStandsForBothTabs() { + browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) + #expect(TabListLogic.rows(controller.model.tabs).map(\.title) == ["Mail"]) + #expect(controller.model.highlightedTab == mail.tabID) + } +} diff --git a/native/ClairUITests/ToolbarTests.swift b/native/ClairUITests/ToolbarTests.swift index cc0965c..7e55b19 100644 --- a/native/ClairUITests/ToolbarTests.swift +++ b/native/ClairUITests/ToolbarTests.swift @@ -69,9 +69,21 @@ struct ToolbarPreferenceTests { } @Test func theModelFollowsThePolicy() { - let model = BrowserWindowModel(profileKind: .regular, sidebar: SidebarState(), showsToolbar: false) + let toolbarOff = ToolbarPreference(defaults: UserDefaults(suiteName: "ToolbarTests.off")!) + toolbarOff.isOn = false + let browser = FakeBrowser() + let controller = BrowserWindowController( + browser: browser, spaces: browser.spaces, + preferences: SidebarPreferences(defaults: UserDefaults(suiteName: "ToolbarTests")!), + toolbarPreference: toolbarOff) + browser.clairWindow = controller + let mail = browser.addTab(title: "Mail") + let news = browser.addTab(title: "News") + let model = controller.model #expect(!model.showsPageHeader && model.sidebarShowsControls) - model.paneCount = 2 + // A split shows both panes' headers (add-split-view D9). + browser.makeSplit(mail.tabID, with: news.tabID) + #expect(model.paneCount == 2) #expect(model.showsPageHeader && !model.sidebarShowsControls) } } diff --git a/openspec/changes/add-split-view/arc-reference/README.md b/openspec/changes/add-split-view/arc-reference/README.md index 07ce084..57c0684 100644 --- a/openspec/changes/add-split-view/arc-reference/README.md +++ b/openspec/changes/add-split-view/arc-reference/README.md @@ -22,12 +22,48 @@ Keep these screenshots. They move with the change when it's archived. - Esc in the command bar of Add Split View's empty pane closes the pane. Clair keeps the new tab page in it for now, to keep the first version simple (the owner, in PR #259). - The pane that isn't focused shows its hidden controls when the pointer comes near its header. Clair shows them while the pointer is anywhere over that pane. -## To probe (tasks.md 1.1) +## Probed (tasks.md 1.1) -- The drag-onto-page UI: the portrait card's size, the drop zone's tint and border, and the slide's timing. -- The split row with long titles at the default sidebar width. -- Closing one pane of a pinned split. -- With a Peek open from one pane, what a click on the other pane does. +Probed on 2026-11-25 with `tests/probe/` in the owner's Arc, Light Mode, a 1920 × 976 pt window with the toolbar on (`localhost` pages show Arc's Developer Mode toolbar). Arc takes the drag from real mouse events (`build/probe/bin/drag`); the probe's XCUITest `drag` doesn't start one. + +| File | Shows | +|---|---| +| drag-onto-page.jpg | A pinned tab dragged over the trailing half of a page that isn't split, mid-drag. | +| drag-across-sheet.jpg | Frames of one drag, 133 ms apart: over the leading half, across to the trailing half, and back to the sidebar. | +| split-with-pinned-tab.jpg | That drop: a Today split row of "colour" and "Ars Tec…", selected, the trailing pane focused, the pinned tab's row still in its folder. | +| today-split-pinned-pane-closed.jpg | The pinned tab's pane of that split closed: "colour" shows alone, the pin stays in its folder. | +| peek-in-split.jpg | A Peek opened from the leading pane of a split. | +| peek-in-split-other-pane-clicked.jpg | Then a click on the part of the trailing pane the Peek doesn't cover. | +| pinned-split-shown.jpg | Two Today tabs made a split, then Cmd+D: the pinned split row, selected. | +| pinned-split-pane-closed.jpg | Its trailing pane closed with the pane's ×. | +| pinned-split-pane-restored.jpg | Then Restore Last Closed Tab. | +| pinned-split-row-menu.jpg | The pinned split row's menu. | + +**Dragging a tab onto the page** (drag-onto-page.jpg, drag-across-sheet.jpg): +- The drag becomes a white portrait card with rounded corners, about **216 × 250 pt**, with the favicon centred above the title in bold, up to three lines, centred under the pointer. +- The drop zone is the half under the pointer: exactly the place the pane would take, half the page area less the 10 pt gap. It has a **2 pt border in the accent colour** with rounded corners, and a fill of the accent colour at very low opacity over the window background (about 4%: 216, 202, 207 outside and 206, 199, 213 inside, with a purple accent). +- The page slides to the other half, with its card and toolbar, 10 pt from the zone: here from 228–1910 pt to 228–1064 pt. The slide takes about **200 ms, ease-out** (most of the distance in the first 100 ms). +- Moving to the other half moves the zone at once, and the page slides across through its full width, again in about 200 ms. +- Back over the sidebar, the zone goes, the page slides back to full width in about 200 ms, and the card turns back into the tab's row. + +**The split row** (split-with-pinned-tab.jpg, pinned-split-shown.jpg): at this sidebar width (about 228 pt), the row is inset about 4 pt, and each chip takes half of it, about 99 pt, 3 pt apart, its title truncated with "…" ("Counte…", "Ars Tec…"). With the − button of a selected pinned split, the trailing chip narrows to make room ("col…"). + +**Closing one pane of a pinned split** (pinned-split-pane-closed.jpg, pinned-split-pane-restored.jpg): this differs from what the spec said before the probe. +- The closed page **leaves the pinned item**: the pinned split becomes a single pinned tab of the other page, in the split's place, selected, with its − button. Clicking it doesn't bring the closed page back. +- Restore Last Closed Tab brings the page back, and the item is a pinned split again with both pages. +- Closing the pane of a *pinned tab in a Today split* is different: the pin stays as it was, and the Today tab shows alone (today-split-pinned-pane-closed.jpg). + +The spec (“Closing a pane of a pinned split”) and design D10 now follow Arc. + +**A Peek in a split** (peek-in-split.jpg, peek-in-split-other-pane-clicked.jpg): +- The Peek is centred over the whole page area, and only its parent's pane washes out, as noted below. +- Clicking the uncovered part of the other pane closes the Peek, as a click outside a Peek does, and the parent's pane stays focused: the click doesn't focus the other pane. +- Arc shows Close, Expand **and** Open in Split View on a Peek whose parent is in a split, since it allows more panes. Clair hides the last, as its splits hold two tabs. + +**Other things seen:** +- The split button's tooltip is "Split View Options". The spec keeps "Split view". +- Cmd+D on a Today split pins it as one row at the end of the pinned section. +- The pinned split row's menu: Share Split View…, Separate All Tabs, Add Tab…, Convert to Vertical Split View, a "Tab Options" heading with a submenu per page, Change Icon…, Rename…, Duplicate, Move to ›, Archive Item and Close (⌘W). Clair's row menu is the tab menu of the chip under the pointer (spec "The split row's menu"). ## Peek in a split diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/drag-across-sheet.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/drag-across-sheet.jpg new file mode 100644 index 0000000..06f4b1a Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/drag-across-sheet.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/drag-onto-page.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/drag-onto-page.jpg new file mode 100644 index 0000000..2fcdc4a Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/drag-onto-page.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split-other-pane-clicked.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split-other-pane-clicked.jpg new file mode 100644 index 0000000..7fc6d58 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split-other-pane-clicked.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split.jpg new file mode 100644 index 0000000..f87c532 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/peek-in-split.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-closed.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-closed.jpg new file mode 100644 index 0000000..122c511 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-closed.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-restored.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-restored.jpg new file mode 100644 index 0000000..1e5ad46 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-pane-restored.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-row-menu.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-row-menu.jpg new file mode 100644 index 0000000..dc4c7b7 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-row-menu.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-shown.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-shown.jpg new file mode 100644 index 0000000..9ed8f14 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/pinned-split-shown.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/split-with-pinned-tab.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/split-with-pinned-tab.jpg new file mode 100644 index 0000000..b9c10e0 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/split-with-pinned-tab.jpg differ diff --git a/openspec/changes/add-split-view/arc-reference/screenshots/today-split-pinned-pane-closed.jpg b/openspec/changes/add-split-view/arc-reference/screenshots/today-split-pinned-pane-closed.jpg new file mode 100644 index 0000000..1251fe6 Binary files /dev/null and b/openspec/changes/add-split-view/arc-reference/screenshots/today-split-pinned-pane-closed.jpg differ diff --git a/openspec/changes/add-split-view/design.md b/openspec/changes/add-split-view/design.md index 33e50f0..df90f27 100644 --- a/openspec/changes/add-split-view/design.md +++ b/openspec/changes/add-split-view/design.md @@ -29,31 +29,41 @@ See proposal.md, "Why". The behaviour is in `specs/split-view/spec.md`; this cov `ClairSplits`, one per native window like `ClairPeeks`, wraps `TabStripModel`'s split calls and observes `TabStripModelObserver`'s split changes (`OnSplitTabChanged`). A Clair split *is* a Chromium split: its ID is the `SplitTabId`, its ratio is `split_ratio`, and its pane order is the tab order. +**Audit of Chromium 157's split code (task 2.1).** `TabStripModel`'s split calls check no feature (`kSideBySide` is a layout, not a flag), and its metrics and UKM don't touch Views. The observers of `OnSplitTabChanged` that reach `BrowserView` (`SplitTabHighlightController`, the scrims, the toolbar's split button) are created only with a `BrowserView`, which a native window has none of; `SplitViewIphController` uses the user-education interface every browser has. The session service writes splits and session restore and tab restore bring them back without a flag. Nothing needed guarding. Two of Chromium's behaviours shape the code instead: a tab moved or inserted inside a split ends it (so a pane's Peek sits after the whole split, D3), and `UpdateTabInSplit(kReplace)` closes the replaced tab (so Replace ends the split and restores it with the same ID, D8). + *Alternative:* a table of Clair's own, as for Peeks, with any number of panes, as Dia allows. Clair would then have to save splits itself, carry them through tab restore, keep them together across windows, and keep both pages visible. Chromium already does all of this for two tabs, and the MVP asks for two. See "Beyond two panes". ### D2. The contract `ClairHost.h` gains: -- on `ClairTab`, `splitID` (an opaque string, or nil) and `splitRatio`; +- on `ClairTab`, `splitPartnerID` (the other tab, or none), `isLeadingPane` and `splitRatio`. ClairUI needs the partner rather than an opaque split ID: a Today split with a pinned tab's page has only one tab in `-tabsInSpace:`, and the other comes from its pin; - on `ClairBrowser`: - `splitTab:withTab:side:`, which puts the second tab on the given side (leading or trailing), focused, wherever each was; - `splitTabWithNewTab:`, which adds a new tab page as the trailing, focused pane, for Add Split View and New Tab; + - `showSplitOfTab:`, which shows a split with the pane focused last, for the split row and the tab commands; - `replacePaneOfTab:withTab:`, `swapSplitOfTab:`, `separateSplitOfTab:`, `closeSplitOfTab:` (both tabs) and `setSplitRatio:ofTab:`; - - `canAddPaneToTab:`, for the "Cannot Add New Pane" toast. + - `openPeekInSplitOfTab:` (D11); +- on `ClairWindow`, `statusTextDidChange:isLink:tab:` in place of `statusTextDidChange:`, so the link status can word a link with the modifier keys and sit in its pane (D13a). + +"Cannot Add New Pane" needs no call: the menu bar item is the engine's (D9), and ClairUI's menus read `splitPartnerID`. Focusing a pane is the existing `activateTab:`. In Chromium, the focused pane is the active tab, and its partner is the other tab of its split. -The rows ClairUI lists come from `-tabsInSpace:` as now. `TabListLogic` folds two adjacent tabs with the same `splitID` into one row. A pinned section and the favorites can now hold a split item (D10). +The rows ClairUI lists come from `-tabsInSpace:` as now, the trailing pane right after the leading one and its Peek. `TabListLogic` folds a tab and its partner into one row. A pinned section, a folder and the favorites can now hold a split item (D10). ### D3. Panes in `PageCardView` -`PageCardView` lays out `panes`, an array of one or two `PaneView`s, in place of its single page holder. Each `PaneView` holds: +In the strip, a pane's Peek sits after the split, the leading pane's Peek first, never between the panes, where Chromium would end the split; `ClairPeeks` places and repairs it there, repairing in pane order. In the window, the leading pane's Peek draws over the trailing pane by lowering that pane's layer, not raising the Peek's, so both stay below the command bar, find and the notice, and the divider hides while a Peek shows. Focusing the other pane closes a Peek open over a pane, as in Arc (`arc-reference/README.md`). + +`BrowserRootView` holds two `PageCardView`s, `card` and `secondCard`, and lays them out side by side over the page area while split (`SplitLogic.paneFrames`); outside a split, `secondCard` is hidden and `card` takes the whole area. Each card keeps what it had: - its own rounded card and shadow; -- a `PageToolbar` header; -- the tab's page view, still, crashed-page view and docked DevTools; -- its focus ring (2 pt, `controlAccentColor`), shown only while it has a partner and is focused. +- a `PageToolbar` header, from its own hosting view (`PageHeaderSlot.pane(0)` and `.pane(1)`); +- the tab's page view, a Peek over it, crashed-page view, infobars and docked DevTools; +- its focus ring (2 pt, `controlAccentColor`), shown only while split and focused. -A `SplitDivider` sits in the 10 pt gap (Arc's measurement in change 1's `arc-reference/look-and-behaviour.md`, 356 + 10 + 356). It shows a grabber and the resize cursor. While dragging, it sets the panes' widths locally, then calls `setSplitRatio` when the drag ends. The ratio is clamped so that each pane's page, below its header and inside its card, is at least about 210 pt wide, Dia's minimum as the owner measured it with DevTools. It needn't be exact. In a page area too narrow for that, the clamp gives way and the ratio holds. When a drag ends within 20 pt of the centre, the divider animates to it and the ratio is saved as 0.5. +Page full screen from a pane shows that pane's card alone over the page area: the trailing pane's page stays in `secondCard`, which fills the area while `card` hides. A pane's infobar buttons and crashed-page Reload act on that pane's tab, and an unfocused pane's header shows its own page's Reload or Stop, copies its own URL, and opens its own back and forward history, focusing the pane first where the engine acts on the active tab. + +A `SplitDividerView` sits in the 10 pt gap (Arc's measurement in change 1's `arc-reference/look-and-behaviour.md`, 356 + 10 + 356). It shows the resize cursor and a grabber at 35% of its colour, fading to full while the pointer is over the divider or drags it. While dragging, it sets `BrowserWindowModel.liveSplitRatio`, with the panes of the split it's dragged in, which lays that split's panes out, then calls `setSplitRatio` when the drag ends. Another split shown, or none, drops it. The ratio is clamped so that each pane's page, below its header and inside its card, is at least about 210 pt wide, Dia's minimum as the owner measured it with DevTools. It needn't be exact. In a page area too narrow for that, the clamp gives way and the ratio holds. While the divider is within 20 pt of the centre, during the drag and when it ends, the panes take equal widths, with the trackpad's alignment feedback as it snaps, and the ratio is saved as 0.5. The rules are `SplitLogic`'s, apart from the views, for unit tests. `BrowserWindowModel.paneCount` becomes 2 while the active tab has a partner, so `PageHeaderPolicy` shows pane headers and hides the sidebar's controls with no further change (`add-page-toolbar` D1). The Peek, find field, loading indicator and toasts are measured against the page area, the union of the panes. Find is the exception: it uses the focused pane, as the spec says. The loading indicator follows the active tab, as now, and centres on that tab's pane. @@ -69,12 +79,12 @@ Clicking in the other pane has to focus it and still reach the page. The engine ### D6. Option+click -One patch, `split-on-option-click.patch`, changes the click mapping on macOS in both places: Blink's `NavigationPolicyFromEventModifiers` and `ui::DispositionFromClick`. Option with no Shift now gives the split-view policy and `NEW_SPLIT_VIEW`, the same as Cmd+Option. The link then reaches `ClairBrowserWindow`'s `OpenURL` path as `NEW_SPLIT_VIEW`, like Shift+click's `NEW_WINDOW` for Peeks, and `ClairSplits::OpenURL` handles it: -- **from a page that isn't split:** a new foreground tab next to the source, then `AddToNewSplit` with the new tab trailing and active; +One patch, `split-on-option-click.patch`, changes the click mapping on macOS in both places: Blink's `NavigationPolicyFromEventModifiers` and `ui::DispositionFromClick`. Option with no Shift now gives the split-view policy and `NEW_SPLIT_VIEW`, the same as Cmd+Option. The link then reaches `BrowserWebContentsDelegate`'s `OpenURLFromTab` (or `AddNewContents`, for a link with a target) as `NEW_SPLIT_VIEW`, where the native window's link hook, which already sends Shift+click's `NEW_WINDOW` to Peeks, now named `clair::MaybeOpenLink`, hands it to `ClairSplits::OpenLink`: +- **from a page that isn't split:** a new background tab right after the source, then `AddToNewSplit` with the new tab trailing and active, so the split's row keeps the source's place (Chromium's own navigator would put the new tab at the top, where Clair places new tabs); - **from a split pane:** load the URL in the partner as `CURRENT_TAB`, renderer-initiated off, as a new navigation that keeps its history, then activate it; - **from a Peek:** `CURRENT_TAB` in the Peek. -Open Link in Split View (`IDC_CONTENT_CONTEXT_OPENLINKSPLITVIEW`) is no longer removed. It already opens with `NEW_SPLIT_VIEW`, so it takes the same path. `ClairPinnedLinkThrottle` only sees navigations in place, and a split's new tab is a new tab, so a pinned tab's Option+click makes a split, not a Peek. +Open Link in Split View (`IDC_CONTENT_CONTEXT_OPENLINKSPLITVIEW`) is no longer removed. It doesn't use `NEW_SPLIT_VIEW`: Chromium's `RenderViewContextMenu::OpenLinkInSplitView` opens a background tab and calls `AddToNewSplit` with the active tab, or, in a split, loads the link in the other pane, as Option+click does. Its new tab lands first in the split, so `ClairSplits` puts the tab that was active, where the link was clicked, back in the leading pane once Chromium is done; session restore and tab restore keep their saved order. In a split, Chromium names the item "Open Link in Left View" or "Right View", and it doesn't focus the other pane. `ClairPinnedLinkThrottle` only sees navigations in place, and a split's new tab is a new tab, so a pinned tab's Option+click makes a split, not a Peek. *Alternative:* catch the download in `DownloadRequestLimiter` or `RenderFrameHostImpl::DownloadURL`. That runs after the renderer has decided "download", loses the click's context, and still needs a patch. @@ -83,7 +93,8 @@ Open Link in Split View (`IDC_CONTENT_CONTEXT_OPENLINKSPLITVIEW`) is no longer r Chromium keeps a split's tabs adjacent in its tab strip. `ClairSpaceTabs` (the Space's row order across windows) keeps them adjacent too, and moves them together: - a split moves as one with `MoveSplitTo` within a window; - between windows, it moves with `DetachSplitTabForInsertion` and `InsertDetachedSplitTabAt`, which is how `share-tabs-across-windows` moves a tab when another window selects it; -- Move to Space moves both tabs. +- Move to Space moves both tabs; to a Space of another profile, both reopen there and make the split again, with its ratio; +- dragging the row in Today moves both tabs as one block, leading pane first. The tab commands' row list (`spaces`) treats the pair as one row, as it treats a tab and its Peek. @@ -91,33 +102,35 @@ New tabs still go to the top. A split's new tab is inserted next to its source w ### D8. Dragging onto the page -`PageCardView` registers for the sidebar's existing tab drag type. Over the page: -- the drag image becomes a portrait card with the favicon and title (about 115×210 pt in Arc); +`PageDropView`, over the page area and transparent to clicks, registers for the sidebar's existing tab drag type, as `FavoritesDropArea` does. Over the page: +- the drag image becomes a portrait card with the favicon and title (`DraggedPageCard`, about 216×250 pt, as measured in task 1.1); - the half under the pointer, or the pane under it while split, becomes a drop zone tinted with the accent colour at low opacity, with an accent border; - the page animates to the other half. The drop calls `splitTab:withTab:side:` with the half it was dropped on, so the dropped tab lands there, focused, or `replacePaneOfTab:withTab:` while split. The replaced tab stays where Chromium leaves it, right after the split, which is the row below the split's row. -The card size, the zone's tint and the slide's timing are to be measured from an Arc recording with `tests/probe/` (task 1.1), as for Peek. +The card size, the zone's tint and the slide's timing come from an Arc recording with `tests/probe/` (task 1.1): a 2 pt accent border on the accent at about 5% opacity, and a 200 ms ease-out slide. A closed pinned tab or favorite dropped on the page opens first, then splits. ### D9. The split button and menus -The split button takes Arc's slot, the trailing one (`add-page-toolbar` D4 measured Arc's split button there, 21 pt from the edge, with site controls 36 pt to its left). In the single-page toolbar, site controls, extensions and indicators each move one slot left. In a pane header, × takes the trailing slot and the split button the next. `ToolbarArrangement` takes the slots as a list, so its narrow-window rules are unchanged: the split button and site controls are never left out. The menu is an `NSMenu` built from the window model: +The split button takes Arc's slot, the trailing one (`add-page-toolbar` D4 measured Arc's split button there, 21 pt from the edge, with site controls 36 pt to its left). In the single-page toolbar, site controls, extensions and indicators each move one slot left. In a pane header, × takes the trailing slot and the split button the next. `ToolbarArrangement` takes the slots as a list, so its narrow-window rules are unchanged: the split button and site controls are never left out. The button is the toolbar's `IconButton`, with its hover background and grey, and the SF Symbol `square.split.2x1`; its click pops up an `NSMenu` below it (`SplitButton`), built from `SplitLogic`'s entries: - **on a single page:** a section header "Split with Tab", the Space's Today tabs other than the shown one, a separator, then New Tab; - **on a split:** Move Left or Move Right, Separate Tabs and Close This Tab. -`PageHeaderContent` gains `.pane(leading:focused:)`: +`PageHeaderContent` gains `.pane(leading:expanded:)`, expanded while the pane is focused or under the pointer: - the leading pane gets the toggle; -- the focused pane gets reload, the split button, site controls, extensions and indicators, and so does the other pane while the pointer is over it, anywhere in the pane (Arc shows them only near its header). Its hover tracking covers the whole `PaneView`. Clicking one of them focuses the pane first (`activateTab:`), so it acts on that pane's tab; +- the focused pane gets reload, the split button, site controls, extensions and indicators, and so does the other pane while the pointer is over it, anywhere in the pane (Arc shows them only near its header). Its hover tracking covers the whole card. Clicking one of them focuses the pane first (`activateTab:`), so it acts on that pane's tab; - every pane gets back, forward, the link icon, the host and ×, as Arc's unfocused pane shows. +The other pane's controls fade in and out over 150 ms as the pointer comes and goes, the host sliding to make room, as the header animates its `PageHeaderContent`. + In a pane, × is centred 21 pt from the pane's edge, the split button 57 pt, site controls 93 pt, and extensions and indicators follow at 36 pt steps, as now. Menu bar items: -- Tabs › Split with Tab ›, and View › Add Split View, Close Split Pane and Separate Tabs, are added where the folder change added New Folder…, through the native window's menu install (`InstallNativeWindowMenus`) and `ExecuteCommand`. +- Tabs › Split with Tab ›, and View › Add Split View, Close Split Pane and Separate Tabs, are `ClairUI`'s, as `PinsMenu` adds the folder change's New Folder…: a `SplitMenu` installs, titles and enables them for the main window, and acts through the D2 calls. "Cannot Add New Pane" is `ClairUI`'s toast. - `IDC_NEW_SPLIT_TAB` stays hidden. Clair's own items replace it. -The tab context menus gain Split with Tab › from the menus `PinsLogic` and the sidebar already build. +The tab context menus gain Split with Tab › from the menus `PinsLogic` and the sidebar already build, disabled on a pinned tab or favorite whose page is already in a split. Its items come from the window (`SplitActions.splitWithTabItems`); a closed pin's page opens first. **Wording:** Clair says "Separate Tabs" everywhere, as Dia does. Arc's View menu says "Separate Page from Split View". @@ -125,25 +138,27 @@ The tab context menus gain Split with Tab › from the menus `PinsLogic` and the `ClairPinStore` gains a **split record**, `{id, sortKey, ratio}`, with the place a pin has: a Space's pinned section, a folder in it, or a profile's favorites. A folder holds pins and splits, still one level deep. Each of its two pins names the split and its index (0 or 1), instead of its own place. The format follows `add-tab-folders`' iCloud-ready records: a move rewrites the split record only. -In `ClairHost.h`, `ClairPinnedItem` gains a split kind holding its two pins and its ratio, and the favorites list returns items in place of bare pins. Selecting a split item binds or opens both pins' tabs and makes them a Chromium split with the saved ratio: -- **Closing one pane** unbinds that pin only. The split record stays, so selecting the row again reopens it into the split. +In `ClairHost.h`, `ClairPinnedItem` gains a split kind (`ClairPinnedSplit`) holding its two pins and its ratio, each pin names its split, a folder lists items (pins and splits) in place of pins, and the favorites list returns items in place of bare pins. Calls that name a pin of a split (move, unpin, remove, open) act on the whole split, and `separatePinnedSplit:` separates one whose pages are closed. Selecting a split item binds or opens both pins' tabs and makes them a Chromium split with the saved ratio: +- **Closing one pane** takes its pin out of the item, as Arc does (`arc-reference/README.md`, "Closing one pane of a pinned split"): the split record goes, the other pin takes its place and sort key, and the closed pin is removed as Remove Pin removes one. Restore Last Closed Tab brings back the split record with both pins and its ratio, and reopens the pair as a split. - **Separate** turns the record into two pins at its sort key, in pane order. - **Unpin and Remove Favorite** move or remove both pins. - **Restore Last Closed Tab** brings a removed split record back with its pins. A Today split holding a pin-bound tab (the spec's "A split with a pinned tab or favorite") is a Chromium split whose rows the sidebar shows in Today. The pin keeps its binding, so its row or tile stays and selects the split. +A favorite's page in a split loads URLs from the command bar in its pane: `clair::LeavesFavorite`, which sends another site's URL from a favorite to a new Today tab (`add-pinned-tabs-and-favorites` D7), skips a tab in a split. A split dragged over the favorites turns into its tile, a segment per page (`DraggedTile`, from `BrowserWindowModel.icons(of:)`). + ### D11. Peeks in a split -`PeekLayout` is unchanged and measures from the page area (D3), so a Peek is centred over both panes. Only the parent's `PaneView` takes the shrink and wash, as in Arc; the other pane keeps its size and colour. Task 1.1 checks what a click on that other pane does in Arc. Open in Split View expands the Peek as Expand does (`ClairPeeks`), then calls `AddToNewSplit` with the parent. The button isn't built while the parent has a partner, since a split holds two tabs. +`PeekLayout` is unchanged and measures from the page area (D3), so a Peek is centred over both panes. Only the parent's card takes the shrink and wash, as in Arc; the other pane keeps its size and colour. A click on the other pane closes the Peek, as Arc does (task 1.1); in Clair it also focuses that pane. Arc keeps Open in Split View on a Peek in a split, since it allows more panes; Clair doesn't show it. Open in Split View expands the Peek as Expand does (`ClairPeeks`), then calls `AddToNewSplit` with the parent. The button isn't built while the parent has a partner, since a split holds two tabs. ### D12. Closing -Closing a tab in a split dissolves the split in `TabStripModel`, and the other tab stays where it was. `ClairSplits` then activates it, so the spec's "other tab shows alone" holds whatever Clair's next-tab rule would pick. The split row's × closes both tabs: `CloseTabs` on the pair, each with its leave-page confirmation, so tab restore records one `Split` entry. +Closing a tab in a split dissolves the split in `TabStripModel`, and the other tab stays where it was. `ClairSplits` then activates it, so the spec's "other tab shows alone" holds whatever Clair's next-tab rule would pick. In Today, hovering a split's row shows a × on each chip, which closes its tab as the pane's × does. A pinned split's − closes both tabs: `CloseTabs` on the pair, each with its leave-page confirmation, so tab restore records one `Split` entry. ### D13b. The command bar's place -The command bar is placed against the window today. While `paneCount` is 2, its horizontal centre becomes the focused `PaneView`'s centre in window coordinates, clamped so that the bar stays inside the window's content. Its vertical place doesn't change. Add Split View and the Split with Tab menus' New Tab make the split first, with a new tab page in the new pane (`splitTabWithNewTab:`, without a URL), so the command bar then centres on that pane like any other. It opens in Cmd+L's mode on the new tab, so a chosen page loads there. Esc leaves the new tab page in its pane. Arc closes its empty pane on Esc instead; the owner chose the simpler behaviour for now. +The command bar is placed against the window today. While `paneCount` is 2, its horizontal centre becomes the focused pane's centre in window coordinates, clamped so that the bar stays inside the window's content. Its vertical place doesn't change. Add Split View and the Split with Tab menus' New Tab make the split first, with a new tab page in the new pane (`splitTabWithNewTab:`, without a URL), so the command bar then centres on that pane like any other. It opens in Cmd+L's mode on the new tab, so a chosen page loads there. Esc leaves the new tab page in its pane. Arc closes its empty pane on Esc instead; the owner chose the simpler behaviour for now. ### D13a. Link status with a modifier diff --git a/openspec/changes/add-split-view/specs/favorites/spec.md b/openspec/changes/add-split-view/specs/favorites/spec.md index a0d22b4..f197468 100644 --- a/openspec/changes/add-split-view/specs/favorites/spec.md +++ b/openspec/changes/add-split-view/specs/favorites/spec.md @@ -27,3 +27,18 @@ A favorite's context menu SHALL offer Copy Link, Rename…, Mute or Unmute, Edit #### Scenario: The shown favorite's menu - **WHEN** the window shows "Mail" and the user right-clicks its tile - **THEN** the menu offers Copy Link, Rename…, Mute, Edit Pinned Page, Duplicate, Split with Tab, Close Tab and Remove Favorite + +### Requirement: Leaving a favorite's site +From a favorite, a URL the user enters in the command bar or URL field that is on another site (another scheme or host, as for Peeks in `peek`) SHALL open in a new Today tab at the top, leaving the favorite's page as it was. A URL on the same site SHALL load in the favorite. A favorite's page in a split (`split-view`) SHALL load either in its pane. A favorite's page navigated away from its pinned URL SHALL keep Back to Pinned URL in the Tabs menu (`pinned-tabs`). + +#### Scenario: Another site from the URL field +- **WHEN** the window shows the favorite "Mail" at `https://mail.example.com/` and the user enters `https://news.example.org/` in the URL field +- **THEN** a new Today tab at the top shows `https://news.example.org/`, and "Mail" keeps its page + +#### Scenario: The same site +- **WHEN** the user enters `https://mail.example.com/settings` there instead +- **THEN** "Mail" loads it + +#### Scenario: Another site in a favorited split's pane +- **WHEN** the window shows a favorited split of "Mail" and "Calendar", with "Mail" focused, and the user enters `https://news.example.org/` in the command bar +- **THEN** "Mail"'s pane loads `https://news.example.org/`, and no Today tab opens diff --git a/openspec/changes/add-split-view/specs/split-view/spec.md b/openspec/changes/add-split-view/specs/split-view/spec.md index 2c51d53..69804a8 100644 --- a/openspec/changes/add-split-view/specs/split-view/spec.md +++ b/openspec/changes/add-split-view/specs/split-view/spec.md @@ -69,7 +69,7 @@ While the pointer is over the pane that isn't focused, its header SHALL show its - **THEN** that pane is focused, and the Site Control Center opens for its page ### Requirement: Resizing the panes -A divider in the gap between the panes SHALL show a grabber and the resize pointer. Dragging it SHALL resize both panes, stopping when either pane's page would be narrower than about 210 points, as in Dia. The split SHALL keep the ratio, across tab switches and relaunches. A new split SHALL start with equal panes, and a drag ending near the centre SHALL snap to equal panes. While the page area is too narrow for two such pages, the panes SHALL keep their ratio. +A divider in the gap between the panes SHALL show the resize pointer and a faint grabber. Dragging it SHALL resize both panes, stopping when either pane's page would be narrower than about 210 points, as in Dia. The split SHALL keep the ratio, across tab switches and relaunches. A new split SHALL start with equal panes, and the divider SHALL snap to equal panes while it's dragged near the centre. While the page area is too narrow for two such pages, the panes SHALL keep their ratio. #### Scenario: Dragging the divider - **WHEN** the user drags the divider of an equal split in a wide window 200 points toward the trailing edge @@ -80,8 +80,12 @@ A divider in the gap between the panes SHALL show a grabber and the resize point - **THEN** the trailing pane's page stops at about 210 points wide #### Scenario: Snapping to the centre -- **WHEN** the user drags the divider to within about 20 points of the page area's centre and lets go -- **THEN** the panes become equal +- **WHEN** the user drags the divider to within about 20 points of the page area's centre +- **THEN** the panes become equal before the user lets go, and stay equal once the user does + +#### Scenario: The grabber +- **WHEN** the pointer moves over the divider +- **THEN** the grabber fades to its full colour, and back to faint once the pointer leaves #### Scenario: Coming back to the split - **WHEN** the user resized a split, selects another tab and then selects the split again @@ -250,7 +254,7 @@ A Today tab's, pinned tab's or favorite's Split with Tab › SHALL be disabled, - **THEN** Split with Tab is disabled ### Requirement: Closing a pane -Each pane's × in its header, Close This Tab in its split menu, Cmd+W and View › Close Split Pane (⌃⇧−) on the focused pane SHALL close that pane's tab only, with its leave-page confirmation. The other tab SHALL then show alone, active, in the split's place in the sidebar. A pinned tab's or favorite's pane SHALL close as Close and Keep Pinned does. +Each pane's × in its header, Close This Tab in its split menu, Cmd+W and View › Close Split Pane (⌃⇧−) on the focused pane SHALL close that pane's tab only, with its leave-page confirmation. The other tab SHALL then show alone, active, in the split's place in the sidebar. The pane of a pinned tab or favorite in a Today split SHALL close as Close and Keep Pinned does. A pane of a pinned or favorited split SHALL close as "Closing a pane of a pinned split" says. #### Scenario: × on a pane - **WHEN** a split shows "News" and "Docs" and the user clicks × in the "Docs" pane's header @@ -268,12 +272,16 @@ Separate Tabs, in a pane's split menu, the split row's menu and View, SHALL end - **THEN** the sidebar lists "News" and then "Docs" where the split's row was, and the window shows "Docs" alone ### Requirement: The split row -In the sidebar, a split SHALL show as one row with a chip per tab, in pane order, each with the tab's favicon and title (or custom name), truncated to share the row, as in Arc. While the split isn't selected, a thin divider SHALL separate the chips. While it's selected, the row SHALL be highlighted and each chip SHALL show as its own grey pill. +In the sidebar, a split SHALL show as one row with a chip per tab, in pane order, each with the tab's favicon and title (or custom name), truncated to share the row, as in Arc. While the split isn't selected, a thin divider SHALL separate the chips. While it's selected, the row SHALL be highlighted and each chip SHALL show as its own grey pill, in the same place as before, as in Arc. #### Scenario: A split in Today - **WHEN** a Space has the Today tabs "Mail" and a split of "News" and "Docs" - **THEN** the sidebar lists "Mail" and one row holding a "News" chip and a "Docs" chip +#### Scenario: Selecting it +- **WHEN** the user selects that split +- **THEN** the row is highlighted, each chip is a grey pill, and neither chip moves + #### Scenario: The selected split - **WHEN** the window shows the split - **THEN** its row is highlighted, and each chip is a grey pill on it @@ -285,16 +293,16 @@ Clicking anywhere on a split row SHALL show the split with the pane that was foc - **WHEN** a split of "News" and "Docs" was last focused on "Docs", another tab is shown, and the user clicks the "News" chip - **THEN** the window shows the split with "Docs" focused -### Requirement: Closing a split from its row -Hovering a split's row in Today SHALL show a close button at its trailing end, with the tooltip "Close tab" and ⌘W, which SHALL close both tabs, each with its leave-page confirmation. Middle-clicking the row SHALL do the same. Restore Last Closed Tab SHALL bring the split back as it was. +### Requirement: Closing a page from its row +Hovering a split's row in Today SHALL show a close button at the trailing end of each chip, with the tooltip "Close tab", and ⌘W on the focused pane's chip while the split shows. Each SHALL close its chip's tab only, as the pane's × does (see "Closing a pane"). Middle-clicking a chip SHALL do the same. -#### Scenario: Closing the row -- **WHEN** the user hovers the split's row and clicks its × -- **THEN** both tabs close, and the row goes +#### Scenario: Closing one chip +- **WHEN** a Today split shows "News" and "Docs" and the user hovers its row and clicks the "Docs" chip's × +- **THEN** "Docs" closes, and "News" shows alone, in the split's place in the list -#### Scenario: Restoring it -- **WHEN** the user then chooses Restore Last Closed Tab -- **THEN** the split comes back in its place, with both pages and its ratio +#### Scenario: Hovering the row +- **WHEN** the user hovers either chip of the row +- **THEN** both the "News" chip and the "Docs" chip show a × ### Requirement: The split row's menu Right-clicking a split row SHALL open the menu of its kind for the tab whose chip is under the pointer (Today tab menu, `pinned-tabs`, `favorites`), without Split with Tab ›, Back to Pinned URL or Edit Pinned Page ›, with Separate Tabs added. Pin Tab, Pin to Favorites, Unpin Tab, Remove Favorite and Move to Space SHALL act on the whole split. @@ -379,6 +387,10 @@ A split made of a Today tab and a pinned tab's or favorite's page SHALL show as ### Requirement: Pinning a split Pin Tab (Cmd+D) on a split, Pin Tab in its row's menu, and dragging its row into the pinned section SHALL pin the split as one item, keeping its pages, ratio and selection. Pin to Favorites and dragging it onto the favorites SHALL make it one favorite. Unpin Tab and dragging it below the divider SHALL make it a Today split again. +#### Scenario: Dragging a split over the favorites +- **WHEN** the user drags a split's row over the favorites +- **THEN** the drag shows the tile it would become, a segment per page with its icon, as "The favorite split tile" describes + #### Scenario: Cmd+D on a split - **WHEN** the window shows a Today split of "News" and "Docs" and the user presses Cmd+D - **THEN** the split is the last item of the pinned section, as one row, and stays shown @@ -399,15 +411,22 @@ A pinned split SHALL show in the pinned section as a split row, with the titles - **THEN** both pinned URLs load, as a split with its ratio ### Requirement: Pages of a pinned split -A pinned or favorited split SHALL keep a pinned URL for each page. Selecting it SHALL open each page that isn't open, as a split. Closing one pane SHALL keep it in the split; the other page SHALL show alone until the split is selected again. Its row or tile SHALL show no "/" and offer no Back to Pinned URL. +A pinned or favorited split SHALL keep a pinned URL for each page. Selecting it SHALL open each page that isn't open, as a split. Its row or tile SHALL show no "/" and offer no Back to Pinned URL. + +#### Scenario: Navigated away +- **WHEN** the "Mail" pane of a pinned split follows a link to another page of its site +- **THEN** the row shows the new title in its chip, with no "/", and Tabs › Back to Pinned URL is disabled + +### Requirement: Closing a pane of a pinned split +Closing one pane of a pinned or favorited split SHALL take that page out of the item, as in Arc: the item SHALL become a pinned tab, or a favorite, of the other page, in the split's place, showing that page alone. Restore Last Closed Tab SHALL bring the closed page back into the item as a split, with its pinned URL and the ratio. #### Scenario: Closing one pane - **WHEN** a pinned split of "Mail" and "Calendar" shows and the user closes the "Calendar" pane -- **THEN** "Mail" shows alone, the row still holds both chips, and clicking the row opens "Calendar" again beside "Mail" +- **THEN** "Mail" shows alone, as a pinned tab in the split's place, and the pinned section has no "Calendar" -#### Scenario: Navigated away -- **WHEN** the "Mail" pane follows a link to another page of its site -- **THEN** the row shows the new title in its chip, with no "/", and Tabs › Back to Pinned URL is disabled +#### Scenario: Restoring the closed pane +- **WHEN** the user then chooses Restore Last Closed Tab +- **THEN** the pinned split of "Mail" and "Calendar" is back in its place, shown with its ratio ### Requirement: The favorite split tile A favorited split SHALL take one tile in the favorites grid, divided into a segment per page by a thin line, each segment with its page's icon centred, as in Arc. While the window shows it, the tile SHALL turn white in Light Mode, or light grey in Dark Mode, with a 2-point ring that blends from the leading page's icon colour to the trailing page's. diff --git a/openspec/changes/add-split-view/tasks.md b/openspec/changes/add-split-view/tasks.md index 5ecf57a..86dd0a0 100644 --- a/openspec/changes/add-split-view/tasks.md +++ b/openspec/changes/add-split-view/tasks.md @@ -10,7 +10,7 @@ Suggested order: ## 1. References, contract and fakes -- [ ] 1.1 Probe Arc with `tests/probe/` for D8's open values, and add the screenshots and numbers to `arc-reference/README.md`: +- [x] 1.1 Probe Arc with `tests/probe/` for D8's open values, and add the screenshots and numbers to `arc-reference/README.md`: - a 60 fps recording of a tab dragged onto the page and across it: the portrait card's size, the drop zone's tint and border, and the slide's timing; - the split row with three-word titles at the default sidebar width; - closing one pane of a pinned split; @@ -18,7 +18,7 @@ Suggested order: Verify that the README lists each. If closing a pinned split's pane differs from the spec's "Pages of a pinned split", update the spec and D10 before 2.6. - [ ] 1.2 Change `native/ClairHost.h` as D2 and D10 list: - - `ClairTab.splitID` and `splitRatio`; + - `ClairTab.splitPartnerID`, `isLeadingPane` and `splitRatio`; - the split calls on `ClairBrowser`; - the split kind of `ClairPinnedItem`; - favorites as items. @@ -51,7 +51,7 @@ Suggested order: - the runtime tests in 3.12 cover Option+click on a single page, in each pane of a split (no new tab, Back returns), from a favorite (no Peek), inside a Peek, and from the context menu; - no download starts in any of these. - [ ] 2.5 Add the split record to `ClairPinStore` (D10): split records with their place and ratio, pins that name their split and index, and splits in folders, still one level deep. Add pinning, unpinning, favoriting and separating a split, Remove Pin, Remove Favorite, Restore Last Closed Tab, and Move to Space. Verify with the runtime tests in 3.12 that pinned and favorited splits, their order, pages and ratio survive a relaunch, and that Separate leaves two pins in place (each read from `Local State` after quitting). -- [ ] 2.6 Bind pinned and favorited splits (D10): selecting one opens its unopened pages as a split with its ratio; closing one pane unbinds only that pin; a Today split with a pin-bound tab keeps the binding. Verify with the runtime tests in 3.12. +- [ ] 2.6 Bind pinned and favorited splits (D10): selecting one opens its unopened pages as a split with its ratio; closing one pane takes its pin out of the item, leaving the other pin in its place, and Restore Last Closed Tab brings the split back; a Today split with a pin-bound tab keeps the binding. Verify with the runtime tests in 3.12. - [ ] 2.7 Peek's Open in Split View (D11): expand and split, and no button while the parent has a partner. Verify with the runtime tests in 3.12. - [ ] 2.8 Bridge the D2 calls and snapshots, and the menu bar items of D9: Tabs › Split with Tab ›, and View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) and Separate Tabs, with Add Split View showing "Cannot Add New Pane" while split. Verify with the runtime tests in 3.12. - [ ] 2.9 Build the engine with `gh workflow run engine.yml -f ref=`. Verify that `chromium-engine-` is published and CI's engine check passes. @@ -64,7 +64,7 @@ Suggested order: ## 3. ClairUI - [ ] 3.1 Fold split tabs into one row in `TabListLogic` and the window model, and set `paneCount` from the active tab's partner (D2, D3). Verify with `ClairUI` unit tests in CI: rows for a Today split, a pinned split, a favorited split, and a Today split holding a pin-bound tab; and `PageHeaderPolicy` with the toolbar off while split. -- [ ] 3.2 Lay out the panes in `PageCardView` (D3): `PaneView`s with their own cards, the focus ring, the 10 pt gap, and the find field, loading indicator, Peek and toasts against the right area. Verify with unit tests in CI for the pane frames at a few widths and ratios, and by hand in 3.11. +- [ ] 3.2 Lay out the panes (D3): two `PageCardView`s with their own cards, the focus ring, the 10 pt gap, and the find field, loading indicator, Peek and toasts against the right area. Verify with unit tests in CI for the pane frames at a few widths and ratios, and by hand in 3.11. - [ ] 3.3 Add `SplitDivider` (D3): grabber, resize cursor, live widths, the page minimum of about 210 pt (and the ratio held when the area is too narrow), the snap to equal panes within 20 pt of the centre, and `setSplitRatio` when the drag ends. Verify with unit tests in CI for the clamp, the narrow case, the snap and the ratio, and by hand in 3.11. - [ ] 3.4 Add the pane headers and the split button (D9): - `PageHeaderContent.pane(leading:focused:)`, with × at the trailing slot; @@ -105,7 +105,7 @@ Suggested order: - closing the row and Restore Last Closed Tab; - a split and its ratio after a relaunch and Reopen Closed Window; - pinning, favoriting, separating and relaunching a pinned split, one in a folder included; - - one pane of a pinned split closed and reopened; + - one pane of a pinned split closed, and restored with Restore Last Closed Tab; - Open in Split View from a Peek, and its absence on a Peek in a split. Verify that they pass in `quality.yml` on the branch. diff --git a/tests/probe/README.md b/tests/probe/README.md index bbf19ee..772cffe 100644 --- a/tests/probe/README.md +++ b/tests/probe/README.md @@ -180,7 +180,9 @@ These come from the add-peek change (its design.md has the numbers): `key l cmd` and `type` load the URL in the tab that was showing, which may be the owner's. Then a closing Cmd+W closes that tab, not yours. Check which tab is selected in a screenshot before navigating or closing. -- **Drags in Clair**: on the owner's Mac the probe's `drag` reaches Clair +- **Drags in Clair and Arc**: Arc takes real mouse drags from `build/probe/bin/drag` + (a tab dragged onto the page, into a folder), but the probe's `drag` + doesn't start one there. On the owner's Mac the probe's `drag` reaches Clair with no events at all, though `click` and `hover` do, so it moves nothing there. Drag with the mouse's own events instead: `build/probe/bin/drag x1 y1 x2 y2`, in screen points, after `activate`. diff --git a/tests/probe/tools/drag.swift b/tests/probe/tools/drag.swift index c617f99..23c8186 100644 --- a/tests/probe/tools/drag.swift +++ b/tests/probe/tools/drag.swift @@ -11,7 +11,8 @@ // or as long as a last odd number gives, which leaves time to screenshot the // drag. It moves the real pointer, and the shell it runs from needs // permission to post events (Privacy & Security > Accessibility). Bring the -// app forward first (`probe.sh send activate`). Arc ignores these events. +// app forward first (`probe.sh send activate`). Arc takes these drags too, +// though the probe's `drag` doesn't start one there. import CoreGraphics import Foundation diff --git a/tests/runtime/ClairRuntimeTests/NativeWindowTests.swift b/tests/runtime/ClairRuntimeTests/NativeWindowTests.swift index 3b000e8..344ee02 100644 --- a/tests/runtime/ClairRuntimeTests/NativeWindowTests.swift +++ b/tests/runtime/ClairRuntimeTests/NativeWindowTests.swift @@ -383,10 +383,17 @@ extension Browser { XCTAssertEqual(control.frame.midX - card.minX, x, accuracy: 1, "\(identifier)'s place in the toolbar \(when)") XCTAssertEqual(control.frame.midY - card.minY, 16, accuracy: 1, "\(identifier) isn't centred in the toolbar \(when)") } + // The split button takes the trailing slot, and site controls the next + // (add-split-view D9). + let splitButton = element("clair.splitButton", in: toolbar) + XCTAssertTrue(splitButton.exists, "The toolbar has no split button \(when)") + if splitButton.exists { + XCTAssertEqual(card.maxX - splitButton.frame.midX, 21, accuracy: 1, "The split button's place \(when)") + } let siteControls = element("clair.siteControls", in: toolbar) XCTAssertTrue(siteControls.exists, "The toolbar has no site controls \(when)") if siteControls.exists { - XCTAssertEqual(card.maxX - siteControls.frame.midX, 21, accuracy: 1, "The site controls' place \(when)") + XCTAssertEqual(card.maxX - siteControls.frame.midX, 57, accuracy: 1, "The site controls' place \(when)") } let host = element("clair.urlField", in: toolbar) XCTAssertTrue(host.exists, "The toolbar has no host \(when)") diff --git a/tests/runtime/ClairRuntimeTests/SplitViewTests.swift b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift new file mode 100644 index 0000000..9c2c43e --- /dev/null +++ b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift @@ -0,0 +1,478 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import Foundation +import XCTest + +extension Browser { + /// The split rows' labels, each "leading, trailing", from one snapshot. + var splitRows: [String] { titles(of: "clair.splitRow") } + + func splitRow(_ label: String) -> XCUIElement { + nativeWindow.descendants(matching: .any) + .matching(NSPredicate(format: "identifier == 'clair.splitRow' AND label == %@", label)).firstMatch + } + + func waitForSplitRows(_ seconds: TimeInterval = 15, _ condition: @escaping ([String]) -> Bool) async -> Bool { + await Harness.wait(for: seconds) { condition(self.splitRows) } + } + + var viewMenu: XCUIElement { ui.menuBars.menuBarItems["View"] } + + /// Chooses an item of the View menu. + func chooseViewItem(_ title: String) throws { + try require(viewMenu.waitForExistence(timeout: 30), "The menu bar has no View menu") + viewMenu.click() + let item = viewMenu.menuItems[title] + try require(item.waitForExistence(timeout: 5), "The View menu has no \(title)") + item.click() + } + + /// Chooses `title` in Tabs › Split with Tab ›. + func splitWithTabFromMenuBar(_ title: String) throws { + let submenu = try tabMenuItem("Split with Tab") + try require(submenu.isEnabled, "Tab › Split with Tab is off") + submenu.hover() + let item = submenu.menuItems[title] + try require(item.waitForExistence(timeout: 5), "Tab › Split with Tab has no \(title)") + item.click() + } + + /// Chooses `title` in a row's Split with Tab › menu: the context menu's, + /// not the Tab menu's item of the same title. + func splitWithTab(_ title: String, inMenuOf row: XCUIElement) throws { + row.rightClick() + let found = visibleMenuItem("Split with Tab") + try require(found != nil, "The row's menu has no Split with Tab") + guard let submenu = found else { return } + submenu.hover() + let item = submenu.menuItems[title] + try require(item.waitForExistence(timeout: 5), "Split with Tab has no \(title)") + item.click() + } + + /// How many pages are open. + func pageCount() async throws -> Int { + try await pageTargets().count + } +} + +extension DevToolsSession { + /// Option+clicks the element with `id` (CDP's modifier bit 1 is Alt). + func optionClick(_ id: String) async throws { + try await click(id, modifiers: 1) + } + + /// Right-clicks the element with `id`, which opens the page's context menu. + func rightClick(_ id: String) async throws { + let center = + try await evaluate( + "(() => { const r = document.getElementById('\(id)').getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2]; })()" + ) as? [Double] ?? [0, 0] + for type in ["mousePressed", "mouseReleased"] { + try await send( + "Input.dispatchMouseEvent", + ["type": type, "x": center[0], "y": center[1], "button": "right", "clickCount": 1]) + } + } + + /// Whether the page has the keyboard. + func isFocused() async throws -> Bool { + try await evaluate("document.hasFocus()") as? Bool ?? false + } +} + +/// Split view (add-split-view task 3.12): two tabs side by side as one row, +/// made from the menus and Option+click, focused, rearranged, closed, +/// pinned and restored. +@MainActor +final class SplitViewTests: NativeWindowTestCase { + static let links = "Clair split links" + + /// Starts Clair with Counter a, then the page of links, which is active. + func startWithLinks() async throws -> (Browser, DevToolsSession, DevToolsSession) { + let browser = try await startBrowser() + let counter = try await browser.open(url("counter.html?a")) + let links = try await browser.open(url("split.html")) + browser.ui.activate() + try require(browser.nativeWindow.waitForExistence(timeout: 30), "Clair shows no native window") + let active = await browser.waitForActiveRow(Self.links) + try require(active, "The page of links isn't active: \(browser.activeRow ?? "none")") + return (browser, links, counter) + } + + /// A split from the menus: both pages visible, one row, focus by click, + /// Move Right, "Cannot Add New Pane", Ctrl+Tab, Separate Tabs and Cmd+W + /// on a pane. + func testMakingAndRearrangingASplit() async throws { + executionTimeAllowance = 300 + let (browser, links, counter) = try await startWithLinks() + defer { + links.close() + counter.close() + } + let other = try await browser.open(url("counter.html?other")) + defer { other.close() } + browser.tabRow(Self.links)?.click() + _ = await browser.waitForActiveRow(Self.links) + + // Split with Tab › from the row's menu: the chosen tab trails, focused. + try browser.splitWithTab("Counter a", inMenuOf: try XCTUnwrap(browser.tabRow(Self.links))) + let split = "\(Self.links), Counter a" + var made = await browser.waitForSplitRows { $0 == [split] } + try require(made, "Split with Tab made no split row: \(browser.splitRows)") + XCTAssertFalse(browser.tabTitles.contains(Self.links), "The split's tab kept a row of its own") + XCTAssertTrue(browser.element("clair.pane.0").exists && browser.element("clair.pane.1").exists, "No two panes") + XCTAssertTrue(browser.element("clair.splitDivider").exists, "The split shows no divider") + let linksVisibility = try await browser.visibility(of: links) + let counterVisibility = try await browser.visibility(of: counter) + XCTAssertEqual(linksVisibility, "visible", "The leading pane's page isn't visible") + XCTAssertEqual(counterVisibility, "visible", "The trailing pane's page isn't visible") + + // A click in the other pane focuses it. + browser.element("clair.pane.0").click() + let focused = await Harness.wait(for: 10) { try await links.isFocused() } + XCTAssertTrue(focused, "A click in the leading pane didn't focus it") + + // Move Right from the leading pane's split button swaps the panes. + let header = browser.element("clair.paneToolbar.0") + let button = browser.element("clair.splitButton", in: header) + try require(button.waitForExistence(timeout: 5), "The focused pane's header has no split button") + button.click() + let moveLeft = browser.visibleMenuItem("Move Left") + try require(moveLeft != nil, "The pane's split menu has no Move Left") + XCTAssertFalse(moveLeft?.isEnabled ?? true, "Move Left is on in the leading pane") + let moveRight = browser.visibleMenuItem("Move Right") + try require(moveRight != nil, "The pane's split menu has no Move Right") + moveRight?.click() + let swapped = await browser.waitForSplitRows { $0 == ["Counter a, \(Self.links)"] } + XCTAssertTrue(swapped, "Move Right didn't swap the panes: \(browser.splitRows)") + + // Add Split View while split: a toast, and no third pane. + let pages = try await browser.pageCount() + browser.ui.typeKey("=", modifierFlags: [.control, .shift]) + let toast = browser.element("clair.toast") + XCTAssertTrue(toast.waitForExistence(timeout: 5), "Add Split View showed no toast while split") + XCTAssertEqual(toast.value as? String, "Cannot Add New Pane") + let pagesAfter = try await browser.pageCount() + XCTAssertEqual(pagesAfter, pages, "Add Split View opened a page while split") + + // Ctrl+Tab leaves the split, both pages hidden, and Ctrl+Shift+Tab comes + // back to it in one stop, both visible. + browser.ui.typeKey(.tab, modifierFlags: .control) + let left = await Harness.wait(for: 15) { + let leading = try await browser.visibility(of: links) + let trailing = try await browser.visibility(of: counter) + return leading == "hidden" && trailing == "hidden" + } + XCTAssertTrue(left, "Ctrl+Tab didn't leave the split, or left a pane visible") + browser.ui.typeKey(.tab, modifierFlags: [.control, .shift]) + let back = await Harness.wait(for: 15) { + let leading = try await browser.visibility(of: links) + let trailing = try await browser.visibility(of: counter) + return leading == "visible" && trailing == "visible" + } + XCTAssertTrue(back, "Ctrl+Shift+Tab didn't come back to the split in one stop") + + // Separate Tabs from the View menu: two rows in pane order. + try browser.chooseViewItem("Separate Tabs") + let separated = await browser.waitForSplitRows { $0.isEmpty } + XCTAssertTrue(separated, "Separate Tabs left a split row") + let rows = await browser.waitForTabs { + guard let a = $0.firstIndex(of: "Counter a"), let l = $0.firstIndex(of: Self.links) else { return false } + return l == a + 1 + } + XCTAssertTrue(rows, "Separate Tabs didn't leave both rows in pane order: \(browser.tabTitles)") + + // Tabs › Split with Tab ›, then Cmd+W closes the focused pane only. + browser.tabRow(Self.links)?.click() + _ = await browser.waitForActiveRow(Self.links) + try browser.splitWithTabFromMenuBar("Counter a") + made = await browser.waitForSplitRows { $0 == [split] } + try require(made, "Tabs › Split with Tab made no split: \(browser.splitRows)") + let disabled = try browser.tabMenuItem("Split with Tab") + XCTAssertFalse(disabled.isEnabled, "Tabs › Split with Tab is on while split") + browser.ui.typeKey(.escape, modifierFlags: []) + browser.ui.typeKey("w", modifierFlags: .command) + let closed = await browser.waitForTarget("counter.html?a", open: false) + XCTAssertTrue(closed, "Cmd+W didn't close the focused pane") + let kept = await browser.waitForActiveRow(Self.links) + XCTAssertTrue(kept, "The other pane didn't show alone, active: \(browser.activeRow ?? "none")") + XCTAssertTrue(browser.splitRows.isEmpty, "Closing a pane left a split row") + } + + /// Option+click: on a single page it splits with the link; in a split it + /// loads in the other pane, with Back; from a pinned tab it splits instead + /// of a Peek; inside a Peek it's a plain click; the context menu's Open + /// Link in Split View does the same. None downloads. + func testOptionClickAndTheContextMenu() async throws { + let (browser, links, counter) = try await startWithLinks() + defer { + links.close() + counter.close() + } + let downloads = FileManager.default.temporaryDirectory.appending(path: "clair-split-downloads-\(UUID())") + let allow = try await browser.allowDownloads(to: downloads) + defer { allow.close() } + + // A single page: the link opens beside it, trailing and focused. + var pages = try await browser.pageCount() + try await links.optionClick("same") + let opened = await browser.waitForTarget("?split-same") + try require(opened, "Option+click opened nothing") + let made = await browser.waitForSplitRows { $0 == ["\(Self.links), Counter split-same"] } + try require(made, "Option+click made no split: \(browser.splitRows)") + var pagesAfter = try await browser.pageCount() + XCTAssertEqual(pagesAfter, pages + 1, "Option+click opened more than one page") + + // In a split: the other pane navigates, no tab opens, and Back returns. + pages = pagesAfter + try await links.optionClick("second") + let loaded = await browser.waitForTarget("?split-second") + XCTAssertTrue(loaded, "Option+click in a split didn't load the link") + let gone = await browser.waitForTarget("?split-same", open: false) + XCTAssertTrue(gone, "Option+click in a split didn't load in the other pane") + pagesAfter = try await browser.pageCount() + XCTAssertEqual(pagesAfter, pages, "Option+click in a split opened a tab") + let partner = try await browser.session(endingWith: "?split-second") + _ = try await partner.evaluate("history.back(); 1") + let returned = await browser.waitForTarget("?split-same") + XCTAssertTrue(returned, "Back in the other pane didn't return") + partner.close() + + // From the context menu, on a single page. + try browser.chooseViewItem("Separate Tabs") + _ = await browser.waitForSplitRows { $0.isEmpty } + browser.tabRow(Self.links)?.click() + _ = await browser.waitForActiveRow(Self.links) + try await links.rightClick("other") + let item = browser.ui.menuItems["Open Link in Split View"] + try require(item.waitForExistence(timeout: 10), "The link's context menu has no Open Link in Split View") + item.click() + let fromMenu = await browser.waitForTarget("?split-other") + XCTAssertTrue(fromMenu, "Open Link in Split View opened nothing") + let menuSplit = await browser.waitForSplitRows { $0.contains { $0.hasPrefix(Self.links) } } + XCTAssertTrue(menuSplit, "Open Link in Split View made no split: \(browser.splitRows)") + try browser.chooseViewItem("Separate Tabs") + _ = await browser.waitForSplitRows { $0.isEmpty } + + // Inside a Peek, Option+click is a plain click. + let peekTarget = try await browser.open(url("peek.html")) + defer { peekTarget.close() } + _ = await browser.waitForActiveRow("Clair Peek links") + try await peekTarget.shiftClick("plain") + try require(browser.peek.waitForExistence(timeout: 15), "Shift+click showed no Peek") + let inPeek = try await browser.session(endingWith: "?plain") + _ = try await inPeek.evaluate( + "document.body.insertAdjacentHTML('beforeend', 'go'); 1") + try await inPeek.optionClick("go") + let navigated = await browser.waitForTarget("?in-peek") + XCTAssertTrue(navigated, "Option+click inside a Peek didn't navigate it") + XCTAssertTrue(browser.peek.exists, "Option+click inside a Peek closed it") + XCTAssertTrue(browser.splitRows.isEmpty, "Option+click inside a Peek made a split") + inPeek.close() + browser.ui.typeKey(.escape, modifierFlags: []) + + // From a pinned tab, a link to another site splits rather than Peeks. + let pins = try await browser.open(url("pins.html")) + defer { pins.close() } + _ = await browser.waitForActiveRow("Clair pins page") + browser.ui.typeKey("d", modifierFlags: .command) + let pinned = await browser.waitForPins { $0 == ["Clair pins page"] } + try require(pinned, "Cmd+D didn't pin the page") + try await pins.optionClick("other") + let fromPin = await browser.waitForTarget("?other") + XCTAssertTrue(fromPin, "Option+click on the pinned tab opened nothing") + XCTAssertFalse(browser.peek.exists, "Option+click on the pinned tab opened a Peek") + let pinSplit = await browser.waitForSplitRows { !$0.isEmpty } + XCTAssertTrue(pinSplit, "Option+click on the pinned tab made no split") + + // Nothing downloaded. + let files = (try? FileManager.default.contentsOfDirectory(atPath: downloads.path)) ?? [] + XCTAssertTrue(files.isEmpty, "Option+click downloaded \(files)") + } + + /// Peek's Open in Split View, and no such button on a Peek in a split. + func testOpenInSplitViewFromAPeek() async throws { + executionTimeAllowance = 300 + let browser = try await startBrowser() + let links = try await browser.open(url("peek.html")) + defer { links.close() } + browser.ui.activate() + try require(browser.nativeWindow.waitForExistence(timeout: 30), "Clair shows no native window") + _ = await browser.waitForActiveRow("Clair Peek links") + try await links.shiftClick("plain") + try require(browser.peek.waitForExistence(timeout: 15), "Shift+click showed no Peek") + let button = browser.element("clair.peekSplit") + try require(button.waitForExistence(timeout: 5), "The Peek has no Open in Split View") + button.click() + let made = await browser.waitForSplitRows { $0 == ["Clair Peek links, Clair Peek target"] } + XCTAssertTrue(made, "Open in Split View made no split: \(browser.splitRows)") + XCTAssertFalse(browser.peek.exists, "The Peek stayed after Open in Split View") + let peekPage = try await browser.session(endingWith: "?plain") + defer { peekPage.close() } + let visible = try await browser.visibility(of: peekPage) + XCTAssertEqual(visible, "visible", "The Peek's page isn't visible in its pane") + + // A Peek from a pane: no Open in Split View. + browser.element("clair.pane.0").click() + try await Task.sleep(for: .seconds(1)) + try await links.shiftClick("blank") + try require(browser.peek.waitForExistence(timeout: 15), "Shift+click in a pane showed no Peek") + XCTAssertFalse(browser.element("clair.peekSplit").exists, "A Peek in a split offers Open in Split View") + // A click in the other pane, beside the Peek centred over both, closes + // it. + browser.element("clair.pane.1").coordinate(withNormalizedOffset: CGVector(dx: 0.97, dy: 0.5)).click() + let closed = await browser.waitForTarget("?blank", open: false) + XCTAssertTrue(closed, "A click in the other pane didn't close the Peek") + } + + /// A chip's × closes its page only; a split survives Reopen Closed Window + /// and a relaunch with its ratio. + func testASplitComesBack() async throws { + try Harness.setRestoreWindows(true) + let (browser, links, counter) = try await startWithLinks() + try await links.optionClick("same") + let split = "\(Self.links), Counter split-same" + var made = await browser.waitForSplitRows { $0 == [split] } + try require(made, "Option+click made no split") + links.close() + counter.close() + + // Hovering the row shows a × on each chip; one closes its page only, + // and the other shows alone. + browser.element("clair.splitChip.0", in: browser.splitRow(split)).hover() + let close = browser.element("clair.splitClose.1", in: browser.splitRow(split)) + try require(close.waitForExistence(timeout: 5), "Hovering the split row shows no × on the other chip") + XCTAssertTrue( + browser.element("clair.splitClose.0", in: browser.splitRow(split)).exists, + "Hovering the split row shows no × on the hovered chip") + close.click() + let closed = await browser.waitForTarget("?split-same", open: false) + XCTAssertTrue(closed, "The chip's × didn't close its page") + let alone = await browser.waitForSplitRows { $0.isEmpty } + XCTAssertTrue(alone, "The split row stayed after closing a page: \(browser.splitRows)") + let linksOpen = await browser.waitForTarget("split.html") + XCTAssertTrue(linksOpen, "The chip's × closed the other page too") + + // Split again for the rest. + let again = try await browser.session(endingWith: "split.html") + try await again.optionClick("same") + again.close() + made = await browser.waitForSplitRows { $0 == [split] } + try require(made, "Option+click didn't make the split again") + + // A new ratio, from the divider, if the runner may drag. + let divider = browser.element("clair.splitDivider") + try require(divider.waitForExistence(timeout: 10), "The split shows no divider") + let start = divider.frame + var dragged = false + if CGPreflightPostEventAccess() { + try browser.drag(from: CGPoint(x: start.midX, y: start.midY), to: CGPoint(x: start.midX - 120, y: start.midY)) + dragged = await Harness.wait(for: 10) { browser.element("clair.splitDivider").frame.midX < start.midX - 60 } + XCTAssertTrue(dragged, "Dragging the divider didn't move it") + } + let moved = browser.element("clair.splitDivider").frame + + // Relaunching keeps the split and its ratio. + try await browser.relaunch() + made = await browser.waitForSplitRows(30) { $0 == [split] } + XCTAssertTrue(made, "The split didn't come back after a relaunch: \(browser.splitRows)") + browser.splitRow(split).click() + let shown = browser.element("clair.splitDivider") + XCTAssertTrue(shown.waitForExistence(timeout: 15), "The restored split shows no divider") + if dragged { + XCTAssertEqual(shown.frame.midX, moved.midX, accuracy: 3, "The ratio changed across a relaunch") + } + + // Reopen Closed Window brings it back too. Closing the last window + // closes its tabs; with another window open, they'd move there + // (share-tabs-across-windows D4). + browser.ui.typeKey("w", modifierFlags: [.command, .shift]) + for page in ["split.html", "?split-same"] { + let gone = await browser.waitForTarget(page, open: false, seconds: 30) + try require(gone, "The split's page \(page) is still open after its window closed") + } + browser.ui.typeKey("t", modifierFlags: [.command, .shift]) + for page in ["split.html", "?split-same"] { + let reopened = await browser.waitForTarget(page, seconds: 30) + XCTAssertTrue(reopened, "Reopen Closed Window didn't bring \(page) back") + } + // As the split: one row, and both panes with the divider between them. + made = await browser.waitForSplitRows(30) { $0 == [split] } + XCTAssertTrue(made, "The reopened window doesn't list the split: \(browser.splitRows)") + browser.splitRow(split).click() + XCTAssertTrue( + browser.element("clair.splitDivider").waitForExistence(timeout: 15), "The reopened split shows no divider") + for pane in 0..<2 { + XCTAssertTrue( + browser.element("clair.paneToolbar.\(pane)").waitForExistence(timeout: 10), + "The reopened split shows no pane \(pane)") + } + } + + /// A pinned split: Cmd+D pins both as one item, closing one pane takes it + /// out and Restore brings it back, favoriting and a relaunch keep it, and + /// Separate Tabs leaves two pins in its place. + func testPinnedSplits() async throws { + executionTimeAllowance = 420 + let (browser, links, counter) = try await startWithLinks() + defer { + links.close() + counter.close() + } + try await links.optionClick("same") + let split = "\(Self.links), Counter split-same" + let made = await browser.waitForSplitRows { $0 == [split] } + try require(made, "Option+click made no split") + + // Cmd+D pins the split as one item. + browser.ui.typeKey("d", modifierFlags: .command) + let pinned = await Harness.wait(for: 15) { browser.pinTitles.isEmpty && browser.splitRows == [split] } + XCTAssertTrue(pinned, "Cmd+D didn't pin the split as one row") + try await browser.relaunch() + + // After the relaunch: the row is back; Cmd+1, the first row, opens both + // pages. + var back = await browser.waitForSplitRows(30) { $0 == [split] } + try require(back, "The pinned split didn't come back: \(browser.splitRows)") + browser.ui.typeKey("1", modifierFlags: .command) + let both = await Harness.wait(for: 20) { + let leading = try await browser.target(endingWith: "split.html") + let trailing = try await browser.target(endingWith: "?split-same") + return leading != nil && trailing != nil + } + XCTAssertTrue(both, "Selecting the pinned split didn't open both pages") + + // Closing one pane takes its pin out; Restore Last Closed Tab brings the + // split back. + browser.element("clair.pane.1").click() + try await Task.sleep(for: .seconds(1)) + browser.ui.typeKey("w", modifierFlags: .command) + let out = await Harness.wait(for: 15) { browser.splitRows.isEmpty && browser.pinTitles.count == 1 } + XCTAssertTrue(out, "Closing a pane didn't leave one pin: \(browser.pinTitles), \(browser.splitRows)") + browser.ui.typeKey("t", modifierFlags: [.command, .shift]) + back = await browser.waitForSplitRows { $0 == [split] } + XCTAssertTrue(back, "Restore Last Closed Tab didn't bring the pinned split back: \(browser.splitRows)") + + // Pin to Favorites makes one tile, which a relaunch keeps. + try browser.choose("Pin to Favorites", inMenuOf: browser.element("clair.splitChip.0")) + let tile = browser.element("clair.favoriteSplitTile") + XCTAssertTrue(tile.waitForExistence(timeout: 15), "Pin to Favorites made no split tile") + try await browser.relaunch() + XCTAssertTrue(browser.element("clair.favoriteSplitTile").waitForExistence(timeout: 30), "The tile didn't come back") + let records = try Array(browser.pinRecords().values) + let splits = records.filter { $0["kind"] as? String == "split" } + XCTAssertEqual(splits.count, 1, "Local State holds \(splits.count) split records") + XCTAssertEqual( + records.filter { $0["split"] != nil }.count, 2, "Local State's pins don't name their split") + + // Separate Tabs leaves two favorites in its place. + try browser.chooseOnScreen("Separate Tabs", inMenuOf: browser.element("clair.splitChip.0", in: tile)) + let separated = await browser.waitForFavorites { $0.count == 2 } + XCTAssertTrue(separated, "Separate Tabs didn't leave two favorites: \(browser.favoriteTitles)") + XCTAssertFalse(browser.element("clair.favoriteSplitTile").exists, "The split tile stayed") + } +} diff --git a/tests/runtime/pages/split.html b/tests/runtime/pages/split.html new file mode 100644 index 0000000..cc9e341 --- /dev/null +++ b/tests/runtime/pages/split.html @@ -0,0 +1,13 @@ + + +Clair split links + + +

A counter on the same site

+

Another counter

+

A page on another site

+