this repo has no description
2
fork

Configure Feed

Select the types of activity you want to include in your feed.

convert facet to markdown

+54
+54
Sources/bskyKit/Models/Timeline.swift
··· 266 266 public let createdAt: Date? 267 267 public let embed: Embed? 268 268 public let facets: [Facet]? 269 + public let markdownText: String 269 270 270 271 enum CodingKeys: String, CodingKey { 271 272 case type = "$type" 272 273 case text, langs, reply, createdAt, embed, facets 274 + } 275 + 276 + public init(from decoder: Decoder) throws { 277 + let container = try decoder.container(keyedBy: CodingKeys.self) 278 + type = try container.decodeIfPresent(String.self, forKey: .type) 279 + text = try container.decodeIfPresent(String.self, forKey: .text) 280 + langs = try container.decodeIfPresent([String].self, forKey: .langs) 281 + reply = try container.decodeIfPresent(ReplyDetail.self, forKey: .reply) 282 + createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) 283 + embed = try container.decodeIfPresent(Embed.self, forKey: .embed) 284 + facets = try container.decodeIfPresent([Facet].self, forKey: .facets) 285 + markdownText = Record.convertToMarkdown(original: text ?? "", facets: facets) 286 + } 287 + 288 + public func encode(to encoder: Encoder) throws { 289 + var container = encoder.container(keyedBy: CodingKeys.self) 290 + try container.encodeIfPresent(type, forKey: .type) 291 + try container.encodeIfPresent(text, forKey: .text) 292 + try container.encodeIfPresent(langs, forKey: .langs) 293 + try container.encodeIfPresent(reply, forKey: .reply) 294 + try container.encodeIfPresent(createdAt, forKey: .createdAt) 295 + try container.encodeIfPresent(embed, forKey: .embed) 296 + try container.encodeIfPresent(facets, forKey: .facets) 297 + } 298 + 299 + private static func convertToMarkdown(original: String, facets: [Facet]?) -> String { 300 + guard let facets, !facets.isEmpty else { return original } 301 + 302 + var result = original 303 + let sortedFacets = facets.sorted { $0.index.byteEnd > $1.index.byteEnd } 304 + let utf8 = Array(original.utf8) 305 + 306 + for facet in sortedFacets { 307 + let start = facet.index.byteStart 308 + let end = facet.index.byteEnd 309 + 310 + guard start >= 0, end <= utf8.count, start < end else { continue } 311 + guard let uri = facet.features.first(where: { $0.uri != nil })?.uri else { continue } 312 + 313 + let startBytes = utf8.prefix(start) 314 + let rangeBytes = utf8[start..<end] 315 + 316 + guard let startStr = String(bytes: startBytes, encoding: .utf8), 317 + let rangeStr = String(bytes: rangeBytes, encoding: .utf8) else { continue } 318 + 319 + let startIndex = result.index(result.startIndex, offsetBy: startStr.count) 320 + let endIndex = result.index(startIndex, offsetBy: rangeStr.count) 321 + 322 + let markdownLink = "[\(rangeStr)](\(uri))" 323 + result.replaceSubrange(startIndex..<endIndex, with: markdownLink) 324 + } 325 + 326 + return result 273 327 } 274 328 } 275 329