Skip to content
Open
Show file tree
Hide file tree
Changes from 15 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
3 changes: 1 addition & 2 deletions wakelock_plus/example/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,10 @@
/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,30 @@
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);
}
}

var webm =
'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='
var mp4 =
Expand Down Expand Up @@ -46,21 +73,19 @@ var oldIOS =
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()
}
}
Expand Down Expand Up @@ -106,27 +131,39 @@ var NoSleep = (function () {
},
{
key: 'enable',
value: function enable() {
value: async function enable() {
var _this2 = this

if (nativeWakeLock) {
_nativeRequestInProgress = true
// Disalbe 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.
console.log("Wake Lock active.");
_this2._wakeLock.addEventListener('release', function () {
_releasedNative = true
_this2.nativeEnabled = false
_this2._wakeLock = null
console.log("Wake Lock released.");
})
})
.catch(function (err) {
_nativeRequestInProgress = false
console.error(err.name + ', ' + err.message)
_this2.nativeEnabled = false
var errorMessage = err.name + ', ' + err.message
console.error(errorMessage)
_nativeEnabledCompleter.completeError(errorMessage)
_nativeEnabledCompleter = null
})
// We then wait for screen to be made available.
return _nativeEnabledCompleter.future
} else if (oldIOS) {
this.disable()
console.warn(
Expand All @@ -138,17 +175,35 @@ var NoSleep = (function () {
window.setTimeout(window.stop, 0)
}
}, 15000)
return Promise.resolve()
} 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
console.error(errorMessage)
_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()
}

Expand All @@ -162,34 +217,30 @@ var NoSleep = (function () {
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
return this.nativeEnabled
} else if (oldIOS) {
return this.noSleepTimer != null
} else {
if (_playVideoCompleter != null) {
await _playVideoCompleter.future
}
if (this.noSleepVideo == undefined) {
return false
}
Expand All @@ -208,17 +259,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) {
throw e
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're immediately rethrowing in the catch, why bother catching at all? Doesn't this mess up the stack trace?

}
return Promise.resolve()
},
}

Expand Down
46 changes: 34 additions & 12 deletions wakelock_plus/lib/src/wakelock_plus_web_plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,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,30 +14,52 @@ 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.
late Future<void> _jsLoaded;
bool _jsLibraryLoaded = false;

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

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

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

return completer.future;
}

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

await _ensureJsLoaded();
final completer = Completer<bool>();

wakelock_plus_web.enabled().toDart.then(
Expand Down
Loading
Loading