aboutsummaryrefslogtreecommitdiff
path: root/Sources/NorgUI/Helpers/NorgLinkURL.swift
blob: 9b73fe3e177645e8e55099a1b26fb743cfc10db4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Foundation
import NorgKit

public enum NorgLinkURL {
  public static let scheme = "norgui-link"

  public static func encode(_ link: InlineLink) -> URL? {
    var components = URLComponents()
    components.scheme = scheme
    components.host = link.kind == .anchor ? "anchor" : "link"
    if let target = link.target {
      components.queryItems = [URLQueryItem(name: "target", value: target)]
    }
    return components.url
  }

  public static func decode(_ url: URL) -> InlineLink? {
    guard url.scheme == scheme else { return nil }
    let kind: InlineLink.Kind = url.host == "anchor" ? .anchor : .link
    let target =
      URLComponents(url: url, resolvingAgainstBaseURL: false)?
      .queryItems?.first { $0.name == "target" }?.value
    return InlineLink(kind: kind, target: target)
  }
}