Skip to content

fix: add support for non-root base-href #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
8892812
fix: add support for non-root base-href
holzgeist Sep 18, 2024
31526ae
Moved no_sleep.js to lib/assets.
diegotori Dec 3, 2024
606ade6
Added web alias to all package:web calls in import_js_library.dart.
diegotori Dec 3, 2024
b4114a9
Added more simplified library URL method in import_js_library.dart.
diegotori Dec 3, 2024
e948054
WakelockPlusWebPlugin now lazily loads no_sleep.js on demand as oppos…
diegotori Dec 3, 2024
9e1fd5b
Got the WakelockPlusWebPlugin tests passing.
diegotori Dec 3, 2024
39f6598
Fixed example app web-related depreactions.
diegotori Dec 3, 2024
f2542bd
Added straggler from previous commit.
diegotori Dec 3, 2024
b8d0b58
Added correct script tag error handling by checking if the target is …
diegotori Dec 3, 2024
bd3e7a7
Upgraded flutter_lints to latest version.
diegotori Dec 3, 2024
4900aaf
Revamped the no_sleep.js script to use a Promise-based Completer so t…
diegotori Dec 3, 2024
ac4e069
Fixed a dart lint issue due to HTML in the documentation of _importJS…
diegotori Dec 3, 2024
a7ddb22
Added minor comments to no_sleep.js.
diegotori Dec 3, 2024
897dca4
Merge branch 'main' into fix-support-non-root-base-href
diegotori Dec 21, 2024
f5d5bc4
Fixed a pubspec straggler from the previous commit.
diegotori Dec 21, 2024
8f38c22
Update wakelock_plus/lib/assets/no_sleep.js due to typo
diegotori Jan 8, 2025
bb3d4ca
chore: apply suggestions
holzgeist Feb 20, 2025
be5d5f5
Merge branch 'main' into fix-support-non-root-base-href
diegotori Mar 26, 2025
bb5d60d
Moved no_sleep.js copyright notice to the top of the file.
diegotori Mar 26, 2025
12cd725
fix: don't perform any work after completing future
holzgeist Apr 17, 2025
8f1ed7a
Merge branch 'main' into fix-support-non-root-base-href
diegotori Apr 17, 2025
3886996
Merge branch 'main' into fix-support-non-root-base-href
diegotori Apr 17, 2025
27f6d07
Merge branch 'main' into fix-support-non-root-base-href
diegotori Apr 24, 2025
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
5 changes: 1 addition & 4 deletions wakelock_plus/example/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,9 @@
.pub/
/build/

# Web related
lib/generated_plugin_registrant.dart

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json
!/ios/Podfile
!/ios/Podfile
23 changes: 1 addition & 22 deletions wakelock_plus/example/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,8 @@

<title>example</title>
<link rel="manifest" href="manifest.json">

<script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function(engineInitializer) {
engineInitializer.initializeEngine().then(function(appRunner) {
appRunner.runApp();
});
}
});
});
</script>
<script src="flutter_bootstrap.js" async></script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
class PromiseCompleter {
_promise;
_resolve;
_reject;
constructor() {
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}

isCompleted = false;

get future() {
return this._promise;
}

complete(value) {
this.isCompleted = true;
this._resolve(value);
}

completeError(error) {
this._reject(error);
}
}

/*! Based On NoSleep.js v0.12.0 - git.io/vfn01 - Rich Tibbett - MIT license */

var webm =
'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='
var mp4 =
Expand Down Expand Up @@ -26,48 +55,28 @@ function _classCallCheck(instance, Constructor) {
}
}

// Detect iOS browsers < version 10
var oldIOS =
typeof navigator !== 'undefined' &&
parseFloat(
(
'' +
(/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(
navigator.userAgent
) || [0, ''])[1]
)
.replace('undefined', '3_2')
.replace('_', '.')
.replace('_', '')
) < 10 &&
!window.MSStream

// Detect native Wake Lock API support
var nativeWakeLock = 'wakeLock' in navigator

