Repository Public License
1import LunarDesign2import NavigatorCore3import Persistence4import SwiftUI56#if canImport(AppKit)7import AppKit8#elseif canImport(UIKit)9import UIKit10#endif1112/// Hosts a registered panel beside the page (Mac, iPad) or inside a sheet (iPhone): the shell draws the header,13/// the contribution fills the rest.14struct PanelContainer: View {15 @Environment(\.lunarTheme) private var theme16 let window: WindowModel17 let panel: SidePanelContribution18 var showsClose = true1920 var body: some View {21 VStack(spacing: 0) {22 LunarSheetHeader(panel.title.string, icon: panel.icon, closeLabel: L("Close"),23 onClose: showsClose ? { window.panel = nil } : nil)24 .padding(.horizontal, LunarSpacing.xs)25 .padding(.top, LunarSpacing.xs)26 panel.content(window)27 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)28 }29 .accessibilityElement(children: .contain)30 .accessibilityIdentifier("panel." + panel.id.rawValue)31 }32}3334struct HistoryDay: Identifiable, Equatable {35 var day: Date36 var entries: [NavigationEntry]37 var id: Date { day }3839 /// Groups visits (most recent first) by calendar day, keeping one row per address per day.40 static func group(_ entries: [NavigationEntry], calendar: Calendar = .current) -> [HistoryDay] {41 var days: [HistoryDay] = []42 var seen = Set<String>()43 for entry in entries {44 let day = calendar.startOfDay(for: entry.visitedAt)45 if days.last?.day != day {46 days.append(HistoryDay(day: day, entries: []))47 seen.removeAll()48 }49 guard seen.insert(entry.url.absoluteString).inserted else { continue }50 days[days.count - 1].entries.append(entry)51 }52 return days53 }5455 static func title(for day: Date, calendar: Calendar = .current, now: Date = .now) -> String {56 if calendar.isDate(day, inSameDayAs: now) { return L("Today") }57 if let yesterday = calendar.date(byAdding: .day, value: -1, to: now), calendar.isDate(day, inSameDayAs: yesterday) {58 return L("Yesterday")59 }60 return day.formatted(date: .complete, time: .omitted)61 }62}6364struct HistoryPanel: View {65 @Environment(\.lunarTheme) private var theme66 @Environment(BrowserStore.self) private var store67 let window: WindowModel6869 @State private var query = ""70 @State private var days: [HistoryDay] = []71 @State private var results: [HistoryPage] = []72 @State private var isLoaded = false73 @State private var confirmsClear = false7475 var body: some View {76 VStack(spacing: LunarSpacing.xs) {77 LunarSearchField(text: $query, prompt: L("Search history"), leading: .symbol("magnifyingglass"))78 .padding(.horizontal, LunarSpacing.sm)79 .accessibilityIdentifier("history.search")80 if isLoaded && days.isEmpty && query.isEmpty {81 LunarEmptyState(icon: .symbol("clock"), title: L("No history yet"),82 message: L("Pages you visit appear here. History stays on this device."))83 .frame(maxHeight: .infinity)84 } else if !query.isEmpty && results.isEmpty && isLoaded {85 LunarEmptyState(icon: .symbol("magnifyingglass"), title: L("No result"),86 message: L("Nothing in your history matches “%@”.", query))87 .frame(maxHeight: .infinity)88 } else {89 ScrollView {90 LazyVStack(alignment: .leading, spacing: 2, pinnedViews: []) {91 if query.isEmpty {92 ForEach(days) { day in93 dayHeader(day)94 ForEach(day.entries) { entry in95 row(title: entry.title, url: entry.url, time: entry.visitedAt) { delete(entry) }96 }97 }98 } else {99 ForEach(results, id: \.url) { page in100 row(title: page.title, url: page.url, time: nil) { deleteURL(page.url) }101 }102 }103 }104 .padding(.horizontal, LunarSpacing.xs)105 .padding(.bottom, LunarSpacing.sm)106 }107 .scrollIndicators(.never)108 }109 if !days.isEmpty {110 LunarHairline()111 Button(L("Clear All History…")) { confirmsClear = true }112 .buttonStyle(.lunar(.destructive, size: .compact))113 .padding(.bottom, LunarSpacing.sm)114 .accessibilityIdentifier("history.clearAll")115 .confirmationDialog(L("Clear all history?"), isPresented: $confirmsClear, titleVisibility: .visible) {116 Button(L("Clear History"), role: .destructive) { clearAll() }117 Button(L("Cancel"), role: .cancel) {}118 } message: {119 Text(L("Every visit recorded on this device is deleted. This cannot be undone."))120 }121 }122 }123 .task(id: "\(query)#\(store.historyRevision)") { await load() }124 }125126 private func dayHeader(_ day: HistoryDay) -> some View {127 HStack {128 Text(HistoryDay.title(for: day.day)).textCase(.uppercase).lunarFont(.overline).foregroundStyle(theme.textSecondary)129 .accessibilityAddTraits(.isHeader)130 Spacer()131 Button(L("Delete day")) { delete(day) }132 .buttonStyle(.plain)133 .lunarFont(.caption)134 .foregroundStyle(theme.accent)135 .accessibilityLabel(L("Delete the history of %@", HistoryDay.title(for: day.day)))136 }137 .padding(.horizontal, LunarSpacing.sm)138 .padding(.top, LunarSpacing.sm)139 .padding(.bottom, LunarSpacing.unit)140 }141142 private func row(title: String, url: URL, time: Date?, onDelete: @escaping () -> Void) -> some View {143 LunarHoverRow {144 HStack(spacing: LunarSpacing.sm) {145 Button { open(url) } label: {146 HStack(spacing: LunarSpacing.sm) {147 FaviconView(page: url, title: title.isEmpty ? URLDisplay.host(url) : title, size: 20,148 profile: window.dataProfileID)149 VStack(alignment: .leading, spacing: 1) {150 Text(title.isEmpty ? URLDisplay.short(url) : title).lunarFont(.bodyEmphasized)151 .foregroundStyle(theme.textPrimary).lineLimit(1)152 Text(URLDisplay.short(url)).lunarFont(.caption).foregroundStyle(theme.textSecondary)153 .lineLimit(1).truncationMode(.middle)154 }155 Spacer(minLength: 0)156 if let time {157 Text(time.formatted(date: .omitted, time: .shortened)).lunarFont(.caption).lunarTabularDigits()158 .foregroundStyle(theme.textTertiary)159 }160 }161 .contentShape(Rectangle())162 }163 .buttonStyle(LunarPressStyle())164 .accessibilityElement(children: .combine)165 .accessibilityHint(L("Opens the page"))166 .accessibilityIdentifier("history.row")167 LunarIconButton(systemName: "xmark", label: L("Delete from history"), diameter: 24, action: onDelete)168 }169 .padding(.horizontal, LunarSpacing.sm)170 .frame(minHeight: 48)171 }172 .contextMenu {173 Button(L("Open")) { open(url) }174 Button(L("Open in New Tab")) { window.newTab(url: url, transition: .link) }175 Button(L("Copy Link")) { Pasteboard.copy(url.absoluteString) }176 Divider()177 Button(L("Delete from History"), role: .destructive, action: onDelete)178 }179 }180181 private func open(_ url: URL) {182 window.navigate(to: url, transition: .link)183 #if os(iOS)184 window.panel = nil185 #endif186 }187188 private func load() async {189 let profile = window.dataProfileID190 if query.trimmingCharacters(in: .whitespaces).isEmpty {191 let visits = (try? await store.database.history.visits(profile: profile, limit: 400)) ?? []192 days = HistoryDay.group(visits)193 results = []194 } else {195 results = (try? await store.database.history.search(query, profile: profile, limit: 60)) ?? []196 }197 isLoaded = true198 }199200 private func delete(_ entry: NavigationEntry) {201 Task {202 // The row stands for every visit of that address on that day.203 let day = Calendar.current.startOfDay(for: entry.visitedAt)204 let end = Calendar.current.date(byAdding: .day, value: 1, to: day) ?? day.addingTimeInterval(86_400)205 let sameDay = (try? await store.database.history.visits(profile: window.dataProfileID,206 in: DateInterval(start: day, end: end), limit: 2_000)) ?? []207 for visit in sameDay where visit.url == entry.url { _ = try? await store.database.history.deleteVisit(visit.id) }208 store.historyChanged()209 }210 }211212 private func deleteURL(_ url: URL) {213 Task {214 try? await store.database.history.deleteURL(url, profile: window.dataProfileID)215 store.historyChanged()216 }217 }218219 private func delete(_ day: HistoryDay) {220 Task {221 let end = Calendar.current.date(byAdding: .day, value: 1, to: day.day) ?? day.day.addingTimeInterval(86_400)222 _ = try? await store.database.history.deleteVisits(in: DateInterval(start: day.day, end: end), profile: window.dataProfileID)223 store.historyChanged()224 }225 }226227 private func clearAll() {228 Task {229 _ = try? await store.database.history.deleteAll(profile: window.dataProfileID)230 store.historyChanged()231 }232 }233}234235enum Pasteboard {236 @MainActor static func copy(_ text: String) {237 #if os(macOS)238 NSPasteboard.general.clearContents()239 NSPasteboard.general.setString(text, forType: .string)240 #else241 UIPasteboard.general.string = text242 #endif243 }244}245