Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ core/types
cli/assets
dist
android/capacitor/src/main/assets/native-bridge.js
android/capacitor/src/main/assets/display-features.js
ios/Sources/Capacitor/assets/native-bridge.js
ios/Sources/Capacitor/assets/display-features.js
ios/Frameworks/Capacitor.xcframework/ios-arm64_x86_64-simulator/Capacitor.framework/native-bridge.js
ios/Frameworks/Capacitor.xcframework/ios-arm64/Capacitor.framework/native-bridge.js
1 change: 1 addition & 0 deletions android-template/variables.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ext {
androidxFragmentVersion = '1.9.1'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.17.1'
androidxWindowVersion = '1.5.1'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
Expand Down
3 changes: 3 additions & 0 deletions android/capacitor/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ ext {
androidxCoreVersion = rootProject.hasProperty('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.19.1'
androidxFragmentVersion = rootProject.hasProperty('androidxFragmentVersion') ? rootProject.ext.androidxFragmentVersion : '1.9.1'
androidxWebkitVersion = rootProject.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.17.1'
androidxWindowVersion = rootProject.hasProperty('androidxWindowVersion') ? rootProject.ext.androidxWindowVersion : '1.5.1'
junitVersion = rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
androidxJunitVersion = rootProject.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
androidxEspressoCoreVersion = rootProject.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
Expand Down Expand Up @@ -76,6 +77,8 @@ dependencies {
implementation "androidx.fragment:fragment:$androidxFragmentVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.webkit:webkit:$androidxWebkitVersion"
implementation "androidx.window:window:$androidxWindowVersion"
implementation "androidx.window:window-java:$androidxWindowVersion"
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
Expand Down
232 changes: 232 additions & 0 deletions android/capacitor/src/main/assets/display-features.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@

/*! Capacitor: https://capacitorjs.com/ - MIT License */
/* Generated File. Do not edit. */

var __osDisplayFeaturesPolyfill = (function (exports) {
'use strict';

/**
* Note: When making changes to this file, run `npm run build:nativebridge`
* afterwards to build the display-features.js files to the android and iOS projects.
*/
const isPosture = (value) => value === 'continuous' || value === 'folded';
const isSegment = (value) => value !== null &&
typeof value === 'object' &&
[value.left, value.top, value.width, value.height].every((n) => typeof n === 'number' && Number.isFinite(n)) &&
value.left >= 0 &&
value.top >= 0 &&
value.width > 0 &&
value.height > 0;
const parseSegments = (value) => {
if (!Array.isArray(value) || value.length < 1 || value.length > 2 || !value.every(isSegment)) {
return null;
}
return value
.map(({ left, top, width, height }) => ({ left, top, width, height }))
.sort((a, b) => a.left - b.left || a.top - b.top);
};
const segmentsEqual = (a, b) => a.length === b.length &&
a.every((s, i) => s.left === b[i].left && s.top === b[i].top && s.width === b[i].width && s.height === b[i].height);
const segmentIndices = (segments) => segments.length === 2 && segments[1].left > segments[0].left
? [
[0, 0],
[1, 0],
]
: segments.map((_, i) => [0, i]);
const cssVariables = (state) => {
const vars = new Map();
const indices = segmentIndices(state.segments);
vars.set('--device-posture', state.posture);
vars.set('--horizontal-viewport-segments', String(Math.max(...indices.map(([x]) => x)) + 1));
vars.set('--vertical-viewport-segments', String(Math.max(...indices.map(([, y]) => y)) + 1));
if (state.segments.length > 1) {
state.segments.forEach((s, i) => {
const suffix = `${indices[i][0]}-${indices[i][1]}`;
vars.set(`--viewport-segment-top-${suffix}`, `${s.top}px`);
vars.set(`--viewport-segment-left-${suffix}`, `${s.left}px`);
vars.set(`--viewport-segment-bottom-${suffix}`, `${s.top + s.height}px`);
vars.set(`--viewport-segment-right-${suffix}`, `${s.left + s.width}px`);
vars.set(`--viewport-segment-width-${suffix}`, `${s.width}px`);
vars.set(`--viewport-segment-height-${suffix}`, `${s.height}px`);
});
}
return vars;
};
const readNativeState = (win) => {
var _a;
const getState = (_a = win.__osDisplayFeaturesNative) === null || _a === void 0 ? void 0 : _a.getState;
if (typeof getState !== 'function') {
return {};
}
try {
const json = getState.call(win.__osDisplayFeaturesNative);
const parsed = json ? JSON.parse(json) : null;
return parsed !== null && typeof parsed === 'object' ? parsed : {};
}
catch (e) {
console.warn('Display Features: unable to read initial state from native', e);
return {};
}
};
const sameOriginParent = (win) => {
var _a;
const parent = (_a = win.frameElement) === null || _a === void 0 ? void 0 : _a.ownerDocument.defaultView;
return (parent === null || parent === void 0 ? void 0 : parent.__osDisplayFeatures) ? parent : null;
};
const initDisplayFeatures = (win) => {
var _a, _b;
if (win.__osDisplayFeatures) {
return;
}
const isTopFrame = win.parent === win;
const parent = isTopFrame ? null : sameOriginParent(win);
if (!isTopFrame && !parent) {
return;
}
const viewportSegment = () => ({ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight });
const initial = parent
? { posture: (_a = parent.navigator.devicePosture) === null || _a === void 0 ? void 0 : _a.type }
: readNativeState(win);
const state = {
posture: isPosture(initial.posture) ? initial.posture : 'continuous',
segments: (_b = (parent ? null : parseSegments(initial.segments))) !== null && _b !== void 0 ? _b : [viewportSegment()],
};
class DevicePosture extends EventTarget {
constructor() {
super(...arguments);
this.changeHandler = null;
this.changeHandlerRegistered = false;
}
get type() {
return state.posture;
}
get onchange() {
return this.changeHandler;
}
set onchange(handler) {
this.changeHandler = typeof handler === 'function' ? handler : null;
if (this.changeHandler && !this.changeHandlerRegistered) {
this.changeHandlerRegistered = true;
this.addEventListener('change', (ev) => { var _a; return (_a = this.changeHandler) === null || _a === void 0 ? void 0 : _a.call(this, ev); });
}
}
}
const devicePosture = new DevicePosture();
const getSegments = () => (isTopFrame ? state.segments : [viewportSegment()]).map((s) => new DOMRect(s.left, s.top, s.width, s.height));
try {
Object.defineProperty(win.navigator, 'devicePosture', {
configurable: true,
enumerable: true,
get: () => devicePosture,
});
if (win.viewport && typeof win.viewport === 'object') {
Object.defineProperty(win.viewport, 'segments', { configurable: true, enumerable: true, get: getSegments });
}
else {
const viewport = {};
Object.defineProperty(viewport, 'segments', { configurable: true, enumerable: true, get: getSegments });
Object.defineProperty(win, 'viewport', { configurable: true, enumerable: true, value: viewport });
}
}
catch (e) {
console.warn('Display Features: unable to install the polyfill', e);
return;
}
const appliedVariables = new Set();
const applyCssVariables = () => {
const style = win.document.documentElement.style;
const vars = cssVariables(state);
appliedVariables.forEach((name) => {
if (!vars.has(name)) {
style.removeProperty(name);
appliedVariables.delete(name);
}
});
vars.forEach((value, name) => {
style.setProperty(name, value);
appliedVariables.add(name);
});
};
let announcedPosture = state.posture;
let resizePending = false;
let eventsQueued = false;
const queueEvents = () => {
if (eventsQueued) {
return;
}
eventsQueued = true;
win.setTimeout(() => {
eventsQueued = false;
if (state.posture !== announcedPosture) {
announcedPosture = state.posture;
devicePosture.dispatchEvent(new Event('change'));
}
if (resizePending) {
resizePending = false;
win.dispatchEvent(new Event('resize'));
}
}, 0);
};
let pending = null;
const apply = (next) => {
if (win.document.visibilityState === 'hidden') {
pending = next;
return;
}
pending = null;
const postureChanged = next.posture !== state.posture;
const segmentsChanged = !segmentsEqual(next.segments, state.segments);
if (!postureChanged && !segmentsChanged) {
return;
}
state.posture = next.posture;
state.segments = next.segments;
applyCssVariables();
resizePending = resizePending || segmentsChanged;
queueEvents();
};
win.document.addEventListener('visibilitychange', () => {
if (pending && win.document.visibilityState !== 'hidden') {
apply(pending);
}
});
const forwardToFrames = (posture) => {
win.document.querySelectorAll('iframe, frame').forEach((element) => {
var _a, _b;
const frame = (_a = element.contentDocument) === null || _a === void 0 ? void 0 : _a.defaultView;
(_b = frame === null || frame === void 0 ? void 0 : frame.__osDisplayFeatures) === null || _b === void 0 ? void 0 : _b.update({ posture });
});
};
win.__osDisplayFeatures = {
update: (update) => {
var _a;
if (update === null || typeof update !== 'object') {
return;
}
const base = pending !== null && pending !== void 0 ? pending : state;
const next = {
posture: isPosture(update.posture) ? update.posture : base.posture,
segments: (_a = (isTopFrame ? parseSegments(update.segments) : null)) !== null && _a !== void 0 ? _a : base.segments,
};
apply(next);
forwardToFrames(next.posture);
},
};
if (win.document.documentElement) {
applyCssVariables();
}
else {
win.document.addEventListener('DOMContentLoaded', applyCssVariables, { once: true });
}
};
if (typeof window !== 'undefined') {
initDisplayFeatures(window);
}

exports.initDisplayFeatures = initDisplayFeatures;

Object.defineProperty(exports, '__esModule', { value: true });

return exports;

})({});
26 changes: 25 additions & 1 deletion android/capacitor/src/main/java/com/getcapacitor/Bridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ public class Bridge {
// A reference to the containing Fragment if used
private final Fragment fragment;
private WebViewLocalServer localServer;
private DisplayFeatures displayFeatures;
private String localUrl;
private String appUrl;
private String appUrlConfig;
Expand Down Expand Up @@ -224,8 +225,11 @@ private void loadWebView() {

// Start the local web server
JSInjector injector = getJSInjector();
String allowedOrigin = Uri.parse(appUrl).buildUpon().path(null).fragment(null).clearQuery().build().toString();
if (config.isDisplayFeaturesPolyfillEnabled()) {
installDisplayFeatures(allowedOrigin);
}
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
String allowedOrigin = Uri.parse(appUrl).buildUpon().path(null).fragment(null).clearQuery().build().toString();
try {
WebViewCompat.addDocumentStartJavaScript(webView, injector.getScriptString(), Collections.singleton(allowedOrigin));
injector = null;
Expand Down Expand Up @@ -968,6 +972,20 @@ private JSInjector getJSInjector() {
return null;
}

private void installDisplayFeatures(String allowedOrigin) {
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
try {
String script = JSExport.getDisplayFeaturesJS(context);
WebViewCompat.addDocumentStartJavaScript(webView, script, Collections.singleton(allowedOrigin));
displayFeatures = new DisplayFeatures(context, webView);
} catch (JSExportException | IllegalArgumentException ex) {
Logger.error("Unable to install the Display Features polyfill", ex);
}
} else {
Logger.warn("Display Features polyfill not installed: this WebView does not support document start scripts");
}
}

/**
* Inject JavaScript from an external file before the WebView loads.
* @param path relative to public folder
Expand Down Expand Up @@ -1245,6 +1263,9 @@ public void onRestart() {
* Handle onStart lifecycle event and notify the plugins
*/
public void onStart() {
if (displayFeatures != null) {
displayFeatures.start();
}
for (PluginHandle plugin : plugins.values()) {
plugin.getInstance().handleOnStart();
}
Expand Down Expand Up @@ -1272,6 +1293,9 @@ public void onPause() {
* Handle onStop lifecycle event and notify the plugins
*/
public void onStop() {
if (displayFeatures != null) {
displayFeatures.stop();
}
for (PluginHandle plugin : plugins.values()) {
plugin.getInstance().handleOnStop();
}
Expand Down
20 changes: 20 additions & 0 deletions android/capacitor/src/main/java/com/getcapacitor/CapConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ public class CapConfig {
private boolean zoomableWebView = false;
private boolean resolveServiceWorkerRequests = true;

// Display Features Config
private boolean displayFeaturesPolyfill = true;

// Embedded
private String startPath;

Expand Down Expand Up @@ -161,6 +164,9 @@ private CapConfig(Builder builder) {
this.zoomableWebView = builder.zoomableWebView;
this.resolveServiceWorkerRequests = builder.resolveServiceWorkerRequests;

// Display Features Config
this.displayFeaturesPolyfill = builder.displayFeaturesPolyfill;

// Embedded
this.startPath = builder.startPath;

Expand Down Expand Up @@ -288,6 +294,8 @@ private void deserializeConfig(@Nullable Context context) {
JSONUtils.getBoolean(configJSON, "initialFocus", initialFocus)
);

displayFeaturesPolyfill = JSONUtils.getBoolean(configJSON, "displayFeatures.polyfill", displayFeaturesPolyfill);

// Plugins
pluginsConfiguration = deserializePluginsConfig(JSONUtils.getObject(configJSON, "plugins"));
}
Expand Down Expand Up @@ -377,6 +385,10 @@ public boolean isInitialFocus() {
return initialFocus;
}

public boolean isDisplayFeaturesPolyfillEnabled() {
return displayFeaturesPolyfill;
}

public boolean isUsingLegacyBridge() {
return useLegacyBridge;
}
Expand Down Expand Up @@ -464,6 +476,9 @@ public static class Builder {
private boolean zoomableWebView = false;
private boolean resolveServiceWorkerRequests = true;

// Display Features Config
private boolean displayFeaturesPolyfill = true;

// Embedded
private String startPath = null;

Expand Down Expand Up @@ -586,5 +601,10 @@ public Builder setInitialFocus(boolean focus) {
this.initialFocus = focus;
return this;
}

public Builder setDisplayFeaturesPolyfill(boolean enabled) {
this.displayFeaturesPolyfill = enabled;
return this;
}
}
}
Loading