diff --git a/README.md b/README.md index df9dbd7..878de04 100644 --- a/README.md +++ b/README.md @@ -52,16 +52,35 @@ Read about [Setting Permissions](https://capacitorjs.com/docs/android/configurat ## Location Button -Importing `@capacitor/geolocation` registers ``. The plugin +Importing `@capacitor/geolocation` registers `` on Android. The plugin includes the Native Islands runtime, so applications do not install it separately. ```html ``` -On Android, the element renders a native button and emits `location-grant`, -`location-position`, and `location-error` DOM events. Browsers use -`navigator.geolocation`. Native iOS support is not currently provided. +The element shows the system location button on Android 17 and later, and Google's +compatibility button on older versions. It emits `location-grant`, `location-position`, and +`location-error` DOM events. On iOS and web it renders nothing. Call +[`getLocationButtonState()`](#getlocationbuttonstate) to hide the button or show your own control. + +Attributes: `text-type` (`use-precise-location` by default, or `share-precise-location`, +`near-my-precise-location`, `near-your-precise-location`, `precise-location`, `none`), `timeout` +(5000 ms), `maximum-age` (3000 ms) and `enable-location-fallback` (`true`). The system translates +the label, so it can differ from your app's language. + +To grant precise location only through the button, keep `ACCESS_COARSE_LOCATION` and declare +`ACCESS_FINE_LOCATION` with the `onlyForLocationButton` flag: + +```xml + +``` + +On Android 17 and later, the regular API then gets approximate location until the button grants +precise location: after a request, `coarseLocation` is `granted` and `location` is `denied`. Older +versions ignore the flag. Style the element with ordinary CSS. The icon can inherit `color` or use its component-specific custom property: @@ -79,7 +98,8 @@ os-location-button { ``` The native button supports opaque hexadecimal and RGB colors. Border width supports -`0px` through `3px`; the corner radius supports `0px` through `68px`. +`0px` through `3px`; the corner radius supports `0px` through `68px`. Android draws no button +smaller than 48 by 48 pixels. ## API @@ -90,6 +110,7 @@ The native button supports opaque hexadecimal and RGB colors. Border width suppo * [`clearWatch(...)`](#clearwatch) * [`checkPermissions()`](#checkpermissions) * [`requestPermissions(...)`](#requestpermissions) +* [`getLocationButtonState()`](#getlocationbuttonstate) * [Interfaces](#interfaces) * [Type Aliases](#type-aliases) @@ -193,6 +214,23 @@ Not available on web. -------------------- +### getLocationButtonState() + +```typescript +getLocationButtonState() => Promise +``` + +Check which location button this device supports. + +The button is Android only. Use this to hide it, or to show your own control instead. + +**Returns:** Promise<LocationButtonState> + +**Since:** 9.0.0 + +-------------------- + + ### Interfaces @@ -238,6 +276,13 @@ Not available on web. | **`permissions`** | GeolocationPermissionType[] | +#### LocationButtonState + +| Prop | Type | Description | Since | +| ----------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`state`** | 'system' \| 'compat' \| 'unavailable' | `system` on Android 17 and later, where the system draws the button. `compat` on older Android versions, which show Google's compatibility button. `unavailable` on iOS and web, where the `os-location-button` element renders nothing. | 9.0.0 | + + ### Type Aliases diff --git a/android/libs/IONGeolocationLib-debug.aar b/android/libs/IONGeolocationLib-debug.aar index 57a852d..1ff2f30 100644 Binary files a/android/libs/IONGeolocationLib-debug.aar and b/android/libs/IONGeolocationLib-debug.aar differ diff --git a/android/libs/ionnativeislands-android-release.aar b/android/libs/ionnativeislands-android-release.aar index 2e0c4ad..fb32521 100644 Binary files a/android/libs/ionnativeislands-android-release.aar and b/android/libs/ionnativeislands-android-release.aar differ diff --git a/android/src/main/kotlin/com/capacitorjs/plugins/geolocation/GeolocationPlugin.kt b/android/src/main/kotlin/com/capacitorjs/plugins/geolocation/GeolocationPlugin.kt index aee36f4..c80bfb7 100644 --- a/android/src/main/kotlin/com/capacitorjs/plugins/geolocation/GeolocationPlugin.kt +++ b/android/src/main/kotlin/com/capacitorjs/plugins/geolocation/GeolocationPlugin.kt @@ -85,17 +85,13 @@ class GeolocationPlugin : Plugin() { } } - /** Native Islands carrier methods hosted by Geolocation. */ @PluginMethod - fun nativeIslandsLocationButtonCapabilities(call: PluginCall) { - call.resolve( - JSObject().put( - "requiresUnobscuredSurface", - IONGLOCLocationButtonRegistry.requiresUnobscuredSurface(), - ), - ) + fun getLocationButtonState(call: PluginCall) { + val state = if (IONGLOCLocationButtonRegistry.requiresUnobscuredSurface()) "system" else "compat" + call.resolve(JSObject().put("state", state)) } + /** Native Islands carrier methods hosted by Geolocation. */ @PluginMethod fun nativeIslandsApplyLayout(call: PluginCall) { nativeIslandsController.submitLayout(call.data, failure = { code, message -> call.reject(message, code) }) { diff --git a/example-app-location-button/android/app/src/main/AndroidManifest.xml b/example-app-location-button/android/app/src/main/AndroidManifest.xml index 572c80d..a8368c1 100644 --- a/example-app-location-button/android/app/src/main/AndroidManifest.xml +++ b/example-app-location-button/android/app/src/main/AndroidManifest.xml @@ -2,7 +2,9 @@ - +

- Renders the system LocationButton on Android 17+ (compileSdk 37), falling back to an - AppCompat replica below that. Tapping requests precise location directly — no - separate permission step. On grant, fetchPosition() delegates to the same - IONGLOCController.getCurrentPosition() used by the regular API below. + Android only: the system location button on Android 17 and later, Google's compat + button before that, and nothing on iOS and web.

os-location-button

+

getLocationButtonState(): …

@@ -154,16 +153,16 @@ window.customElements.define(

Fetch options (plugin properties)

- - + +
- - + +
- +

@@ -171,7 +170,7 @@ window.customElements.define(

Layout (app-level CSS — not a plugin feature)

- +
@@ -182,7 +181,7 @@ window.customElements.define(
- +
@@ -213,6 +212,29 @@ window.customElements.define(

Result:


         
+ +
+ +

Permissions

+

+ checkPermissions() and requestPermissions() from the plugin's normal JS API. + coarseLocation asks for ACCESS_COARSE_LOCATION only; location asks for + coarse and fine. +

+

+ +

+

+ +

+

+ +

+ +
+

Result:

+

+        
`; @@ -222,6 +244,9 @@ window.customElements.define( const self = this; const locationButton = self.shadowRoot.querySelector('os-location-button'); + Geolocation.getLocationButtonState().then(({ state }) => { + self.shadowRoot.querySelector('#lb-state').textContent = state; + }); const locationButtonEventsList = self.shadowRoot.querySelector('#location-button-events-list'); function logLocationButtonEvent(text) { @@ -318,8 +343,6 @@ window.customElements.define( }); // Fetch option controls — each maps to a real plugin-supported HTML attribute. - // `timeout`/`maximum-age` apply on every platform; `enable-location-fallback` is Android-only - // (silently ignored on iOS/web, per the regular getCurrentPosition() API it delegates to). bindRange('lb-timeout', 'lb-timeout-value', (value) => { locationButton.setAttribute('timeout', value); }); @@ -382,6 +405,31 @@ window.customElements.define( resultElement.textContent = `Error: code=${exception.code} message="${exception.message}"`; } }); + + const permissionsResult = self.shadowRoot.querySelector('#permissions-result'); + + async function showPermissions(label, action) { + try { + const status = await action(); + permissionsResult.textContent = `${label}:\n${JSON.stringify(status, null, 2)}`; + } catch (exception) { + permissionsResult.textContent = `${label} error: code=${exception.code} message="${exception.message}"`; + } + } + + self.shadowRoot.querySelector('#check-permissions').addEventListener('click', () => { + showPermissions('checkPermissions()', () => Geolocation.checkPermissions()); + }); + self.shadowRoot.querySelector('#request-permissions-coarse').addEventListener('click', () => { + showPermissions("requestPermissions({ permissions: ['coarseLocation'] })", () => + Geolocation.requestPermissions({ permissions: ['coarseLocation'] }), + ); + }); + self.shadowRoot.querySelector('#request-permissions-coarse-fine').addEventListener('click', () => { + showPermissions("requestPermissions({ permissions: ['location'] })", () => + Geolocation.requestPermissions({ permissions: ['location'] }), + ); + }); } }, ); diff --git a/ios/Sources/GeolocationPlugin/GeolocationPlugin.swift b/ios/Sources/GeolocationPlugin/GeolocationPlugin.swift index a312af5..9ac0564 100644 --- a/ios/Sources/GeolocationPlugin/GeolocationPlugin.swift +++ b/ios/Sources/GeolocationPlugin/GeolocationPlugin.swift @@ -12,7 +12,8 @@ public class GeolocationPlugin: CAPPlugin, CAPBridgedPlugin { .init(name: "watchPosition", returnType: CAPPluginReturnCallback), .init(name: "clearWatch", returnType: CAPPluginReturnPromise), .init(name: "checkPermissions", returnType: CAPPluginReturnPromise), - .init(name: "requestPermissions", returnType: CAPPluginReturnPromise) + .init(name: "requestPermissions", returnType: CAPPluginReturnPromise), + .init(name: "getLocationButtonState", returnType: CAPPluginReturnPromise) ] private var locationService: (any IONGLOCService)? @@ -113,6 +114,10 @@ public class GeolocationPlugin: CAPPlugin, CAPBridgedPlugin { checkPermissions(call) } } + + @objc func getLocationButtonState(_ call: CAPPluginCall) { + call.resolve(["state": "unavailable"]) + } } private extension GeolocationPlugin { diff --git a/src/definitions.ts b/src/definitions.ts index 6838720..340397b 100644 --- a/src/definitions.ts +++ b/src/definitions.ts @@ -75,6 +75,28 @@ export interface GeolocationPlugin { * @since 1.0.0 */ requestPermissions(permissions?: GeolocationPluginPermissions): Promise; + + /** + * Check which location button this device supports. + * + * The button is Android only. Use this to hide it, or to show your own control instead. + * + * @since 9.0.0 + */ + getLocationButtonState(): Promise; +} + +export interface LocationButtonState { + /** + * `system` on Android 17 and later, where the system draws the button. + * + * `compat` on older Android versions, which show Google's compatibility button. + * + * `unavailable` on iOS and web, where the `os-location-button` element renders nothing. + * + * @since 9.0.0 + */ + state: 'system' | 'compat' | 'unavailable'; } export interface ClearWatchOptions { diff --git a/src/location-button.ts b/src/location-button.ts index be5bd1a..c2bd373 100644 --- a/src/location-button.ts +++ b/src/location-button.ts @@ -27,14 +27,14 @@ declare global { } } -const TEXT_LABELS: Record = { - 'use-precise-location': 'Use precise location', - 'share-precise-location': 'Share precise location', - 'near-my-precise-location': 'Near my precise location', - 'near-your-precise-location': 'Near your precise location', - 'precise-location': 'Precise location', - none: 'Share location', -}; +const TEXT_TYPES = [ + 'use-precise-location', + 'share-precise-location', + 'near-my-precise-location', + 'near-your-precise-location', + 'precise-location', + 'none', +]; const STYLE_PROPERTIES = { backgroundColor: 'background-color', @@ -57,8 +57,8 @@ const HEX_COLOR = /^#[0-9A-Fa-f]{6}$/; const RGB_COLOR = /^rgba?\((.+)\)$/; function textType(element: HTMLElement): string { - const value = element.getAttribute('text-type') ?? 'precise-location'; - return value in TEXT_LABELS ? value : 'precise-location'; + const value = element.getAttribute('text-type') ?? 'use-precise-location'; + return TEXT_TYPES.includes(value) ? value : 'use-precise-location'; } function colorStyle(style: CSSStyleDeclaration, name: string, fallback: string): string { @@ -106,158 +106,16 @@ function booleanAttribute(element: HTMLElement, name: string, fallback: boolean) return fallback; } -function dispatch(element: HTMLElement, type: string, detail: T): void { - element.dispatchEvent(new CustomEvent(type, { bubbles: true, composed: true, detail })); -} - -interface LocationPosition { - coords: { - latitude: number; - longitude: number; - accuracy: number; - altitude: number | null; - altitudeAccuracy?: number | null; - heading: number | null; - speed: number | null; - magneticHeading?: number | null; - trueHeading?: number | null; - headingAccuracy?: number | null; - course?: number | null; - }; - timestamp: number; -} - -interface LocationButtonCarrier extends GeolocationPlugin { - nativeIslandsLocationButtonCapabilities(): Promise<{ - requiresUnobscuredSurface?: boolean; - }>; -} - -function toLocationButtonPosition(position: LocationPosition): LocationButtonPositionDetail { - return { - timestamp: position.timestamp, - coords: { - latitude: position.coords.latitude, - longitude: position.coords.longitude, - accuracy: position.coords.accuracy, - altitude: position.coords.altitude, - altitudeAccuracy: position.coords.altitudeAccuracy, - heading: position.coords.heading, - speed: position.coords.speed, - magneticHeading: position.coords.magneticHeading, - trueHeading: position.coords.trueHeading, - headingAccuracy: position.coords.headingAccuracy, - course: position.coords.course, - }, - }; -} - -function dispatchPosition(element: HTMLElement, position: LocationPosition): void { - dispatch(element, 'location-position', toLocationButtonPosition(position)); -} - -async function requestNativeFallback(element: HTMLElement, geolocationPlugin: GeolocationPlugin): Promise { - try { - const position = await geolocationPlugin.getCurrentPosition({ - enableHighAccuracy: true, - timeout: nonNegativeIntegerAttribute(element, 'timeout', 10_000, 1), - maximumAge: nonNegativeIntegerAttribute(element, 'maximum-age', 0), - enableLocationFallback: booleanAttribute(element, 'enable-location-fallback', true), - }); - dispatch(element, 'location-grant', { granted: true }); - dispatchPosition(element, position); - } catch (error) { - const code = (error as { code?: unknown } | undefined)?.code; - if (code === 'OS-PLUG-GLOC-0003' || code === 'OS-PLUG-GLOC-0008') { - dispatch(element, 'location-grant', { granted: false }); - } - dispatch(element, 'location-error', { - reason: error instanceof Error && error.message ? error.message : 'Location request failed', - code: typeof code === 'string' ? code : undefined, - }); - } -} - -function browserFallback(element: HTMLElement, geolocationPlugin: GeolocationPlugin): void { - // Same shadow-DOM concern as the native path's getProperties() call: this is the actual - // fallback face used in PWA/web, on iOS, and whenever native composition isn't available. - // Without this, an element nested inside a shadow root never gets the plugin's sizing CSS and - // collapses to zero size — clicking "does nothing" because there's nothing there to click, not - // because the handler is broken. - installFallbackStyles(styleRootFor(element)); - element.dataset.osLocationButtonFallbackFace = ''; - const button = document.createElement('button'); - button.type = 'button'; - button.className = 'os-location-button-fallback'; - const normalizedTextType = textType(element); - const label = TEXT_LABELS[normalizedTextType]; - const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - icon.classList.add('os-location-button-fallback__icon'); - icon.setAttribute('viewBox', '0 0 960 960'); - icon.setAttribute('aria-hidden', 'true'); - const iconPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - iconPath.setAttribute( - 'd', - 'M440 918v-80q-125-14-214.5-103.5T122 520H42v-80h80q14-125 103.5-214.5T440 122V42h80v80q125 14 214.5 103.5T838 440h80v80h-80q-14 125-103.5 214.5T520 838v80h-80Zm40-158q116 0 198-82t82-198q0-116-82-198t-198-82q-116 0-198 82t-82 198q0 116 82 198t198 82Zm0-120q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 66-47 113t-113 47Zm0-80q33 0 56.5-23.5T560 480q0-33-23.5-56.5T480 400q-33 0-56.5 23.5T400 480q0 33 23.5 56.5T480 560Z', - ); - icon.append(iconPath); - const text = document.createElement('span'); - text.className = normalizedTextType === 'none' ? 'os-location-button-fallback__visually-hidden' : ''; - text.textContent = label; - button.append(icon, text); - button.setAttribute('aria-label', label); - button.addEventListener('click', () => { - if (Capacitor.getPlatform() !== 'web') { - void requestNativeFallback(element, geolocationPlugin); - return; - } - if (!navigator.geolocation) { - dispatch(element, 'location-error', { - reason: 'Browser geolocation is unavailable', - }); - return; - } - navigator.geolocation.getCurrentPosition( - (position) => { - dispatch(element, 'location-grant', { - granted: true, - }); - dispatchPosition(element, position); - }, - (error) => { - if (error.code === error.PERMISSION_DENIED) { - dispatch(element, 'location-grant', { - granted: false, - }); - } - dispatch(element, 'location-error', { - reason: error.message || 'Browser location request failed', - }); - }, - { - enableHighAccuracy: true, - timeout: nonNegativeIntegerAttribute(element, 'timeout', 10_000, 1), - maximumAge: nonNegativeIntegerAttribute(element, 'maximum-age', 0), - }, - ); - }); - element.replaceChildren(button); -} - const installedStyleRoots = new WeakSet(); -// A native island's host element can live inside a shadow root (e.g. an app wrapping its UI in a -// custom element with attachShadow()). Shadow DOM style encapsulation means CSS appended to -// document.head never reaches it, so an element that gets emptied once native composition -// activates (see clearChildren() in the shared runtime) has no sizing CSS and collapses to zero -// height. Resolving the actual root here lets installFallbackStyles() inject a scoped copy where -// the element really lives, not just into the top-level document. +// The element can live inside a shadow root, which CSS in document.head never reaches. Without its +// sizing CSS it collapses to zero size and the native button has nothing to fill. function styleRootFor(element: HTMLElement): Document | ShadowRoot { const root = element.getRootNode(); return root instanceof ShadowRoot ? root : document; } -function installFallbackStyles(root: Document | ShadowRoot = document): void { +function installStyles(root: Document | ShadowRoot = document): void { if (installedStyleRoots.has(root)) return; installedStyleRoots.add(root); if (root.querySelector('style[data-os-location-button]')) return; @@ -267,7 +125,7 @@ function installFallbackStyles(root: Document | ShadowRoot = document): void { style.textContent = ` :where(os-location-button) { display: inline-block; - inline-size: min(100%, 22rem); + inline-size: 100%; min-inline-size: 3rem; block-size: 3rem; min-block-size: 3rem; @@ -280,72 +138,11 @@ function installFallbackStyles(root: Document | ShadowRoot = document): void { color: #ffffff; } - :where([data-os-location-button-fallback-face]) { + :where(os-location-button[data-native-islands-fallback]) { background-clip: text !important; border-image-source: linear-gradient(transparent, transparent) !important; border-image-slice: 1 !important; } - - .os-location-button-fallback { - position: relative; - isolation: isolate; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 0.5rem; - inline-size: 100%; - block-size: 100%; - min-inline-size: 3rem; - min-block-size: 3rem; - padding-inline: 1rem; - border: inherit; - border-image-source: linear-gradient(transparent, transparent); - border-image-slice: 1; - border-radius: inherit; - background-color: inherit; - background-clip: text; - color: inherit; - font: 500 0.875rem/1.25rem Roboto, system-ui, sans-serif; - letter-spacing: 0.007142857em; - } - - .os-location-button-fallback::before { - content: ''; - position: absolute; - inset: 0; - z-index: 0; - box-sizing: border-box; - border-width: inherit; - border-style: inherit; - border-color: inherit; - border-radius: inherit; - background-color: inherit; - } - - .os-location-button-fallback > * { - position: relative; - z-index: 1; - } - - .os-location-button-fallback__icon { - color: var(--os-location-button-icon-color, currentColor); - inline-size: 1.25rem; - block-size: 1.25rem; - flex: 0 0 auto; - fill: currentColor; - } - - .os-location-button-fallback__visually-hidden { - position: absolute; - inline-size: 1px; - block-size: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; - border: 0; - } `; if (root instanceof ShadowRoot) { @@ -369,18 +166,7 @@ function installFallbackStyles(root: Document | ShadowRoot = document): void { ); } -async function requiresUnobscuredSurface(geolocationPlugin: GeolocationPlugin): Promise { - const carrier = geolocationPlugin as LocationButtonCarrier; - if (typeof carrier.nativeIslandsLocationButtonCapabilities !== 'function') return true; - try { - const capabilities = await carrier.nativeIslandsLocationButtonCapabilities(); - return capabilities.requiresUnobscuredSurface !== false; - } catch { - return true; - } -} - -function registerLocationButton(geolocationPlugin: GeolocationPlugin, protectedSurface: boolean): void { +function registerLocationButton(protectedSurface: boolean): void { if ( typeof document === 'undefined' || typeof HTMLElement === 'undefined' || @@ -390,31 +176,6 @@ function registerLocationButton(geolocationPlugin: GeolocationPlugin, protectedS return; } - installFallbackStyles(); - - if (Capacitor.isNativePlatform() && Capacitor.getPlatform() !== 'android') { - class OsLocationButtonFallback extends HTMLElement { - private connected = false; - - static get observedAttributes(): string[] { - return OBSERVED_ATTRIBUTES; - } - - connectedCallback(): void { - if (this.connected) return; - this.connected = true; - browserFallback(this, geolocationPlugin); - } - - attributeChangedCallback(_name: string, oldValue: string | null, newValue: string | null): void { - if (this.connected && oldValue !== newValue) browserFallback(this, geolocationPlugin); - } - } - - customElements.define('os-location-button', OsLocationButtonFallback); - return; - } - defineNativeIsland({ tagName: 'os-location-button', nativeComponent: 'os.locationButton', @@ -428,7 +189,7 @@ function registerLocationButton(geolocationPlugin: GeolocationPlugin, protectedS // Runs synchronously during connectedCallback() (activateNative() -> send('create')), // before any async/rAF-scheduled geometry measurement — early enough to guarantee the // element has sizing CSS before it's first measured, even inside a shadow root. - installFallbackStyles(styleRootFor(element)); + installStyles(styleRootFor(element)); const style = getComputedStyle(element); const cornerRadius = pixelStyle(style, 'border-top-left-radius', 0, 68, 16); const textColor = colorStyle(style, STYLE_PROPERTIES.textColor, '#FFFFFF'); @@ -440,12 +201,12 @@ function registerLocationButton(geolocationPlugin: GeolocationPlugin, protectedS strokeColor: colorStyle(style, STYLE_PROPERTIES.strokeColor, '#000000'), cornerRadius, strokeWidth: pixelStyle(style, STYLE_PROPERTIES.strokeWidth, 0, 3, 0), - maximumAge: nonNegativeIntegerAttribute(element, 'maximum-age', 0), - timeout: nonNegativeIntegerAttribute(element, 'timeout', 10_000, 1), + maximumAge: nonNegativeIntegerAttribute(element, 'maximum-age', 3_000), + timeout: nonNegativeIntegerAttribute(element, 'timeout', 5_000, 1), enableLocationFallback: booleanAttribute(element, 'enable-location-fallback', true), }; }, - renderFallback: (element) => browserFallback(element, geolocationPlugin), + renderFallback: () => undefined, events: { grant: 'location-grant', position: 'location-position', @@ -455,45 +216,51 @@ function registerLocationButton(geolocationPlugin: GeolocationPlugin, protectedS } export function registerLocationButtonElement(geolocationPlugin: GeolocationPlugin): void { - if (Capacitor.getPlatform() === 'android') { - const dedicatedNativeIslands = Capacitor.isPluginAvailable('NativeIslands'); - - initializeNativeIslands( - createCapacitorTransport( - dedicatedNativeIslands - ? { - pluginName: 'NativeIslands', - platforms: ['android'], - } - : { - pluginName: 'Geolocation', - plugin: geolocationPlugin, - methods: { - applyLayout: 'nativeIslandsApplyLayout', - applyScrollOffsets: 'nativeIslandsApplyScrollOffsets', - command: 'nativeIslandsCommand', - reset: 'nativeIslandsReset', - }, - eventPrefix: 'nativeIslands:', - platforms: ['android'], - }, - ), - { - identity: dedicatedNativeIslands ? '@capacitor/native-islands' : '@capacitor/geolocation/location-button', - priority: dedicatedNativeIslands - ? NATIVE_ISLANDS_TRANSPORT_PRIORITY.dedicated - : NATIVE_ISLANDS_TRANSPORT_PRIORITY.carrier, - }, - ); - } - - if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { - installFallbackStyles(); - void requiresUnobscuredSurface(geolocationPlugin).then((protectedSurface) => { - registerLocationButton(geolocationPlugin, protectedSurface); - }); + if (Capacitor.getPlatform() !== 'android') { + if (typeof customElements !== 'undefined' && !customElements.get('os-location-button')) { + customElements.define( + 'os-location-button', + class extends HTMLElement { + connectedCallback(): void { + this.style.setProperty('display', 'none', 'important'); + } + }, + ); + } return; } - registerLocationButton(geolocationPlugin, false); + const dedicatedNativeIslands = Capacitor.isPluginAvailable('NativeIslands'); + initializeNativeIslands( + createCapacitorTransport( + dedicatedNativeIslands + ? { + pluginName: 'NativeIslands', + platforms: ['android'], + } + : { + pluginName: 'Geolocation', + plugin: geolocationPlugin, + methods: { + applyLayout: 'nativeIslandsApplyLayout', + applyScrollOffsets: 'nativeIslandsApplyScrollOffsets', + command: 'nativeIslandsCommand', + reset: 'nativeIslandsReset', + }, + eventPrefix: 'nativeIslands:', + platforms: ['android'], + }, + ), + { + identity: dedicatedNativeIslands ? '@capacitor/native-islands' : '@capacitor/geolocation/location-button', + priority: dedicatedNativeIslands + ? NATIVE_ISLANDS_TRANSPORT_PRIORITY.dedicated + : NATIVE_ISLANDS_TRANSPORT_PRIORITY.carrier, + }, + ); + + void geolocationPlugin.getLocationButtonState().then(({ state }) => { + installStyles(); + registerLocationButton(state === 'system'); + }); } diff --git a/src/web.ts b/src/web.ts index 98bc555..e10da4e 100644 --- a/src/web.ts +++ b/src/web.ts @@ -3,6 +3,7 @@ import { WebPlugin } from '@capacitor/core'; import type { CallbackID, GeolocationPlugin, + LocationButtonState, PermissionStatus, Position, PositionOptions, @@ -135,6 +136,10 @@ export class GeolocationWeb extends WebPlugin implements GeolocationPlugin { async requestPermissions(): Promise { throw this.unimplemented('Not implemented on web.'); } + + async getLocationButtonState(): Promise { + return { state: 'unavailable' }; + } } const Geolocation = new GeolocationWeb(); diff --git a/test/native-islands-carrier.test.mjs b/test/native-islands-carrier.test.mjs index 41e2951..158e659 100644 --- a/test/native-islands-carrier.test.mjs +++ b/test/native-islands-carrier.test.mjs @@ -7,7 +7,7 @@ const transport = readFileSync(new URL('../src/location-button.ts', import.meta. test('Native Islands subscribes before location-button registration can apply layout', () => { const registration = transport.slice(transport.indexOf('export function registerLocationButtonElement')); const initialize = registration.indexOf('initializeNativeIslands('); - const register = registration.indexOf('requiresUnobscuredSurface(geolocationPlugin).then'); + const register = registration.indexOf('getLocationButtonState().then'); assert.ok(initialize >= 0); assert.ok(register > initialize); diff --git a/vendor/capacitor-native-islands-1.0.0.tgz b/vendor/capacitor-native-islands-1.0.0.tgz index 6fcd875..ec3f8e1 100644 Binary files a/vendor/capacitor-native-islands-1.0.0.tgz and b/vendor/capacitor-native-islands-1.0.0.tgz differ