From 2cda1ed8ddfcf58256b55910ce944adec1b086f2 Mon Sep 17 00:00:00 2001
From: Patryk Klatka <patryk.klatka@gmail.com>
Date: Wed, 27 Mar 2024 12:29:30 +0100
Subject: [PATCH] Change logic of `refresh` method (#172)

Co-authored-by: Mattias Pfeiffer <mattias@pfeiffer.dk>
---
 .../com/reactnativeturbowebview/RNVisitableView.kt   | 12 +++++-------
 packages/turbo/ios/RNVisitableView.swift             |  9 +++++----
 2 files changed, 10 insertions(+), 11 deletions(-)

diff --git a/packages/turbo/android/src/main/java/com/reactnativeturbowebview/RNVisitableView.kt b/packages/turbo/android/src/main/java/com/reactnativeturbowebview/RNVisitableView.kt
index 183fcf14..8c2bed42 100644
--- a/packages/turbo/android/src/main/java/com/reactnativeturbowebview/RNVisitableView.kt
+++ b/packages/turbo/android/src/main/java/com/reactnativeturbowebview/RNVisitableView.kt
@@ -23,6 +23,10 @@ import dev.hotwire.turbo.errors.WebError
 import dev.hotwire.turbo.errors.WebSslError
 import dev.hotwire.turbo.visit.TurboVisitAction
 
+const val REFRESH_SCRIPT = "typeof Turbo.session.refresh === 'function'" +
+        "? Turbo.session.refresh(document.baseURI)" + // Turbo 8+
+        ": Turbo.visit(document.baseURI, { action: 'replace', shouldCacheSnapshot: 'false' })" // Older Turbo versions 
+
 class RNVisitableView(context: Context) : LinearLayout(context), SessionSubscriber {
 
   private val reactContext = context as ReactApplicationContext
@@ -117,13 +121,7 @@ class RNVisitableView(context: Context) : LinearLayout(context), SessionSubscrib
   }
 
   override fun refresh() {
-    session.visit(
-      url = url,
-      restoreWithCachedSnapshot = false,
-      reload = false,
-      viewTreeLifecycleOwner = viewTreeLifecycleOwner,
-      visitOptions = TurboVisitOptions(action = TurboVisitAction.REPLACE)
-    )
+    webView.evaluateJavascript(REFRESH_SCRIPT, null)
   }
 
   override fun reload(displayProgress: Boolean) {
diff --git a/packages/turbo/ios/RNVisitableView.swift b/packages/turbo/ios/RNVisitableView.swift
index 0e9697de..b985c8fe 100644
--- a/packages/turbo/ios/RNVisitableView.swift
+++ b/packages/turbo/ios/RNVisitableView.swift
@@ -7,6 +7,10 @@
 
 import UIKit
 
+let REFRESH_SCRIPT = "typeof Turbo.session.refresh === 'function'" +
+            "? Turbo.session.refresh(document.baseURI)" + // Turbo 8+
+            ": Turbo.visit(document.baseURI, { action: 'replace', shouldCacheSnapshot: 'false' })" // Older Turbo versions
+
 class RNVisitableView: UIView, RNSessionSubscriber {
   var id: UUID = UUID()
   @objc var sessionHandle: NSString? = nil
@@ -120,10 +124,7 @@ class RNVisitableView: UIView, RNSessionSubscriber {
   }
 
   public func refresh() {
-    if (controller == nil) {
-      return
-    }
-    session.visit(controller!, action: .replace)
+      webView.evaluateJavaScript(REFRESH_SCRIPT)
   }
 
   private func visit() {