Compare commits
No commits in common. "ad558510906c6a2da3397f4ee5a8c2386d959229" and "e0eba95b4897d78d82dd9b7591e0c4eef2a1be84" have entirely different histories.
ad55851090
...
e0eba95b48
|
@ -19,14 +19,13 @@ let package = Package(
|
|||
.package(path: "../Pachyderm"),
|
||||
.package(path: "../InstanceFeatures"),
|
||||
.package(path: "../TuskerComponents"),
|
||||
.package(path: "../MatchedGeometryPresentation"),
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "ComposeUI",
|
||||
dependencies: ["Pachyderm", "InstanceFeatures", "TuskerComponents", "MatchedGeometryPresentation"]),
|
||||
dependencies: ["Pachyderm", "InstanceFeatures", "TuskerComponents"]),
|
||||
.testTarget(
|
||||
name: "ComposeUITests",
|
||||
dependencies: ["ComposeUI"]),
|
||||
|
|
|
@ -8,7 +8,6 @@
|
|||
import SwiftUI
|
||||
import TuskerComponents
|
||||
import Vision
|
||||
import MatchedGeometryPresentation
|
||||
|
||||
class AttachmentRowController: ViewController {
|
||||
let parent: ComposeController
|
||||
|
@ -16,16 +15,12 @@ class AttachmentRowController: ViewController {
|
|||
|
||||
@Published var descriptionMode: DescriptionMode = .allowEntry
|
||||
@Published var textRecognitionError: Error?
|
||||
@Published var focusAttachmentOnTextEditorUnfocus = false
|
||||
|
||||
let thumbnailController: AttachmentThumbnailController
|
||||
|
||||
private var descriptionObservation: NSKeyValueObservation?
|
||||
|
||||
init(parent: ComposeController, attachment: DraftAttachment) {
|
||||
self.parent = parent
|
||||
self.attachment = attachment
|
||||
self.thumbnailController = AttachmentThumbnailController(attachment: attachment)
|
||||
|
||||
descriptionObservation = attachment.observe(\.attachmentDescription, changeHandler: { [unowned self] _, _ in
|
||||
// the faultingState is non-zero for objects that are being cascade deleted when the draft is deleted
|
||||
|
@ -62,11 +57,6 @@ class AttachmentRowController: ViewController {
|
|||
}
|
||||
}
|
||||
|
||||
private func focusAttachment() {
|
||||
focusAttachmentOnTextEditorUnfocus = false
|
||||
parent.focusedAttachment = (attachment, thumbnailController)
|
||||
}
|
||||
|
||||
private func recognizeText() {
|
||||
descriptionMode = .recognizingText
|
||||
|
||||
|
@ -119,7 +109,6 @@ class AttachmentRowController: ViewController {
|
|||
struct AttachmentView: View {
|
||||
@ObservedObject private var attachment: DraftAttachment
|
||||
@EnvironmentObject private var controller: AttachmentRowController
|
||||
@FocusState private var textEditorFocused: Bool
|
||||
|
||||
init(attachment: DraftAttachment) {
|
||||
self.attachment = attachment
|
||||
|
@ -127,19 +116,9 @@ class AttachmentRowController: ViewController {
|
|||
|
||||
var body: some View {
|
||||
HStack(alignment: .center, spacing: 4) {
|
||||
ControllerView(controller: { controller.thumbnailController })
|
||||
.clipShape(RoundedRectangle(cornerRadius: 8))
|
||||
.environment(\.attachmentThumbnailConfiguration, .init(contentMode: .fit, fullSize: false))
|
||||
.matchedGeometrySource(id: attachment.id, presentationID: attachment.id)
|
||||
.overlay {
|
||||
thumbnailFocusedOverlay
|
||||
}
|
||||
AttachmentThumbnailView(attachment: attachment, fullSize: false)
|
||||
.frame(width: 80, height: 80)
|
||||
.onTapGesture {
|
||||
textEditorFocused = false
|
||||
// if we just focus the attachment immediately, the text editor doesn't actually unfocus
|
||||
controller.focusAttachmentOnTextEditorUnfocus = true
|
||||
}
|
||||
.cornerRadius(8)
|
||||
.contextMenu {
|
||||
if attachment.drawingData != nil {
|
||||
Button(action: controller.editDrawing) {
|
||||
|
@ -150,19 +129,21 @@ class AttachmentRowController: ViewController {
|
|||
Label("Recognize Text", systemImage: "doc.text.viewfinder")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Button(role: .destructive, action: controller.removeAttachment) {
|
||||
Label("Delete", systemImage: "trash")
|
||||
}
|
||||
} previewIfAvailable: {
|
||||
ControllerView(controller: { controller.thumbnailController })
|
||||
AttachmentThumbnailView(attachment: attachment, fullSize: true)
|
||||
}
|
||||
|
||||
switch controller.descriptionMode {
|
||||
case .allowEntry:
|
||||
InlineAttachmentDescriptionView(attachment: attachment, minHeight: 80)
|
||||
.matchedGeometrySource(id: AttachmentDescriptionTextViewID(attachment), presentationID: attachment.id)
|
||||
.focused($textEditorFocused)
|
||||
AttachmentDescriptionTextView(
|
||||
text: $attachment.attachmentDescription,
|
||||
placeholder: Text("Describe for the visually impaired…"),
|
||||
minHeight: 80
|
||||
)
|
||||
|
||||
case .recognizingText:
|
||||
ProgressView()
|
||||
|
@ -175,25 +156,7 @@ class AttachmentRowController: ViewController {
|
|||
Text(error.localizedDescription)
|
||||
}
|
||||
.onAppear(perform: controller.updateAttachmentDescriptionState)
|
||||
.onChange(of: textEditorFocused) { newValue in
|
||||
if !newValue && controller.focusAttachmentOnTextEditorUnfocus {
|
||||
controller.focusAttachment()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var thumbnailFocusedOverlay: some View {
|
||||
Image(systemName: "arrow.up.backward.and.arrow.down.forward")
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Color.black.opacity(0.35))
|
||||
.clipShape(RoundedRectangle(cornerRadius: 8))
|
||||
// use .opacity and an animation, because .transition doesn't seem to play nice with @FocusState
|
||||
.opacity(textEditorFocused ? 1 : 0)
|
||||
.animation(.linear(duration: 0.1), value: textEditorFocused)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,167 +0,0 @@
|
|||
//
|
||||
// AttachmentThumbnailController.swift
|
||||
// ComposeUI
|
||||
//
|
||||
// Created by Shadowfacts on 11/10/21.
|
||||
// Copyright © 2021 Shadowfacts. All rights reserved.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import Photos
|
||||
import TuskerComponents
|
||||
|
||||
class AttachmentThumbnailController: ViewController {
|
||||
let attachment: DraftAttachment
|
||||
|
||||
@Published private var image: UIImage?
|
||||
@Published private var gifController: GIFController?
|
||||
@Published private var fullSize: Bool = false
|
||||
@Published private var imageBackground: Color?
|
||||
|
||||
init(attachment: DraftAttachment) {
|
||||
self.attachment = attachment
|
||||
}
|
||||
|
||||
func loadImageIfNecessary(fullSize: Bool) {
|
||||
if (gifController != nil) || (image != nil && fullSize == self.fullSize) {
|
||||
return
|
||||
}
|
||||
self.fullSize = fullSize
|
||||
|
||||
switch attachment.data {
|
||||
case .asset(let id):
|
||||
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject else {
|
||||
return
|
||||
}
|
||||
let isGIF = PHAssetResource.assetResources(for: asset).contains(where: { $0.uniformTypeIdentifier == UTType.gif.identifier })
|
||||
if isGIF {
|
||||
PHImageManager.default().requestImageDataAndOrientation(for: asset, options: nil) { data, typeIdentifier, orientation, info in
|
||||
guard let data else { return }
|
||||
if typeIdentifier == UTType.gif.identifier {
|
||||
self.gifController = GIFController(gifData: data)
|
||||
} else {
|
||||
let image = UIImage(data: data)
|
||||
DispatchQueue.main.async {
|
||||
self.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let size: CGSize
|
||||
if fullSize {
|
||||
size = PHImageManagerMaximumSize
|
||||
} else {
|
||||
// currently only used as thumbnail in ComposeAttachmentRow
|
||||
size = CGSize(width: 80, height: 80)
|
||||
}
|
||||
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: nil) { (image, _) in
|
||||
DispatchQueue.main.async {
|
||||
self.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case .drawing(let drawing):
|
||||
image = drawing.imageInLightMode(from: drawing.bounds)
|
||||
|
||||
case .file(let url, let type):
|
||||
if type.conforms(to: .movie) {
|
||||
let asset = AVURLAsset(url: url)
|
||||
let imageGenerator = AVAssetImageGenerator(asset: asset)
|
||||
if let cgImage = try? imageGenerator.copyCGImage(at: .zero, actualTime: nil) {
|
||||
self.image = UIImage(cgImage: cgImage)
|
||||
}
|
||||
} else if let data = try? Data(contentsOf: url) {
|
||||
if type == .gif {
|
||||
self.gifController = GIFController(gifData: data)
|
||||
} else if type.conforms(to: .image),
|
||||
let image = UIImage(data: data) {
|
||||
if fullSize {
|
||||
image.prepareForDisplay { prepared in
|
||||
DispatchQueue.main.async {
|
||||
self.image = prepared
|
||||
}
|
||||
}
|
||||
} else {
|
||||
image.prepareThumbnail(of: CGSize(width: 80, height: 80)) { prepared in
|
||||
DispatchQueue.main.async {
|
||||
self.image = prepared
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var view: some SwiftUI.View {
|
||||
View()
|
||||
}
|
||||
|
||||
struct View: SwiftUI.View {
|
||||
@EnvironmentObject private var controller: AttachmentThumbnailController
|
||||
@Environment(\.attachmentThumbnailConfiguration) private var config
|
||||
|
||||
var body: some SwiftUI.View {
|
||||
content
|
||||
.onAppear {
|
||||
controller.loadImageIfNecessary(fullSize: config.fullSize)
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var content: some SwiftUI.View {
|
||||
if let gifController = controller.gifController {
|
||||
GIFViewWrapper(controller: gifController)
|
||||
} else if let image = controller.image {
|
||||
Image(uiImage: image)
|
||||
.resizable()
|
||||
.aspectRatio(config.aspectRatio, contentMode: config.contentMode)
|
||||
} else {
|
||||
Image(systemName: "photo")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AttachmentThumbnailConfiguration {
|
||||
let aspectRatio: CGFloat?
|
||||
let contentMode: ContentMode
|
||||
let fullSize: Bool
|
||||
|
||||
init(aspectRatio: CGFloat? = nil, contentMode: ContentMode = .fit, fullSize: Bool = false) {
|
||||
self.aspectRatio = aspectRatio
|
||||
self.contentMode = contentMode
|
||||
self.fullSize = fullSize
|
||||
}
|
||||
}
|
||||
|
||||
private struct AttachmentThumbnailConfigurationEnvironmentKey: EnvironmentKey {
|
||||
static let defaultValue = AttachmentThumbnailConfiguration()
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
var attachmentThumbnailConfiguration: AttachmentThumbnailConfiguration {
|
||||
get { self[AttachmentThumbnailConfigurationEnvironmentKey.self] }
|
||||
set { self[AttachmentThumbnailConfigurationEnvironmentKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
private struct GIFViewWrapper: UIViewRepresentable {
|
||||
typealias UIViewType = GIFImageView
|
||||
|
||||
@State var controller: GIFController
|
||||
|
||||
func makeUIView(context: Context) -> GIFImageView {
|
||||
let view = GIFImageView()
|
||||
controller.attach(to: view)
|
||||
controller.startAnimating()
|
||||
view.contentMode = .scaleAspectFit
|
||||
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
view.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
|
||||
return view
|
||||
}
|
||||
|
||||
func updateUIView(_ uiView: GIFImageView, context: Context) {
|
||||
}
|
||||
}
|
|
@ -148,7 +148,6 @@ class AttachmentsListController: ViewController {
|
|||
ForEach(draft.attachments.array as! [DraftAttachment]) { attachment in
|
||||
ControllerView(controller: { AttachmentRowController(parent: controller.parent, attachment: attachment) })
|
||||
.listRowInsets(EdgeInsets(top: cellPadding / 2, leading: cellPadding / 2, bottom: cellPadding / 2, trailing: cellPadding / 2))
|
||||
.id(attachment.id)
|
||||
}
|
||||
.onMove(perform: controller.moveAttachments)
|
||||
.onDelete(perform: controller.deleteAttachments)
|
||||
|
|
|
@ -9,7 +9,6 @@ import SwiftUI
|
|||
import Combine
|
||||
import Pachyderm
|
||||
import TuskerComponents
|
||||
import MatchedGeometryPresentation
|
||||
|
||||
public final class ComposeController: ViewController {
|
||||
public typealias FetchStatus = (String) -> (any StatusProtocol)?
|
||||
|
@ -39,8 +38,6 @@ public final class ComposeController: ViewController {
|
|||
// this property is here rather than on the AttachmentsListController so that the ComposeView
|
||||
// updates when it changes, because changes to it may alter postButtonEnabled
|
||||
@Published var attachmentsMissingDescriptions = Set<UUID>()
|
||||
@Published var focusedAttachment: (DraftAttachment, AttachmentThumbnailController)?
|
||||
let scrollToAttachment = PassthroughSubject<UUID, Never>()
|
||||
@Published var contentWarningBecomeFirstResponder = false
|
||||
@Published var mainComposeTextViewBecomeFirstResponder = false
|
||||
@Published var currentInput: (any ComposeInput)? = nil
|
||||
|
@ -259,12 +256,7 @@ public final class ComposeController: ViewController {
|
|||
config.backgroundColor
|
||||
.edgesIgnoringSafeArea(.all)
|
||||
|
||||
ScrollViewReader { proxy in
|
||||
mainList
|
||||
.onReceive(controller.scrollToAttachment) { id in
|
||||
proxy.scrollTo(id, anchor: .center)
|
||||
}
|
||||
}
|
||||
mainList
|
||||
|
||||
if let poster = poster {
|
||||
// can't use SwiftUI.ProgressView because there's no UIProgressView.Style.bar equivalent, see FB8587149
|
||||
|
@ -304,23 +296,6 @@ public final class ComposeController: ViewController {
|
|||
}, message: { error in
|
||||
Text(error.localizedDescription)
|
||||
})
|
||||
.matchedGeometryPresentation(id: Binding(get: {
|
||||
controller.focusedAttachment?.0.id
|
||||
}, set: {
|
||||
if $0 == nil {
|
||||
controller.focusedAttachment = nil
|
||||
} else {
|
||||
fatalError()
|
||||
}
|
||||
}), backgroundColor: .black) {
|
||||
ControllerView(controller: {
|
||||
FocusedAttachmentController(
|
||||
parent: controller,
|
||||
attachment: controller.focusedAttachment!.0,
|
||||
thumbnailController: controller.focusedAttachment!.1
|
||||
)
|
||||
})
|
||||
}
|
||||
.onDisappear(perform: controller.onDisappear)
|
||||
.navigationTitle(controller.navigationTitle)
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
|
|
|
@ -134,10 +134,9 @@ private struct DraftRow: View {
|
|||
|
||||
HStack(spacing: 8) {
|
||||
ForEach(draft.draftAttachments) { attachment in
|
||||
ControllerView(controller: { AttachmentThumbnailController(attachment: attachment) })
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 5))
|
||||
.frame(height: 50)
|
||||
AttachmentThumbnailView(attachment: attachment, fullSize: false)
|
||||
.frame(width: 50, height: 50)
|
||||
.cornerRadius(5)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,122 +0,0 @@
|
|||
//
|
||||
// FocusedAttachmentController.swift
|
||||
// ComposeUI
|
||||
//
|
||||
// Created by Shadowfacts on 4/29/23.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import MatchedGeometryPresentation
|
||||
import AVKit
|
||||
|
||||
class FocusedAttachmentController: ViewController {
|
||||
|
||||
unowned let parent: ComposeController
|
||||
let attachment: DraftAttachment
|
||||
let thumbnailController: AttachmentThumbnailController
|
||||
private let player: AVPlayer?
|
||||
|
||||
init(parent: ComposeController, attachment: DraftAttachment, thumbnailController: AttachmentThumbnailController) {
|
||||
self.parent = parent
|
||||
self.attachment = attachment
|
||||
self.thumbnailController = thumbnailController
|
||||
|
||||
if case let .file(url, type) = attachment.data,
|
||||
type.conforms(to: .movie) {
|
||||
self.player = AVPlayer(url: url)
|
||||
self.player!.isMuted = true
|
||||
} else {
|
||||
self.player = nil
|
||||
}
|
||||
}
|
||||
|
||||
var view: some View {
|
||||
FocusedAttachmentView(attachment: attachment)
|
||||
}
|
||||
|
||||
struct FocusedAttachmentView: View {
|
||||
@ObservedObject var attachment: DraftAttachment
|
||||
@EnvironmentObject private var controller: FocusedAttachmentController
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@FocusState private var textEditorFocused: Bool
|
||||
@EnvironmentObject private var matchedGeomState: MatchedGeometryState
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
|
||||
if let player = controller.player {
|
||||
VideoPlayer(player: player)
|
||||
.matchedGeometryDestination(id: attachment.id)
|
||||
.onAppear {
|
||||
player.play()
|
||||
}
|
||||
} else if #available(iOS 16.0, *) {
|
||||
ZoomableScrollView {
|
||||
attachmentView
|
||||
.matchedGeometryDestination(id: attachment.id)
|
||||
}
|
||||
} else {
|
||||
attachmentView
|
||||
.matchedGeometryDestination(id: attachment.id)
|
||||
}
|
||||
|
||||
Spacer(minLength: 0)
|
||||
|
||||
FocusedAttachmentDescriptionView(attachment: attachment)
|
||||
.environment(\.colorScheme, .dark)
|
||||
.matchedGeometryDestination(id: AttachmentDescriptionTextViewID(attachment))
|
||||
.frame(height: 150)
|
||||
.focused($textEditorFocused)
|
||||
}
|
||||
.background(.black)
|
||||
.overlay(alignment: .topLeading, content: {
|
||||
Button {
|
||||
// set the mode to dismissing immediately, so that layout changes due to the keyboard hiding
|
||||
// (which happens before the dismiss animation controller starts running) don't alter the destination frames
|
||||
if textEditorFocused {
|
||||
matchedGeomState.mode = .dismissing
|
||||
}
|
||||
dismiss()
|
||||
} label: {
|
||||
Image(systemName: "arrow.down.forward.and.arrow.up.backward")
|
||||
}
|
||||
.buttonStyle(DismissFocusedAttachmentButtonStyle())
|
||||
.padding([.top, .leading], 4)
|
||||
})
|
||||
}
|
||||
|
||||
private var attachmentView: some View {
|
||||
ControllerView(controller: { controller.thumbnailController })
|
||||
.environment(\.attachmentThumbnailConfiguration, .init(contentMode: .fit, fullSize: true))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DismissFocusedAttachmentButtonStyle: ButtonStyle {
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(.black.opacity(0.5))
|
||||
|
||||
configuration.label
|
||||
.foregroundColor(.white)
|
||||
.imageScale(.large)
|
||||
}
|
||||
.frame(width: 40, height: 40)
|
||||
}
|
||||
}
|
||||
|
||||
struct AttachmentDescriptionTextViewID: Hashable {
|
||||
let attachmentID: UUID
|
||||
|
||||
init(_ attachment: DraftAttachment) {
|
||||
self.attachmentID = attachment.id
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(attachmentID)
|
||||
hasher.combine("descriptionTextView")
|
||||
}
|
||||
}
|
||||
|
|
@ -203,8 +203,7 @@ extension DraftAttachment {
|
|||
return
|
||||
}
|
||||
|
||||
if type != .gif,
|
||||
type.conforms(to: .image) {
|
||||
if type.conforms(to: .image) {
|
||||
let result = Self.processImageData(fileData, type: type, features: features, skipAllConversion: skipAllConversion)
|
||||
completion(.success(result))
|
||||
} else {
|
||||
|
|
|
@ -10,13 +10,7 @@ import Combine
|
|||
|
||||
@available(iOS, obsoleted: 16.0)
|
||||
class KeyboardReader: ObservableObject {
|
||||
// @Published var isVisible = false
|
||||
@Published var keyboardHeight: CGFloat = 0
|
||||
|
||||
var isVisible: Bool {
|
||||
// when a hardware keyboard is connected, the height is very short, so we don't consider that being "visible"
|
||||
keyboardHeight > 72
|
||||
}
|
||||
@Published var isVisible = false
|
||||
|
||||
init() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(willShow), name: UIResponder.keyboardWillShowNotification, object: nil)
|
||||
|
@ -24,16 +18,12 @@ class KeyboardReader: ObservableObject {
|
|||
}
|
||||
|
||||
@objc func willShow(_ notification: Foundation.Notification) {
|
||||
// when a hardware keyboard is connected, the height is very short, so we don't consider that being "visible"
|
||||
let endFrame = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
|
||||
// isVisible = endFrame.height > 72
|
||||
keyboardHeight = endFrame.height
|
||||
isVisible = endFrame.height > 72
|
||||
}
|
||||
|
||||
@objc func willHide() {
|
||||
// sometimes willHide is called during a SwiftUI view update
|
||||
DispatchQueue.main.async {
|
||||
// self.isVisible = false
|
||||
self.keyboardHeight = 0
|
||||
}
|
||||
isVisible = false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,24 +7,22 @@
|
|||
|
||||
import SwiftUI
|
||||
|
||||
private var placeholder: some View {
|
||||
Text("Describe for the visually impaired…")
|
||||
}
|
||||
|
||||
struct InlineAttachmentDescriptionView: View {
|
||||
@ObservedObject private var attachment: DraftAttachment
|
||||
struct AttachmentDescriptionTextView: View {
|
||||
@Binding private var text: String
|
||||
private let placeholder: Text?
|
||||
private let minHeight: CGFloat
|
||||
|
||||
@State private var height: CGFloat?
|
||||
|
||||
init(attachment: DraftAttachment, minHeight: CGFloat) {
|
||||
self.attachment = attachment
|
||||
init(text: Binding<String>, placeholder: Text?, minHeight: CGFloat) {
|
||||
self._text = text
|
||||
self.placeholder = placeholder
|
||||
self.minHeight = minHeight
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ZStack(alignment: .topLeading) {
|
||||
if attachment.attachmentDescription.isEmpty {
|
||||
if text.isEmpty, let placeholder {
|
||||
placeholder
|
||||
.font(.body)
|
||||
.foregroundColor(.secondary)
|
||||
|
@ -32,9 +30,9 @@ struct InlineAttachmentDescriptionView: View {
|
|||
}
|
||||
|
||||
WrappedTextView(
|
||||
text: $attachment.attachmentDescription,
|
||||
backgroundColor: .clear,
|
||||
textDidChange: self.textDidChange
|
||||
text: $text,
|
||||
textDidChange: self.textDidChange,
|
||||
font: .preferredFont(forTextStyle: .body)
|
||||
)
|
||||
.frame(height: height ?? minHeight)
|
||||
}
|
||||
|
@ -45,43 +43,20 @@ struct InlineAttachmentDescriptionView: View {
|
|||
}
|
||||
}
|
||||
|
||||
struct FocusedAttachmentDescriptionView: View {
|
||||
@ObservedObject var attachment: DraftAttachment
|
||||
|
||||
var body: some View {
|
||||
ZStack(alignment: .topLeading) {
|
||||
WrappedTextView(
|
||||
text: $attachment.attachmentDescription,
|
||||
backgroundColor: .secondarySystemBackground,
|
||||
textDidChange: nil
|
||||
)
|
||||
.edgesIgnoringSafeArea([.bottom, .leading, .trailing])
|
||||
|
||||
if attachment.attachmentDescription.isEmpty {
|
||||
placeholder
|
||||
.font(.body)
|
||||
.foregroundColor(.secondary)
|
||||
.offset(x: 4, y: 8)
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct WrappedTextView: UIViewRepresentable {
|
||||
typealias UIViewType = UITextView
|
||||
|
||||
@Binding var text: String
|
||||
let backgroundColor: UIColor
|
||||
let textDidChange: (((UITextView) -> Void))?
|
||||
let textDidChange: ((UITextView) -> Void)
|
||||
let font: UIFont
|
||||
|
||||
@Environment(\.isEnabled) private var isEnabled
|
||||
|
||||
func makeUIView(context: Context) -> UITextView {
|
||||
let view = UITextView()
|
||||
view.delegate = context.coordinator
|
||||
view.backgroundColor = backgroundColor
|
||||
view.font = .preferredFont(forTextStyle: .body)
|
||||
view.backgroundColor = .clear
|
||||
view.font = font
|
||||
view.adjustsFontForContentSizeCategory = true
|
||||
view.textContainer.lineBreakMode = .byWordWrapping
|
||||
return view
|
||||
|
@ -93,12 +68,10 @@ private struct WrappedTextView: UIViewRepresentable {
|
|||
context.coordinator.textView = uiView
|
||||
context.coordinator.text = $text
|
||||
context.coordinator.didChange = textDidChange
|
||||
if let textDidChange {
|
||||
// wait until the next runloop iteration so that SwiftUI view updates have finished and
|
||||
// the text view knows its new content size
|
||||
DispatchQueue.main.async {
|
||||
textDidChange(uiView)
|
||||
}
|
||||
// wait until the next runloop iteration so that SwiftUI view updates have finished and
|
||||
// the text view knows its new content size
|
||||
DispatchQueue.main.async {
|
||||
self.textDidChange(uiView)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -109,10 +82,10 @@ private struct WrappedTextView: UIViewRepresentable {
|
|||
class Coordinator: NSObject, UITextViewDelegate, TextViewCaretScrolling {
|
||||
weak var textView: UITextView?
|
||||
var text: Binding<String>
|
||||
var didChange: ((UITextView) -> Void)?
|
||||
var didChange: (UITextView) -> Void
|
||||
var caretScrollPositionAnimator: UIViewPropertyAnimator?
|
||||
|
||||
init(text: Binding<String>, didChange: ((UITextView) -> Void)?) {
|
||||
init(text: Binding<String>, didChange: @escaping (UITextView) -> Void) {
|
||||
self.text = text
|
||||
self.didChange = didChange
|
||||
|
||||
|
@ -131,7 +104,7 @@ private struct WrappedTextView: UIViewRepresentable {
|
|||
|
||||
func textViewDidChange(_ textView: UITextView) {
|
||||
text.wrappedValue = textView.text
|
||||
didChange?(textView)
|
||||
didChange(textView)
|
||||
|
||||
ensureCursorVisible(textView: textView)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,135 @@
|
|||
//
|
||||
// AttachmentThumbnailView.swift
|
||||
// ComposeUI
|
||||
//
|
||||
// Created by Shadowfacts on 11/10/21.
|
||||
// Copyright © 2021 Shadowfacts. All rights reserved.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import Photos
|
||||
import TuskerComponents
|
||||
|
||||
struct AttachmentThumbnailView: View {
|
||||
let attachment: DraftAttachment
|
||||
let fullSize: Bool
|
||||
|
||||
@State private var gifData: Data? = nil
|
||||
@State private var image: UIImage? = nil
|
||||
@State private var imageContentMode: ContentMode = .fill
|
||||
@State private var imageBackgroundColor: Color = .black
|
||||
|
||||
@Environment(\.colorScheme) private var colorScheme: ColorScheme
|
||||
|
||||
var body: some View {
|
||||
if let gifData {
|
||||
GIFViewWrapper(gifData: gifData)
|
||||
} else if let image {
|
||||
Image(uiImage: image)
|
||||
.resizable()
|
||||
.aspectRatio(contentMode: imageContentMode)
|
||||
.background(imageBackgroundColor)
|
||||
} else {
|
||||
Image(systemName: placeholderImageName)
|
||||
.onAppear(perform: self.loadImage)
|
||||
}
|
||||
}
|
||||
|
||||
private var placeholderImageName: String {
|
||||
switch colorScheme {
|
||||
case .light:
|
||||
return "photo"
|
||||
case .dark:
|
||||
return "photo.fill"
|
||||
@unknown default:
|
||||
return "photo"
|
||||
}
|
||||
}
|
||||
|
||||
private func loadImage() {
|
||||
switch attachment.data {
|
||||
case .asset(let id):
|
||||
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject else {
|
||||
return
|
||||
}
|
||||
let size: CGSize
|
||||
if fullSize {
|
||||
size = PHImageManagerMaximumSize
|
||||
} else {
|
||||
// currently only used as thumbnail in ComposeAttachmentRow
|
||||
size = CGSize(width: 80, height: 80)
|
||||
}
|
||||
let isGIF = PHAssetResource.assetResources(for: asset).contains(where: { $0.uniformTypeIdentifier == UTType.gif.identifier })
|
||||
if isGIF {
|
||||
PHImageManager.default().requestImageDataAndOrientation(for: asset, options: nil) { data, typeIdentifier, orientation, info in
|
||||
if typeIdentifier == UTType.gif.identifier {
|
||||
self.gifData = data
|
||||
} else if let data {
|
||||
let image = UIImage(data: data)
|
||||
DispatchQueue.main.async {
|
||||
self.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: nil) { (image, _) in
|
||||
DispatchQueue.main.async {
|
||||
self.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case let .drawing(drawing):
|
||||
image = drawing.imageInLightMode(from: drawing.bounds)
|
||||
imageContentMode = .fit
|
||||
imageBackgroundColor = .white
|
||||
|
||||
case .file(let url, let type):
|
||||
if type.conforms(to: .movie) {
|
||||
let asset = AVURLAsset(url: url)
|
||||
let imageGenerator = AVAssetImageGenerator(asset: asset)
|
||||
if let cgImage = try? imageGenerator.copyCGImage(at: .zero, actualTime: nil) {
|
||||
self.image = UIImage(cgImage: cgImage)
|
||||
}
|
||||
} else if let data = try? Data(contentsOf: url) {
|
||||
if type == .gif {
|
||||
self.gifData = data
|
||||
} else if type.conforms(to: .image),
|
||||
let image = UIImage(data: data) {
|
||||
if fullSize {
|
||||
image.prepareForDisplay {
|
||||
self.image = $0
|
||||
}
|
||||
} else {
|
||||
image.prepareThumbnail(of: CGSize(width: 80, height: 80)) {
|
||||
self.image = $0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct GIFViewWrapper: UIViewRepresentable {
|
||||
typealias UIViewType = GIFImageView
|
||||
|
||||
@State private var controller: GIFController
|
||||
|
||||
init(gifData: Data) {
|
||||
self._controller = State(wrappedValue: GIFController(gifData: gifData))
|
||||
}
|
||||
|
||||
func makeUIView(context: Context) -> GIFImageView {
|
||||
let view = GIFImageView()
|
||||
controller.attach(to: view)
|
||||
controller.startAnimating()
|
||||
view.contentMode = .scaleAspectFit
|
||||
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
view.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
|
||||
return view
|
||||
}
|
||||
|
||||
func updateUIView(_ uiView: GIFImageView, context: Context) {
|
||||
}
|
||||
}
|
|
@ -1,111 +0,0 @@
|
|||
//
|
||||
// ZoomableScrollView.swift
|
||||
// ComposeUI
|
||||
//
|
||||
// Created by Shadowfacts on 4/29/23.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
@available(iOS 16.0, *)
|
||||
struct ZoomableScrollView<Content: View>: UIViewControllerRepresentable {
|
||||
let content: Content
|
||||
|
||||
init(@ViewBuilder content: () -> Content) {
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
func makeUIViewController(context: Context) -> Controller {
|
||||
return Controller(content: content)
|
||||
}
|
||||
|
||||
func updateUIViewController(_ uiViewController: Controller, context: Context) {
|
||||
uiViewController.host.rootView = content
|
||||
}
|
||||
|
||||
class Controller: UIViewController, UIScrollViewDelegate {
|
||||
let scrollView = UIScrollView()
|
||||
let host: UIHostingController<Content>
|
||||
|
||||
private var lastIntrinsicSize: CGSize?
|
||||
private var contentViewTopConstraint: NSLayoutConstraint!
|
||||
private var contentViewLeadingConstraint: NSLayoutConstraint!
|
||||
private var hostBoundsObservation: NSKeyValueObservation?
|
||||
|
||||
init(content: Content) {
|
||||
self.host = UIHostingController(rootView: content)
|
||||
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
scrollView.delegate = self
|
||||
scrollView.bouncesZoom = true
|
||||
scrollView.translatesAutoresizingMaskIntoConstraints = false
|
||||
view.addSubview(scrollView)
|
||||
|
||||
host.sizingOptions = .intrinsicContentSize
|
||||
host.view.backgroundColor = .clear
|
||||
host.view.translatesAutoresizingMaskIntoConstraints = false
|
||||
addChild(host)
|
||||
scrollView.addSubview(host.view)
|
||||
host.didMove(toParent: self)
|
||||
|
||||
contentViewLeadingConstraint = host.view.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor)
|
||||
contentViewTopConstraint = host.view.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor)
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
scrollView.frameLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor),
|
||||
scrollView.frameLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor),
|
||||
scrollView.frameLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor),
|
||||
scrollView.frameLayoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor),
|
||||
|
||||
contentViewLeadingConstraint,
|
||||
contentViewTopConstraint,
|
||||
])
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
|
||||
if !host.view.intrinsicContentSize.equalTo(.zero),
|
||||
host.view.intrinsicContentSize != lastIntrinsicSize {
|
||||
self.lastIntrinsicSize = host.view.intrinsicContentSize
|
||||
|
||||
let maxHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
|
||||
let maxWidth = view.bounds.width - view.safeAreaInsets.left - view.safeAreaInsets.right
|
||||
let heightScale = maxHeight / host.view.intrinsicContentSize.height
|
||||
let widthScale = maxWidth / host.view.intrinsicContentSize.width
|
||||
let minScale = min(widthScale, heightScale)
|
||||
let maxScale = minScale >= 1 ? minScale + 2 : 2
|
||||
scrollView.minimumZoomScale = minScale
|
||||
scrollView.maximumZoomScale = maxScale
|
||||
scrollView.zoomScale = minScale
|
||||
}
|
||||
|
||||
centerImage()
|
||||
}
|
||||
|
||||
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
|
||||
return host.view
|
||||
}
|
||||
|
||||
func scrollViewDidZoom(_ scrollView: UIScrollView) {
|
||||
centerImage()
|
||||
}
|
||||
|
||||
func centerImage() {
|
||||
let yOffset = max(0, (view.bounds.size.height - host.view.bounds.height * scrollView.zoomScale) / 2)
|
||||
contentViewTopConstraint.constant = yOffset
|
||||
|
||||
let xOffset = max(0, (view.bounds.size.width - host.view.bounds.width * scrollView.zoomScale) / 2)
|
||||
contentViewLeadingConstraint.constant = xOffset
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
|
@ -1,26 +0,0 @@
|
|||
// swift-tools-version: 5.8
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "MatchedGeometryPresentation",
|
||||
platforms: [
|
||||
.iOS(.v15),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, making them visible to other packages.
|
||||
.library(
|
||||
name: "MatchedGeometryPresentation",
|
||||
targets: ["MatchedGeometryPresentation"]),
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package, defining a module or a test suite.
|
||||
// Targets can depend on other targets in this package and products from dependencies.
|
||||
.target(
|
||||
name: "MatchedGeometryPresentation"),
|
||||
// .testTarget(
|
||||
// name: "MatchedGeometryPresentationTests",
|
||||
// dependencies: ["MatchedGeometryPresentation"]),
|
||||
]
|
||||
)
|
|
@ -1,125 +0,0 @@
|
|||
//
|
||||
// MatchedGeometryModifiers.swift
|
||||
// MatchGeom
|
||||
//
|
||||
// Created by Shadowfacts on 4/24/23.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
extension View {
|
||||
public func matchedGeometryPresentation<ID: Hashable, Presented: View>(id: Binding<ID?>, backgroundColor: UIColor, @ViewBuilder presenting: () -> Presented) -> some View {
|
||||
self.modifier(MatchedGeometryPresentationModifier(id: id, backgroundColor: backgroundColor, presented: presenting()))
|
||||
}
|
||||
|
||||
public func matchedGeometrySource<ID: Hashable, ID2: Hashable>(id: ID, presentationID: ID2) -> some View {
|
||||
self.modifier(MatchedGeometrySourceModifier(id: AnyHashable(id), presentationID: AnyHashable(presentationID), matched: { AnyView(self) }))
|
||||
}
|
||||
|
||||
public func matchedGeometryDestination<ID: Hashable>(id: ID) -> some View {
|
||||
self.modifier(MatchedGeometryDestinationModifier(id: AnyHashable(id), matched: self))
|
||||
}
|
||||
}
|
||||
|
||||
private struct MatchedGeometryPresentationModifier<ID: Hashable, Presented: View>: ViewModifier {
|
||||
@Binding var id: ID?
|
||||
let backgroundColor: UIColor
|
||||
let presented: Presented
|
||||
@StateObject private var state = MatchedGeometryState()
|
||||
|
||||
private var isPresented: Binding<Bool> {
|
||||
Binding {
|
||||
id != nil
|
||||
} set: {
|
||||
if $0 {
|
||||
fatalError()
|
||||
} else {
|
||||
id = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.environmentObject(state)
|
||||
.backgroundPreferenceValue(MatchedGeometrySourcesKey.self, { sources in
|
||||
Color.clear
|
||||
.presentViewController(makeVC(allSources: sources), isPresented: isPresented)
|
||||
})
|
||||
}
|
||||
|
||||
private func makeVC(allSources: [SourceKey: (AnyView, CGRect)]) -> () -> UIViewController {
|
||||
return {
|
||||
// force unwrap is safe, this closure is only called when being presented so we must have an id
|
||||
let id = AnyHashable(id!)
|
||||
return MatchedGeometryViewController(
|
||||
presentationID: id,
|
||||
content: presented,
|
||||
state: state,
|
||||
backgroundColor: backgroundColor
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct MatchedGeometrySourceModifier: ViewModifier {
|
||||
let id: AnyHashable
|
||||
let presentationID: AnyHashable
|
||||
let matched: () -> AnyView
|
||||
@EnvironmentObject private var state: MatchedGeometryState
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.background(GeometryReader { proxy in
|
||||
Color.clear
|
||||
.preference(key: MatchedGeometryDestinationFrameKey.self, value: proxy.frame(in: .global))
|
||||
.onPreferenceChange(MatchedGeometryDestinationFrameKey.self) { newValue in
|
||||
if let newValue {
|
||||
state.sources[SourceKey(presentationID: presentationID, matchedID: id)] = (matched, newValue)
|
||||
}
|
||||
}
|
||||
})
|
||||
.opacity(state.animating && state.presentationID == presentationID ? 0 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MatchedGeometryDestinationModifier<Matched: View>: ViewModifier {
|
||||
let id: AnyHashable
|
||||
let matched: Matched
|
||||
@EnvironmentObject private var state: MatchedGeometryState
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.background(GeometryReader { proxy in
|
||||
Color.clear
|
||||
.preference(key: MatchedGeometryDestinationFrameKey.self, value: proxy.frame(in: .global))
|
||||
.onPreferenceChange(MatchedGeometryDestinationFrameKey.self) { newValue in
|
||||
if let newValue,
|
||||
// ignore intermediate layouts that may happen while the dismiss animation is happening
|
||||
state.mode != .dismissing {
|
||||
state.destinations[id] = (AnyView(matched), newValue)
|
||||
}
|
||||
}
|
||||
})
|
||||
.opacity(state.animating ? 0 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MatchedGeometryDestinationFrameKey: PreferenceKey {
|
||||
static let defaultValue: CGRect? = nil
|
||||
static func reduce(value: inout CGRect?, nextValue: () -> CGRect?) {
|
||||
value = nextValue()
|
||||
}
|
||||
}
|
||||
|
||||
private struct MatchedGeometrySourcesKey: PreferenceKey {
|
||||
static let defaultValue: [SourceKey: (AnyView, CGRect)] = [:]
|
||||
static func reduce(value: inout Value, nextValue: () -> Value) {
|
||||
value.merge(nextValue(), uniquingKeysWith: { _, new in new })
|
||||
}
|
||||
}
|
||||
|
||||
struct SourceKey: Hashable {
|
||||
let presentationID: AnyHashable
|
||||
let matchedID: AnyHashable
|
||||
}
|
|
@ -1,234 +0,0 @@
|
|||
//
|
||||
// MatchedGeometryViewController.swift
|
||||
// MatchGeom
|
||||
//
|
||||
// Created by Shadowfacts on 4/24/23.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import Combine
|
||||
|
||||
private let mass: CGFloat = 1
|
||||
private let presentStiffness: CGFloat = 300
|
||||
private let presentDamping: CGFloat = 20
|
||||
private let dismissStiffness: CGFloat = 200
|
||||
private let dismissDamping: CGFloat = 20
|
||||
|
||||
public class MatchedGeometryState: ObservableObject {
|
||||
@Published var presentationID: AnyHashable?
|
||||
@Published var animating: Bool = false
|
||||
@Published public var mode: Mode = .presenting
|
||||
@Published var sources: [SourceKey: (() -> AnyView, CGRect)] = [:]
|
||||
@Published var currentFrames: [AnyHashable: CGRect] = [:]
|
||||
@Published var destinations: [AnyHashable: (AnyView, CGRect)] = [:]
|
||||
|
||||
public enum Mode: Equatable {
|
||||
case presenting
|
||||
case idle
|
||||
case dismissing
|
||||
}
|
||||
}
|
||||
|
||||
class MatchedGeometryViewController<Content: View>: UIViewController, UIViewControllerTransitioningDelegate {
|
||||
|
||||
let presentationID: AnyHashable
|
||||
let content: Content
|
||||
let state: MatchedGeometryState
|
||||
let backgroundColor: UIColor
|
||||
var contentHost: UIHostingController<ContentContainerView>!
|
||||
var matchedHost: UIHostingController<MatchedContainerView>!
|
||||
|
||||
init(presentationID: AnyHashable, content: Content, state: MatchedGeometryState, backgroundColor: UIColor) {
|
||||
self.presentationID = presentationID
|
||||
self.content = content
|
||||
self.state = state
|
||||
self.backgroundColor = backgroundColor
|
||||
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
|
||||
modalPresentationStyle = .custom
|
||||
transitioningDelegate = self
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
contentHost = UIHostingController(rootView: ContentContainerView(content: content, state: state))
|
||||
contentHost.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
contentHost.view.frame = view.bounds
|
||||
contentHost.view.backgroundColor = backgroundColor
|
||||
addChild(contentHost)
|
||||
view.addSubview(contentHost.view)
|
||||
contentHost.didMove(toParent: self)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
|
||||
state.presentationID = presentationID
|
||||
}
|
||||
|
||||
var currentPresentationSources: [AnyHashable: (() -> AnyView, CGRect)] {
|
||||
Dictionary(uniqueKeysWithValues: state.sources.filter { $0.key.presentationID == presentationID }.map { ($0.key.matchedID, $0.value) })
|
||||
}
|
||||
|
||||
func addMatchedHostingController() {
|
||||
let sources = currentPresentationSources.map { (id: $0.key, view: $0.value.0) }
|
||||
matchedHost = UIHostingController(rootView: MatchedContainerView(sources: sources, state: state))
|
||||
matchedHost.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
matchedHost.view.frame = view.bounds
|
||||
matchedHost.view.backgroundColor = .clear
|
||||
matchedHost.view.layer.zPosition = 100
|
||||
addChild(matchedHost)
|
||||
view.addSubview(matchedHost.view)
|
||||
matchedHost.didMove(toParent: self)
|
||||
}
|
||||
|
||||
struct ContentContainerView: View {
|
||||
let content: Content
|
||||
let state: MatchedGeometryState
|
||||
|
||||
var body: some View {
|
||||
content
|
||||
.environmentObject(state)
|
||||
}
|
||||
}
|
||||
|
||||
struct MatchedContainerView: View {
|
||||
let sources: [(id: AnyHashable, view: () -> AnyView)]
|
||||
@ObservedObject var state: MatchedGeometryState
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
ForEach(sources, id: \.id) { (id, view) in
|
||||
matchedView(id: id, source: view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchedView(id: AnyHashable, source: () -> AnyView) -> some View {
|
||||
let frame = state.currentFrames[id]!
|
||||
let dest = state.destinations[id]!.0
|
||||
return ZStack {
|
||||
source()
|
||||
dest
|
||||
.opacity(state.mode == .presenting ? (state.animating ? 1 : 0) : (state.animating ? 0 : 1))
|
||||
}
|
||||
.frame(width: frame.width, height: frame.height)
|
||||
.position(x: frame.midX, y: frame.midY)
|
||||
.ignoresSafeArea()
|
||||
.animation(.interpolatingSpring(mass: Double(mass), stiffness: Double(state.mode == .presenting ? presentStiffness : dismissStiffness), damping: Double(state.mode == .presenting ? presentDamping : dismissDamping), initialVelocity: 0), value: frame)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: UIViewControllerTransitioningDelegate
|
||||
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
|
||||
return MatchedGeometryPresentationAnimationController<Content>()
|
||||
}
|
||||
|
||||
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
|
||||
return MatchedGeometryDismissAnimationController<Content>()
|
||||
}
|
||||
|
||||
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
|
||||
return MatchedGeometryPresentationController(presentedViewController: presented, presenting: presenting)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class MatchedGeometryPresentationAnimationController<Content: View>: NSObject, UIViewControllerAnimatedTransitioning {
|
||||
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
|
||||
return 0.8
|
||||
}
|
||||
|
||||
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
|
||||
let matchedGeomVC = transitionContext.viewController(forKey: .to) as! MatchedGeometryViewController<Content>
|
||||
let container = transitionContext.containerView
|
||||
|
||||
// add the VC to the container, which kicks off layout out the content hosting controller
|
||||
container.addSubview(matchedGeomVC.view)
|
||||
|
||||
// layout out the content hosting controller and having enough destinations may take a while
|
||||
// so listen for when it's ready, rather than trying to guess at the timing
|
||||
let cancellable = matchedGeomVC.state.$destinations
|
||||
.filter { destinations in matchedGeomVC.currentPresentationSources.allSatisfy { source in destinations.keys.contains(source.key) } }
|
||||
.first()
|
||||
.sink { destinations in
|
||||
matchedGeomVC.addMatchedHostingController()
|
||||
|
||||
// setup the initial state for the animation
|
||||
matchedGeomVC.matchedHost.view.isHidden = true
|
||||
matchedGeomVC.state.mode = .presenting
|
||||
matchedGeomVC.state.currentFrames = matchedGeomVC.currentPresentationSources.mapValues(\.1)
|
||||
|
||||
// wait one runloop iteration for the matched hosting controller to be setup
|
||||
DispatchQueue.main.async {
|
||||
matchedGeomVC.matchedHost.view.isHidden = false
|
||||
matchedGeomVC.state.animating = true
|
||||
// get the now-current destinations, in case they've changed since the sunk value was published
|
||||
matchedGeomVC.state.currentFrames = matchedGeomVC.state.destinations.mapValues(\.1)
|
||||
}
|
||||
}
|
||||
|
||||
matchedGeomVC.contentHost.view.layer.opacity = 0
|
||||
let spring = UISpringTimingParameters(mass: mass, stiffness: presentStiffness, damping: presentDamping, initialVelocity: .zero)
|
||||
let animator = UIViewPropertyAnimator(duration: self.transitionDuration(using: transitionContext), timingParameters: spring)
|
||||
animator.addAnimations {
|
||||
matchedGeomVC.contentHost.view.layer.opacity = 1
|
||||
}
|
||||
animator.addCompletion { _ in
|
||||
transitionContext.completeTransition(true)
|
||||
matchedGeomVC.state.animating = false
|
||||
matchedGeomVC.state.mode = .idle
|
||||
|
||||
matchedGeomVC.matchedHost?.view.removeFromSuperview()
|
||||
matchedGeomVC.matchedHost?.removeFromParent()
|
||||
cancellable.cancel()
|
||||
}
|
||||
animator.startAnimation()
|
||||
}
|
||||
}
|
||||
|
||||
class MatchedGeometryDismissAnimationController<Content: View>: NSObject, UIViewControllerAnimatedTransitioning {
|
||||
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
|
||||
return 0.8
|
||||
}
|
||||
|
||||
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
|
||||
let matchedGeomVC = transitionContext.viewController(forKey: .from) as! MatchedGeometryViewController<Content>
|
||||
|
||||
// recreate the matched host b/c using the current destinations doesn't seem to update the existing one
|
||||
matchedGeomVC.addMatchedHostingController()
|
||||
matchedGeomVC.matchedHost.view.isHidden = true
|
||||
matchedGeomVC.state.mode = .dismissing
|
||||
matchedGeomVC.state.currentFrames = matchedGeomVC.state.destinations.mapValues(\.1)
|
||||
|
||||
DispatchQueue.main.async {
|
||||
matchedGeomVC.matchedHost.view.isHidden = false
|
||||
matchedGeomVC.state.animating = true
|
||||
matchedGeomVC.state.currentFrames = matchedGeomVC.currentPresentationSources.mapValues(\.1)
|
||||
}
|
||||
|
||||
let spring = UISpringTimingParameters(mass: mass, stiffness: dismissStiffness, damping: dismissDamping, initialVelocity: .zero)
|
||||
let animator = UIViewPropertyAnimator(duration: transitionDuration(using: transitionContext), timingParameters: spring)
|
||||
animator.addAnimations {
|
||||
matchedGeomVC.contentHost.view.layer.opacity = 0
|
||||
}
|
||||
animator.addCompletion { _ in
|
||||
transitionContext.completeTransition(true)
|
||||
matchedGeomVC.state.animating = false
|
||||
}
|
||||
animator.startAnimation()
|
||||
}
|
||||
}
|
||||
|
||||
class MatchedGeometryPresentationController: UIPresentationController {
|
||||
override func dismissalTransitionWillBegin() {
|
||||
super.dismissalTransitionWillBegin()
|
||||
delegate?.presentationControllerWillDismiss?(self)
|
||||
}
|
||||
}
|
|
@ -1,61 +0,0 @@
|
|||
//
|
||||
// View+PresentViewController.swift
|
||||
// MatchGeom
|
||||
//
|
||||
// Created by Shadowfacts on 4/24/23.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
extension View {
|
||||
func presentViewController(_ makeVC: @escaping () -> UIViewController, isPresented: Binding<Bool>) -> some View {
|
||||
self
|
||||
.background(
|
||||
ViewControllerPresenter(makeVC: makeVC, isPresented: isPresented)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ViewControllerPresenter: UIViewControllerRepresentable {
|
||||
let makeVC: () -> UIViewController
|
||||
@Binding var isPresented: Bool
|
||||
|
||||
func makeUIViewController(context: Context) -> UIViewController {
|
||||
return UIViewController()
|
||||
}
|
||||
|
||||
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
|
||||
if isPresented {
|
||||
if uiViewController.presentedViewController == nil {
|
||||
let presented = makeVC()
|
||||
presented.presentationController!.delegate = context.coordinator
|
||||
uiViewController.present(presented, animated: true)
|
||||
context.coordinator.didPresent = true
|
||||
}
|
||||
} else {
|
||||
if context.coordinator.didPresent,
|
||||
let presentedViewController = uiViewController.presentedViewController,
|
||||
!presentedViewController.isBeingDismissed {
|
||||
uiViewController.dismiss(animated: true)
|
||||
context.coordinator.didPresent = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
return Coordinator(isPresented: $isPresented)
|
||||
}
|
||||
|
||||
class Coordinator: NSObject, UIAdaptivePresentationControllerDelegate {
|
||||
@Binding var isPresented: Bool
|
||||
var didPresent = false
|
||||
|
||||
init(isPresented: Binding<Bool>) {
|
||||
self._isPresented = isPresented
|
||||
}
|
||||
|
||||
func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
|
||||
isPresented = false
|
||||
}
|
||||
}
|
||||
}
|
|
@ -634,7 +634,6 @@
|
|||
D6A6C10E25B62D2400298D0F /* DiskCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiskCache.swift; sourceTree = "<group>"; };
|
||||
D6A6C11425B62E9700298D0F /* CacheExpiry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CacheExpiry.swift; sourceTree = "<group>"; };
|
||||
D6A6C11A25B63CEE00298D0F /* MemoryCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemoryCache.swift; sourceTree = "<group>"; };
|
||||
D6A9E04F29F8917500BEDC7E /* MatchedGeometryPresentation */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = MatchedGeometryPresentation; path = Packages/MatchedGeometryPresentation; sourceTree = "<group>"; };
|
||||
D6AC956623C4347E008C9946 /* MainSceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainSceneDelegate.swift; sourceTree = "<group>"; };
|
||||
D6ADB6E728E8C878009924AB /* PublicTimelineDescriptionCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublicTimelineDescriptionCollectionViewCell.swift; sourceTree = "<group>"; };
|
||||
D6ADB6E928E91C30009924AB /* TimelineStatusCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineStatusCollectionViewCell.swift; sourceTree = "<group>"; };
|
||||
|
@ -1458,7 +1457,6 @@
|
|||
D6BD395C29B789D5005FFD2B /* TuskerComponents */,
|
||||
D6BD395729B6441F005FFD2B /* ComposeUI */,
|
||||
D6CA6ED029EF6060003EC5DF /* TuskerPreferences */,
|
||||
D6A9E04F29F8917500BEDC7E /* MatchedGeometryPresentation */,
|
||||
D6D4DDCE212518A000E1C4BB /* Tusker */,
|
||||
D6D4DDE3212518A200E1C4BB /* TuskerTests */,
|
||||
D6D4DDEE212518A200E1C4BB /* TuskerUITests */,
|
||||
|
|
Loading…
Reference in New Issue