Repository Public
1import SwiftUI2import UniformTypeIdentifiers3import WebKit45struct RightPanelView: View {6 @Bindable var state: BrowserWindowState7 let environment: AppEnvironment89 var body: some View {10 VStack(spacing: 0) {11 HStack {12 Text(title).font(.headline)13 Spacer()14 IconButton(symbol: "xmark", label: L("Close Panel"), size: 24) { state.rightPanel = .none }15 }16 .padding(.horizontal, 14).frame(height: BrowserWindowController.toolbarHeight)17 Divider().overlay(Theme.hairline)18 if let tab = state.selectedTab {19 switch state.rightPanel {20 case .pageInfo: PageInfoPanel(tab: tab, state: state, environment: environment).id(tab.id)21 case .developer: DeveloperPanel(tab: tab, state: state).id(tab.id)22 case .intelligence: IntelligencePanel(tab: tab, state: state, environment: environment).id(tab.id)23 case .none: EmptyView()24 }25 }26 }27 }2829 private var title: String {30 switch state.rightPanel {31 case .pageInfo: return L("Page Information")32 case .developer: return L("Developer Tools")33 case .intelligence: return L("SP Intelligence")34 case .none: return ""35 }36 }37}3839struct InfoRow: View {40 let label: String41 let value: String42 var body: some View {43 VStack(alignment: .leading, spacing: 1) {44 Text(label).font(.caption).foregroundStyle(.secondary)45 Text(value.isEmpty ? "—" : value).font(.callout).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)46 }47 .frame(maxWidth: .infinity, alignment: .leading)48 .accessibilityElement(children: .combine)49 }50}5152// MARK: - Page information5354struct PageInfoPanel: View {55 let tab: BrowserTab56 let state: BrowserWindowState57 let environment: AppEnvironment58 @State private var cookies: [HTTPCookie] = []59 @State private var revision = 06061 var body: some View {62 let host = tab.url?.host63 ScrollView {64 VStack(alignment: .leading, spacing: 14) {65 if tab.url == nil {66 StateView(symbol: "info.circle", title: L("No page loaded"), compact: true)67 } else {68 section(L("Address")) {69 InfoRow(label: L("URL"), value: tab.url?.absoluteString ?? "")70 InfoRow(label: L("Site"), value: host.map(URLInspector.registrableDomain(of:)) ?? L("Local file"))71 }72 section(L("Connection")) {73 Label(tab.security.title, systemImage: tab.security.symbol)74 .foregroundStyle(tab.security == .secure ? Color.green : (tab.security == .insecure ? .orange : .primary))75 ForEach(tab.warnings, id: \.self) { warning in76 Label(warning.message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)77 }78 if let certificate = tab.certificate {79 InfoRow(label: L("Certificate issued to"), value: certificate.subject)80 InfoRow(label: L("Issued by"), value: certificate.issuer)81 if let expires = certificate.expires { InfoRow(label: L("Expires"), value: expires.formatted(date: .long, time: .omitted)) }82 Text(L("The certificate is validated by macOS. SP Browser never lets a page bypass a failed validation."))83 .font(.caption).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)84 }85 }86 if host != nil {87 section(L("Permissions for this site")) {88 let _ = revision89 ForEach(SitePermission.allCases, id: \.self) { permission in90 HStack {91 Label(permission.title, systemImage: permission.symbol)92 Spacer()93 Picker(permission.title, selection: Binding(94 get: { tab.profile.permissions.storedDecision(permission, host: host)?.rawValue ?? "default" },95 set: { tab.profile.permissions.set(PermissionDecision(rawValue: $0), for: permission, host: host); revision += 1 })) {96 Text(L("Default (%@)", permission.defaultDecision.title)).tag("default")97 ForEach(PermissionDecision.allCases.filter { $0 != .ask || permission.supportsAsk }, id: \.self) { Text($0.title).tag($0.rawValue) }98 }99 .labelsHidden().fixedSize()100 }101 }102 let blocked = environment.settings.contentBlockerEnabled && !environment.settings.isBlockerDisabled(forHost: host ?? "")103 HStack {104 Label(L("Content blocker"), systemImage: "shield.lefthalf.filled")105 Spacer()106 Button(blocked ? L("On") : L("Off")) { state.perform(.toggleBlockerForSite) }.disabled(!environment.settings.contentBlockerEnabled)107 }108 Text(L("JavaScript and pop-up changes apply at the next page load. Location, notifications and clipboard access are handled by WebKit and macOS and cannot be set per site here."))109 .font(.caption).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)110 }111 section(L("Cookies (%d)", cookies.count)) {112 if cookies.isEmpty { Text(L("This site has stored no cookie in this profile.")).font(.callout).foregroundStyle(.secondary) }113 ForEach(cookies, id: \.self) { cookie in114 HStack(alignment: .top) {115 VStack(alignment: .leading, spacing: 1) {116 Text(cookie.name).font(.system(size: 12, design: .monospaced)).lineLimit(1)117 // Values are deliberately not displayed: they are often session secrets.118 Text([cookie.domain, cookie.isSecure ? "Secure" : nil, cookie.isHTTPOnly ? "HttpOnly" : nil,119 cookie.expiresDate.map { L("until %@", $0.formatted(date: .abbreviated, time: .omitted)) } ?? L("session")]120 .compactMap { $0 }.joined(separator: " · ")).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(2)121 }122 Spacer()123 IconButton(symbol: "trash", label: L("Delete cookie %@", cookie.name), size: 22) {124 Task { await tab.profile.dataStore.httpCookieStore.deleteCookie(cookie); await reload() }125 }126 }127 }128 Button(CommandID.clearSiteData.title, role: .destructive) { state.perform(.clearSiteData) }.padding(.top, 4)129 }130 }131 }132 }133 .padding(14)134 }135 .task(id: tab.url) { await reload() }136 }137138 private func reload() async {139 if let host = tab.url?.host { cookies = await tab.profile.cookies(forHost: host) } else { cookies = [] }140 }141142 private func section<Content: View>(_ title: String, @ViewBuilder content: () -> Content) -> some View {143 VStack(alignment: .leading, spacing: 8) {144 SectionLabel(text: title)145 VStack(alignment: .leading, spacing: 8, content: content).padding(12).frame(maxWidth: .infinity, alignment: .leading).cardSurface(radius: Theme.radiusM)146 }147 }148}149150// MARK: - Developer tools151152struct DeveloperPanel: View {153 let tab: BrowserTab154 let state: BrowserWindowState155 @State private var section = 0156 @State private var metadata: PageMetadata?157 @State private var source = ""158 @State private var loading = false159 @State private var linkFilter = ""160161 var body: some View {162 VStack(spacing: 0) {163 Picker(L("Section"), selection: $section) {164 Text(L("Metadata")).tag(0)165 Text(L("Links")).tag(1)166 Text(L("Resources")).tag(2)167 Text(L("Source")).tag(3)168 }169 .pickerStyle(.segmented).labelsHidden().padding(10)170 if tab.webView == nil || tab.url == nil {171 StateView(symbol: "hammer", title: L("No page loaded"), compact: true)172 } else if loading && metadata == nil {173 ProgressView().frame(maxHeight: .infinity)174 } else {175 switch section {176 case 0: metadataView177 case 1: linksView178 case 2: resourcesView179 default: sourceView180 }181 }182 Divider().overlay(Theme.hairline)183 HStack {184 Button(L("Refresh")) { Task { await load() } }185 Spacer()186 #if DEBUG187 Text(L("Web Inspector: right-click the page › Inspect Element (development builds only).")).font(.caption2).foregroundStyle(.tertiary)188 #endif189 }190 .controlSize(.small).padding(8)191 }192 .task(id: tab.url) { await load() }193 }194195 private func load() async {196 loading = true197 metadata = await tab.pageMetadata()198 let html = await tab.pageSource()199 // Very large documents are cut for display only; the notice below says so.200 source = html.count > 400_000 ? String(html.prefix(400_000)) + "\n\n<!-- " + L("Display truncated at 400,000 characters; use Save to get the whole document.") + " -->" : html201 loading = false202 }203204 @ViewBuilder private var metadataView: some View {205 if let m = metadata {206 ScrollView {207 VStack(alignment: .leading, spacing: 10) {208 InfoRow(label: L("Title (%d characters)", m.title.count), value: m.title)209 InfoRow(label: L("Description (%d characters)", m.description.count), value: m.description)210 InfoRow(label: L("Canonical URL"), value: m.canonical)211 InfoRow(label: L("Robots"), value: m.robots)212 InfoRow(label: L("Language / charset"), value: [m.lang, m.charset].filter { !$0.isEmpty }.joined(separator: " · "))213 InfoRow(label: L("Viewport"), value: m.viewport)214 if !m.generator.isEmpty { InfoRow(label: L("Generator"), value: m.generator) }215 InfoRow(label: L("Images"), value: L("%d images, %d without alternative text", m.images, m.imagesWithoutAlt))216 if let t = m.timing {217 InfoRow(label: L("Timing"), value: L("First byte %d ms · DOM ready %d ms · load %d ms", t.ttfb, t.domContentLoaded, t.load))218 }219 if !m.social.isEmpty {220 SectionLabel(text: L("Social tags")).padding(.top, 6)221 ForEach(m.social.keys.sorted(), id: \.self) { key in InfoRow(label: key, value: m.social[key] ?? "") }222 }223 if !m.headings.isEmpty {224 SectionLabel(text: L("Headings")).padding(.top, 6)225 ForEach(Array(m.headings.enumerated()), id: \.offset) { _, heading in226 Text("\(heading.level) \(heading.text)").font(.system(size: 12)).padding(.leading, heading.level == "H2" ? 12 : 0).textSelection(.enabled)227 }228 }229 }230 .padding(14)231 }232 } else {233 StateView(symbol: "doc.questionmark", title: L("Metadata is not available for this page"), compact: true)234 }235 }236237 @ViewBuilder private var linksView: some View {238 let links = (metadata?.links ?? []).filter { linkFilter.isEmpty || $0.href.localizedCaseInsensitiveContains(linkFilter) || $0.text.localizedCaseInsensitiveContains(linkFilter) }239 VStack(spacing: 0) {240 SearchField(text: $linkFilter, prompt: L("Filter %d links", metadata?.links.count ?? 0))241 List(Array(links.enumerated()), id: \.offset) { _, link in242 VStack(alignment: .leading, spacing: 1) {243 HStack(spacing: 4) {244 Text(link.text.isEmpty ? L("(no text)") : link.text).font(.system(size: 12)).lineLimit(1)245 if link.external { Image(systemName: "arrow.up.right").font(.system(size: 8)).foregroundStyle(.secondary).accessibilityLabel(L("external")) }246 if link.rel.contains("nofollow") { Text("nofollow").font(.system(size: 9)).foregroundStyle(.orange) }247 }248 Text(link.href).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)249 }250 .contextMenu {251 Button(L("Open in New Tab")) { if let url = URL(string: link.href) { state.newTab(url: url, select: false) } }252 Button(L("Copy Address")) { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(link.href, forType: .string) }253 }254 }255 .listStyle(.plain)256 }257 }258259 @ViewBuilder private var resourcesView: some View {260 let resources = metadata?.resources ?? []261 VStack(alignment: .leading, spacing: 0) {262 Text(L("Resource Timing as reported by the page (%d entries). This is not a full network capture: WebKit exposes no public API for headers, bodies or blocked requests, so SP Browser does not produce HAR files.", resources.count))263 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).padding(10)264 List(Array(resources.sorted { $0.start < $1.start }.enumerated()), id: \.offset) { _, resource in265 HStack {266 VStack(alignment: .leading, spacing: 1) {267 Text(URL(string: resource.name)?.lastPathComponent.isEmpty == false ? URL(string: resource.name)!.lastPathComponent : resource.name)268 .font(.system(size: 12)).lineLimit(1)269 Text(URL(string: resource.name)?.host ?? "").font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1)270 }271 Spacer()272 Text(resource.type).font(.system(size: 10)).foregroundStyle(.secondary)273 Text("\(resource.duration) ms").font(.system(size: 10.5, design: .monospaced)).frame(width: 58, alignment: .trailing)274 Text(resource.size > 0 ? formattedBytes(Int64(resource.size)) : "—").font(.system(size: 10.5, design: .monospaced)).frame(width: 62, alignment: .trailing)275 }276 .help(resource.name)277 }278 .listStyle(.plain)279 Button(L("Export Resource Timing as JSON…")) { exportResources(resources) }.controlSize(.small).padding(8).disabled(resources.isEmpty)280 }281 }282283 private var sourceView: some View {284 VStack(spacing: 0) {285 ScrollView([.vertical, .horizontal]) {286 Text(source).font(.system(size: 11, design: .monospaced)).textSelection(.enabled).padding(10)287 .frame(maxWidth: .infinity, alignment: .leading)288 }289 .background(Theme.field)290 HStack {291 Text(L("Current DOM, %@", formattedBytes(Int64(source.utf8.count)))).font(.caption).foregroundStyle(.secondary)292 Spacer()293 Button(L("Copy")) { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(source, forType: .string) }294 Button(L("Save…")) { saveSource() }295 }296 .controlSize(.small).padding(8)297 }298 }299300 private func saveSource() {301 guard let window = state.window else { return }302 let panel = NSSavePanel()303 panel.allowedContentTypes = [.html]304 panel.nameFieldStringValue = DownloadSafety.sanitize(filename: (tab.url?.host ?? "page") + ".html")305 panel.beginSheetModal(for: window) { response in306 guard response == .OK, let url = panel.url else { return }307 Task { @MainActor in308 let full = await tab.pageSource()309 try? Data(full.utf8).write(to: url, options: .atomic)310 }311 }312 }313314 private func exportResources(_ resources: [PageMetadata.Resource]) {315 guard let window = state.window else { return }316 let rows = resources.map { ["url": $0.name, "initiator": $0.type, "startMs": $0.start, "durationMs": $0.duration, "transferSize": $0.size, "protocol": $0.protocol] as [String: Any] }317 let payload: [String: Any] = ["format": "SP Browser Resource Timing export (not HAR)", "page": tab.url?.absoluteString ?? "", "exportedAt": ISO8601DateFormatter().string(from: Date()), "entries": rows]318 guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys]) else { return }319 let panel = NSSavePanel()320 panel.allowedContentTypes = [.json]321 panel.nameFieldStringValue = DownloadSafety.sanitize(filename: (tab.url?.host ?? "page") + "-resources.json")322 panel.beginSheetModal(for: window) { response in323 if response == .OK, let url = panel.url { try? data.write(to: url, options: .atomic) }324 }325 }326}327