yattee/Shared/Views/ShareButton.swift

109 lines
3.2 KiB
Swift
Raw Normal View History

2021-10-26 22:59:59 +00:00
import SwiftUI
struct ShareButton: View {
let contentItem: ContentItem
@Binding var presentingShareSheet: Bool
2021-11-02 19:40:49 +00:00
@Binding var shareURL: String
2021-10-26 22:59:59 +00:00
@EnvironmentObject<AccountsModel> private var accounts
2021-11-02 19:40:49 +00:00
@EnvironmentObject<PlayerModel> private var player
init(
contentItem: ContentItem,
presentingShareSheet: Binding<Bool>,
shareURL: Binding<String>? = nil
) {
self.contentItem = contentItem
_presentingShareSheet = presentingShareSheet
_shareURL = shareURL ?? .constant("")
}
2021-10-26 22:59:59 +00:00
var body: some View {
2021-11-02 19:40:49 +00:00
Menu {
instanceActions
2021-11-02 23:02:02 +00:00
Divider()
2021-11-02 19:40:49 +00:00
youtubeActions
} label: {
Label("Share", systemImage: "square.and.arrow.up")
.labelStyle(.iconOnly)
}
.menuStyle(.borderlessButton)
#if os(macOS)
.frame(maxWidth: 35)
#endif
}
private var instanceActions: some View {
2021-10-28 17:14:55 +00:00
Group {
2021-11-02 19:40:49 +00:00
if let url = accounts.api.shareURL(contentItem) {
Button(labelForShareURL(accounts.app.name)) {
shareAction(url)
}
if contentItem.contentType == .video {
Button(labelForShareURL(accounts.app.name, withTime: true)) {
shareAction(
accounts.api.shareURL(
contentItem,
time: player.player.currentTime()
)!
)
}
}
}
}
}
private var youtubeActions: some View {
Group {
if let url = accounts.api.shareURL(contentItem, frontendHost: "www.youtube.com") {
Button(labelForShareURL("YouTube")) {
shareAction(url)
}
if contentItem.contentType == .video {
Button(labelForShareURL("YouTube", withTime: true)) {
shareAction(
accounts.api.shareURL(
contentItem,
frontendHost: "www.youtube.com",
time: player.player.currentTime()
)!
)
}
2021-10-28 17:14:55 +00:00
}
}
2021-10-26 22:59:59 +00:00
}
}
2021-11-02 19:40:49 +00:00
private func shareAction(_ url: URL) {
#if os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(url.absoluteString, forType: .string)
#else
shareURL = url.absoluteString
presentingShareSheet = true
#endif
}
private func labelForShareURL(_ app: String, withTime: Bool = false) -> String {
let time = withTime ? "with time" : ""
#if os(macOS)
return "Copy \(app) link \(time)"
#else
return "Share \(app) link \(time)"
#endif
2021-10-26 22:59:59 +00:00
}
}
struct ShareButton_Previews: PreviewProvider {
static var previews: some View {
2021-11-02 19:40:49 +00:00
ShareButton(
contentItem: ContentItem(video: Video.fixture),
presentingShareSheet: .constant(false)
)
.injectFixtureEnvironmentObjects()
2021-10-26 22:59:59 +00:00
}
}