var NoSleep = (function () {
var _releasedNative = true
var _nativeRequestInProgress = false
var _nativeEnabledCompleter;
var _playVideoCompleter;

function NoSleep() {
var _this = this

_classCallCheck(this, NoSleep)

this.nativeEnabled = false
if (nativeWakeLock) {
this._wakeLock = null
var handleVisibilityChange = function handleVisibilityChange() {
if (
_this._wakeLock !== null &&
document.visibilityState === 'visible'
) {
if (_this._wakeLock !== null && document.visibilityState === 'visible') {
_this.enable()
}
}
document.addEventListener('visibilitychange', handleVisibilityChange)
document.addEventListener('fullscreenchange', handleVisibilityChange)
} else if (oldIOS) {
this.noSleepTimer = null
} else {
// Set up no sleep video element
this.noSleepVideo = document.createElement('video')
Expand Down Expand Up @@ -106,90 +115,90 @@ var NoSleep = (function () {
},
{
key: 'enable',
value: function enable() {
value: async function enable() {
var _this2 = this

if (nativeWakeLock) {
_nativeRequestInProgress = true
// Disable any previously held wakelocks.
await this.disable()
if (_nativeEnabledCompleter == null) {
_nativeEnabledCompleter = new PromiseCompleter()
}
navigator.wakeLock
.request('screen')
.then(function (wakeLock) {
_releasedNative = false
_nativeRequestInProgress = false

_this2._wakeLock = wakeLock
_this2.nativeEnabled = true
_nativeEnabledCompleter.complete()
_nativeEnabledCompleter = null
// We now have a wakelock. Notify all of the existing callers.
_this2._wakeLock.addEventListener('release', function () {
_releasedNative = true
_this2.nativeEnabled = false
_this2._wakeLock = null
})
})
.catch(function (err) {
_nativeRequestInProgress = false
console.error(err.name + ', ' + err.message)
_this2.nativeEnabled = false
var errorMessage = err.name + ', ' + err.message
_nativeEnabledCompleter.completeError(errorMessage)
_nativeEnabledCompleter = null
})
} else if (oldIOS) {
this.disable()
console.warn(
'\n NoSleep enabled for older iOS devices. This can interrupt\n active or long-running network requests from completing successfully.\n See https://github.com/richtr/NoSleep.js/issues/15 for more details.\n '
)
this.noSleepTimer = window.setInterval(function () {
if (!document.hidden) {
window.location.href = window.location.href.split('#')[0]
window.setTimeout(window.stop, 0)
}
}, 15000)
// We then wait for screen to be made available.
return _nativeEnabledCompleter.future
} else {
this.noSleepVideo.play()
if (_playVideoCompleter == null) {
_playVideoCompleter = new PromiseCompleter()
}
var playPromise = this.noSleepVideo.play()
playPromise.then(function (res) {
_playVideoCompleter.complete()
_playVideoCompleter = null
}).catch(function (err) {
var errorMessage = err.name + ', ' + err.message
_playVideoCompleter.completeError(errorMessage)
_playVideoCompleter = null
});
return _playVideoCompleter.future
}
},
},
{
key: 'disable',
value: function disable() {
value: async function disable() {
if (nativeWakeLock) {
// If we're still trying to enable the wakelock, wait for it to be enabled
if (_nativeEnabledCompleter != null) {
await _nativeEnabledCompleter.future
}
if (this._wakeLock != null) {
_releasedNative = true
this.nativeEnabled = false
this._wakeLock.release()
}

this._wakeLock = null
} else if (oldIOS) {
if (this.noSleepTimer) {
console.warn(
'\n NoSleep now disabled for older iOS devices.\n '
)
window.clearInterval(this.noSleepTimer)
this.noSleepTimer = null
}
} else {
if (_playVideoCompleter != null) {
await _playVideoCompleter.future
}
this.noSleepVideo.pause()
}
return Promise.resolve();
},
},
{
key: 'enabled',
value: async function enabled() {
key: 'isEnabled',
value: async function isEnabled() {
if (nativeWakeLock) {
if (_nativeRequestInProgress == true) {
// Wait until the request is done.
while (true) {
// Wait for 42 milliseconds.
await new Promise((resolve, reject) => setTimeout(resolve, 42))
if (_nativeRequestInProgress == false) {
break
}
}
}

// todo: use WakeLockSentinel.released when that is available (https://developer.mozilla.org/en-US/docs/Web/API/WakeLockSentinel/released)
if (_releasedNative != false) {
return false
// If we're still trying to enable the wakelock, wait for it to be enabled
if (_nativeEnabledCompleter != null) {
await _nativeEnabledCompleter.future
}

return true
} else if (oldIOS) {
return this.noSleepTimer != null
return this.nativeEnabled
} else {
if (_playVideoCompleter != null) {
await _playVideoCompleter.future
}
if (this.noSleepVideo == undefined) {
return false
}
Expand All @@ -208,17 +217,22 @@ var noSleep = new NoSleep()
var Wakelock = {
enabled: async function () {
try {
return noSleep.enabled()
return noSleep.isEnabled()
} catch (e) {
return false
}
},
toggle: async function (enable) {
if (enable) {
noSleep.enable()
} else {
noSleep.disable()
try {
if (enable) {
await noSleep.enable()
} else {
await noSleep.disable()
}
} catch (e) {
return Promise.reject(e);
}
return Promise.resolve()
},
}

Expand Down
47 changes: 19 additions & 28 deletions wakelock_plus/lib/src/wakelock_plus_web_plugin.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import 'dart:async';
import 'dart:js_interop';

import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:wakelock_plus_platform_interface/wakelock_plus_platform_interface.dart';
import 'package:wakelock_plus/src/web_impl/import_js_library.dart';
import 'package:wakelock_plus/src/web_impl/js_wakelock.dart'
as wakelock_plus_web;
import 'package:wakelock_plus_platform_interface/wakelock_plus_platform_interface.dart';

/// The web implementation of the [WakelockPlatformInterface].
///
Expand All @@ -14,43 +13,35 @@ class WakelockPlusWebPlugin extends WakelockPlusPlatformInterface {
/// Registers [WakelockPlusWebPlugin] as the default instance of the
/// [WakelockPlatformInterface].
static void registerWith(Registrar registrar) {
// Import a version of `NoSleep.js` that was adjusted for the wakelock
// plugin.
_jsLoaded = importJsLibrary(
url: 'assets/no_sleep.js', flutterPluginName: 'wakelock_plus');

WakelockPlusPlatformInterface.instance = WakelockPlusWebPlugin();
}

// The future that resolves when the JS library is loaded.
static late Future<void> _jsLoaded;
// The future that signals when the JS is loaded.
// This needs to be `await`ed before accessing any methods of the
// JS-interop layer.
Future<void>? _jsLoaded;

//
// Lazily imports the JS library once, then awaits to ensure that
// it's loaded into the DOM.
//
Future<void> _ensureJsLoaded() async {
_jsLoaded ??= importJsLibrary(
url: 'assets/no_sleep.js', flutterPluginName: 'wakelock_plus');
return _jsLoaded;
}

@override
Future<void> toggle({required bool enable}) async {
// Make sure the JS library is loaded before calling it.
await _jsLoaded;

wakelock_plus_web.toggle(enable);
await _ensureJsLoaded();
await wakelock_plus_web.toggle(enable);
}

@override
Future<bool> get enabled async {
// Make sure the JS library is loaded before calling it.
await _jsLoaded;

final completer = Completer<bool>();

wakelock_plus_web.enabled().toDart.then(
// onResolve
(value) {
completer.complete(value.toDart);
},
// onReject
onError: (error) {
completer.completeError(error);
},
);

return completer.future;
await _ensureJsLoaded();
return wakelock_plus_web.enabled();
}
}
Loading