SPB Git

Repository Public

SidebarView.swift 33.1 KB 673 lines swift

1import SwiftUI23struct SidebarView: View {4    @Bindable var state: BrowserWindowState5    let environment: AppEnvironment6    let topInset: CGFloat78    var body: some View {9        VStack(spacing: 0) {10            HStack(spacing: 6) {11                Spacer()12                if state.isPrivate {13                    Label(L("Private"), systemImage: "eyeglasses").font(.caption.weight(.semibold)).foregroundStyle(Theme.privateTint)14                } else if environment.profiles.count > 1 {15                    Label(state.profile.profile.name, systemImage: state.profile.profile.symbol).font(.caption.weight(.medium))16                        .foregroundStyle(Theme.color(state.profile.profile.colorIndex))17                }18            }19            .padding(.horizontal, 12).frame(height: topInset)2021            WorkspaceSwitcher(state: state).padding(.horizontal, 10).padding(.bottom, 8)2223            HStack(spacing: 2) {24                ForEach(SidebarPanel.allCases) { panel in25                    IconButton(symbol: panel.symbol, label: panel.title, isActive: state.sidebarPanel == panel, size: 28) { state.sidebarPanel = panel }26                        .frame(maxWidth: .infinity)27                }28            }29            .padding(.horizontal, 10).padding(.bottom, 6)30            Divider().overlay(Theme.hairline)3132            Group {33                switch state.sidebarPanel {34                case .tabs: TabsPanel(state: state)35                case .bookmarks: BookmarksPanel(state: state)36                case .history: HistoryPanel(state: state)37                case .readingList: ReadingListPanel(state: state, environment: environment)38                case .devices: OtherDevicesPanel(state: state, environment: environment)39                case .notes: NotesPanel(state: state)40                case .sessions: SessionsPanel(state: state, environment: environment)41                }42            }43            .frame(maxHeight: .infinity)44            .id(state.sidebarPanel)45            .transition(.opacity.combined(with: .offset(y: AuraMotion.policy.allowsSpatial ? 6 : 0)))46        }47        .auraAnimation(.standard, value: state.sidebarPanel)48        .accessibilityElement(children: .contain)49        .accessibilityLabel(L("Sidebar"))50    }51}5253// MARK: - Workspaces5455struct WorkspaceSwitcher: View {56    let state: BrowserWindowState57    @State private var renaming: Workspace?58    @State private var draftName = ""5960    static let symbols = ["person", "books.vertical", "hammer", "briefcase", "house", "graduationcap", "chart.line.uptrend.xyaxis",61                          "cart", "airplane", "gamecontroller", "music.note", "heart", "leaf", "star", "square.stack.3d.up"]6263    var body: some View {64        HStack(spacing: 6) {65            ForEach(state.workspaces) { workspace in66                let active = workspace.id == state.activeWorkspaceID67                Button { state.switchWorkspace(to: workspace.id) } label: {68                    HStack(spacing: 5) {69                        Image(systemName: workspace.symbol).font(.system(size: 11, weight: .semibold))70                        if active { Text(workspace.name).font(.system(size: 12, weight: .semibold)).lineLimit(1) }71                    }72                    .foregroundStyle(active ? Color.white : Theme.color(workspace.colorIndex))73                    .padding(.horizontal, active ? 10 : 0).frame(minWidth: 28).frame(height: 26)74                    .background(Capsule().fill(active ? AnyShapeStyle(Theme.color(workspace.colorIndex)) : AnyShapeStyle(Theme.color(workspace.colorIndex).opacity(0.14))))75                }76                .buttonStyle(.plain)77                .help(workspace.name)78                .accessibilityLabel(L("Workspace %@", workspace.name))79                .accessibilityAddTraits(active ? .isSelected : [])80                .contextMenu { menu(for: workspace) }81            }82            Spacer(minLength: 0)83            if !state.isPrivate {84                IconButton(symbol: "plus", label: L("New Workspace"), size: 24) { state.addWorkspace(name: "") }85            }86        }87        .popover(item: $renaming) { workspace in88            VStack(alignment: .leading, spacing: 10) {89                Text(L("Rename Workspace")).font(.headline)90                TextField(L("Name"), text: $draftName).textFieldStyle(.roundedBorder).frame(width: 220).onSubmit { commitRename(workspace) }91                HStack { Spacer(); Button(L("Cancel")) { renaming = nil }; Button(L("Save")) { commitRename(workspace) }.buttonStyle(.borderedProminent) }92            }93            .padding(14)94        }95    }9697    private func commitRename(_ workspace: Workspace) {98        let name = draftName.trimmingCharacters(in: .whitespaces)99        if !name.isEmpty { update(workspace) { $0.name = name } }100        renaming = nil101    }102103    private func update(_ workspace: Workspace, _ change: (inout Workspace) -> Void) {104        state.saveWorkspaces(state.workspaces.map { item in105            guard item.id == workspace.id else { return item }106            var copy = item107            change(&copy)108            return copy109        })110    }111112    private func move(_ workspace: Workspace, by offset: Int) {113        var list = state.workspaces114        guard let index = list.firstIndex(where: { $0.id == workspace.id }), list.indices.contains(index + offset) else { return }115        list.swapAt(index, index + offset)116        state.saveWorkspaces(list)117    }118119    @ViewBuilder private func menu(for workspace: Workspace) -> some View {120        if !state.isPrivate {121            Button(L("Rename…")) { draftName = workspace.name; renaming = workspace }122            Menu(L("Icon")) {123                ForEach(Self.symbols, id: \.self) { symbol in124                    Button { update(workspace) { $0.symbol = symbol } } label: { Label(symbol, systemImage: symbol) }125                }126            }127            Menu(L("Color")) {128                ForEach(0..<Theme.palette.count, id: \.self) { index in129                    Button(L("Color %d", index + 1)) { update(workspace) { $0.colorIndex = index } }130                }131            }132            Divider()133            Button(L("Move Left")) { move(workspace, by: -1) }.disabled(state.workspaces.first?.id == workspace.id)134            Button(L("Move Right")) { move(workspace, by: 1) }.disabled(state.workspaces.last?.id == workspace.id)135            Divider()136            Button(L("Delete Workspace"), role: .destructive) { state.saveWorkspaces(state.workspaces.filter { $0.id != workspace.id }) }137                .disabled(state.workspaces.count < 2)138        }139    }140}141142// MARK: - Tabs143144struct TabsPanel: View {145    let state: BrowserWindowState146147    var body: some View {148        let tabs = state.visibleTabs149        let pinned = tabs.filter(\.isPinned)150        let ungrouped = tabs.filter { !$0.isPinned && $0.groupID == nil }151        ScrollView {152            VStack(alignment: .leading, spacing: 3) {153                if let favorites = state.activeWorkspace?.favorites, !favorites.isEmpty {154                    SectionLabel(text: L("Favorites")).padding(.top, 4)155                    FlowFavorites(favorites: favorites, state: state)156                }157                if !pinned.isEmpty {158                    SectionLabel(text: L("Pinned")).padding(.top, 6)159                    ForEach(pinned) { TabRow(tab: $0, state: state) }160                }161                ForEach(state.groups.filter { group in tabs.contains { $0.groupID == group.id } }) { group in162                    GroupSection(group: group, tabs: tabs.filter { $0.groupID == group.id }, state: state)163                }164                SectionLabel(text: L("Tabs")).padding(.top, 6)165                ForEach(ungrouped) { TabRow(tab: $0, state: state) }166                Button { state.perform(.newTab) } label: {167                    HoverRow { Label(CommandID.newTab.title, systemImage: "plus").font(.system(size: 12.5)).foregroundStyle(.secondary).padding(.horizontal, 8).padding(.vertical, 6) }168                }169                .buttonStyle(.plain)170            }171            .padding(10)172            // Sidebar Fluidity: rows slide to their new place when tabs open, close, move or change group.173            .auraAnimation(.spring, value: tabs.map(\.id))174            .auraAnimation(.spring, value: tabs.map(\.groupID))175            .auraAnimation(.spring, value: pinned.map(\.id))176        }177        .dropDestination(for: String.self) { items, _ in178            guard let id = items.first.flatMap(UUID.init(uuidString:)) else { return false }179            state.moveTab(id, before: nil)180            return true181        }182    }183}184185struct FlowFavorites: View {186    let favorites: [WorkspaceFavorite]187    let state: BrowserWindowState188189    var body: some View {190        LazyVGrid(columns: [GridItem(.adaptive(minimum: 54), spacing: 6)], spacing: 6) {191            ForEach(favorites) { favorite in192                Button { if let url = URL(string: favorite.url) { state.open(url, inNewTab: NSEvent.modifierFlags.contains(.command)) } } label: {193                    VStack(spacing: 3) {194                        Favicon(image: FaviconLoader.shared.cached(forHost: URL(string: favorite.url)?.host), fallback: favorite.title, size: 20)195                        Text(favorite.title).font(.system(size: 9.5)).lineLimit(1).foregroundStyle(.secondary)196                    }197                    .frame(maxWidth: .infinity).padding(.vertical, 7)198                    .background(RoundedRectangle(cornerRadius: Theme.radiusS, style: .continuous).fill(Theme.hover))199                }200                .buttonStyle(.plain)201                .help(favorite.url)202                .contextMenu {203                    Button(L("Open in New Tab")) { if let url = URL(string: favorite.url) { state.newTab(url: url, select: true) } }204                    Button(L("Remove from Workspace Favorites"), role: .destructive) {205                        guard var workspace = state.activeWorkspace else { return }206                        workspace.favorites.removeAll { $0.id == favorite.id }207                        state.saveWorkspaces(state.workspaces.map { $0.id == workspace.id ? workspace : $0 })208                    }209                }210            }211        }212    }213}214215struct GroupSection: View {216    let group: TabGroup217    let tabs: [BrowserTab]218    let state: BrowserWindowState219    @State private var renaming = false220    @State private var draft = ""221222    var body: some View {223        VStack(alignment: .leading, spacing: 3) {224            HStack(spacing: 6) {225                Button {226                    var copy = group; copy.isCollapsed.toggle(); state.updateGroup(copy)227                } label: {228                    Image(systemName: group.isCollapsed ? "chevron.right" : "chevron.down").font(.system(size: 9, weight: .bold)).frame(width: 12)229                }230                .buttonStyle(.plain).accessibilityLabel(group.isCollapsed ? L("Expand group") : L("Collapse group"))231                Circle().fill(Theme.color(group.colorIndex)).frame(width: 8, height: 8)232                if renaming {233                    TextField(L("Group name"), text: $draft).textFieldStyle(.plain).font(.system(size: 12, weight: .semibold))234                        .onSubmit { var copy = group; copy.name = draft.isEmpty ? group.name : draft; state.updateGroup(copy); renaming = false }235                } else {236                    Text(group.name).font(.system(size: 12, weight: .semibold)).lineLimit(1)237                    Text("\(tabs.count)").font(.caption2).foregroundStyle(.secondary)238                }239                Spacer()240            }241            .padding(.top, 8).padding(.horizontal, 2)242            .contextMenu {243                Button(L("Rename…")) { draft = group.name; renaming = true }244                Menu(L("Color")) {245                    ForEach(0..<Theme.palette.count, id: \.self) { index in246                        Button(L("Color %d", index + 1)) { var copy = group; copy.colorIndex = index; state.updateGroup(copy) }247                    }248                }249                Button(L("Ungroup Tabs")) { state.removeGroup(group, closingTabs: false) }250                Button(L("Close Group"), role: .destructive) { state.removeGroup(group, closingTabs: true) }251            }252            if !group.isCollapsed {253                ForEach(tabs) { TabRow(tab: $0, state: state).padding(.leading, 12) }254            }255        }256    }257}258259struct TabRow: View {260    let tab: BrowserTab261    let state: BrowserWindowState262    @State private var hovering = false263    @State private var isTargeted = false264265    var body: some View {266        let isSelected = state.selectedTabID == tab.id267        HoverRow(isSelected: isSelected, radius: 8) {268            HStack(spacing: 8) {269                if tab.isLoading { ProgressView().controlSize(.small).scaleEffect(0.6).frame(width: 16, height: 16) }270                else { Favicon(image: tab.favicon, fallback: tab.displayTitle).opacity(tab.isSuspended ? 0.45 : 1) }271                Text(tab.displayTitle).font(.system(size: 12.5)).lineLimit(1).foregroundStyle(isSelected ? .primary : .secondary)272                Spacer(minLength: 0)273                if tab.isSuspended { Image(systemName: "moon.zzz").font(.system(size: 9)).foregroundStyle(.tertiary).help(L("Suspended to save memory")) }274                if state.splitTabID == tab.id { Image(systemName: "rectangle.split.2x1").font(.system(size: 9)).foregroundStyle(.secondary) }275                if hovering {276                    Button { state.close(tab) } label: { Image(systemName: "xmark").font(.system(size: 8.5, weight: .bold)).frame(width: 16, height: 16) }277                        .buttonStyle(.plain).accessibilityLabel(L("Close %@", tab.displayTitle))278                }279            }280            .padding(.horizontal, 8).frame(height: 30)281        }282        .overlay(alignment: .top) { if isTargeted { Capsule().fill(Theme.accent).frame(height: 2) } }283        .onHover { hovering = $0 }284        .onTapGesture { state.select(tab) }285        .contextMenu { TabMenu(tab: tab, state: state) }286        .draggable(tab.id.uuidString)287        .dropDestination(for: String.self) { items, _ in288            guard let id = items.first.flatMap(UUID.init(uuidString:)) else { return false }289            state.moveTab(id, before: tab.id)290            return true291        } isTargeted: { isTargeted = $0 }292        .help(tab.url?.absoluteString ?? "")293        .accessibilityElement(children: .ignore)294        .accessibilityLabel(tab.displayTitle)295        .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)296        .accessibilityAction { state.select(tab) }297        .accessibilityAction(named: L("Close Tab")) { state.close(tab) }298    }299}300301// MARK: - Bookmarks302303struct BookmarksPanel: View {304    @Bindable var state: BrowserWindowState305    @State private var query = ""306307    var body: some View {308        let store = state.profile.bookmarks309        let _ = state.bookmarksRevision310        VStack(spacing: 0) {311            SearchField(text: $query, prompt: L("Search bookmarks or #tag"))312            if query.isEmpty {313                let nodes = store.tree()314                if nodes.isEmpty {315                    StateView(symbol: "bookmark", title: L("No bookmarks yet"), message: L("Press ⌘D to bookmark the current page, or import bookmarks from another browser."),316                              actionTitle: CommandID.importBookmarks.title, action: { state.perform(.importBookmarks) }, compact: true)317                } else {318                    ScrollView {319                        VStack(alignment: .leading, spacing: 1) {320                            let tags = store.allTags()321                            if !tags.isEmpty {322                                ScrollView(.horizontal, showsIndicators: false) {323                                    HStack(spacing: 4) {324                                        ForEach(tags, id: \.self) { tag in325                                            Button("#" + tag) { query = "#" + tag }.buttonStyle(.plain).font(.caption)326                                                .padding(.horizontal, 7).padding(.vertical, 3).background(Theme.hover, in: Capsule())327                                        }328                                    }329                                }330                                .padding(.bottom, 6)331                            }332                            ForEach(nodes, id: \.bookmark.id) { BookmarkNodeView(node: $0, state: state, depth: 0) }333                        }334                        .padding(10)335                    }336                }337            } else {338                let results = store.search(query)339                if results.isEmpty {340                    StateView(symbol: "magnifyingglass", title: L("No result"), compact: true)341                } else {342                    ScrollView {343                        VStack(spacing: 1) { ForEach(results) { BookmarkRow(bookmark: $0, state: state) } }.padding(10)344                    }345                }346            }347            Divider().overlay(Theme.hairline)348            HStack {349                Button(L("New Folder")) { _ = store.addFolder(L("New Folder")); state.bookmarksRevision += 1 }350                Spacer()351                Menu {352                    Button(CommandID.importBookmarks.title) { state.perform(.importBookmarks) }353                    Button(CommandID.exportBookmarks.title) { state.perform(.exportBookmarks) }354                } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).fixedSize().accessibilityLabel(L("Import and export"))355            }356            .controlSize(.small).padding(8)357        }358    }359}360361struct BookmarkNodeView: View {362    let node: BookmarkNode363    let state: BrowserWindowState364    let depth: Int365    @State private var expanded = true366    @State private var renaming = false367    @State private var draft = ""368369    var body: some View {370        if node.bookmark.isFolder {371            VStack(alignment: .leading, spacing: 1) {372                HoverRow {373                    HStack(spacing: 6) {374                        Image(systemName: expanded ? "chevron.down" : "chevron.right").font(.system(size: 9, weight: .bold)).frame(width: 12)375                        Image(systemName: "folder").foregroundStyle(Theme.accent).font(.system(size: 12))376                        if renaming {377                            TextField(L("Name"), text: $draft).textFieldStyle(.plain).onSubmit {378                                var copy = node.bookmark; copy.title = draft.isEmpty ? copy.title : draft379                                state.profile.bookmarks.update(copy); renaming = false; state.bookmarksRevision += 1380                            }381                        } else {382                            Text(node.bookmark.title).lineLimit(1)383                        }384                        Spacer()385                    }386                    .font(.system(size: 12.5)).padding(.horizontal, 6).frame(height: 28)387                }388                .onTapGesture { expanded.toggle() }389                .contextMenu {390                    Button(L("Rename…")) { draft = node.bookmark.title; renaming = true }391                    Button(L("Open All in Tabs")) {392                        node.children.compactMap { $0.bookmark.url.flatMap(URL.init(string:)) }.forEach { state.newTab(url: $0, select: false) }393                    }394                    Button(L("Delete Folder and Contents"), role: .destructive) { state.profile.bookmarks.delete(id: node.bookmark.id); state.bookmarksRevision += 1 }395                }396                .dropDestination(for: String.self) { items, _ in397                    guard let id = items.first, id.hasPrefix("bookmark:") else { return false }398                    let moved = state.profile.bookmarks.move(id: String(id.dropFirst(9)), toParent: node.bookmark.id)399                    state.bookmarksRevision += 1400                    return moved401                }402                .accessibilityLabel(L("Folder %@", node.bookmark.title))403                if expanded {404                    ForEach(node.children, id: \.bookmark.id) { BookmarkNodeView(node: $0, state: state, depth: depth + 1) }405                }406            }407            .padding(.leading, CGFloat(depth) * 12)408        } else {409            BookmarkRow(bookmark: node.bookmark, state: state).padding(.leading, CGFloat(depth) * 12)410        }411    }412}413414struct BookmarkRow: View {415    let bookmark: Bookmark416    let state: BrowserWindowState417418    var body: some View {419        HoverRow {420            HStack(spacing: 8) {421                Favicon(image: FaviconLoader.shared.cached(forHost: bookmark.url.flatMap(URL.init(string:))?.host), fallback: bookmark.title)422                VStack(alignment: .leading, spacing: 0) {423                    Text(bookmark.title.isEmpty ? (bookmark.url ?? "") : bookmark.title).lineLimit(1).font(.system(size: 12.5))424                    if !bookmark.tags.isEmpty {425                        Text(bookmark.tags.map { "#" + $0 }.joined(separator: " ")).font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1)426                    }427                }428                Spacer(minLength: 0)429            }430            .padding(.horizontal, 6).frame(minHeight: 28)431        }432        .onTapGesture { open(inNewTab: NSEvent.modifierFlags.contains(.command)) }433        .draggable("bookmark:" + bookmark.id)434        .contextMenu {435            Button(L("Open")) { open(inNewTab: false) }436            Button(L("Open in New Tab")) { open(inNewTab: true) }437            Button(L("Edit…")) { state.editingBookmark = bookmark; state.sheet = .bookmarkEditor }438            Button(L("Copy Address")) {439                NSPasteboard.general.clearContents()440                NSPasteboard.general.setString(bookmark.url ?? "", forType: .string)441            }442            if bookmark.parentID != nil {443                Button(L("Move to Top Level")) { state.profile.bookmarks.move(id: bookmark.id, toParent: nil); state.bookmarksRevision += 1 }444            }445            Button(L("Delete"), role: .destructive) { state.profile.bookmarks.delete(id: bookmark.id); state.bookmarksRevision += 1 }446        }447        .help(bookmark.url ?? "")448        .accessibilityElement(children: .ignore)449        .accessibilityLabel(bookmark.title)450        .accessibilityAddTraits(.isLink)451        .accessibilityAction { open(inNewTab: false) }452    }453454    private func open(inNewTab: Bool) {455        guard let url = bookmark.url.flatMap(URL.init(string:)) else { return }456        state.open(url, inNewTab: inNewTab)457    }458}459460struct SearchField: View {461    @Binding var text: String462    let prompt: String463464    var body: some View {465        HStack(spacing: 6) {466            Image(systemName: "magnifyingglass").foregroundStyle(.secondary).font(.system(size: 11))467            TextField(prompt, text: $text).textFieldStyle(.plain).font(.system(size: 12.5))468            if !text.isEmpty {469                Button { text = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) }470                    .buttonStyle(.plain).accessibilityLabel(L("Clear"))471            }472        }473        .padding(.horizontal, 8).frame(height: 28)474        .background(RoundedRectangle(cornerRadius: Theme.radiusS, style: .continuous).fill(Theme.field))475        .overlay(RoundedRectangle(cornerRadius: Theme.radiusS, style: .continuous).strokeBorder(Theme.hairline))476        .padding(10)477    }478}479480// MARK: - History481482struct HistoryPanel: View {483    @Bindable var state: BrowserWindowState484    @State private var query = ""485486    var body: some View {487        if state.isPrivate {488            StateView(symbol: "eyeglasses", title: L("History is not recorded"),489                      message: L("Pages visited in a private window are not added to history, and its cookies and site data are discarded when the window closes."), compact: true)490        } else {491            let _ = state.historyRevision492            let entries = state.profile.history.search(query, limit: 300)493            VStack(spacing: 0) {494                SearchField(text: $query, prompt: L("Search history"))495                if entries.isEmpty {496                    StateView(symbol: "clock", title: query.isEmpty ? L("No history yet") : L("No result"), compact: true)497                } else {498                    ScrollView {499                        LazyVStack(alignment: .leading, spacing: 1) {500                            ForEach(grouped(entries), id: \.0) { day, items in501                                SectionLabel(text: day).padding(.top, 8).padding(.bottom, 2)502                                ForEach(items) { entry in503                                    HoverRow {504                                        HStack(spacing: 8) {505                                            Favicon(image: FaviconLoader.shared.cached(forHost: URL(string: entry.url)?.host), fallback: entry.title.isEmpty ? entry.url : entry.title)506                                            Text(entry.title.isEmpty ? entry.url : entry.title).font(.system(size: 12.5)).lineLimit(1)507                                            Spacer(minLength: 0)508                                            Text(entry.visitedAt, style: .time).font(.system(size: 10)).foregroundStyle(.tertiary)509                                        }510                                        .padding(.horizontal, 6).frame(height: 28)511                                    }512                                    .onTapGesture { if let url = URL(string: entry.url) { state.open(url, inNewTab: NSEvent.modifierFlags.contains(.command)) } }513                                    .help(entry.url)514                                    .contextMenu {515                                        Button(L("Open in New Tab")) { if let url = URL(string: entry.url) { state.newTab(url: url, select: true) } }516                                        Button(L("Delete This Visit"), role: .destructive) { state.profile.history.delete(id: entry.id); state.profile.flow.update { $0.forget(url: entry.url) }; state.historyRevision += 1 }517                                        if let host = URL(string: entry.url)?.host {518                                            Button(L("Delete All Visits to %@", host), role: .destructive) { state.profile.history.delete(host: host); state.profile.flow.update { $0.forget(host: host) }; state.historyRevision += 1 }519                                        }520                                    }521                                    .accessibilityElement(children: .ignore)522                                    .accessibilityLabel(entry.title.isEmpty ? entry.url : entry.title)523                                    .accessibilityAddTraits(.isLink)524                                }525                            }526                        }527                        .padding(.horizontal, 10).padding(.bottom, 10)528                    }529                }530                Divider().overlay(Theme.hairline)531                HStack {532                    Text(L("%d visits", state.profile.history.count)).font(.caption).foregroundStyle(.secondary)533                    Spacer()534                    Button(CommandID.clearHistory.title) { state.perform(.clearHistory) }.controlSize(.small)535                }536                .padding(8)537            }538        }539    }540541    private func grouped(_ entries: [HistoryEntry]) -> [(String, [HistoryEntry])] {542        let formatter = DateFormatter()543        formatter.dateStyle = .full544        formatter.doesRelativeDateFormatting = true545        var order: [String] = []546        var map: [String: [HistoryEntry]] = [:]547        for entry in entries {548            let key = formatter.string(from: entry.visitedAt)549            if map[key] == nil { order.append(key) }550            map[key, default: []].append(entry)551        }552        return order.map { ($0, map[$0] ?? []) }553    }554}555556// MARK: - Notes557558struct NotesPanel: View {559    let state: BrowserWindowState560    @State private var text = ""561    @State private var loadedKey = ""562    @State private var revision = 0563564    var body: some View {565        let url = state.selectedTab?.url566        VStack(alignment: .leading, spacing: 8) {567            if let url {568                Text(L("Note for this page")).font(.headline)569                Text(url.host ?? url.absoluteString).font(.caption).foregroundStyle(.secondary).lineLimit(1)570                TextEditor(text: $text)571                    .font(.system(size: 13)).scrollContentBackground(.hidden).padding(6)572                    .background(RoundedRectangle(cornerRadius: Theme.radiusS).fill(Theme.field))573                    .overlay(RoundedRectangle(cornerRadius: Theme.radiusS).strokeBorder(Theme.hairline))574                    .frame(minHeight: 140, maxHeight: 260)575                    .accessibilityLabel(L("Note for this page"))576                    .onChange(of: text) {577                        guard loadedKey == NotesStore.key(for: url) else { return }578                        state.profile.notes.save(text, for: url)579                        revision += 1580                    }581                Text(L("Notes stay on this Mac. They are saved as you type.")).font(.caption2).foregroundStyle(.tertiary)582            } else {583                StateView(symbol: "note.text", title: L("Open a page to attach a note"), compact: true).frame(height: 150)584            }585            let _ = revision586            let others = state.profile.notes.all().filter { url == nil || $0.url != NotesStore.key(for: url!) }587            if !others.isEmpty {588                SectionLabel(text: L("Other notes")).padding(.top, 6)589                ScrollView {590                    VStack(spacing: 1) {591                        ForEach(others, id: \.url) { note in592                            HoverRow {593                                VStack(alignment: .leading, spacing: 1) {594                                    Text(note.body).font(.system(size: 12)).lineLimit(2)595                                    Text(URL(string: note.url)?.host ?? note.url).font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1)596                                }597                                .padding(6)598                            }599                            .onTapGesture { if let target = URL(string: note.url) { state.open(target) } }600                            .contextMenu {601                                Button(L("Delete Note"), role: .destructive) {602                                    if let target = URL(string: note.url) { state.profile.notes.save("", for: target); revision += 1 }603                                }604                            }605                        }606                    }607                }608            }609            Spacer(minLength: 0)610        }611        .padding(12)612        .task(id: url) {613            loadedKey = ""614            text = url.flatMap { state.profile.notes.note(for: $0)?.body } ?? ""615            loadedKey = url.map(NotesStore.key(for:)) ?? ""616        }617    }618}619620// MARK: - Sessions621622struct SessionsPanel: View {623    let state: BrowserWindowState624    let environment: AppEnvironment625    @State private var revision = 0626627    var body: some View {628        if state.isPrivate {629            StateView(symbol: "eyeglasses", title: L("Private windows are never saved"), compact: true)630        } else {631            let _ = revision632            let sessions = environment.sessionStore.listNamed()633            ScrollView {634                VStack(alignment: .leading, spacing: 4) {635                    Button { state.perform(.saveSession) } label: { Label(CommandID.saveSession.title, systemImage: "tray.and.arrow.down") }636                        .controlSize(.regular).padding(.bottom, 4)637                    SectionLabel(text: L("Saved sessions"))638                    if sessions.isEmpty {639                        Text(L("Save the open windows and tabs under a name to bring them back later.")).font(.callout).foregroundStyle(.secondary).padding(.vertical, 4)640                    }641                    ForEach(sessions) { session in642                        HoverRow {643                            HStack {644                                VStack(alignment: .leading, spacing: 1) {645                                    Text(session.name.isEmpty ? L("Untitled session") : session.name).font(.system(size: 12.5, weight: .medium)).lineLimit(1)646                                    Text(L("%d tabs · %@", session.tabCount, session.savedAt.formatted(date: .abbreviated, time: .shortened))).font(.system(size: 10.5)).foregroundStyle(.secondary)647                                }648                                Spacer()649                                Button(L("Restore")) { if let snapshot = environment.sessionStore.loadNamed(session) { environment.restore(snapshot) } }.controlSize(.small)650                            }651                            .padding(6)652                        }653                        .contextMenu { Button(L("Delete"), role: .destructive) { environment.sessionStore.deleteNamed(session); revision += 1 } }654                    }655                    if !state.recentlyClosed.isEmpty {656                        SectionLabel(text: L("Recently closed tabs")).padding(.top, 10)657                        ForEach(state.recentlyClosed) { snapshot in658                            HoverRow {659                                Label(snapshot.title.isEmpty ? (snapshot.url ?? "") : snapshot.title, systemImage: "arrow.uturn.backward")660                                    .font(.system(size: 12.5)).lineLimit(1).padding(.horizontal, 6).frame(height: 28)661                            }662                            .onTapGesture { state.reopen(snapshot) }663                            .accessibilityAddTraits(.isButton)664                        }665                    }666                }667                .padding(12)668            }669            .onChange(of: state.sheet) { revision += 1 }670        }671    }672}673
Files main
Menu

Theme