bsky-app/modules/expo-bluesky-gif-view/ios/GifView.swift

186 lines
4.7 KiB
Swift
Raw Normal View History

GIF Viewer (#3605) * ios player autoplay after recycle remove all items from AVPlayer queue recurururururursion use managers in the view add prefetch make sure player items stay in order add controller and item managers start of the view create module, ios * android player smoother basic caching prep cache somewhat works backup other files android impl blegh lets go touchup add prefetch to js use caching * bogus testing commit * add dims to type * save * add the dimensions to the embed info * add a new case * add a new case * limit this case to giphy * use gate * Revert "bogus testing commit" This reverts commit b3c8751b71f7108de9aa843b22ded4e0249fa854. * add web player base * flip mp4/webp * basic mp4 player for web * move some stuff into `ExternalLinkEmbed` instead * use a class component for web * remove extra component * add `onPlayerStateChange` event type on web * layer properly * fix tests * add new test * about ready. native portions done, a few touch ups on web needed show placeholder on ios fix type rm log display thumbnail until video is ready to play add oncanplay, playsinline remove unused method add `isLoaded` change event release player when finished apply gc to the view cleanup logs android gc rm log automatic gc for assets make `nativeRef` private remove unnecessary `await` cleanup rev log only play on prepare whenever needed rm unused perfperfperf rm var comment + android width native height calculations rm pressable add event dispatcher on android add event dispatcher on ios * ready to test ios fix autoplay ios clean oops * autoplay on web * normalize across all platforms add check for `ALT:` separate gif embed logic to another file handle permissions requests flatten web styles normalize styles normalize styles prefetch functions pause animatable on foreground android nits one more oops idk where that code went lint rethink the usage wrap up android clear bg update gradle more android rename dir update android namespace web ios add deps use webp rm unused update types use webp on mobile * rm gate from types * remove unused event param * only start placeholder op if doesn't exist in disk cache * fix gifs animating on app resume android * remove comment * add `isLoaded` for ios * add `isLoaded` to Android * onload for web * add visual loading state * rm a log * implement isloaded for android * dialogs * replace `webpSource` with `source` * update prop name * Move to Tenor for GIFs (#3654) * update some urls * right order for dimensions * add GIF coder for ios * remove giphy check * rewrite tenor urls * remove all the unnecessary stuff for consent * rm print * rm log * check if id and filename are strings * full size playback controls * pass tests * add accessibility to gifs * use `onPlay` and `onPause` * rm unused logic for description * add accessibility label to the controls * add gif into to external embed in composer * make it optional * gif dimensions * make the jsx look nicer --------- Co-authored-by: Dan Abramov <dan.abramov@gmail.com> Co-authored-by: Samuel Newman <mozzius@protonmail.com>
2024-04-23 03:54:15 +02:00
import ExpoModulesCore
import SDWebImage
import SDWebImageWebPCoder
typealias SDWebImageContext = [SDWebImageContextOption: Any]
public class GifView: ExpoView, AVPlayerViewControllerDelegate {
// Events
private let onPlayerStateChange = EventDispatcher()
// SDWebImage
private let imageView = SDAnimatedImageView(frame: .zero)
private let imageManager = SDWebImageManager(
cache: SDImageCache.shared,
loader: SDImageLoadersManager.shared
)
private var isPlaying = true
private var isLoaded = false
// Requests
private var webpOperation: SDWebImageCombinedOperation?
private var placeholderOperation: SDWebImageCombinedOperation?
// Props
var source: String? = nil
var placeholderSource: String? = nil
var autoplay = true {
didSet {
if !autoplay {
self.pause()
} else {
self.play()
}
}
}
// MARK: - Lifecycle
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
self.clipsToBounds = true
self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.imageView.layer.masksToBounds = false
self.imageView.backgroundColor = .clear
self.imageView.contentMode = .scaleToFill
// We have to explicitly set this to false. If we don't, every time
// the view comes into the viewport, it will start animating again
self.imageView.autoPlayAnimatedImage = false
self.addSubview(self.imageView)
}
public override func willMove(toWindow newWindow: UIWindow?) {
if newWindow == nil {
// Don't cancel the placeholder operation, because we really want that to complete for
// when we scroll back up
self.webpOperation?.cancel()
self.placeholderOperation?.cancel()
} else if self.imageView.image == nil {
self.load()
}
}
// MARK: - Loading
private func load() {
guard let source = self.source, let placeholderSource = self.placeholderSource else {
return
}
self.webpOperation?.cancel()
self.placeholderOperation?.cancel()
// We only need to start an operation for the placeholder if it doesn't exist
// in the cache already. Cache key is by default the absolute URL of the image.
// See:
// https://github.com/SDWebImage/SDWebImage/blob/master/Docs/HowToUse.md#using-asynchronous-image-caching-independently
if !SDImageCache.shared.diskImageDataExists(withKey: source),
let url = URL(string: placeholderSource)
{
self.placeholderOperation = imageManager.loadImage(
with: url,
options: [.retryFailed],
context: Util.createContext(),
progress: onProgress(_:_:_:),
completed: onLoaded(_:_:_:_:_:_:)
)
}
if let url = URL(string: source) {
self.webpOperation = imageManager.loadImage(
with: url,
options: [.retryFailed],
context: Util.createContext(),
progress: onProgress(_:_:_:),
completed: onLoaded(_:_:_:_:_:_:)
)
}
}
private func setImage(_ image: UIImage) {
if self.imageView.image == nil || image.sd_isAnimated {
self.imageView.image = image
}
if image.sd_isAnimated {
self.firePlayerStateChange()
if isPlaying {
self.imageView.startAnimating()
}
}
}
// MARK: - Loading blocks
private func onProgress(_ receivedSize: Int, _ expectedSize: Int, _ imageUrl: URL?) {}
private func onLoaded(
_ image: UIImage?,
_ data: Data?,
_ error: Error?,
_ cacheType: SDImageCacheType,
_ finished: Bool,
_ imageUrl: URL?
) {
guard finished else {
return
}
if let placeholderSource = self.placeholderSource,
imageUrl?.absoluteString == placeholderSource,
self.imageView.image == nil,
let image = image
{
self.setImage(image)
return
}
if let source = self.source,
imageUrl?.absoluteString == source,
// UIImage perf suckssss if the image is animated
let data = data,
let animatedImage = SDAnimatedImage(data: data)
{
self.placeholderOperation?.cancel()
self.isPlaying = self.autoplay
self.isLoaded = true
self.setImage(animatedImage)
self.firePlayerStateChange()
}
}
// MARK: - Playback Controls
func play() {
self.imageView.startAnimating()
self.isPlaying = true
self.firePlayerStateChange()
}
func pause() {
self.imageView.stopAnimating()
self.isPlaying = false
self.firePlayerStateChange()
}
func toggle() {
if self.isPlaying {
self.pause()
} else {
self.play()
}
}
// MARK: - Util
private func firePlayerStateChange() {
onPlayerStateChange([
"isPlaying": self.isPlaying,
"isLoaded": self.isLoaded
])
}
}