SPB Git

Repository Public License

BookmarksPanel.swift 15.3 KB 335 lines swift

1import LunarDesign2import NavigatorCore3import Persistence4import SwiftUI5import UniformTypeIdentifiers67/// A Netscape bookmark file, for `fileExporter`.8struct BookmarkFile: FileDocument {9    static let readableContentTypes: [UTType] = [.html]10    var html: String1112    init(html: String) { self.html = html }1314    init(configuration: ReadConfiguration) throws {15        html = String(decoding: configuration.file.regularFileContents ?? Data(), as: UTF8.self)16    }1718    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {19        FileWrapper(regularFileWithContents: Data(html.utf8))20    }21}2223struct FolderChoice: Identifiable, Hashable {24    var id: BookmarkID?25    var title: String26    var depth: Int2728    static func flatten(_ nodes: [BookmarkNode], depth: Int = 0, excluding excluded: BookmarkID? = nil) -> [FolderChoice] {29        nodes.flatMap { node -> [FolderChoice] in30            guard node.bookmark.kind == .folder, node.id != excluded else { return [] }31            return [FolderChoice(id: node.id, title: node.bookmark.title, depth: depth)]32                + flatten(node.children, depth: depth + 1, excluding: excluded)33        }34    }35}3637struct BookmarksPanel: View {38    @Environment(\.lunarTheme) private var theme39    @Environment(BrowserStore.self) private var store40    let window: WindowModel4142    @State private var tree: [BookmarkNode] = []43    @State private var query = ""44    @State private var results: [Bookmark] = []45    @State private var collapsed: Set<BookmarkID> = []46    @State private var isLoaded = false47    @State private var isImporting = false48    @State private var exportDocument: BookmarkFile?49    @State private var isExporting = false5051    var body: some View {52        VStack(spacing: LunarSpacing.xs) {53            LunarSearchField(text: $query, prompt: L("Search bookmarks"), leading: .symbol("magnifyingglass"))54                .padding(.horizontal, LunarSpacing.sm)55                .accessibilityIdentifier("bookmarks.search")56            if isLoaded && tree.isEmpty && query.isEmpty {57                LunarEmptyState(icon: .symbol("bookmark"), title: L("No bookmarks yet"),58                                message: L("Add the page you are reading, or import bookmarks from another browser."),59                                actionTitle: window.hasPage ? L("Bookmark This Page") : nil,60                                action: window.hasPage ? { window.bookmarkCurrentPage() } : nil)61                    .frame(maxHeight: .infinity)62            } else {63                ScrollView {64                    LazyVStack(alignment: .leading, spacing: 2) {65                        if query.isEmpty {66                            ForEach(tree) { node in nodeRows(node, depth: 0) }67                        } else {68                            ForEach(results) { bookmark in row(bookmark, depth: 0, childCount: 0) }69                        }70                    }71                    .padding(.horizontal, LunarSpacing.xs)72                    .padding(.bottom, LunarSpacing.sm)73                }74                .scrollIndicators(.never)75            }76            LunarHairline()77            HStack(spacing: LunarSpacing.xs) {78                Button(L("New Folder")) { newFolder() }.buttonStyle(.lunar(.secondary, size: .compact))79                    .accessibilityIdentifier("bookmarks.newFolder")80                Spacer(minLength: 0)81                Menu {82                    Button(L("Import Bookmarks…")) { isImporting = true }83                    Button(L("Export Bookmarks…")) { export() }.disabled(tree.isEmpty)84                } label: {85                    Text(L("Import / Export")).lunarFont(.subheadline).foregroundStyle(theme.textPrimary)86                        .padding(.horizontal, LunarSpacing.sm).frame(minHeight: LunarMetrics.controlHeightCompact)87                        .background { Capsule().fill(theme.textPrimary.withAlpha(0.06)) }88                        .overlay { Capsule().strokeBorder(theme.hairline, lineWidth: 1) }89                }90                .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()91                .accessibilityIdentifier("bookmarks.importExport")92            }93            .padding(.horizontal, LunarSpacing.sm)94            .padding(.bottom, LunarSpacing.sm)95        }96        .task(id: "\(query)#\(store.bookmarksRevision)") { await load() }97        .fileImporter(isPresented: $isImporting, allowedContentTypes: [.html]) { result in98            if case .success(let url) = result { importFile(url) }99        }100        .fileExporter(isPresented: $isExporting, document: exportDocument, contentType: .html,101                      defaultFilename: L("ORIX Navigator Bookmarks")) { result in102            if case .success = result { window.showToast(L("Bookmarks exported"), status: .success) }103            exportDocument = nil104        }105    }106107    private func nodeRows(_ node: BookmarkNode, depth: Int) -> AnyView {108        AnyView(Group {109            row(node.bookmark, depth: depth, childCount: node.children.count)110            if node.bookmark.kind == .folder, !collapsed.contains(node.id) {111                ForEach(node.children) { child in nodeRows(child, depth: depth + 1) }112            }113        })114    }115116    private func row(_ bookmark: Bookmark, depth: Int, childCount: Int) -> some View {117        let isFolder = bookmark.kind == .folder118        return LunarHoverRow {119            HStack(spacing: LunarSpacing.sm) {120                Button {121                    if isFolder {122                        if collapsed.contains(bookmark.id) { collapsed.remove(bookmark.id) } else { collapsed.insert(bookmark.id) }123                    } else if let url = bookmark.url {124                        window.navigate(to: url, transition: .link)125                        #if os(iOS)126                        window.panel = nil127                        #endif128                    }129                } label: {130                    HStack(spacing: LunarSpacing.sm) {131                        if isFolder {132                            LunarIconView(.symbol(collapsed.contains(bookmark.id) ? "folder" : "folder.fill"), size: 20)133                                .foregroundStyle(theme.accent)134                        } else {135                            FaviconView(page: bookmark.url, title: bookmark.title, size: 20, profile: window.dataProfileID)136                        }137                        VStack(alignment: .leading, spacing: 1) {138                            Text(bookmark.title).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary).lineLimit(1)139                            if let url = bookmark.url {140                                Text(URLDisplay.short(url)).lunarFont(.caption).foregroundStyle(theme.textSecondary)141                                    .lineLimit(1).truncationMode(.middle)142                            } else if isFolder {143                                Text(childCount == 1 ? L("1 item") : L("%d items", childCount)).lunarFont(.caption)144                                    .foregroundStyle(theme.textSecondary)145                            }146                        }147                        Spacer(minLength: 0)148                    }149                    .contentShape(Rectangle())150                }151                .buttonStyle(LunarPressStyle())152                .accessibilityElement(children: .combine)153                .accessibilityValue(isFolder ? (collapsed.contains(bookmark.id) ? L("Collapsed") : L("Expanded")) : "")154                .accessibilityIdentifier(isFolder ? "bookmarks.folder" : "bookmarks.row")155                if !isFolder {156                    LunarIconButton(systemName: bookmark.isFavorite ? "star.fill" : "star",157                                    label: bookmark.isFavorite ? L("Remove from favourites") : L("Add to favourites"),158                                    isActive: bookmark.isFavorite, diameter: 24) {159                        setFavorite(bookmark, !bookmark.isFavorite)160                    }161                }162                LunarIconButton(systemName: "pencil", label: L("Edit"), diameter: 24) { edit(bookmark) }163                    .accessibilityIdentifier("bookmarks.edit")164            }165            .padding(.leading, LunarSpacing.sm + CGFloat(depth) * LunarSpacing.md)166            .padding(.trailing, LunarSpacing.xs)167            .frame(minHeight: 48)168        }169        .contextMenu {170            if let url = bookmark.url {171                Button(L("Open")) { window.navigate(to: url, transition: .link) }172                Button(L("Open in New Tab")) { window.newTab(url: url, transition: .link) }173                Button(L("Copy Link")) { Pasteboard.copy(url.absoluteString) }174                Divider()175            }176            Button(L("Edit…")) { edit(bookmark) }177            Button(L("Delete"), role: .destructive) { delete(bookmark) }178        }179    }180181    private func load() async {182        let profile = window.dataProfileID183        tree = (try? await store.database.bookmarks.tree(profile: profile)) ?? []184        results = query.trimmingCharacters(in: .whitespaces).isEmpty ? []185            : ((try? await store.database.bookmarks.search(query, profile: profile, limit: 80)) ?? [])186        isLoaded = true187    }188189    private func edit(_ bookmark: Bookmark) {190        window.bookmarkDraft = BookmarkDraft(id: bookmark.id, isNew: false, kind: bookmark.kind, title: bookmark.title,191                                             address: bookmark.url?.absoluteString ?? "", parentID: bookmark.parentID,192                                             isFavorite: bookmark.isFavorite)193    }194195    private func newFolder() {196        window.bookmarkDraft = BookmarkDraft(id: BookmarkID(), isNew: true, kind: .folder, title: "", address: "",197                                             parentID: nil, isFavorite: false)198    }199200    private func setFavorite(_ bookmark: Bookmark, _ favorite: Bool) {201        Task {202            try? await store.database.bookmarks.setFavorite(bookmark.id, favorite)203            store.bookmarksChanged()204        }205    }206207    private func delete(_ bookmark: Bookmark) {208        Task {209            _ = try? await store.database.bookmarks.delete(bookmark.id)210            store.bookmarksChanged()211        }212    }213214    private func importFile(_ url: URL) {215        Task {216            let data = await Task.detached { () -> Data? in217                let scoped = url.startAccessingSecurityScopedResource()218                defer { if scoped { url.stopAccessingSecurityScopedResource() } }219                return try? Data(contentsOf: url)220            }.value221            guard let data, let report = try? await store.database.bookmarks.importHTML(data, profile: window.dataProfileID) else {222                window.showToast(L("The file could not be imported"), status: .warning)223                return224            }225            store.bookmarksChanged()226            window.showToast(L("%d bookmarks imported", report.linksCreated), status: .success)227        }228    }229230    private func export() {231        Task {232            guard let html = try? await store.database.bookmarks.exportHTML(profile: window.dataProfileID, title: L("Bookmarks")) else { return }233            exportDocument = BookmarkFile(html: html)234            isExporting = true235        }236    }237}238239/// Sheet for adding or editing a bookmark or a folder.240struct BookmarkEditor: View {241    @Environment(\.lunarTheme) private var theme242    @Environment(BrowserStore.self) private var store243    let window: WindowModel244    @State var draft: BookmarkDraft245    @State private var folders: [FolderChoice] = []246    @State private var addressIsInvalid = false247248    var body: some View {249        VStack(alignment: .leading, spacing: LunarSpacing.md) {250            LunarSheetHeader(title, icon: .symbol(draft.kind == .folder ? "folder" : "bookmark"), closeLabel: L("Cancel")) {251                window.bookmarkDraft = nil252            }253            .padding(.horizontal, -LunarSpacing.xs)254            LunarTextField(draft.kind == .folder ? L("Folder name") : L("Title"), text: $draft.title)255                .accessibilityIdentifier("bookmark.title")256            if draft.kind == .link {257                LunarTextField(L("Address"), text: $draft.address, icon: .symbol("link"))258                    #if os(iOS)259                    .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)260                    #endif261                    .accessibilityIdentifier("bookmark.address")262                if addressIsInvalid {263                    Text(L("Enter a valid web address.")).lunarFont(.footnote).foregroundStyle(theme.danger)264                }265            }266            HStack {267                Text(L("Folder")).lunarFont(.body).foregroundStyle(theme.textPrimary)268                Spacer()269                Picker(L("Folder"), selection: $draft.parentID) {270                    Text(L("Bookmarks")).tag(BookmarkID?.none)271                    ForEach(folders) { folder in272                        Text(String(repeating: "    ", count: folder.depth) + folder.title).tag(folder.id)273                    }274                }275                .labelsHidden()276                .pickerStyle(.menu)277                .accessibilityIdentifier("bookmark.folder")278            }279            if draft.kind == .link {280                Toggle(L("Show on the new tab page"), isOn: $draft.isFavorite).toggleStyle(.lunar)281                    .lunarFont(.body).foregroundStyle(theme.textPrimary)282                    .accessibilityIdentifier("bookmark.favorite")283            }284            HStack(spacing: LunarSpacing.xs) {285                if !draft.isNew {286                    Button(L("Delete")) { delete() }.buttonStyle(.lunar(.destructive))287                        .accessibilityIdentifier("bookmark.delete")288                }289                Spacer(minLength: 0)290                Button(L("Cancel")) { window.bookmarkDraft = nil }.buttonStyle(.lunar(.secondary)).keyboardShortcut(.cancelAction)291                Button(draft.isNew ? L("Add") : L("Save")) { save() }.buttonStyle(.lunar(.primary)).keyboardShortcut(.defaultAction)292                    .disabled(draft.kind == .folder && draft.title.trimmingCharacters(in: .whitespaces).isEmpty)293                    .accessibilityIdentifier("bookmark.save")294            }295        }296        .padding(LunarSpacing.lg)297        .frame(minWidth: 320, idealWidth: 420, maxWidth: 480)298        .background(theme.elevatedSurface)299        .task {300            let tree = (try? await store.database.bookmarks.tree(profile: window.dataProfileID)) ?? []301            folders = FolderChoice.flatten(tree, excluding: draft.kind == .folder ? draft.id : nil)302        }303        .accessibilityElement(children: .contain)304        .accessibilityIdentifier("bookmark.editor")305    }306307    private var title: String {308        switch (draft.kind, draft.isNew) {309        case (.folder, true): L("New Folder")310        case (.folder, false): L("Edit Folder")311        case (.link, true): L("Add Bookmark")312        case (.link, false): L("Edit Bookmark")313        }314    }315316    private func save() {317        Task {318            if await store.save(draft, profile: window.dataProfileID) {319                if draft.isNew, draft.kind == .link { window.showToast(L("Bookmark added"), status: .success) }320                window.bookmarkDraft = nil321            } else {322                addressIsInvalid = true323            }324        }325    }326327    private func delete() {328        Task {329            _ = try? await store.database.bookmarks.delete(draft.id)330            store.bookmarksChanged()331            window.bookmarkDraft = nil332        }333    }334}335
Files main
Menu

Theme