diff --git a/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java b/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java index 4fff13f19..499581e14 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java +++ b/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java @@ -15,6 +15,7 @@ import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsControllerCompat; import androidx.webkit.WebViewCompat; +import com.getcapacitor.JSObject; import com.getcapacitor.Logger; import com.getcapacitor.Plugin; import com.getcapacitor.PluginCall; @@ -157,6 +158,17 @@ public void setStyle(final PluginCall call) { }); } + @PluginMethod + public void getStyle(final PluginCall call) { + String bar = call.getString("bar", BAR_STATUS_BAR); + + getBridge().executeOnMainThread(() -> { + JSObject ret = new JSObject(); + ret.put("style", bar.equals(BAR_GESTURE_BAR) ? currentGestureBarStyle : currentStatusBarStyle); + call.resolve(ret); + }); + } + @PluginMethod public void show(final PluginCall call) { String bar = call.getString("bar", ""); @@ -299,20 +311,18 @@ private void injectSafeAreaCSS(WindowInsetsCompat insets) { } private void setStyle(String style, String bar) { - if (style.equals(STYLE_DEFAULT)) { - style = getStyleForTheme(); - } + String resolvedStyle = style.equals(STYLE_DEFAULT) ? getStyleForTheme() : style; Window window = getActivity().getWindow(); WindowInsetsControllerCompat windowInsetsControllerCompat = WindowCompat.getInsetsController(window, window.getDecorView()); if (bar.isEmpty() || bar.equals(BAR_STATUS_BAR)) { currentStatusBarStyle = style; - windowInsetsControllerCompat.setAppearanceLightStatusBars(!style.equals(STYLE_DARK)); + windowInsetsControllerCompat.setAppearanceLightStatusBars(!resolvedStyle.equals(STYLE_DARK)); } if (bar.isEmpty() || bar.equals(BAR_GESTURE_BAR)) { currentGestureBarStyle = style; - windowInsetsControllerCompat.setAppearanceLightNavigationBars(!style.equals(STYLE_DARK)); + windowInsetsControllerCompat.setAppearanceLightNavigationBars(!resolvedStyle.equals(STYLE_DARK)); } getActivity().getWindow().getDecorView().setBackgroundColor(getThemeColor(getContext(), android.R.attr.windowBackground)); diff --git a/android/capacitor/src/test/java/com/getcapacitor/plugin/SystemBarsTest.java b/android/capacitor/src/test/java/com/getcapacitor/plugin/SystemBarsTest.java index 796c0fe08..0503a2272 100644 --- a/android/capacitor/src/test/java/com/getcapacitor/plugin/SystemBarsTest.java +++ b/android/capacitor/src/test/java/com/getcapacitor/plugin/SystemBarsTest.java @@ -1,12 +1,19 @@ package com.getcapacitor.plugin; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.util.TypedValue; import android.view.View; import android.view.Window; import androidx.appcompat.app.AppCompatActivity; @@ -15,8 +22,12 @@ import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsControllerCompat; import com.getcapacitor.Bridge; +import com.getcapacitor.JSObject; +import com.getcapacitor.PluginCall; import java.lang.reflect.Method; import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; public class SystemBarsTest { @@ -48,6 +59,111 @@ public void showWithNavigationBarShowsOnlyNavigationBars() throws Exception { verify(controller, never()).show(WindowInsetsCompat.Type.statusBars()); } + @Test + public void getStyleReturnsDefaultAfterSettingDefault() throws Exception { + try (StyleFixture fixture = new StyleFixture()) { + fixture.setStyle("DEFAULT", ""); + + verify(fixture.controller).setAppearanceLightStatusBars(true); + assertEquals("DEFAULT", fixture.getStyle("StatusBar")); + assertEquals("DEFAULT", fixture.getStyle("NavigationBar")); + } + } + + @Test + public void getStyleReturnsStyleOfRequestedBar() throws Exception { + try (StyleFixture fixture = new StyleFixture()) { + fixture.setStyle("LIGHT", ""); + fixture.setStyle("DARK", "NavigationBar"); + + assertEquals("LIGHT", fixture.getStyle("StatusBar")); + assertEquals("DARK", fixture.getStyle("NavigationBar")); + } + } + + @Test + public void getStyleDefaultsToStatusBar() throws Exception { + try (StyleFixture fixture = new StyleFixture()) { + fixture.setStyle("DARK", "StatusBar"); + + assertEquals("DARK", fixture.getStyle(null)); + } + } + + @Test + public void configurationChangeReappliesDefaultStyleForNewTheme() throws Exception { + try (StyleFixture fixture = new StyleFixture()) { + fixture.setStyle("DEFAULT", ""); + verify(fixture.controller).setAppearanceLightStatusBars(true); + verify(fixture.controller).setAppearanceLightNavigationBars(true); + + fixture.configuration.uiMode = Configuration.UI_MODE_NIGHT_YES; + fixture.plugin.handleOnConfigurationChanged(fixture.configuration); + + verify(fixture.controller).setAppearanceLightStatusBars(false); + verify(fixture.controller).setAppearanceLightNavigationBars(false); + } + } + + private static class StyleFixture implements AutoCloseable { + + final SystemBars plugin = new SystemBars(); + final Configuration configuration = mock(Configuration.class); + final WindowInsetsControllerCompat controller = mock(WindowInsetsControllerCompat.class); + private final MockedStatic windowCompat = mockStatic(WindowCompat.class); + private final MockedConstruction typedValues = mockConstruction(TypedValue.class); + + StyleFixture() { + Bridge bridge = mock(Bridge.class); + AppCompatActivity activity = mock(AppCompatActivity.class); + Resources resources = mock(Resources.class); + Context context = mock(Context.class); + Window window = mock(Window.class); + View decorView = mock(View.class); + + configuration.uiMode = Configuration.UI_MODE_NIGHT_NO; + when(bridge.getActivity()).thenReturn(activity); + when(bridge.getContext()).thenReturn(context); + when(context.getTheme()).thenReturn(mock(Resources.Theme.class)); + when(activity.getResources()).thenReturn(resources); + when(resources.getConfiguration()).thenReturn(configuration); + when(activity.getWindow()).thenReturn(window); + when(window.getDecorView()).thenReturn(decorView); + doAnswer((invocation) -> { + ((Runnable) invocation.getArgument(0)).run(); + return null; + }) + .when(bridge) + .executeOnMainThread(any(Runnable.class)); + windowCompat.when(() -> WindowCompat.getInsetsController(window, decorView)).thenReturn(controller); + + plugin.setBridge(bridge); + } + + void setStyle(String style, String bar) throws Exception { + Method setStyle = SystemBars.class.getDeclaredMethod("setStyle", String.class, String.class); + setStyle.setAccessible(true); + setStyle.invoke(plugin, style, bar); + } + + String getStyle(String bar) { + PluginCall call = mock(PluginCall.class); + when(call.getString("bar", "StatusBar")).thenReturn(bar == null ? "StatusBar" : bar); + + plugin.getStyle(call); + + ArgumentCaptor result = ArgumentCaptor.forClass(JSObject.class); + verify(call).resolve(result.capture()); + return result.getValue().getString("style"); + } + + @Override + public void close() { + typedValues.close(); + windowCompat.close(); + } + } + @Test public void bottomInsetIsNavigationBarWhenKeyboardHidden() throws Exception { assertEquals(126, invokeGetBottomInset(126, 0, false)); diff --git a/core/src/core-plugins.ts b/core/src/core-plugins.ts index a1efe9c90..fa99a0a47 100644 --- a/core/src/core-plugins.ts +++ b/core/src/core-plugins.ts @@ -1,4 +1,4 @@ -import type { Plugin } from './definitions'; +import type { Plugin, PluginListenerHandle } from './definitions'; import { registerPlugin } from './global'; import { WebPlugin } from './web-plugin'; @@ -604,6 +604,27 @@ export interface SystemBarsAnimationOptions { animation: SystemBarsAnimation; } +export interface SystemBarsGetStyleOptions { + /** + * The system bar to get the style of. + * + * On iOS, only the status bar has a style, so this option is ignored. + * + * @since 9.0.0 + * @default 'StatusBar' + */ + bar?: SystemBarType; +} + +export interface SystemBarsGetStyleResult { + /** + * The style last set for the system bar, using `setStyle()` or the `style` configuration value. + * + * @since 9.0.0 + */ + style: SystemBarsStyle; +} + export interface SystemBarsPlugin { /** * Set the current style of the system bars. @@ -612,6 +633,16 @@ export interface SystemBarsPlugin { */ setStyle(options: SystemBarsStyleOptions): Promise; + /** + * Get the current style of a system bar. + * + * Returns the style that was requested, so `DEFAULT` is returned as `DEFAULT` + * rather than the `LIGHT` or `DARK` style it currently resolves to. + * + * @since 9.0.0 + */ + getStyle(options?: SystemBarsGetStyleOptions): Promise; + /** * Show the system bars. * @@ -634,6 +665,22 @@ export interface SystemBarsPlugin { * @since 8.0.0 */ setAnimation(options: SystemBarsAnimationOptions): Promise; + + /** + * Listen for taps on the status bar. + * + * Only available on iOS. + * + * @since 9.0.0 + */ + addListener(eventName: 'statusTap', listenerFunc: () => void): Promise; + + /** + * Remove all listeners for this plugin. + * + * @since 9.0.0 + */ + removeAllListeners(): Promise; } export class SystemBarsPluginWeb extends WebPlugin implements SystemBarsPlugin { @@ -641,6 +688,10 @@ export class SystemBarsPluginWeb extends WebPlugin implements SystemBarsPlugin { this.unavailable('not available for web'); } + async getStyle(): Promise { + throw this.unavailable('not available for web'); + } + async setAnimation(): Promise { this.unavailable('not available for web'); } diff --git a/core/system-bars.md b/core/system-bars.md index bb9bdd26a..2ec212f03 100644 --- a/core/system-bars.md +++ b/core/system-bars.md @@ -10,6 +10,7 @@ This API differs from the [Status Bar](https://capacitorjs.com/docs/apis/status- | `setBackgroundColor()` | Unsupported | Supported | | `setStyle()` | Supported | Supported - top Status Bar only | | `hide()/show()` | Supported | Supported - top Status Bar only | +| Status bar tap event | `SystemBars.addListener('statusTap', ...)` - iOS only | `window` `statusTap` event - iOS only | ## iOS Note @@ -39,6 +40,11 @@ const setSystemBarStyleLight = async () => { await SystemBars.setStyle({ style: SystemBarsStyle.Light }); }; +const getStatusBarStyle = async () => { + const { style } = await SystemBars.getStyle({ bar: SystemBarType.StatusBar }); + console.log('status bar style', style); +}; + const hideSystemBars = async () => { await SystemBars.hide(); }; @@ -58,6 +64,11 @@ const setStatusBarAnimation = async () => { await SystemBars.setAnimation({ animation: "NONE" }); } +// Listen for taps on the Status Bar, only on iOS +SystemBars.addListener('statusTap', () => { + console.log('status bar tapped'); +}); + ```` ## Configuration @@ -111,9 +122,12 @@ export default config; * [`setStyle(...)`](#setstyle) +* [`getStyle(...)`](#getstyle) * [`show(...)`](#show) * [`hide(...)`](#hide) * [`setAnimation(...)`](#setanimation) +* [`addListener('statusTap', ...)`](#addlistenerstatustap-) +* [`removeAllListeners()`](#removealllisteners) * [Interfaces](#interfaces) * [Type Aliases](#type-aliases) * [Enums](#enums) @@ -140,6 +154,28 @@ Set the current style of the system bars. -------------------- +### getStyle(...) + +```typescript +getStyle(options?: SystemBarsGetStyleOptions) => Promise +``` + +Get the current style of a system bar. + +Returns the style that was requested, so `DEFAULT` is returned as `DEFAULT` +rather than the `LIGHT` or `DARK` style it currently resolves to. + +| Param | Type | +| ------------- | ------------------------------------------------------------------------------- | +| **`options`** | SystemBarsGetStyleOptions | + +**Returns:** Promise<SystemBarsGetStyleResult> + +**Since:** 9.0.0 + +-------------------- + + ### show(...) ```typescript @@ -193,6 +229,41 @@ Only available on iOS. -------------------- +### addListener('statusTap', ...) + +```typescript +addListener(eventName: 'statusTap', listenerFunc: () => void) => Promise +``` + +Listen for taps on the status bar. + +Only available on iOS. + +| Param | Type | +| ------------------ | -------------------------- | +| **`eventName`** | 'statusTap' | +| **`listenerFunc`** | () => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 9.0.0 + +-------------------- + + +### removeAllListeners() + +```typescript +removeAllListeners() => Promise +``` + +Remove all listeners for this plugin. + +**Since:** 9.0.0 + +-------------------- + + ### Interfaces @@ -204,6 +275,20 @@ Only available on iOS. | **`bar`** | SystemBarType | The system bar to which to apply the style. | null | 8.0.0 | +#### SystemBarsGetStyleResult + +| Prop | Type | Description | Since | +| ----------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ----- | +| **`style`** | SystemBarsStyle | The style last set for the system bar, using `setStyle()` or the `style` configuration value. | 9.0.0 | + + +#### SystemBarsGetStyleOptions + +| Prop | Type | Description | Default | Since | +| --------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------ | ----- | +| **`bar`** | SystemBarType | The system bar to get the style of. On iOS, only the status bar has a style, so this option is ignored. | 'StatusBar' | 9.0.0 | + + #### SystemBarsVisibilityOptions | Prop | Type | Description | Default | Since | @@ -219,6 +304,13 @@ Only available on iOS. | **`animation`** | SystemBarsAnimation | The type of status bar animation used when showing or hiding. This option is only supported on iOS. | 'FADE' | 8.0.0 | +#### PluginListenerHandle + +| Prop | Type | +| ------------ | ----------------------------------------- | +| **`remove`** | () => Promise<void> | + + ### Type Aliases diff --git a/ios/Sources/Capacitor/Plugins/SystemBars.swift b/ios/Sources/Capacitor/Plugins/SystemBars.swift index 2c7d6753c..35ab7d68c 100644 --- a/ios/Sources/Capacitor/Plugins/SystemBars.swift +++ b/ios/Sources/Capacitor/Plugins/SystemBars.swift @@ -6,6 +6,7 @@ public class CAPSystemBarsPlugin: CAPPlugin, CAPBridgedPlugin { public let jsName = "SystemBars" public let pluginMethods: [CAPPluginMethod] = [ CAPPluginMethod(name: "setStyle", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getStyle", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "setAnimation", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "show", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "hide", returnType: CAPPluginReturnPromise) @@ -13,6 +14,8 @@ public class CAPSystemBarsPlugin: CAPPlugin, CAPBridgedPlugin { public private(set) var hideHomeIndicator: Bool = false + private var statusBarTapObserver: NSObjectProtocol? + enum Style: String { case dark = "DARK" case light = "LIGHT" @@ -31,6 +34,16 @@ public class CAPSystemBarsPlugin: CAPPlugin, CAPBridgedPlugin { } setHidden(hidden: hidden) + + statusBarTapObserver = NotificationCenter.default.addObserver(forName: .capacitorStatusBarTapped, object: nil, queue: nil) { [weak self] _ in + self?.notifyListeners("statusTap", data: nil) + } + } + + deinit { + if let statusBarTapObserver { + NotificationCenter.default.removeObserver(statusBarTapObserver) + } } @objc func setStyle(_ call: CAPPluginCall) { @@ -38,6 +51,13 @@ public class CAPSystemBarsPlugin: CAPPlugin, CAPBridgedPlugin { call.resolve() } + @objc func getStyle(_ call: CAPPluginCall) { + DispatchQueue.main.async { + let style = Self.style(from: self.bridge?.statusBarStyle ?? .default) + call.resolve(["style": style.rawValue]) + } + } + @objc func show(_ call: CAPPluginCall) { let bar = call.getString("bar") @@ -88,6 +108,17 @@ public class CAPSystemBarsPlugin: CAPPlugin, CAPBridgedPlugin { bridge?.statusBarStyle = newStyle } + static func style(from statusBarStyle: UIStatusBarStyle) -> Style { + switch statusBarStyle { + case .lightContent: + return .dark + case .darkContent: + return .light + default: + return .defaultStyle + } + } + func setHidden(hidden: Bool, bar: String? = nil) { if hidden { if bar == nil || bar?.isEmpty ?? true || bar == "StatusBar" { diff --git a/ios/Tests/CapacitorTests/SystemBarsTests.swift b/ios/Tests/CapacitorTests/SystemBarsTests.swift new file mode 100644 index 000000000..298cc49ce --- /dev/null +++ b/ios/Tests/CapacitorTests/SystemBarsTests.swift @@ -0,0 +1,67 @@ +import XCTest +@testable import Capacitor + +class SpySystemBarsPlugin: CAPSystemBarsPlugin { + var notifiedEvents: [String] = [] + + override func notifyListeners(_ eventName: String, data: [String: Any]?) { + notifiedEvents.append(eventName) + } +} + +class SystemBarsTests: XCTestCase { + private let viewController = MockBridgeViewController() + private lazy var bridge = MockBridge( + with: InstanceConfiguration(with: InstanceDescriptor.init(), isDebug: true), + delegate: viewController, + assetHandler: MockAssetHandler(router: CapacitorRouter()), + delegationHandler: MockDelegationHandler() + ) + + private func makePlugin() -> SpySystemBarsPlugin { + return SpySystemBarsPlugin(bridge: bridge, pluginId: "SystemBars", pluginName: "SystemBars") + } + + func testStatusBarTapNotifiesStatusTapListeners() { + let plugin = makePlugin() + plugin.load() + + NotificationCenter.default.post(name: .capacitorStatusBarTapped, object: nil) + + XCTAssertEqual(plugin.notifiedEvents, ["statusTap"]) + } + + func testDeallocatedPluginStopsObservingStatusBarTaps() { + weak var weakPlugin: SpySystemBarsPlugin? + autoreleasepool { + let plugin = makePlugin() + plugin.load() + weakPlugin = plugin + } + + XCTAssertNil(weakPlugin) + NotificationCenter.default.post(name: .capacitorStatusBarTapped, object: nil) + } + + func testStyleFromStatusBarStyle() { + XCTAssertEqual(CAPSystemBarsPlugin.style(from: .lightContent), .dark) + XCTAssertEqual(CAPSystemBarsPlugin.style(from: .darkContent), .light) + XCTAssertEqual(CAPSystemBarsPlugin.style(from: .default), .defaultStyle) + } + + func testGetStyleReturnsStyleSetBySetStyle() { + let plugin = makePlugin() + let resolved = expectation(description: "getStyle resolves") + var style: String? + let call: CAPPluginCall = CAPPluginCall(callbackId: "test", methodName: "getStyle", options: [:], success: { result, _ in + style = result?.data?["style"] as? String + resolved.fulfill() + }, error: { _ in }) + + plugin.setStyle(style: "DARK") + plugin.getStyle(call) + + wait(for: [resolved], timeout: 1) + XCTAssertEqual(style, "DARK") + } +}