@leokwsw/cordova-foldable-helper 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leo Wu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4
+
5
+ Pod::Spec.new do |spec|
6
+ spec.name = 'LeokwswCordovaFoldableHelper'
7
+ spec.version = package['version']
8
+ spec.summary = package['description']
9
+ spec.license = { :type => 'MIT', :file => 'LICENSE' }
10
+ spec.homepage = 'https://www.npmjs.com/package/@leokwsw/cordova-foldable-helper'
11
+ spec.author = 'Leo Wu'
12
+ spec.source = { :http => "https://registry.npmjs.org/#{package['name']}/-/#{package['name'].split('/').last}-#{spec.version}.tgz" }
13
+ spec.source_files = 'ios/Sources/FoldableLayoutPlugin/*.swift'
14
+ spec.ios.deployment_target = '15.0'
15
+ spec.dependency 'Capacitor', '~> 8.0'
16
+ spec.swift_version = '5.0'
17
+ end
package/Package.swift ADDED
@@ -0,0 +1,20 @@
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "LeokwswCordovaFoldableHelper",
6
+ platforms: [.iOS(.v15)],
7
+ products: [
8
+ .library(name: "LeokwswCordovaFoldableHelper", targets: ["FoldableLayoutPlugin"])
9
+ ],
10
+ dependencies: [
11
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
12
+ ],
13
+ targets: [
14
+ .target(
15
+ name: "FoldableLayoutPlugin",
16
+ dependencies: [.product(name: "Capacitor", package: "capacitor-swift-pm")],
17
+ path: "ios/Sources/FoldableLayoutPlugin"
18
+ )
19
+ ]
20
+ )
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # Foldable Layout
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [繁體中文](README.zh-TW.md)
4
+
5
+ The npm package is `@leokwsw/cordova-foldable-helper`. The Cordova plugin ID and Android namespace are `com.leokwsw.foldable`. Android uses Kotlin and iOS uses Swift. The JavaScript entry point includes TypeScript declarations.
6
+
7
+
8
+ A native plugin for Cordova, Capacitor, and Ionic apps on Android and iOS. It reports fold posture, hinge bounds and orientation, and hardware occlusions so a WebView layout can adapt as the device changes.
9
+
10
+ ## Install
11
+
12
+ Use the plugin directory as `<plugin-path>`. Capacitor also accepts the npm tarball directly. For Cordova, extract a tarball first and pass the extracted package directory.
13
+
14
+ ### Capacitor 8 and Ionic with Capacitor
15
+
16
+ Build your web assets before syncing. In an Ionic project, run `ionic build` to generate them. Use JDK 21 for Capacitor Android.
17
+
18
+ ```sh
19
+ npm install "<plugin-path>"
20
+ npx cap sync
21
+ ```
22
+
23
+ ```ts
24
+ import { FoldableLayout } from '@leokwsw/cordova-foldable-helper';
25
+
26
+ const subscription = await FoldableLayout.watch(state => {
27
+ console.log(state.state, state.hingeAngle, state.fold);
28
+ });
29
+
30
+ // Call when the component or page no longer needs updates.
31
+ await subscription.remove();
32
+ ```
33
+
34
+ ### Cordova and Ionic with Cordova
35
+
36
+ Requires `cordova-android` 14+ or `cordova-ios` 8+. For Android, enable Kotlin in your app's `config.xml` before preparing the platform.
37
+
38
+ ```xml
39
+ <platform name="android">
40
+ <preference name="GradlePluginKotlinEnabled" value="true" />
41
+ </platform>
42
+ ```
43
+
44
+ ```sh
45
+ cordova plugin add "<plugin-path>"
46
+ ```
47
+
48
+ On a clean checkout, run the add command before `cordova prepare`. Cordova restores missing plugins by plugin ID, which differs from this package’s npm name.
49
+
50
+ ```js
51
+ document.addEventListener('deviceready', async () => {
52
+ try {
53
+ const subscription = await window.FoldableLayout.watch(console.log);
54
+ // Keep the handle and call subscription.remove() when leaving the page.
55
+ } catch (error) {
56
+ console.error('Could not start fold monitoring', error);
57
+ }
58
+ }, { once: true });
59
+ ```
60
+
61
+ ## API
62
+
63
+ | Method | Behaviour |
64
+ | --- | --- |
65
+ | `watch(listener, onError?)` | Delivers the initial state and subsequent changes. Returns a promise for a handle with an idempotent `remove()` method. |
66
+ | `getState()` | Reads the first available snapshot, then releases the subscription. |
67
+ | `waitForSettle(quietWindow = 400)` | Returns the latest snapshot after the given number of milliseconds with no changes. |
68
+ | `avoidInsets(area, state, options?)` | Computes padding for an active fold and hardware occlusions. Supports `direction: 'ltr' \| 'rtl'`, `avoidFold`, and `avoidCamera`. Both avoidance options default to `true`. |
69
+ | `isPhoneLayout(shortestSide, state, platform)` | Uses a phone layout on iOS foldables while closed. On other devices, uses a phone layout below 600 logical pixels. Pass `ios`, `android`, or `web`. |
70
+
71
+ Posture values are `notFoldable`, `unknown`, `folded`, `halfOpened`, and `unfolded`. `unknown` means hardware was detected and its posture is still unavailable. `hingeAngle` is measured in degrees when available. `fold` is nullable, and `occlusions` is an array. Each region has `left`, `top`, `right`, `bottom`, and `isActive`. A separating fold can be a line. `isLandscape` describes the window aspect ratio and `isVerticalHinge` describes the direction of the hinge.
72
+
73
+ ### Applying fold and camera insets
74
+
75
+ Measure a stable container and apply padding to its child. Recalculate on fold changes and container resizes. Use a viewport meta tag with `width=device-width, initial-scale=1` and measure at the default zoom so DOM coordinates match the native WebView's logical units.
76
+
77
+ ```ts
78
+ const { left, top, right, bottom } = FoldableLayout.avoidInsets(
79
+ container.getBoundingClientRect(),
80
+ state,
81
+ { direction: getComputedStyle(container).direction === 'rtl' ? 'rtl' : 'ltr' },
82
+ );
83
+
84
+ content.style.padding = `${top}px ${right}px ${bottom}px ${left}px`;
85
+ ```
86
+
87
+ ### Platform behaviour
88
+
89
+ - **Android:** Jetpack WindowManager supplies fold geometry and can identify a flat or half-opened fold without an angle sensor. Sensor readings, where available, classify 0° as closed, 175° and above as unfolded, and intermediate angles as half-opened. Fold bounds are relative to the WebView in dp.
90
+ - **iOS:** Build with Xcode 27.1 or later. Hinge and reserved-region tracking runs on iOS 27.1 and later. Fold and camera regions are relative to the WebView in UIKit points. Earlier iOS versions report window orientation with a non-foldable state.
91
+ - **Browser:** The npm entry point reports a non-foldable state and updates orientation on resize. The Cordova global is available after `deviceready` on supported native platforms.
@@ -0,0 +1,93 @@
1
+ # Foldable Layout
2
+
3
+ [English](README.md)
4
+
5
+ 為 Cordova、Capacitor 及 Ionic 提供 Android(Kotlin)和 iOS(Swift)原生摺疊裝置支援。插件提供 JavaScript API 和 TypeScript 型別宣告,可監聽摺疊狀態與鉸鏈位置,並計算避開摺疊區域和鏡頭遮擋所需的留白。
6
+
7
+ - npm 套件名稱為 `@leokwsw/cordova-foldable-helper`。
8
+ - Cordova 插件 ID 和 Android 命名空間為 `com.leokwsw.foldable`。
9
+
10
+ ## 安裝
11
+
12
+ 下列指令中的 `<plugin-path>` 指本機插件目錄。Capacitor 也可以直接安裝 npm 壓縮檔。Cordova 請先解壓壓縮檔,再指定解壓後的套件目錄。
13
+
14
+ ### Capacitor 8 和使用 Capacitor 的 Ionic 專案
15
+
16
+ 同步前請先建置網頁資源。Ionic 專案可以執行 `ionic build`。Capacitor Android 需使用 JDK 21。
17
+
18
+ ```sh
19
+ npm install "<plugin-path>"
20
+ npx cap sync
21
+ ```
22
+
23
+ 同一段程式可用於 JavaScript 和 TypeScript。
24
+
25
+ ```js
26
+ import { FoldableLayout } from '@leokwsw/cordova-foldable-helper';
27
+
28
+ const subscription = await FoldableLayout.watch(state => {
29
+ console.log(state.state, state.hingeAngle, state.fold);
30
+ });
31
+
32
+ // 在頁面或元件卸載時清理監聽。
33
+ await subscription.remove();
34
+ ```
35
+
36
+ ### Cordova 和使用 Cordova 的 Ionic 專案
37
+
38
+ 需使用 `cordova-android` 14 或以上,或 `cordova-ios` 8 或以上。Android 專案請在根目錄的 `config.xml` 啟用 Kotlin,再準備 Android 平台。
39
+
40
+ ```xml
41
+ <platform name="android">
42
+ <preference name="GradlePluginKotlinEnabled" value="true" />
43
+ </platform>
44
+ ```
45
+
46
+ ```sh
47
+ cordova plugin add "<plugin-path>"
48
+ ```
49
+
50
+ 在全新簽出的專案上,請先執行上述安裝指令,再執行 `cordova prepare`。Cordova 會按插件 ID 還原缺少的插件,而此插件的 ID 與 npm 套件名稱不同。
51
+
52
+ ```js
53
+ document.addEventListener('deviceready', async () => {
54
+ try {
55
+ const subscription = await window.FoldableLayout.watch(console.log);
56
+ // 保留 subscription,離開頁面時呼叫 subscription.remove()。
57
+ } catch (error) {
58
+ console.error('無法啟動摺疊狀態監聽', error);
59
+ }
60
+ }, { once: true });
61
+ ```
62
+
63
+ ## API
64
+
65
+ | 方法 | 行為 |
66
+ | --- | --- |
67
+ | `watch(listener, onError?)` | 接收首次狀態與後續更新,並傳回具備 `remove()` 的訂閱物件。可安全重複呼叫 `remove()`。 |
68
+ | `getState()` | 取得首次可用的狀態後釋放訂閱。 |
69
+ | `waitForSettle(quietWindow = 400)` | 等待指定毫秒數內沒有新變更,再傳回最新狀態。 |
70
+ | `avoidInsets(area, state, options?)` | 計算避開啟用中的摺疊區域和硬體遮擋所需的留白。可設定 `direction` 為 `ltr` 或 `rtl`,以及 `avoidFold` 和 `avoidCamera`。兩個避讓選項預設為 `true`。 |
71
+ | `isPhoneLayout(shortestSide, state, platform)` | iOS 摺疊裝置關閉時使用手機版面,其他裝置在最短邊少於 600 邏輯像素時使用手機版面。平台值為 `ios`、`android` 或 `web`。 |
72
+
73
+ 摺疊狀態有 `notFoldable`、`unknown`、`folded`、`halfOpened` 和 `unfolded`。`unknown` 表示已偵測到摺疊硬體,摺疊狀態暫未取得。`hingeAngle` 有讀數時以度數表示。`fold` 可以是 `null`,`occlusions` 是陣列。每個區域均有 `left`、`top`、`right`、`bottom` 和 `isActive`。摺疊區域可以是一條沒有厚度的線。`isLandscape` 反映視窗長寬比例,`isVerticalHinge` 反映鉸鏈方向。
74
+
75
+ ### 套用摺疊與鏡頭留白
76
+
77
+ 量度外層容器,將計出的留白套用至內層元素。在摺疊狀態改變或容器大小變更時重新計算。將 viewport 設為 `width=device-width, initial-scale=1`,並在預設縮放比例下量度,讓 DOM 座標對應 WebView 的邏輯座標。
78
+
79
+ ```js
80
+ const { left, top, right, bottom } = FoldableLayout.avoidInsets(
81
+ container.getBoundingClientRect(),
82
+ state,
83
+ { direction: getComputedStyle(container).direction === 'rtl' ? 'rtl' : 'ltr' },
84
+ );
85
+
86
+ content.style.padding = `${top}px ${right}px ${bottom}px ${left}px`;
87
+ ```
88
+
89
+ ### 平台行為
90
+
91
+ - **Android** 使用 Jetpack WindowManager 取得摺疊區域。沒有角度感測器時,可依 WindowManager 資料識別完全展開與半開狀態。有感測器時,0° 為關閉,175° 起為展開,中間為半開。座標以 WebView 為原點,單位為 dp。
92
+ - **iOS** 使用 Xcode 27.1 或以上建置。iOS 27.1 或以上可追蹤鉸鏈與預留區域,座標以 WebView 為原點,單位為 UIKit points。較早的 iOS 版本會提供視窗方向及 `notFoldable` 狀態。
93
+ - **瀏覽器** npm 入口提供 `notFoldable` 狀態,視窗大小變更時會更新方向。Cordova 的原生全域 API 在 `deviceready` 後可用。
@@ -0,0 +1,43 @@
1
+ buildscript {
2
+ repositories {
3
+ google()
4
+ mavenCentral()
5
+ }
6
+
7
+ dependencies {
8
+ classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.21'
9
+ }
10
+ }
11
+
12
+ apply plugin: 'com.android.library'
13
+ apply plugin: 'org.jetbrains.kotlin.android'
14
+
15
+ android {
16
+ namespace 'com.leokwsw.foldable'
17
+ compileSdk rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
18
+
19
+ defaultConfig {
20
+ minSdk rootProject.ext.has('minSdkVersion') ? rootProject.ext.minSdkVersion : 24
21
+ }
22
+
23
+ compileOptions {
24
+ sourceCompatibility JavaVersion.VERSION_17
25
+ targetCompatibility JavaVersion.VERSION_17
26
+ }
27
+ }
28
+
29
+ kotlin {
30
+ compilerOptions {
31
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
32
+ }
33
+ }
34
+
35
+ def androidxAppCompatVersion = rootProject.ext.has('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1'
36
+ def androidxCoreVersion = rootProject.ext.has('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.17.0'
37
+
38
+ dependencies {
39
+ implementation project(':capacitor-android')
40
+ implementation "androidx.appcompat:appcompat:${androidxAppCompatVersion}"
41
+ implementation "androidx.core:core:${androidxCoreVersion}"
42
+ implementation 'androidx.window:window-java:1.4.0'
43
+ }
@@ -0,0 +1,66 @@
1
+ package com.leokwsw.foldable
2
+
3
+ import org.apache.cordova.CallbackContext
4
+ import org.apache.cordova.CordovaPlugin
5
+ import org.apache.cordova.PluginResult
6
+ import org.json.JSONArray
7
+ import org.json.JSONObject
8
+
9
+ class CordovaFoldableLayout : CordovaPlugin() {
10
+ private val watchers = mutableMapOf<String, CallbackContext>()
11
+ private var monitor: FoldMonitor? = null
12
+ private var paused = false
13
+
14
+ override fun execute(action: String, args: JSONArray, callback: CallbackContext): Boolean {
15
+ if (action != "watch" && action != "unwatch") return false
16
+ val id = args.getString(0)
17
+ cordova.activity.runOnUiThread {
18
+ if (action == "watch") {
19
+ val monitor = monitor ?: FoldMonitor(cordova.activity, webView.view)
20
+ .also { monitor = it }
21
+ val start = watchers.isEmpty() && !paused
22
+ watchers[id] = callback
23
+ if (start) {
24
+ monitor.start(::emit)
25
+ } else if (paused || monitor.isReady) {
26
+ send(callback, monitor.snapshot())
27
+ }
28
+ } else {
29
+ watchers.remove(id)?.sendPluginResult(PluginResult(PluginResult.Status.NO_RESULT))
30
+ if (watchers.isEmpty()) monitor?.stop()
31
+ callback.success()
32
+ }
33
+ }
34
+ return true
35
+ }
36
+
37
+ private fun emit(state: JSONObject) {
38
+ watchers.values.forEach { send(it, state) }
39
+ }
40
+
41
+ private fun send(callback: CallbackContext, state: JSONObject) {
42
+ val result = PluginResult(PluginResult.Status.OK, state)
43
+ result.keepCallback = true
44
+ callback.sendPluginResult(result)
45
+ }
46
+
47
+ override fun onPause(multitasking: Boolean) {
48
+ paused = true
49
+ monitor?.stop()
50
+ }
51
+
52
+ override fun onResume(multitasking: Boolean) {
53
+ paused = false
54
+ if (watchers.isNotEmpty()) monitor?.start(::emit)
55
+ }
56
+
57
+ override fun onReset() {
58
+ cordova.activity.runOnUiThread {
59
+ watchers.values.forEach { it.sendPluginResult(PluginResult(PluginResult.Status.NO_RESULT)) }
60
+ watchers.clear()
61
+ monitor?.stop()
62
+ }
63
+ }
64
+
65
+ override fun onDestroy() = onReset()
66
+ }
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,117 @@
1
+ package com.leokwsw.foldable
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.hardware.Sensor
6
+ import android.hardware.SensorEvent
7
+ import android.hardware.SensorEventListener
8
+ import android.hardware.SensorManager
9
+ import android.view.View
10
+ import android.view.ViewTreeObserver
11
+ import androidx.core.content.ContextCompat
12
+ import androidx.core.util.Consumer
13
+ import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter
14
+ import androidx.window.layout.FoldingFeature
15
+ import androidx.window.layout.WindowInfoTracker
16
+ import androidx.window.layout.WindowLayoutInfo
17
+ import androidx.window.layout.WindowMetricsCalculator
18
+ import org.json.JSONArray
19
+ import org.json.JSONObject
20
+
21
+ internal class FoldMonitor(private val activity: Activity, private val webView: View) : SensorEventListener {
22
+ private val sensors = activity.getSystemService(Context.SENSOR_SERVICE) as SensorManager
23
+ private val hinge = sensors.getDefaultSensor(Sensor.TYPE_HINGE_ANGLE)
24
+ private val tracker = WindowInfoTrackerCallbackAdapter(WindowInfoTracker.getOrCreate(activity))
25
+ private val layoutCallback = Consumer<WindowLayoutInfo>(::onWindowLayout)
26
+ private val viewCallback = ViewTreeObserver.OnGlobalLayoutListener(::emit)
27
+ private var listener: ((JSONObject) -> Unit)? = null
28
+ private var fold: FoldingFeature? = null
29
+ private var angle: Float? = null
30
+ private var previous: String? = null
31
+
32
+ var isReady = false
33
+ private set
34
+
35
+ fun start(listener: (JSONObject) -> Unit) {
36
+ if (this.listener != null) return
37
+ this.listener = listener
38
+ webView.viewTreeObserver.addOnGlobalLayoutListener(viewCallback)
39
+ hinge?.let { sensors.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL) }
40
+ tracker.addWindowLayoutInfoListener(activity, ContextCompat.getMainExecutor(activity), layoutCallback)
41
+ }
42
+
43
+ fun stop() {
44
+ listener = null
45
+ tracker.removeWindowLayoutInfoListener(layoutCallback)
46
+ sensors.unregisterListener(this)
47
+ val observer = webView.viewTreeObserver
48
+ if (observer.isAlive) observer.removeOnGlobalLayoutListener(viewCallback)
49
+ previous = null
50
+ isReady = false
51
+ fold = null
52
+ angle = null
53
+ }
54
+
55
+ fun snapshot(): JSONObject {
56
+ val window = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity).bounds
57
+ val feature = fold
58
+ val angle = angle
59
+ val foldable = feature != null || hinge != null ||
60
+ activity.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")
61
+ val state = when {
62
+ angle != null && angle <= 0 -> "folded"
63
+ angle != null && angle >= 175 -> "unfolded"
64
+ angle != null || feature?.state == FoldingFeature.State.HALF_OPENED -> "halfOpened"
65
+ feature != null -> "unfolded"
66
+ foldable -> "unknown"
67
+ else -> "notFoldable"
68
+ }
69
+
70
+ return JSONObject()
71
+ .put("state", state)
72
+ .put("isFoldableDevice", foldable)
73
+ .put("hingeAngle", angle ?: JSONObject.NULL)
74
+ .put("isLandscape", window.width() > window.height())
75
+ .put("isVerticalHinge", feature?.orientation == FoldingFeature.Orientation.VERTICAL)
76
+ .put("fold", feature?.let(::foldRegion) ?: JSONObject.NULL)
77
+ .put("occlusions", JSONArray())
78
+ }
79
+
80
+ private fun foldRegion(feature: FoldingFeature): JSONObject {
81
+ val bounds = feature.bounds
82
+ val origin = IntArray(2)
83
+ webView.getLocationInWindow(origin)
84
+ val density = webView.resources.displayMetrics.density
85
+ return JSONObject()
86
+ .put("left", (bounds.left - origin[0]) / density)
87
+ .put("top", (bounds.top - origin[1]) / density)
88
+ .put("right", (bounds.right - origin[0]) / density)
89
+ .put("bottom", (bounds.bottom - origin[1]) / density)
90
+ .put("isActive", feature.isSeparating)
91
+ }
92
+
93
+ private fun onWindowLayout(info: WindowLayoutInfo) {
94
+ if (listener == null) return
95
+ isReady = true
96
+ fold = info.displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull()
97
+ emit()
98
+ }
99
+
100
+ private fun emit() {
101
+ val listener = listener ?: return
102
+ if (!isReady) return
103
+ val result = snapshot()
104
+ val serialized = result.toString()
105
+ if (serialized == previous) return
106
+ previous = serialized
107
+ listener(result)
108
+ }
109
+
110
+ override fun onSensorChanged(event: SensorEvent) {
111
+ if (listener == null) return
112
+ angle = event.values.firstOrNull()?.takeIf { it.isFinite() } ?: return
113
+ emit()
114
+ }
115
+
116
+ override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit
117
+ }
@@ -0,0 +1,63 @@
1
+ package com.leokwsw.foldable
2
+
3
+ import com.getcapacitor.JSObject
4
+ import com.getcapacitor.Plugin
5
+ import com.getcapacitor.PluginCall
6
+ import com.getcapacitor.PluginMethod
7
+ import com.getcapacitor.annotation.CapacitorPlugin
8
+
9
+ @CapacitorPlugin(name = "FoldableLayout")
10
+ class FoldableLayoutPlugin : Plugin() {
11
+ private val watchers = mutableSetOf<String>()
12
+ private var monitor: FoldMonitor? = null
13
+ private var paused = false
14
+
15
+ @PluginMethod
16
+ fun start(call: PluginCall) {
17
+ activity.runOnUiThread {
18
+ val id = call.getString("id")
19
+ if (id == null) {
20
+ call.reject("Fold watcher requires an ID")
21
+ return@runOnUiThread
22
+ }
23
+ val monitor = monitor()
24
+ if (watchers.add(id) && watchers.size == 1 && !paused) startMonitor()
25
+ if (paused || monitor.isReady) {
26
+ call.resolve(JSObject.fromJSONObject(monitor.snapshot()))
27
+ } else {
28
+ call.resolve()
29
+ }
30
+ }
31
+ }
32
+
33
+ @PluginMethod
34
+ fun stop(call: PluginCall) {
35
+ activity.runOnUiThread {
36
+ val id = call.getString("id")
37
+ if (id != null && watchers.remove(id) && watchers.isEmpty()) monitor?.stop()
38
+ call.resolve()
39
+ }
40
+ }
41
+
42
+ private fun monitor(): FoldMonitor =
43
+ monitor ?: FoldMonitor(activity, bridge.webView).also { monitor = it }
44
+
45
+ private fun startMonitor() {
46
+ monitor().start { state -> notifyListeners("change", JSObject.fromJSONObject(state)) }
47
+ }
48
+
49
+ override fun handleOnPause() {
50
+ paused = true
51
+ monitor?.stop()
52
+ }
53
+
54
+ override fun handleOnResume() {
55
+ paused = false
56
+ if (watchers.isNotEmpty()) startMonitor()
57
+ }
58
+
59
+ override fun handleOnDestroy() {
60
+ watchers.clear()
61
+ monitor?.stop()
62
+ }
63
+ }
package/index.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ export type FoldPosture = 'notFoldable' | 'unknown' | 'folded' | 'halfOpened' | 'unfolded';
2
+
3
+ export interface Bounds {
4
+ left: number;
5
+ top: number;
6
+ right: number;
7
+ bottom: number;
8
+ }
9
+
10
+ export interface FoldRegion extends Bounds {
11
+ isActive: boolean;
12
+ }
13
+
14
+ export interface FoldState {
15
+ state: FoldPosture;
16
+ isFoldableDevice: boolean;
17
+ hingeAngle: number | null;
18
+ isLandscape: boolean;
19
+ isVerticalHinge: boolean;
20
+ fold: FoldRegion | null;
21
+ occlusions: FoldRegion[];
22
+ }
23
+
24
+ export type Insets = Bounds;
25
+
26
+ export interface InsetOptions {
27
+ direction?: 'ltr' | 'rtl';
28
+ avoidCamera?: boolean;
29
+ avoidFold?: boolean;
30
+ }
31
+
32
+ export interface FoldSubscription {
33
+ remove(): Promise<void>;
34
+ }
35
+
36
+ export interface FoldableLayoutAPI {
37
+ watch(listener: (state: FoldState) => void, onError?: (error: unknown) => void): Promise<FoldSubscription>;
38
+ getState(): Promise<FoldState>;
39
+ waitForSettle(quietWindow?: number): Promise<FoldState>;
40
+ avoidInsets: typeof avoidInsets;
41
+ isPhoneLayout(shortestSide: number, state: FoldState, platform: 'ios' | 'android' | 'web'): boolean;
42
+ }
43
+
44
+ export function avoidInsets(area: Bounds, state: FoldState, options?: InsetOptions): Insets;
45
+ export const FoldableLayout: FoldableLayoutAPI;
46
+
47
+ declare global {
48
+ interface Window {
49
+ FoldableLayout?: FoldableLayoutAPI;
50
+ }
51
+ }
package/index.js ADDED
@@ -0,0 +1,62 @@
1
+ const { createAPI, avoidInsets } = require('./www/layout');
2
+
3
+ let native;
4
+ async function subscribe(id, listener, onError) {
5
+ if (typeof window !== 'undefined' && window.cordova && window.FoldableLayout) {
6
+ return window.FoldableLayout.watch(listener, onError);
7
+ }
8
+
9
+ // The optional peer is only used by Capacitor applications.
10
+ if (typeof window !== 'undefined' && window.Capacitor?.isNativePlatform()) {
11
+ native ??= require('@capacitor/core').registerPlugin('FoldableLayout');
12
+ let active = true;
13
+ let received = false;
14
+ const connection = await native.addListener('change', state => {
15
+ if (!active) return;
16
+ received = true;
17
+ listener(state);
18
+ });
19
+ try {
20
+ const initial = await native.start({ id });
21
+ if (!received && initial?.state) listener(initial);
22
+ } catch (error) {
23
+ active = false;
24
+ await Promise.allSettled([connection.remove(), native.stop({ id })]);
25
+ throw error;
26
+ }
27
+
28
+ let removal;
29
+ return {
30
+ remove() {
31
+ active = false;
32
+ removal ??= Promise.all([connection.remove(), native.stop({ id })]).then(() => undefined);
33
+ return removal;
34
+ }
35
+ };
36
+ }
37
+
38
+ const viewport = typeof window === 'undefined' ? undefined : window;
39
+ const read = () => ({
40
+ state: 'notFoldable',
41
+ isFoldableDevice: false,
42
+ hingeAngle: null,
43
+ isLandscape: viewport ? viewport.innerWidth > viewport.innerHeight : false,
44
+ isVerticalHinge: false,
45
+ fold: null,
46
+ occlusions: []
47
+ });
48
+
49
+ let previous = read();
50
+ listener(previous);
51
+ function resize() {
52
+ const state = read();
53
+ if (state.isLandscape === previous.isLandscape) return;
54
+ previous = state;
55
+ listener(state);
56
+ }
57
+ viewport?.addEventListener('resize', resize);
58
+ return { async remove() { viewport?.removeEventListener('resize', resize); } };
59
+ }
60
+
61
+ exports.FoldableLayout = createAPI(subscribe);
62
+ exports.avoidInsets = avoidInsets;
@@ -0,0 +1,147 @@
1
+ import UIKit
2
+
3
+ final class FoldMonitor {
4
+ private weak var view: UIView?
5
+ private var listener: (([String: Any]) -> Void)?
6
+ private var probe: FoldLayoutProbe?
7
+ private var interaction: UIInteraction?
8
+ private var hinge: AnyObject?
9
+ private var previous: NSDictionary?
10
+
11
+ var isReady: Bool { previous != nil }
12
+
13
+ init(view: UIView) {
14
+ self.view = view
15
+ }
16
+
17
+ func start(_ listener: @escaping ([String: Any]) -> Void) {
18
+ guard let view, self.listener == nil else { return }
19
+ self.listener = listener
20
+ let probe = FoldLayoutProbe(frame: view.bounds)
21
+ probe.autoresizingMask = [.flexibleWidth, .flexibleHeight]
22
+ probe.isUserInteractionEnabled = false
23
+ probe.onChange = { [weak self] in self?.emit() }
24
+ view.addSubview(probe)
25
+ self.probe = probe
26
+
27
+ if #available(iOS 27.1, *) {
28
+ let interaction = UIHingeInteraction { [weak self] _, update in
29
+ self?.hinge = update.hinge
30
+ self?.emit()
31
+ }
32
+ self.interaction = interaction
33
+ probe.addInteraction(interaction)
34
+ }
35
+
36
+ probe.setNeedsUpdateConstraints()
37
+ // Allow the first layout pass to populate the hardware regions.
38
+ DispatchQueue.main.async { [weak self, weak probe] in
39
+ guard let self, let probe, self.probe === probe else { return }
40
+ probe.updateConstraintsIfNeeded()
41
+ self.emit()
42
+ }
43
+ }
44
+
45
+ func stop() {
46
+ listener = nil
47
+ if let interaction { probe?.removeInteraction(interaction) }
48
+ probe?.removeFromSuperview()
49
+ probe = nil
50
+ interaction = nil
51
+ hinge = nil
52
+ previous = nil
53
+ }
54
+
55
+ func snapshot() -> [String: Any] {
56
+ let bounds = view?.window?.rootViewController?.viewIfLoaded?.bounds ?? view?.bounds ?? .zero
57
+ var result: [String: Any] = [
58
+ "state": "notFoldable",
59
+ "isFoldableDevice": false,
60
+ "hingeAngle": NSNull(),
61
+ "isLandscape": bounds.width > bounds.height,
62
+ "isVerticalHinge": false,
63
+ "fold": NSNull(),
64
+ "occlusions": [[String: Any]]()
65
+ ]
66
+
67
+ if #available(iOS 27.1, *) {
68
+ if let hinge = hinge as? UIHinge {
69
+ let angle = hinge.angle * 180 / .pi
70
+ result["isFoldableDevice"] = true
71
+ if angle.isFinite { result["hingeAngle"] = angle }
72
+ switch hinge.status {
73
+ case .closed: result["state"] = "folded"
74
+ case .fullyOpen: result["state"] = "unfolded"
75
+ case .partiallyOpen: result["state"] = "halfOpened"
76
+ default:
77
+ result["state"] = angle.isFinite
78
+ ? (angle <= 0 ? "folded" : angle >= 175 ? "unfolded" : "halfOpened")
79
+ : "unknown"
80
+ }
81
+ }
82
+ if let region = probe?.division {
83
+ result["isFoldableDevice"] = true
84
+ if hinge == nil { result["state"] = "unknown" }
85
+ result["isVerticalHinge"] = region.frame.height > region.frame.width
86
+ result["fold"] = region.payload
87
+ }
88
+ result["occlusions"] = probe?.occlusions.map(\.payload) ?? []
89
+ }
90
+ return result
91
+ }
92
+
93
+ private func emit() {
94
+ guard let listener else { return }
95
+ let state = snapshot()
96
+ if previous?.isEqual(to: state) == true { return }
97
+ previous = state as NSDictionary
98
+ listener(state)
99
+ }
100
+ }
101
+
102
+ private final class FoldLayoutProbe: UIView {
103
+ struct Region {
104
+ let frame: CGRect
105
+ let isActive: Bool
106
+
107
+ var payload: [String: Any] {
108
+ [
109
+ "left": frame.minX, "top": frame.minY,
110
+ "right": frame.maxX, "bottom": frame.maxY,
111
+ "isActive": isActive
112
+ ]
113
+ }
114
+ }
115
+
116
+ var onChange: (() -> Void)?
117
+ private(set) var division: Region?
118
+ private(set) var occlusions: [Region] = []
119
+
120
+ override class var requiresConstraintBasedLayout: Bool { true }
121
+
122
+ override func updateConstraints() {
123
+ if #available(iOS 27.1, *) {
124
+ division = reservedRegions(kind: .division, options: .includeInactive)
125
+ .first.map { Region(frame: $0.frame, isActive: $0.isActive) }
126
+ occlusions = reservedRegions(kind: .occlusion, options: .includeInactive)
127
+ .map { Region(frame: $0.frame, isActive: $0.isActive) }
128
+ }
129
+ super.updateConstraints()
130
+ scheduleChange()
131
+ }
132
+
133
+ override func layoutSubviews() {
134
+ super.layoutSubviews()
135
+ scheduleChange()
136
+ }
137
+
138
+ override func didMoveToWindow() {
139
+ super.didMoveToWindow()
140
+ setNeedsUpdateConstraints()
141
+ scheduleChange()
142
+ }
143
+
144
+ private func scheduleChange() {
145
+ DispatchQueue.main.async { [weak self] in self?.onChange?() }
146
+ }
147
+ }
@@ -0,0 +1,46 @@
1
+ import Capacitor
2
+ import UIKit
3
+
4
+ @objc(FoldableLayoutPlugin)
5
+ public final class FoldableLayoutPlugin: CAPPlugin, CAPBridgedPlugin {
6
+ public let identifier = "FoldableLayoutPlugin"
7
+ public let jsName = "FoldableLayout"
8
+ public let pluginMethods: [CAPPluginMethod] = [
9
+ CAPPluginMethod(name: "start", returnType: CAPPluginReturnPromise),
10
+ CAPPluginMethod(name: "stop", returnType: CAPPluginReturnPromise)
11
+ ]
12
+
13
+ private var watchers: Set<String> = []
14
+ private var monitor: FoldMonitor?
15
+
16
+ @objc public func start(_ call: CAPPluginCall) {
17
+ DispatchQueue.main.async { [self] in
18
+ guard let id = call.getString("id"), let view = self.bridge?.webView else {
19
+ call.reject("Fold watcher requires an ID and an attached WebView")
20
+ return
21
+ }
22
+ let monitor = self.monitor ?? FoldMonitor(view: view)
23
+ self.monitor = monitor
24
+ if self.watchers.insert(id).inserted && self.watchers.count == 1 {
25
+ monitor.start { [weak self] state in self?.notifyListeners("change", data: state) }
26
+ }
27
+ if monitor.isReady { call.resolve(monitor.snapshot()) }
28
+ else { call.resolve() }
29
+ }
30
+ }
31
+
32
+ @objc public func stop(_ call: CAPPluginCall) {
33
+ DispatchQueue.main.async { [self] in
34
+ if let id = call.getString("id"), self.watchers.remove(id) != nil, self.watchers.isEmpty {
35
+ self.monitor?.stop()
36
+ self.monitor = nil
37
+ }
38
+ call.resolve()
39
+ }
40
+ }
41
+
42
+ deinit {
43
+ let monitor = monitor
44
+ DispatchQueue.main.async { monitor?.stop() }
45
+ }
46
+ }
@@ -0,0 +1,62 @@
1
+ import Cordova
2
+ import UIKit
3
+
4
+ @objc(CordovaFoldableLayout)
5
+ final class CordovaFoldableLayout: CDVPlugin {
6
+ private var watchers: [String: String] = [:]
7
+ private var monitor: FoldMonitor?
8
+
9
+ @objc(watch:)
10
+ func watch(_ command: CDVInvokedUrlCommand) {
11
+ guard let id = command.argument(at: 0) as? String, let view = webView else {
12
+ commandDelegate.send(CDVPluginResult(status: .error), callbackId: command.callbackId)
13
+ return
14
+ }
15
+ let monitor = self.monitor ?? FoldMonitor(view: view)
16
+ self.monitor = monitor
17
+ let start = watchers.isEmpty
18
+ watchers[id] = command.callbackId
19
+ if start {
20
+ monitor.start { [weak self] state in
21
+ guard let self else { return }
22
+ for callback in self.watchers.values { self.send(state, to: callback) }
23
+ }
24
+ } else if monitor.isReady {
25
+ send(monitor.snapshot(), to: command.callbackId)
26
+ }
27
+ }
28
+
29
+ @objc(unwatch:)
30
+ func unwatch(_ command: CDVInvokedUrlCommand) {
31
+ if let id = command.argument(at: 0) as? String, let callback = watchers.removeValue(forKey: id) {
32
+ commandDelegate.send(CDVPluginResult(status: .noResult), callbackId: callback)
33
+ }
34
+ if watchers.isEmpty {
35
+ monitor?.stop()
36
+ monitor = nil
37
+ }
38
+ commandDelegate.send(CDVPluginResult(status: .ok), callbackId: command.callbackId)
39
+ }
40
+
41
+ override func onReset() {
42
+ for callback in watchers.values {
43
+ commandDelegate.send(CDVPluginResult(status: .noResult), callbackId: callback)
44
+ }
45
+ watchers.removeAll()
46
+ monitor?.stop()
47
+ monitor = nil
48
+ }
49
+
50
+ override func dispose() {
51
+ watchers.removeAll()
52
+ monitor?.stop()
53
+ monitor = nil
54
+ super.dispose()
55
+ }
56
+
57
+ private func send(_ state: [String: Any], to callback: String) {
58
+ let result = CDVPluginResult(status: .ok, messageAs: state)
59
+ result.setKeepCallbackAs(true)
60
+ commandDelegate.send(result, callbackId: callback)
61
+ }
62
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@leokwsw/cordova-foldable-helper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Fold posture, hinge geometry and layout insets for Cordova and Capacitor",
5
+ "license": "MIT",
6
+ "keywords": ["cordova", "cordova-android", "cordova-ios", "capacitor", "ionic", "foldable"],
7
+ "main": "index.js",
8
+ "types": "index.d.ts",
9
+ "files": ["android", "ios", "www", "index.js", "index.d.ts", "plugin.xml", "Package.swift", "LeokwswCordovaFoldableHelper.podspec", "README.zh-TW.md"],
10
+ "cordova": {
11
+ "id": "com.leokwsw.foldable",
12
+ "platforms": ["android", "ios"]
13
+ },
14
+ "capacitor": {
15
+ "android": { "src": "android" },
16
+ "ios": { "src": "ios/Sources/FoldableLayoutPlugin" }
17
+ },
18
+ "peerDependencies": {
19
+ "@capacitor/core": "^8.0.0"
20
+ },
21
+ "peerDependenciesMeta": {
22
+ "@capacitor/core": { "optional": true }
23
+ },
24
+ "scripts": { "test": "node --test" }
25
+ }
package/plugin.xml ADDED
@@ -0,0 +1,33 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
3
+ id="com.leokwsw.foldable" version="0.1.0">
4
+ <name>FoldableLayout</name>
5
+ <license>MIT</license>
6
+ <engines>
7
+ <engine name="cordova-android" version=">=14.0.0" />
8
+ <engine name="cordova-ios" version=">=8.0.0" />
9
+ </engines>
10
+ <js-module src="www/layout.js" name="layout" />
11
+ <js-module src="www/cordova.js" name="cordova">
12
+ <clobbers target="FoldableLayout" />
13
+ </js-module>
14
+ <platform name="android">
15
+ <config-file target="res/xml/config.xml" parent="/*">
16
+ <feature name="FoldableLayout">
17
+ <param name="android-package" value="com.leokwsw.foldable.CordovaFoldableLayout" />
18
+ </feature>
19
+ </config-file>
20
+ <framework src="androidx.window:window-java:1.4.0" />
21
+ <source-file src="android/src/main/kotlin/com/leokwsw/foldable/FoldMonitor.kt" target-dir="app/src/main/kotlin/com/leokwsw/foldable" />
22
+ <source-file src="android/cordova/CordovaFoldableLayout.kt" target-dir="app/src/main/kotlin/com/leokwsw/foldable" />
23
+ </platform>
24
+ <platform name="ios">
25
+ <config-file target="config.xml" parent="/*">
26
+ <feature name="FoldableLayout">
27
+ <param name="ios-package" value="CordovaFoldableLayout" />
28
+ </feature>
29
+ </config-file>
30
+ <source-file src="ios/Sources/FoldableLayoutPlugin/FoldMonitor.swift" />
31
+ <source-file src="ios/cordova/CordovaFoldableLayout.swift" />
32
+ </platform>
33
+ </plugin>
package/www/cordova.js ADDED
@@ -0,0 +1,27 @@
1
+ const exec = require('cordova/exec');
2
+ const { createAPI } = require('com.leokwsw.foldable.layout');
3
+
4
+ module.exports = createAPI((id, listener, onError) => new Promise((resolve, reject) => {
5
+ let active = true;
6
+ let started = false;
7
+ let removal;
8
+ const handle = {
9
+ remove() {
10
+ active = false;
11
+ removal ??= new Promise((done, fail) => {
12
+ exec(done, fail, 'FoldableLayout', 'unwatch', [id]);
13
+ });
14
+ return removal;
15
+ }
16
+ };
17
+ exec(state => {
18
+ if (!active) return;
19
+ started = true;
20
+ resolve(handle);
21
+ listener(state);
22
+ }, error => {
23
+ active = false;
24
+ if (started) onError?.(error);
25
+ else reject(error);
26
+ }, 'FoldableLayout', 'watch', [id]);
27
+ }));
package/www/layout.js ADDED
@@ -0,0 +1,91 @@
1
+ function avoidInsets(area, info, options = {}) {
2
+ const { direction = 'ltr', avoidCamera = true, avoidFold = true } = options;
3
+ const insets = { left: 0, top: 0, right: 0, bottom: 0 };
4
+ const width = Math.max(0, area.right - area.left);
5
+ const height = Math.max(0, area.bottom - area.top);
6
+ if (width === 0 || height === 0) return insets;
7
+
8
+ if (avoidCamera) {
9
+ for (const region of info.occlusions) {
10
+ if (!region.isActive || region.left >= area.right || region.right <= area.left ||
11
+ region.top >= area.bottom || region.bottom <= area.top) continue;
12
+ if (region.top + region.bottom < area.top + area.bottom) {
13
+ insets.top = Math.max(insets.top, region.bottom - area.top);
14
+ } else {
15
+ insets.bottom = Math.max(insets.bottom, area.bottom - region.top);
16
+ }
17
+ }
18
+ }
19
+
20
+ const fold = info.fold;
21
+ // A separating fold can have zero width or height.
22
+ if (avoidFold && fold && fold.isActive &&
23
+ fold.left < area.right && fold.right > area.left &&
24
+ fold.top < area.bottom && fold.bottom > area.top) {
25
+ if (!info.isVerticalHinge) {
26
+ insets.bottom = Math.max(insets.bottom, area.bottom - fold.top);
27
+ } else if (direction === 'rtl') {
28
+ insets.left = Math.max(insets.left, fold.right - area.left);
29
+ } else {
30
+ insets.right = Math.max(insets.right, area.right - fold.left);
31
+ }
32
+ }
33
+
34
+ insets.left = Math.min(insets.left, width);
35
+ insets.right = Math.min(insets.right, width - insets.left);
36
+ insets.top = Math.min(insets.top, height);
37
+ insets.bottom = Math.min(insets.bottom, height - insets.top);
38
+ return insets;
39
+ }
40
+
41
+ function isPhoneLayout(shortestSide, info, platform) {
42
+ if (platform === 'ios' && info.isFoldableDevice) return info.state === 'folded';
43
+ return shortestSide < 600;
44
+ }
45
+
46
+ function createAPI(subscribe) {
47
+ const session = Math.random().toString(36).slice(2);
48
+ let nextId = 0;
49
+ async function watch(listener, onError) {
50
+ return subscribe(`${session}-${++nextId}`, listener, onError);
51
+ }
52
+
53
+ function getState() {
54
+ return readState(0, false);
55
+ }
56
+
57
+ function waitForSettle(quietWindow = 400) {
58
+ return readState(quietWindow, true);
59
+ }
60
+
61
+ function readState(quietWindow, settle) {
62
+ let timer;
63
+ let pending = true;
64
+ return new Promise((resolve, reject) => {
65
+ async function finish(value, failed = false) {
66
+ if (!pending) return;
67
+ pending = false;
68
+ clearTimeout(timer);
69
+ try {
70
+ await (await subscription).remove();
71
+ if (failed) reject(value);
72
+ else resolve(value);
73
+ } catch (error) {
74
+ reject(failed ? value : error);
75
+ }
76
+ }
77
+
78
+ const subscription = Promise.resolve().then(() => watch(state => {
79
+ if (!pending) return;
80
+ clearTimeout(timer);
81
+ if (settle) timer = setTimeout(() => finish(state), quietWindow);
82
+ else finish(state);
83
+ }, error => finish(error, true)));
84
+ subscription.catch(error => finish(error, true));
85
+ });
86
+ }
87
+
88
+ return { watch, getState, waitForSettle, avoidInsets, isPhoneLayout };
89
+ }
90
+
91
+ module.exports = { createAPI, avoidInsets };