HighlightLink.swift (3497B)
1 // 2 // HighlightLink.swift 3 // damus 4 // 5 // Created by eric on 4/28/24. 6 // 7 8 import SwiftUI 9 import Kingfisher 10 11 struct HighlightLink: View { 12 let state: DamusState 13 let url: URL 14 let content: String 15 @Environment(\.openURL) var openURL 16 17 func text_fragment_url() -> URL? { 18 let fragmentDirective = "#:~:" 19 let textDirective = "text=" 20 let separator = "," 21 var text = "" 22 23 let components = content.components(separatedBy: " ") 24 if components.count <= 10 { 25 text = content 26 } else { 27 let textStart = Array(components.prefix(5)).joined(separator: " ") 28 let textEnd = Array(components.suffix(2)).joined(separator: " ") 29 text = textStart + separator + textEnd 30 } 31 32 let url_with_fragments = url.absoluteString + fragmentDirective + textDirective + text 33 return URL(string: url_with_fragments) 34 } 35 36 func get_url_icon() -> URL? { 37 var icon = URL(string: url.absoluteString + "/favicon.ico") 38 if let url_host = url.host() { 39 icon = URL(string: "https://" + url_host + "/favicon.ico") 40 } 41 return icon 42 } 43 44 var body: some View { 45 Button(action: { 46 openURL(text_fragment_url() ?? url) 47 }, label: { 48 HStack(spacing: 10) { 49 if let url = get_url_icon() { 50 KFAnimatedImage(url) 51 .imageContext(.pfp, disable_animation: true) 52 .cancelOnDisappear(true) 53 .configure { view in 54 view.framePreloadCount = 3 55 } 56 .placeholder { _ in 57 Image("link") 58 .resizable() 59 .padding(5) 60 .foregroundColor(DamusColors.neutral6) 61 .background(DamusColors.adaptableWhite) 62 } 63 .frame(width: 35, height: 35) 64 .kfClickable() 65 .clipShape(RoundedRectangle(cornerRadius: 10)) 66 .scaledToFit() 67 } else { 68 Image("link") 69 .resizable() 70 .padding(5) 71 .foregroundColor(DamusColors.neutral6) 72 .background(DamusColors.adaptableWhite) 73 .frame(width: 35, height: 35) 74 .clipShape(RoundedRectangle(cornerRadius: 10)) 75 } 76 77 Text(url.absoluteString) 78 .font(eventviewsize_to_font(.normal, font_size: state.settings.font_size)) 79 .foregroundColor(DamusColors.adaptableBlack) 80 .truncationMode(.tail) 81 .lineLimit(1) 82 } 83 .padding([.leading, .vertical], 7) 84 .frame(maxWidth: .infinity, alignment: .leading) 85 .background(DamusColors.neutral3) 86 .cornerRadius(10) 87 .overlay( 88 RoundedRectangle(cornerRadius: 10) 89 .stroke(DamusColors.neutral3, lineWidth: 2) 90 ) 91 }) 92 } 93 } 94 95 struct HighlightLink_Previews: PreviewProvider { 96 static var previews: some View { 97 let url = URL(string: "https://damus.io")! 98 VStack { 99 HighlightLink(state: test_damus_state, url: url, content: "") 100 } 101 } 102 }