Repository Public
1// ORIX Docs2// File: App/Sources/Sheets/LinkSheet.swift3// Description: Adds, edits or removes a hyperlink on the selection: a validated web or e-mail address, or a heading or bookmark of the4// document. Without a selection it also asks for the text to insert.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011/// A row of the "place in this document" list.12private struct LinkTarget: Identifiable, Hashable {13 let id: String // stored after "#"14 let title: String15 let detail: String?16 let level: Int17 let symbol: String18}1920struct LinkSheet: View {21 enum Mode: Hashable { case web, place }22 let session: DocumentSession23 private let story: StoryID24 /// The selection the link applies to; nil when text has to be inserted.25 private let range: (path: ParaPath, range: Range<Int>)?26 private let coversSeveralParagraphs: Bool27 private let existing: String?28 private let targets: [LinkTarget]2930 @State private var mode: Mode31 @State private var address: String32 @State private var target: String?33 @State private var text = ""34 @FocusState private var addressFocused: Bool3536 init(session: DocumentSession) {37 self.session = session38 let sel = session.selection39 story = sel.story40 let blocks = session.doc.blocks(in: sel.story)41 var found: String?42 var span: (ParaPath, Range<Int>)?43 var several = false44 if sel.isCaret {45 // The caret inside a link edits that link.46 if let p = blocks.paragraph(at: sel.head.path) {47 var offset = 048 var spans: [(Range<Int>, String)] = []49 for r in p.runs {50 if let l = r.props.link {51 if let last = spans.last, last.1 == l, last.0.upperBound == offset { spans[spans.count - 1].0 = last.0.lowerBound..<(offset + r.length) }52 else { spans.append((offset..<(offset + r.length), l)) }53 }54 offset += r.length55 }56 if let hit = spans.first(where: { $0.0.lowerBound <= sel.head.offset && sel.head.offset <= $0.0.upperBound }) { found = hit.1; span = (sel.head.path, hit.0) }57 }58 } else {59 found = blocks.paragraph(at: sel.start.path)?.run(containing: sel.start.offset)?.props.link60 several = sel.start.path != sel.end.path61 span = (sel.start.path, sel.start.offset..<(several ? sel.start.offset : sel.end.offset))62 }63 existing = found64 range = span.map { (path: $0.0, range: $0.1) }65 coversSeveralParagraphs = several6667 let n = session.numbering68 var list = n.outline.map { LinkTarget(id: $0.id, title: ($0.number.map { $0 + " " } ?? "") + $0.text, detail: nil, level: $0.level, symbol: "text.alignleft") }69 list += n.bookmarks.keys.sorted().map { LinkTarget(id: $0, title: $0, detail: String(localized: "Bookmark"), level: 1, symbol: "bookmark") }70 targets = list7172 if let found, found.hasPrefix("#") {73 let id = String(found.dropFirst())74 _mode = State(initialValue: .place); _address = State(initialValue: "")75 _target = State(initialValue: list.contains { $0.id == id } ? id : nil)76 } else {77 _mode = State(initialValue: .web); _address = State(initialValue: found ?? ""); _target = State(initialValue: nil)78 }79 }8081 /// A usable link from what was typed: "https://…", "http://…" or "mailto:…". A bare domain gets "https://", a bare address "mailto:".82 static func normalizedAddress(_ raw: String) -> String? {83 let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)84 guard !t.isEmpty, !t.contains(where: \.isWhitespace) else { return nil }85 let lower = t.lowercased()86 var candidate = t87 if lower.hasPrefix("mailto:") {88 let addr = String(t.dropFirst(7)).split(separator: "?").first.map(String.init) ?? ""89 return isMailAddress(addr) ? t : nil90 }91 if !(lower.hasPrefix("http://") || lower.hasPrefix("https://")) {92 if t.contains("://") { return nil }93 if isMailAddress(t) { return "mailto:" + t }94 if lower.range(of: #"^[a-z][a-z0-9+.\-]*:(?![0-9])"#, options: .regularExpression) != nil { return nil }95 candidate = "https://" + t96 }97 guard let c = URLComponents(string: candidate), let host = c.host, !host.isEmpty else { return nil }98 guard host == "localhost" || (host.contains(".") && !host.hasPrefix(".") && !host.hasSuffix(".")) else { return nil }99 return candidate100 }101102 private static func isMailAddress(_ s: String) -> Bool {103 s.range(of: #"^[^@\s/:]+@[^@\s/:]+\.[^@\s/:]+$"#, options: .regularExpression) != nil104 }105106 private var resolved: String? {107 switch mode {108 case .web: return LinkSheet.normalizedAddress(address)109 case .place: return target.map { "#" + $0 }110 }111 }112113 private func close() { session.activeSheet = nil }114115 private func select(_ e: inout DocumentEditor) {116 guard let range, !coversSeveralParagraphs else { return }117 e.selection = Selection(story: story, anchor: Position(path: range.path, offset: range.range.lowerBound), head: Position(path: range.path, offset: range.range.upperBound))118 }119120 private func apply() {121 guard let link = resolved else { return }122 if range != nil {123 session.perform(existing == nil ? String(localized: "Add Link") : String(localized: "Edit Link")) { e in select(&e); e.setLink(link) }124 } else {125 var shown = text.trimmingCharacters(in: .whitespacesAndNewlines)126 if shown.isEmpty { shown = mode == .place ? (targets.first { $0.id == target }?.title ?? link) : link.replacingOccurrences(of: "mailto:", with: "") }127 session.perform(String(localized: "Insert Link")) { e in128 let style = e.doc.styles.style(StyleID.hyperlink) != nil ? StyleID.hyperlink : nil129 e.insertRuns([Run(shown, props: CharProps(link: link), charStyle: style)])130 }131 }132 close()133 }134135 private func remove() {136 session.perform(String(localized: "Remove Link")) { e in select(&e); e.setLink(nil) }137 close()138 }139140 var body: some View {141 let link = resolved142 SheetScaffold(title: existing == nil ? "Add Link" : "Edit Link", symbol: "link", width: 500,143 primaryTitle: existing == nil ? (range == nil ? "Insert" : "Add Link") : "Update", primaryEnabled: link != nil,144 onPrimary: apply, onCancel: close,145 accessory: {146 if existing != nil {147 Button("Remove Link", role: .destructive, action: remove)148 .buttonStyle(ORIXButtonStyle(prominent: false)).accessibilityIdentifier("link-remove")149 }150 }) {151 VStack(alignment: .leading, spacing: ORIX.Space.m) {152 Picker("Link to", selection: $mode) {153 Text("Web or e-mail address").tag(Mode.web)154 Text("Place in this document").tag(Mode.place)155 }156 .pickerStyle(.segmented).labelsHidden().accessibilityLabel(Text("Link to")).accessibilityIdentifier("link-mode")157158 if mode == .web {159 LabeledField(label: "Address") {160 TextField("", text: $address, prompt: Text(verbatim: "https://example.org · name@example.org"))161 .textFieldStyle(.roundedBorder).focused($addressFocused)162 .accessibilityLabel(Text("Address")).accessibilityIdentifier("link-address")163 }164 if address.trimmingCharacters(in: .whitespaces).isEmpty {165 Text("Web addresses (http, https) and e-mail addresses (mailto) are accepted.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)166 } else if let link {167 if link != address.trimmingCharacters(in: .whitespaces) { Notice(kind: .info, text: String(localized: "The link will be \(link)")) }168 } else {169 Notice(kind: .error, text: String(localized: "This is not a valid web or e-mail address. Use http://, https:// or mailto:."))170 }171 } else if targets.isEmpty {172 EmptyState(symbol: "text.alignleft", title: "No headings or bookmarks", message: "Give a paragraph a heading style, or insert a bookmark, to link to it.")173 .frame(height: 150)174 } else {175 ScrollView {176 LazyVStack(alignment: .leading, spacing: 1) {177 ForEach(targets) { t in178 let selected = t.id == target179 Button { target = t.id } label: {180 HStack(spacing: 6) {181 Image(systemName: selected ? "checkmark.circle.fill" : t.symbol).font(.system(size: 10.5))182 .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textTertiary).frame(width: 14)183 Text(verbatim: t.title).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text).lineLimit(1)184 Spacer(minLength: 4)185 if let d = t.detail { Text(verbatim: d).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary) }186 }187 .padding(.leading, CGFloat(max(0, t.level - 1)) * 12 + 8).padding(.trailing, 8).padding(.vertical, 5)188 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(selected ? ORIX.Palette.accent.opacity(0.14) : .clear))189 .contentShape(Rectangle())190 }191 .buttonStyle(.plain)192 .accessibilityAddTraits(selected ? .isSelected : [])193 }194 }195 .padding(4)196 }197 .frame(height: 190).well()198 .accessibilityIdentifier("link-targets")199 }200201 if range == nil {202 LabeledField(label: "Text to insert") {203 TextField("", text: $text, prompt: Text("Uses the address or the heading when left empty")).textFieldStyle(.roundedBorder)204 .accessibilityLabel(Text("Text to insert")).accessibilityIdentifier("link-text")205 }206 } else if coversSeveralParagraphs {207 Text("The link applies to the whole selection.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)208 }209 }210 }211 .onAppear { if mode == .web { addressFocused = true } }212 }213}214