Skip to content

Commit

Permalink
Revert "up"
Browse files Browse the repository at this point in the history
This reverts commit 3adf6b5.
  • Loading branch information
michalziolkowski committed Dec 8, 2024
1 parent 3adf6b5 commit cd45a64
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 176 deletions.
8 changes: 4 additions & 4 deletions packages/action/release/index.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
import android.util.Log;
import android.content.Context;
import android.view.View;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

// React Native Bridge Imports
import com.facebook.react.bridge.ReactApplicationContext;
Expand All @@ -32,11 +28,6 @@ public class SherloModule extends ReactContextBaseJavaModule {
public static final String TAG = "SherloModule";
private static final String CONFIG_FILENAME = "config.sherlo";
private static final String PROTOCOL_FILENAME = "protocol.sherlo";

// Add these constants for snapshot stabilization
private static final long STABILIZATION_THRESHOLD = 2000; // 2 seconds minimum wait time
private static final long STABILIZATION_TIMEOUT = 10000; // 10 second maximum wait time
private static final long STABILIZATION_INTERVAL = 500; // Check every 500ms

private final ReactApplicationContext reactContext;
private static String syncDirectoryPath = "";
Expand Down Expand Up @@ -228,76 +219,25 @@ public void getSnapshot(Promise promise) {
promise.reject("no_activity", "No current activity");
return;
}

final long startTime = System.currentTimeMillis();
final AtomicInteger stableInRow = new AtomicInteger(0);
final AtomicReference<String> previousSnapshot = new AtomicReference<>();
final AtomicReference<String> finalSnapshot = new AtomicReference<>();
final Handler handler = new Handler(Looper.getMainLooper());

// Declare the Runnable reference first
final Runnable[] captureRunnableRef = new Runnable[1];

// Create and assign the Runnable
captureRunnableRef[0] = new Runnable() {
@Override
public void run() {
try {
SnapshotHelper.captureView(activity, new SnapshotHelper.SnapshotCallback() {
@Override
public void onSnapshot(SnapshotHelper.ScreenshotResult result) {
long elapsedTime = System.currentTimeMillis() - startTime;

if (previousSnapshot.get() != null &&
previousSnapshot.get().equals(result.base64)) {
stableInRow.incrementAndGet();
} else {
stableInRow.set(0);
}
previousSnapshot.set(result.base64);
finalSnapshot.set(result.base64);

boolean isStabilized = (stableInRow.get() > 0 &&
elapsedTime > STABILIZATION_THRESHOLD);
boolean isTimedOut = (elapsedTime > STABILIZATION_TIMEOUT);

if (isStabilized || isTimedOut) {
// Process final snapshot
try {
String inspectorData = InspectorHelper.getInspectorData(activity);

String resultJson = new JSONObject()
.put("resolution", new JSONObject()
.put("width", result.resolution.x)
.put("height", result.resolution.y))
.put("base64", finalSnapshot.get())
.put("inspectorData", new JSONObject(inspectorData))
.put("isUnstable", stableInRow.get() == 0)
.toString();

promise.resolve(resultJson);
} catch (Exception e) {
promise.reject("error", e.getMessage(), e);
}
} else {
// Use the reference from the array
handler.postDelayed(captureRunnableRef[0], STABILIZATION_INTERVAL);
}
}

@Override
public void onError(String error) {
promise.reject("error", error);
}
});
} catch (Exception e) {
promise.reject("error", e.getMessage(), e);
}

activity.runOnUiThread(() -> {
try {
String inspectorData = InspectorHelper.getInspectorData(activity);
SnapshotHelper.ScreenshotResult screenshotResult = SnapshotHelper.captureView(activity);

String resultJson = new JSONObject()
.put("resolution", new JSONObject()
.put("width", screenshotResult.resolution.x)
.put("height", screenshotResult.resolution.y))
.put("base64", screenshotResult.base64)
.put("inspectorData", new JSONObject(inspectorData))
.toString();

promise.resolve(resultJson);
} catch (Exception e) {
promise.reject("error", e.getMessage(), e);
}
};

// Start the capture loop on the main thread using the reference from the array
activity.runOnUiThread(captureRunnableRef[0]);
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,6 @@ public class SnapshotHelper {
};
}

public interface SnapshotCallback {
void onSnapshot(ScreenshotResult result);
void onError(String error);
}

/**
* Screenshot a view and return the captured bitmap as a Base64 string.
*
Expand Down Expand Up @@ -305,13 +300,4 @@ public ScreenshotResult(Point resolution, String base64) {
this.base64 = base64;
}
}

public static void captureView(@NonNull final android.app.Activity activity, @NonNull final SnapshotCallback callback) {
try {
ScreenshotResult result = captureView(activity);
callback.onSnapshot(result);
} catch (Exception e) {
callback.onError(e.getMessage());
}
}
}
114 changes: 43 additions & 71 deletions packages/react-native-storybook/ios/SherloModule.m
Original file line number Diff line number Diff line change
Expand Up @@ -277,84 +277,56 @@ - (void)handleError:(NSString *)errorCode error:(NSError *)error {
RCT_EXPORT_METHOD(getSnapshot:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
dispatch_async(dispatch_get_main_queue(), ^{
@try {
// Constants for stabilization (in seconds)
const NSTimeInterval STABILIZATION_TIMEOUT = 10.0;
const NSTimeInterval STABILIZATION_THRESHOLD = 2.0;
const NSTimeInterval STABILIZATION_INTERVAL = 0.5;
// Get inspector data
NSError *inspectorError = nil;
NSString *inspectorData = [InspectorHelper dumpBoundaries:&inspectorError];

NSDate *startTime = [NSDate date];
__block NSInteger stableInRow = 0;
__block NSString *previousSnapshot = nil;
__block NSString *finalSnapshot = nil;
// Create snapshot helper
if (inspectorError) {
reject(@"error", @"Failed to get inspector data", inspectorError);
return;
}

// Get snapshot - initialize with bridge
SnapshotHelper *snapshotHelper = [[SnapshotHelper alloc] initWithBridge:self.bridge];

// Function to check stabilization and capture
void (^captureAndCheck)(void) = ^void() {
[snapshotHelper captureView:^(NSString *base64Image) {
NSTimeInterval elapsedTime = -[startTime timeIntervalSinceNow];
[snapshotHelper captureView:^(NSString *base64Image) {
@try {
// Get screen resolution
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [[UIScreen mainScreen] scale];

// Compare with previous snapshot
if (previousSnapshot && [previousSnapshot isEqualToString:base64Image]) {
stableInRow++;
} else {
stableInRow = 0;
}
previousSnapshot = base64Image;
finalSnapshot = base64Image;
// Create resolution dictionary
NSDictionary *resolution = @{
@"width": @(screenSize.width * scale),
@"height": @(screenSize.height * scale)
};

BOOL isStabilized = (stableInRow > 0 && elapsedTime > STABILIZATION_THRESHOLD);
BOOL isTimedOut = (elapsedTime > STABILIZATION_TIMEOUT);
// Create final result dictionary
NSDictionary *result = @{
@"resolution": resolution,
@"base64": base64Image,
@"inspectorData": [NSJSONSerialization JSONObjectWithData:[inspectorData dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:nil]
};

if (isStabilized || isTimedOut) {
// Now that we have the final snapshot, gather additional data
NSError *inspectorError = nil;
NSString *inspectorData = [InspectorHelper dumpBoundaries:&inspectorError];

if (inspectorError) {
reject(@"error", @"Failed to get inspector data", inspectorError);
return;
}

CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [[UIScreen mainScreen] scale];

NSDictionary *result = @{
@"resolution": @{
@"width": @(screenSize.width * scale),
@"height": @(screenSize.height * scale)
},
@"base64": finalSnapshot,
@"inspectorData": [NSJSONSerialization JSONObjectWithData:[inspectorData dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:nil],
@"isUnstable": @(stableInRow == 0)
};

NSError *jsonError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result
options:0
error:&jsonError];

if (jsonError) {
reject(@"error", @"Failed to create JSON result", jsonError);
return;
}

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
resolve(jsonString);
} else {
// Continue capturing
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, STABILIZATION_INTERVAL * NSEC_PER_SEC),
dispatch_get_main_queue(),
captureAndCheck);
// Convert to JSON string
NSError *jsonError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result
options:0
error:&jsonError];

if (jsonError) {
reject(@"error", @"Failed to create JSON result", jsonError);
return;
}
} reject:reject];
};

// Start the capture loop
captureAndCheck();

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
resolve(jsonString);
} @catch (NSException *exception) {
reject(@"error", exception.reason, nil);
}
} reject:reject];

} @catch (NSException *exception) {
reject(@"error", exception.reason, nil);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,11 @@ function getStorybook(view: StorybookView, params?: StorybookParams): () => Reac

let snapshotBase64;
let inspectorData;
let isUnstable;
if (!containsError) {
const snapshot = await SherloModule.getSnapshot();
const snapshotJSON = JSON.parse(snapshot);
snapshotBase64 = snapshotJSON?.base64;
inspectorData = JSON.stringify(snapshotJSON?.inspectorData);
isUnstable = snapshotJSON?.isUnstable;
}

RunnerBridge.log('requesting screenshot from master script', {
Expand All @@ -96,7 +94,6 @@ function getStorybook(view: StorybookView, params?: StorybookParams): () => Reac
hasError: containsError,
inspectorData: !!inspectorData,
snapshotBase64: !!snapshotBase64,
isUnstable: !!isUnstable,
});

await SherloModule.clearFocus();
Expand All @@ -106,7 +103,6 @@ function getStorybook(view: StorybookView, params?: StorybookParams): () => Reac
hasError: containsError,
inspectorData,
snapshotBase64,
isUnstable,
});

RunnerBridge.log('received screenshot from master script', response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export type AppProtocolItem =
hasError?: boolean;
inspectorData?: string;
snapshotBase64?: string;
isUnstable?: boolean;
};

export type AckStartProtocolItem = {
Expand Down
4 changes: 2 additions & 2 deletions testing/expo-storybook-8/builds/development/android.apk
Git LFS file not shown
4 changes: 2 additions & 2 deletions testing/expo-storybook-8/builds/development/ios.tar.gz
Git LFS file not shown

0 comments on commit cd45a64

Please sign in to comment.