remove node_modules

This commit is contained in:
opbnq
2025-03-07 07:23:26 -08:00
parent 522a9c4f87
commit 667f791ab7
99 changed files with 1 additions and 14954 deletions

View File

@@ -1,32 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const call = newRuntimeCaller(objectNames.Application);
const HideMethod = 0;
const ShowMethod = 1;
const QuitMethod = 2;
/**
* Hides a certain method by calling the HideMethod function.
*/
export function Hide() {
return call(HideMethod);
}
/**
* Calls the ShowMethod and returns the result.
*/
export function Show() {
return call(ShowMethod);
}
/**
* Calls the QuitMethod to terminate the program.
*/
export function Quit() {
return call(QuitMethod);
}

View File

@@ -1,20 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const call = newRuntimeCaller(objectNames.Browser);
const BrowserOpenURL = 0;
/**
* Open a browser window to the given URL.
*
* @param url - The URL to open
*/
export function OpenURL(url) {
return call(BrowserOpenURL, { url: url.toString() });
}

View File

@@ -1,144 +0,0 @@
// Source: https://github.com/inspect-js/is-callable
// The MIT License (MIT)
//
// Copyright (c) 2015 Jordan Harband
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
}
catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
}
else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
}
catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) {
return false;
}
fnToStr.call(value);
return true;
}
catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`
var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
var all = document.all;
if (toStr.call(all) === toStr.call(document.all)) {
isDDA = function isDocumentDotAll(value) {
/* globals document: false */
// in IE 6-8, typeof document.all is "object" and it's truthy
if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
try {
var str = toStr.call(value);
return (str === ddaClass
|| str === ddaClass2
|| str === ddaClass3 // opera 12.16
|| str === objectClass // IE 6-8
) && value('') == null; // eslint-disable-line eqeqeq
}
catch (e) { /**/ }
}
return false;
};
}
}
function isCallableRefApply(value) {
if (isDDA(value)) {
return true;
}
if (!value) {
return false;
}
if (typeof value !== 'function' && typeof value !== 'object') {
return false;
}
try {
reflectApply(value, null, badArrayLike);
}
catch (e) {
if (e !== isCallableMarker) {
return false;
}
}
return !isES6ClassFn(value) && tryFunctionObject(value);
}
function isCallableNoRefApply(value) {
if (isDDA(value)) {
return true;
}
if (!value) {
return false;
}
if (typeof value !== 'function' && typeof value !== 'object') {
return false;
}
if (hasToStringTag) {
return tryFunctionObject(value);
}
if (isES6ClassFn(value)) {
return false;
}
var strClass = toStr.call(value);
if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) {
return false;
}
return tryFunctionObject(value);
}
;
export default reflectApply ? isCallableRefApply : isCallableNoRefApply;

View File

@@ -1,194 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { CancellablePromise } from "./cancellable.js";
import { newRuntimeCaller, objectNames } from "./runtime.js";
import { nanoid } from "./nanoid.js";
// Setup
window._wails = window._wails || {};
window._wails.callResultHandler = resultHandler;
window._wails.callErrorHandler = errorHandler;
const call = newRuntimeCaller(objectNames.Call);
const cancelCall = newRuntimeCaller(objectNames.CancelCall);
const callResponses = new Map();
const CallBinding = 0;
const CancelMethod = 0;
/**
* Exception class that will be thrown in case the bound method returns an error.
* The value of the {@link RuntimeError#name} property is "RuntimeError".
*/
export class RuntimeError extends Error {
/**
* Constructs a new RuntimeError instance.
* @param message - The error message.
* @param options - Options to be forwarded to the Error constructor.
*/
constructor(message, options) {
super(message, options);
this.name = "RuntimeError";
}
}
/**
* Handles the result of a call request.
*
* @param id - The id of the request to handle the result for.
* @param data - The result data of the request.
* @param isJSON - Indicates whether the data is JSON or not.
*/
function resultHandler(id, data, isJSON) {
const resolvers = getAndDeleteResponse(id);
if (!resolvers) {
return;
}
if (!data) {
resolvers.resolve(undefined);
}
else if (!isJSON) {
resolvers.resolve(data);
}
else {
try {
resolvers.resolve(JSON.parse(data));
}
catch (err) {
resolvers.reject(new TypeError("could not parse result: " + err.message, { cause: err }));
}
}
}
/**
* Handles the error from a call request.
*
* @param id - The id of the promise handler.
* @param data - The error data to reject the promise handler with.
* @param isJSON - Indicates whether the data is JSON or not.
*/
function errorHandler(id, data, isJSON) {
const resolvers = getAndDeleteResponse(id);
if (!resolvers) {
return;
}
if (!isJSON) {
resolvers.reject(new Error(data));
}
else {
let error;
try {
error = JSON.parse(data);
}
catch (err) {
resolvers.reject(new TypeError("could not parse error: " + err.message, { cause: err }));
return;
}
let options = {};
if (error.cause) {
options.cause = error.cause;
}
let exception;
switch (error.kind) {
case "ReferenceError":
exception = new ReferenceError(error.message, options);
break;
case "TypeError":
exception = new TypeError(error.message, options);
break;
case "RuntimeError":
exception = new RuntimeError(error.message, options);
break;
default:
exception = new Error(error.message, options);
break;
}
resolvers.reject(exception);
}
}
/**
* Retrieves and removes the response associated with the given ID from the callResponses map.
*
* @param id - The ID of the response to be retrieved and removed.
* @returns The response object associated with the given ID, if any.
*/
function getAndDeleteResponse(id) {
const response = callResponses.get(id);
callResponses.delete(id);
return response;
}
/**
* Generates a unique ID using the nanoid library.
*
* @returns A unique ID that does not exist in the callResponses set.
*/
function generateID() {
let result;
do {
result = nanoid();
} while (callResponses.has(result));
return result;
}
/**
* Call a bound method according to the given call options.
*
* In case of failure, the returned promise will reject with an exception
* among ReferenceError (unknown method), TypeError (wrong argument count or type),
* {@link RuntimeError} (method returned an error), or other (network or internal errors).
* The exception might have a "cause" field with the value returned
* by the application- or service-level error marshaling functions.
*
* @param options - A method call descriptor.
* @returns The result of the call.
*/
export function Call(options) {
const id = generateID();
const result = CancellablePromise.withResolvers();
callResponses.set(id, { resolve: result.resolve, reject: result.reject });
const request = call(CallBinding, Object.assign({ "call-id": id }, options));
let running = false;
request.then(() => {
running = true;
}, (err) => {
callResponses.delete(id);
result.reject(err);
});
const cancel = () => {
callResponses.delete(id);
return cancelCall(CancelMethod, { "call-id": id }).catch((err) => {
console.error("Error while requesting binding call cancellation:", err);
});
};
result.oncancelled = () => {
if (running) {
return cancel();
}
else {
return request.then(cancel);
}
};
return result.promise;
}
/**
* Calls a bound method by name with the specified arguments.
* See {@link Call} for details.
*
* @param methodName - The name of the method in the format 'package.struct.method'.
* @param args - The arguments to pass to the method.
* @returns The result of the method call.
*/
export function ByName(methodName, ...args) {
return Call({ methodName, args });
}
/**
* Calls a method by its numeric ID with the specified arguments.
* See {@link Call} for details.
*
* @param methodID - The ID of the method to call.
* @param args - The arguments to pass to the method.
* @return The result of the method call.
*/
export function ByID(methodID, ...args) {
return Call({ methodID, args });
}

View File

@@ -1,792 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
var _a;
import isCallable from "./callable.js";
/**
* Exception class that will be used as rejection reason
* in case a {@link CancellablePromise} is cancelled successfully.
*
* The value of the {@link name} property is the string `"CancelError"`.
* The value of the {@link cause} property is the cause passed to the cancel method, if any.
*/
export class CancelError extends Error {
/**
* Constructs a new `CancelError` instance.
* @param message - The error message.
* @param options - Options to be forwarded to the Error constructor.
*/
constructor(message, options) {
super(message, options);
this.name = "CancelError";
}
}
/**
* Exception class that will be reported as an unhandled rejection
* in case a {@link CancellablePromise} rejects after being cancelled,
* or when the `oncancelled` callback throws or rejects.
*
* The value of the {@link name} property is the string `"CancelledRejectionError"`.
* The value of the {@link cause} property is the reason the promise rejected with.
*
* Because the original promise was cancelled,
* a wrapper promise will be passed to the unhandled rejection listener instead.
* The {@link promise} property holds a reference to the original promise.
*/
export class CancelledRejectionError extends Error {
/**
* Constructs a new `CancelledRejectionError` instance.
* @param promise - The promise that caused the error originally.
* @param reason - The rejection reason.
* @param info - An optional informative message specifying the circumstances in which the error was thrown.
* Defaults to the string `"Unhandled rejection in cancelled promise."`.
*/
constructor(promise, reason, info) {
super((info !== null && info !== void 0 ? info : "Unhandled rejection in cancelled promise.") + " Reason: " + errorMessage(reason), { cause: reason });
this.promise = promise;
this.name = "CancelledRejectionError";
}
}
// Private field names.
const barrierSym = Symbol("barrier");
const cancelImplSym = Symbol("cancelImpl");
const species = (_a = Symbol.species) !== null && _a !== void 0 ? _a : Symbol("speciesPolyfill");
/**
* A promise with an attached method for cancelling long-running operations (see {@link CancellablePromise#cancel}).
* Cancellation can optionally be bound to an {@link AbortSignal}
* for better composability (see {@link CancellablePromise#cancelOn}).
*
* Cancelling a pending promise will result in an immediate rejection
* with an instance of {@link CancelError} as reason,
* but whoever started the promise will be responsible
* for actually aborting the underlying operation.
* To this purpose, the constructor and all chaining methods
* accept optional cancellation callbacks.
*
* If a `CancellablePromise` still resolves after having been cancelled,
* the result will be discarded. If it rejects, the reason
* will be reported as an unhandled rejection,
* wrapped in a {@link CancelledRejectionError} instance.
* To facilitate the handling of cancellation requests,
* cancelled `CancellablePromise`s will _not_ report unhandled `CancelError`s
* whose `cause` field is the same as the one with which the current promise was cancelled.
*
* All usual promise methods are defined and return a `CancellablePromise`
* whose cancel method will cancel the parent operation as well, propagating the cancellation reason
* upwards through promise chains.
* Conversely, cancelling a promise will not automatically cancel dependent promises downstream:
* ```ts
* let root = new CancellablePromise((resolve, reject) => { ... });
* let child1 = root.then(() => { ... });
* let child2 = child1.then(() => { ... });
* let child3 = root.catch(() => { ... });
* child1.cancel(); // Cancels child1 and root, but not child2 or child3
* ```
* Cancelling a promise that has already settled is safe and has no consequence.
*
* The `cancel` method returns a promise that _always fulfills_
* after the whole chain has processed the cancel request
* and all attached callbacks up to that moment have run.
*
* All ES2024 promise methods (static and instance) are defined on CancellablePromise,
* but actual availability may vary with OS/webview version.
*
* In line with the proposal at https://github.com/tc39/proposal-rm-builtin-subclassing,
* `CancellablePromise` does not support transparent subclassing.
* Extenders should take care to provide their own method implementations.
* This might be reconsidered in case the proposal is retired.
*
* CancellablePromise is a wrapper around the DOM Promise object
* and is compliant with the [Promises/A+ specification](https://promisesaplus.com/)
* (it passes the [compliance suite](https://github.com/promises-aplus/promises-tests))
* if so is the underlying implementation.
*/
export class CancellablePromise extends Promise {
/**
* Creates a new `CancellablePromise`.
*
* @param executor - A callback used to initialize the promise. This callback is passed two arguments:
* a `resolve` callback used to resolve the promise with a value
* or the result of another promise (possibly cancellable),
* and a `reject` callback used to reject the promise with a provided reason or error.
* If the value provided to the `resolve` callback is a thenable _and_ cancellable object
* (it has a `then` _and_ a `cancel` method),
* cancellation requests will be forwarded to that object and the oncancelled will not be invoked anymore.
* If any one of the two callbacks is called _after_ the promise has been cancelled,
* the provided values will be cancelled and resolved as usual,
* but their results will be discarded.
* However, if the resolution process ultimately ends up in a rejection
* that is not due to cancellation, the rejection reason
* will be wrapped in a {@link CancelledRejectionError}
* and bubbled up as an unhandled rejection.
* @param oncancelled - It is the caller's responsibility to ensure that any operation
* started by the executor is properly halted upon cancellation.
* This optional callback can be used to that purpose.
* It will be called _synchronously_ with a cancellation cause
* when cancellation is requested, _after_ the promise has already rejected
* with a {@link CancelError}, but _before_
* any {@link then}/{@link catch}/{@link finally} callback runs.
* If the callback returns a thenable, the promise returned from {@link cancel}
* will only fulfill after the former has settled.
* Unhandled exceptions or rejections from the callback will be wrapped
* in a {@link CancelledRejectionError} and bubbled up as unhandled rejections.
* If the `resolve` callback is called before cancellation with a cancellable promise,
* cancellation requests on this promise will be diverted to that promise,
* and the original `oncancelled` callback will be discarded.
*/
constructor(executor, oncancelled) {
let resolve;
let reject;
super((res, rej) => { resolve = res; reject = rej; });
if (this.constructor[species] !== Promise) {
throw new TypeError("CancellablePromise does not support transparent subclassing. Please refrain from overriding the [Symbol.species] static property.");
}
let promise = {
promise: this,
resolve,
reject,
get oncancelled() { return oncancelled !== null && oncancelled !== void 0 ? oncancelled : null; },
set oncancelled(cb) { oncancelled = cb !== null && cb !== void 0 ? cb : undefined; }
};
const state = {
get root() { return state; },
resolving: false,
settled: false
};
// Setup cancellation system.
void Object.defineProperties(this, {
[barrierSym]: {
configurable: false,
enumerable: false,
writable: true,
value: null
},
[cancelImplSym]: {
configurable: false,
enumerable: false,
writable: false,
value: cancellerFor(promise, state)
}
});
// Run the actual executor.
const rejector = rejectorFor(promise, state);
try {
executor(resolverFor(promise, state), rejector);
}
catch (err) {
if (state.resolving) {
console.log("Unhandled exception in CancellablePromise executor.", err);
}
else {
rejector(err);
}
}
}
/**
* Cancels immediately the execution of the operation associated with this promise.
* The promise rejects with a {@link CancelError} instance as reason,
* with the {@link CancelError#cause} property set to the given argument, if any.
*
* Has no effect if called after the promise has already settled;
* repeated calls in particular are safe, but only the first one
* will set the cancellation cause.
*
* The `CancelError` exception _need not_ be handled explicitly _on the promises that are being cancelled:_
* cancelling a promise with no attached rejection handler does not trigger an unhandled rejection event.
* Therefore, the following idioms are all equally correct:
* ```ts
* new CancellablePromise((resolve, reject) => { ... }).cancel();
* new CancellablePromise((resolve, reject) => { ... }).then(...).cancel();
* new CancellablePromise((resolve, reject) => { ... }).then(...).catch(...).cancel();
* ```
* Whenever some cancelled promise in a chain rejects with a `CancelError`
* with the same cancellation cause as itself, the error will be discarded silently.
* However, the `CancelError` _will still be delivered_ to all attached rejection handlers
* added by {@link then} and related methods:
* ```ts
* let cancellable = new CancellablePromise((resolve, reject) => { ... });
* cancellable.then(() => { ... }).catch(console.log);
* cancellable.cancel(); // A CancelError is printed to the console.
* ```
* If the `CancelError` is not handled downstream by the time it reaches
* a _non-cancelled_ promise, it _will_ trigger an unhandled rejection event,
* just like normal rejections would:
* ```ts
* let cancellable = new CancellablePromise((resolve, reject) => { ... });
* let chained = cancellable.then(() => { ... }).then(() => { ... }); // No catch...
* cancellable.cancel(); // Unhandled rejection event on chained!
* ```
* Therefore, it is important to either cancel whole promise chains from their tail,
* as shown in the correct idioms above, or take care of handling errors everywhere.
*
* @returns A cancellable promise that _fulfills_ after the cancel callback (if any)
* and all handlers attached up to the call to cancel have run.
* If the cancel callback returns a thenable, the promise returned by `cancel`
* will also wait for that thenable to settle.
* This enables callers to wait for the cancelled operation to terminate
* without being forced to handle potential errors at the call site.
* ```ts
* cancellable.cancel().then(() => {
* // Cleanup finished, it's safe to do something else.
* }, (err) => {
* // Unreachable: the promise returned from cancel will never reject.
* });
* ```
* Note that the returned promise will _not_ handle implicitly any rejection
* that might have occurred already in the cancelled chain.
* It will just track whether registered handlers have been executed or not.
* Therefore, unhandled rejections will never be silently handled by calling cancel.
*/
cancel(cause) {
return new CancellablePromise((resolve) => {
// INVARIANT: the result of this[cancelImplSym] and the barrier do not ever reject.
// Unfortunately macOS High Sierra does not support Promise.allSettled.
Promise.all([
this[cancelImplSym](new CancelError("Promise cancelled.", { cause })),
currentBarrier(this)
]).then(() => resolve(), () => resolve());
});
}
/**
* Binds promise cancellation to the abort event of the given {@link AbortSignal}.
* If the signal has already aborted, the promise will be cancelled immediately.
* When either condition is verified, the cancellation cause will be set
* to the signal's abort reason (see {@link AbortSignal#reason}).
*
* Has no effect if called (or if the signal aborts) _after_ the promise has already settled.
* Only the first signal to abort will set the cancellation cause.
*
* For more details about the cancellation process,
* see {@link cancel} and the `CancellablePromise` constructor.
*
* This method enables `await`ing cancellable promises without having
* to store them for future cancellation, e.g.:
* ```ts
* await longRunningOperation().cancelOn(signal);
* ```
* instead of:
* ```ts
* let promiseToBeCancelled = longRunningOperation();
* await promiseToBeCancelled;
* ```
*
* @returns This promise, for method chaining.
*/
cancelOn(signal) {
if (signal.aborted) {
void this.cancel(signal.reason);
}
else {
signal.addEventListener('abort', () => void this.cancel(signal.reason), { capture: true });
}
return this;
}
/**
* Attaches callbacks for the resolution and/or rejection of the `CancellablePromise`.
*
* The optional `oncancelled` argument will be invoked when the returned promise is cancelled,
* with the same semantics as the `oncancelled` argument of the constructor.
* When the parent promise rejects or is cancelled, the `onrejected` callback will run,
* _even after the returned promise has been cancelled:_
* in that case, should it reject or throw, the reason will be wrapped
* in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection.
*
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A `CancellablePromise` for the completion of whichever callback is executed.
* The returned promise is hooked up to propagate cancellation requests up the chain, but not down:
*
* - if the parent promise is cancelled, the `onrejected` handler will be invoked with a `CancelError`
* and the returned promise _will resolve regularly_ with its result;
* - conversely, if the returned promise is cancelled, _the parent promise is cancelled too;_
* the `onrejected` handler will still be invoked with the parent's `CancelError`,
* but its result will be discarded
* and the returned promise will reject with a `CancelError` as well.
*
* The promise returned from {@link cancel} will fulfill only after all attached handlers
* up the entire promise chain have been run.
*
* If either callback returns a cancellable promise,
* cancellation requests will be diverted to it,
* and the specified `oncancelled` callback will be discarded.
*/
then(onfulfilled, onrejected, oncancelled) {
if (!(this instanceof CancellablePromise)) {
throw new TypeError("CancellablePromise.prototype.then called on an invalid object.");
}
// NOTE: TypeScript's built-in type for then is broken,
// as it allows specifying an arbitrary TResult1 != T even when onfulfilled is not a function.
// We cannot fix it if we want to CancellablePromise to implement PromiseLike<T>.
if (!isCallable(onfulfilled)) {
onfulfilled = identity;
}
if (!isCallable(onrejected)) {
onrejected = thrower;
}
if (onfulfilled === identity && onrejected == thrower) {
// Shortcut for trivial arguments.
return new CancellablePromise((resolve) => resolve(this));
}
const barrier = {};
this[barrierSym] = barrier;
return new CancellablePromise((resolve, reject) => {
void super.then((value) => {
var _a;
if (this[barrierSym] === barrier) {
this[barrierSym] = null;
}
(_a = barrier.resolve) === null || _a === void 0 ? void 0 : _a.call(barrier);
try {
resolve(onfulfilled(value));
}
catch (err) {
reject(err);
}
}, (reason) => {
var _a;
if (this[barrierSym] === barrier) {
this[barrierSym] = null;
}
(_a = barrier.resolve) === null || _a === void 0 ? void 0 : _a.call(barrier);
try {
resolve(onrejected(reason));
}
catch (err) {
reject(err);
}
});
}, async (cause) => {
//cancelled = true;
try {
return oncancelled === null || oncancelled === void 0 ? void 0 : oncancelled(cause);
}
finally {
await this.cancel(cause);
}
});
}
/**
* Attaches a callback for only the rejection of the Promise.
*
* The optional `oncancelled` argument will be invoked when the returned promise is cancelled,
* with the same semantics as the `oncancelled` argument of the constructor.
* When the parent promise rejects or is cancelled, the `onrejected` callback will run,
* _even after the returned promise has been cancelled:_
* in that case, should it reject or throw, the reason will be wrapped
* in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection.
*
* It is equivalent to
* ```ts
* cancellablePromise.then(undefined, onrejected, oncancelled);
* ```
* and the same caveats apply.
*
* @returns A Promise for the completion of the callback.
* Cancellation requests on the returned promise
* will propagate up the chain to the parent promise,
* but not in the other direction.
*
* The promise returned from {@link cancel} will fulfill only after all attached handlers
* up the entire promise chain have been run.
*
* If `onrejected` returns a cancellable promise,
* cancellation requests will be diverted to it,
* and the specified `oncancelled` callback will be discarded.
* See {@link then} for more details.
*/
catch(onrejected, oncancelled) {
return this.then(undefined, onrejected, oncancelled);
}
/**
* Attaches a callback that is invoked when the CancellablePromise is settled (fulfilled or rejected). The
* resolved value cannot be accessed or modified from the callback.
* The returned promise will settle in the same state as the original one
* after the provided callback has completed execution,
* unless the callback throws or returns a rejecting promise,
* in which case the returned promise will reject as well.
*
* The optional `oncancelled` argument will be invoked when the returned promise is cancelled,
* with the same semantics as the `oncancelled` argument of the constructor.
* Once the parent promise settles, the `onfinally` callback will run,
* _even after the returned promise has been cancelled:_
* in that case, should it reject or throw, the reason will be wrapped
* in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection.
*
* This method is implemented in terms of {@link then} and the same caveats apply.
* It is polyfilled, hence available in every OS/webview version.
*
* @returns A Promise for the completion of the callback.
* Cancellation requests on the returned promise
* will propagate up the chain to the parent promise,
* but not in the other direction.
*
* The promise returned from {@link cancel} will fulfill only after all attached handlers
* up the entire promise chain have been run.
*
* If `onfinally` returns a cancellable promise,
* cancellation requests will be diverted to it,
* and the specified `oncancelled` callback will be discarded.
* See {@link then} for more details.
*/
finally(onfinally, oncancelled) {
if (!(this instanceof CancellablePromise)) {
throw new TypeError("CancellablePromise.prototype.finally called on an invalid object.");
}
if (!isCallable(onfinally)) {
return this.then(onfinally, onfinally, oncancelled);
}
return this.then((value) => CancellablePromise.resolve(onfinally()).then(() => value), (reason) => CancellablePromise.resolve(onfinally()).then(() => { throw reason; }), oncancelled);
}
/**
* We use the `[Symbol.species]` static property, if available,
* to disable the built-in automatic subclassing features from {@link Promise}.
* It is critical for performance reasons that extenders do not override this.
* Once the proposal at https://github.com/tc39/proposal-rm-builtin-subclassing
* is either accepted or retired, this implementation will have to be revised accordingly.
*
* @ignore
* @internal
*/
static get [species]() {
return Promise;
}
static all(values) {
let collected = Array.from(values);
const promise = collected.length === 0
? CancellablePromise.resolve(collected)
: new CancellablePromise((resolve, reject) => {
void Promise.all(collected).then(resolve, reject);
}, (cause) => cancelAll(promise, collected, cause));
return promise;
}
static allSettled(values) {
let collected = Array.from(values);
const promise = collected.length === 0
? CancellablePromise.resolve(collected)
: new CancellablePromise((resolve, reject) => {
void Promise.allSettled(collected).then(resolve, reject);
}, (cause) => cancelAll(promise, collected, cause));
return promise;
}
static any(values) {
let collected = Array.from(values);
const promise = collected.length === 0
? CancellablePromise.resolve(collected)
: new CancellablePromise((resolve, reject) => {
void Promise.any(collected).then(resolve, reject);
}, (cause) => cancelAll(promise, collected, cause));
return promise;
}
static race(values) {
let collected = Array.from(values);
const promise = new CancellablePromise((resolve, reject) => {
void Promise.race(collected).then(resolve, reject);
}, (cause) => cancelAll(promise, collected, cause));
return promise;
}
/**
* Creates a new cancelled CancellablePromise for the provided cause.
*
* @group Static Methods
*/
static cancel(cause) {
const p = new CancellablePromise(() => { });
p.cancel(cause);
return p;
}
/**
* Creates a new CancellablePromise that cancels
* after the specified timeout, with the provided cause.
*
* If the {@link AbortSignal.timeout} factory method is available,
* it is used to base the timeout on _active_ time rather than _elapsed_ time.
* Otherwise, `timeout` falls back to {@link setTimeout}.
*
* @group Static Methods
*/
static timeout(milliseconds, cause) {
const promise = new CancellablePromise(() => { });
if (AbortSignal && typeof AbortSignal === 'function' && AbortSignal.timeout && typeof AbortSignal.timeout === 'function') {
AbortSignal.timeout(milliseconds).addEventListener('abort', () => void promise.cancel(cause));
}
else {
setTimeout(() => void promise.cancel(cause), milliseconds);
}
return promise;
}
static sleep(milliseconds, value) {
return new CancellablePromise((resolve) => {
setTimeout(() => resolve(value), milliseconds);
});
}
/**
* Creates a new rejected CancellablePromise for the provided reason.
*
* @group Static Methods
*/
static reject(reason) {
return new CancellablePromise((_, reject) => reject(reason));
}
static resolve(value) {
if (value instanceof CancellablePromise) {
// Optimise for cancellable promises.
return value;
}
return new CancellablePromise((resolve) => resolve(value));
}
/**
* Creates a new CancellablePromise and returns it in an object, along with its resolve and reject functions
* and a getter/setter for the cancellation callback.
*
* This method is polyfilled, hence available in every OS/webview version.
*
* @group Static Methods
*/
static withResolvers() {
let result = { oncancelled: null };
result.promise = new CancellablePromise((resolve, reject) => {
result.resolve = resolve;
result.reject = reject;
}, (cause) => { var _a; (_a = result.oncancelled) === null || _a === void 0 ? void 0 : _a.call(result, cause); });
return result;
}
}
/**
* Returns a callback that implements the cancellation algorithm for the given cancellable promise.
* The promise returned from the resulting function does not reject.
*/
function cancellerFor(promise, state) {
let cancellationPromise = undefined;
return (reason) => {
if (!state.settled) {
state.settled = true;
state.reason = reason;
promise.reject(reason);
// Attach an error handler that ignores this specific rejection reason and nothing else.
// In theory, a sane underlying implementation at this point
// should always reject with our cancellation reason,
// hence the handler will never throw.
void Promise.prototype.then.call(promise.promise, undefined, (err) => {
if (err !== reason) {
throw err;
}
});
}
// If reason is not set, the promise resolved regularly, hence we must not call oncancelled.
// If oncancelled is unset, no need to go any further.
if (!state.reason || !promise.oncancelled) {
return;
}
cancellationPromise = new Promise((resolve) => {
try {
resolve(promise.oncancelled(state.reason.cause));
}
catch (err) {
Promise.reject(new CancelledRejectionError(promise.promise, err, "Unhandled exception in oncancelled callback."));
}
}).catch((reason) => {
Promise.reject(new CancelledRejectionError(promise.promise, reason, "Unhandled rejection in oncancelled callback."));
});
// Unset oncancelled to prevent repeated calls.
promise.oncancelled = null;
return cancellationPromise;
};
}
/**
* Returns a callback that implements the resolution algorithm for the given cancellable promise.
*/
function resolverFor(promise, state) {
return (value) => {
if (state.resolving) {
return;
}
state.resolving = true;
if (value === promise.promise) {
if (state.settled) {
return;
}
state.settled = true;
promise.reject(new TypeError("A promise cannot be resolved with itself."));
return;
}
if (value != null && (typeof value === 'object' || typeof value === 'function')) {
let then;
try {
then = value.then;
}
catch (err) {
state.settled = true;
promise.reject(err);
return;
}
if (isCallable(then)) {
try {
let cancel = value.cancel;
if (isCallable(cancel)) {
const oncancelled = (cause) => {
Reflect.apply(cancel, value, [cause]);
};
if (state.reason) {
// If already cancelled, propagate cancellation.
// The promise returned from the canceller algorithm does not reject
// so it can be discarded safely.
void cancellerFor(Object.assign(Object.assign({}, promise), { oncancelled }), state)(state.reason);
}
else {
promise.oncancelled = oncancelled;
}
}
}
catch (_a) { }
const newState = {
root: state.root,
resolving: false,
get settled() { return this.root.settled; },
set settled(value) { this.root.settled = value; },
get reason() { return this.root.reason; }
};
const rejector = rejectorFor(promise, newState);
try {
Reflect.apply(then, value, [resolverFor(promise, newState), rejector]);
}
catch (err) {
rejector(err);
}
return; // IMPORTANT!
}
}
if (state.settled) {
return;
}
state.settled = true;
promise.resolve(value);
};
}
/**
* Returns a callback that implements the rejection algorithm for the given cancellable promise.
*/
function rejectorFor(promise, state) {
return (reason) => {
if (state.resolving) {
return;
}
state.resolving = true;
if (state.settled) {
try {
if (reason instanceof CancelError && state.reason instanceof CancelError && Object.is(reason.cause, state.reason.cause)) {
// Swallow late rejections that are CancelErrors whose cancellation cause is the same as ours.
return;
}
}
catch (_a) { }
void Promise.reject(new CancelledRejectionError(promise.promise, reason));
}
else {
state.settled = true;
promise.reject(reason);
}
};
}
/**
* Cancels all values in an array that look like cancellable thenables.
* Returns a promise that fulfills once all cancellation procedures for the given values have settled.
*/
function cancelAll(parent, values, cause) {
const results = [];
for (const value of values) {
let cancel;
try {
if (!isCallable(value.then)) {
continue;
}
cancel = value.cancel;
if (!isCallable(cancel)) {
continue;
}
}
catch (_a) {
continue;
}
let result;
try {
result = Reflect.apply(cancel, value, [cause]);
}
catch (err) {
Promise.reject(new CancelledRejectionError(parent, err, "Unhandled exception in cancel method."));
continue;
}
if (!result) {
continue;
}
results.push((result instanceof Promise ? result : Promise.resolve(result)).catch((reason) => {
Promise.reject(new CancelledRejectionError(parent, reason, "Unhandled rejection in cancel method."));
}));
}
return Promise.all(results);
}
/**
* Returns its argument.
*/
function identity(x) {
return x;
}
/**
* Throws its argument.
*/
function thrower(reason) {
throw reason;
}
/**
* Attempts various strategies to convert an error to a string.
*/
function errorMessage(err) {
try {
if (err instanceof Error || typeof err !== 'object' || err.toString !== Object.prototype.toString) {
return "" + err;
}
}
catch (_a) { }
try {
return JSON.stringify(err);
}
catch (_b) { }
try {
return Object.prototype.toString.call(err);
}
catch (_c) { }
return "<could not convert error to string>";
}
/**
* Gets the current barrier promise for the given cancellable promise. If necessary, initialises the barrier.
*/
function currentBarrier(promise) {
var _a;
let pwr = (_a = promise[barrierSym]) !== null && _a !== void 0 ? _a : {};
if (!('promise' in pwr)) {
Object.assign(pwr, promiseWithResolvers());
}
if (promise[barrierSym] == null) {
pwr.resolve();
promise[barrierSym] = pwr;
}
return pwr.promise;
}
// Polyfill Promise.withResolvers.
let promiseWithResolvers = Promise.withResolvers;
if (promiseWithResolvers && typeof promiseWithResolvers === 'function') {
promiseWithResolvers = promiseWithResolvers.bind(Promise);
}
else {
promiseWithResolvers = function () {
let resolve;
let reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
};
}

View File

@@ -1,30 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const call = newRuntimeCaller(objectNames.Clipboard);
const ClipboardSetText = 0;
const ClipboardText = 1;
/**
* Sets the text to the Clipboard.
*
* @param text - The text to be set to the Clipboard.
* @return A Promise that resolves when the operation is successful.
*/
export function SetText(text) {
return call(ClipboardSetText, { text });
}
/**
* Get the Clipboard text
*
* @returns A promise that resolves with the text from the Clipboard.
*/
export function Text() {
return call(ClipboardText);
}

View File

@@ -1,80 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
import { IsDebug } from "./system.js";
import { eventTarget } from "./utils";
// setup
window.addEventListener('contextmenu', contextMenuHandler);
const call = newRuntimeCaller(objectNames.ContextMenu);
const ContextMenuOpen = 0;
function openContextMenu(id, x, y, data) {
void call(ContextMenuOpen, { id, x, y, data });
}
function contextMenuHandler(event) {
const target = eventTarget(event);
// Check for custom context menu
const customContextMenu = window.getComputedStyle(target).getPropertyValue("--custom-contextmenu").trim();
if (customContextMenu) {
event.preventDefault();
const data = window.getComputedStyle(target).getPropertyValue("--custom-contextmenu-data");
openContextMenu(customContextMenu, event.clientX, event.clientY, data);
}
else {
processDefaultContextMenu(event, target);
}
}
/*
--default-contextmenu: auto; (default) will show the default context menu if contentEditable is true OR text has been selected OR element is input or textarea
--default-contextmenu: show; will always show the default context menu
--default-contextmenu: hide; will always hide the default context menu
This rule is inherited like normal CSS rules, so nesting works as expected
*/
function processDefaultContextMenu(event, target) {
// Debug builds always show the menu
if (IsDebug()) {
return;
}
// Process default context menu
switch (window.getComputedStyle(target).getPropertyValue("--default-contextmenu").trim()) {
case 'show':
return;
case 'hide':
event.preventDefault();
return;
}
// Check if contentEditable is true
if (target.isContentEditable) {
return;
}
// Check if text has been selected
const selection = window.getSelection();
const hasSelection = selection && selection.toString().length > 0;
if (hasSelection) {
for (let i = 0; i < selection.rangeCount; i++) {
const range = selection.getRangeAt(i);
const rects = range.getClientRects();
for (let j = 0; j < rects.length; j++) {
const rect = rects[j];
if (document.elementFromPoint(rect.left, rect.top) === target) {
return;
}
}
}
}
// Check if tag is input or textarea.
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
if (hasSelection || (!target.readOnly && !target.disabled)) {
return;
}
}
// hide default context menu
event.preventDefault();
}

View File

@@ -1,94 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
/**
* Any is a dummy creation function for simple or unknown types.
*/
export function Any(source) {
return source;
}
/**
* ByteSlice is a creation function that replaces
* null strings with empty strings.
*/
export function ByteSlice(source) {
return ((source == null) ? "" : source);
}
/**
* Array takes a creation function for an arbitrary type
* and returns an in-place creation function for an array
* whose elements are of that type.
*/
export function Array(element) {
if (element === Any) {
return (source) => (source === null ? [] : source);
}
return (source) => {
if (source === null) {
return [];
}
for (let i = 0; i < source.length; i++) {
source[i] = element(source[i]);
}
return source;
};
}
/**
* Map takes creation functions for two arbitrary types
* and returns an in-place creation function for an object
* whose keys and values are of those types.
*/
export function Map(key, value) {
if (value === Any) {
return (source) => (source === null ? {} : source);
}
return (source) => {
if (source === null) {
return {};
}
for (const key in source) {
source[key] = value(source[key]);
}
return source;
};
}
/**
* Nullable takes a creation function for an arbitrary type
* and returns a creation function for a nullable value of that type.
*/
export function Nullable(element) {
if (element === Any) {
return Any;
}
return (source) => (source === null ? null : element(source));
}
/**
* Struct takes an object mapping field names to creation functions
* and returns an in-place creation function for a struct.
*/
export function Struct(createField) {
let allAny = true;
for (const name in createField) {
if (createField[name] !== Any) {
allAny = false;
break;
}
}
if (allAny) {
return Any;
}
return (source) => {
for (const name in createField) {
if (name in source) {
source[name] = createField[name](source[name]);
}
}
return source;
};
}

View File

@@ -1,134 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
import { nanoid } from './nanoid.js';
// setup
window._wails = window._wails || {};
window._wails.dialogErrorCallback = dialogErrorCallback;
window._wails.dialogResultCallback = dialogResultCallback;
const call = newRuntimeCaller(objectNames.Dialog);
const dialogResponses = new Map();
// Define constants from the `methods` object in Title Case
const DialogInfo = 0;
const DialogWarning = 1;
const DialogError = 2;
const DialogQuestion = 3;
const DialogOpenFile = 4;
const DialogSaveFile = 5;
/**
* Handles the result of a dialog request.
*
* @param id - The id of the request to handle the result for.
* @param data - The result data of the request.
* @param isJSON - Indicates whether the data is JSON or not.
*/
function dialogResultCallback(id, data, isJSON) {
let resolvers = getAndDeleteResponse(id);
if (!resolvers) {
return;
}
if (isJSON) {
try {
resolvers.resolve(JSON.parse(data));
}
catch (err) {
resolvers.reject(new TypeError("could not parse result: " + err.message, { cause: err }));
}
}
else {
resolvers.resolve(data);
}
}
/**
* Handles the error from a dialog request.
*
* @param id - The id of the promise handler.
* @param message - An error message.
*/
function dialogErrorCallback(id, message) {
var _a;
(_a = getAndDeleteResponse(id)) === null || _a === void 0 ? void 0 : _a.reject(new window.Error(message));
}
/**
* Retrieves and removes the response associated with the given ID from the dialogResponses map.
*
* @param id - The ID of the response to be retrieved and removed.
* @returns The response object associated with the given ID, if any.
*/
function getAndDeleteResponse(id) {
const response = dialogResponses.get(id);
dialogResponses.delete(id);
return response;
}
/**
* Generates a unique ID using the nanoid library.
*
* @returns A unique ID that does not exist in the dialogResponses set.
*/
function generateID() {
let result;
do {
result = nanoid();
} while (dialogResponses.has(result));
return result;
}
/**
* Presents a dialog of specified type with the given options.
*
* @param type - Dialog type.
* @param options - Options for the dialog.
* @returns A promise that resolves with result of dialog.
*/
function dialog(type, options = {}) {
const id = generateID();
return new Promise((resolve, reject) => {
dialogResponses.set(id, { resolve, reject });
call(type, Object.assign({ "dialog-id": id }, options)).catch((err) => {
dialogResponses.delete(id);
reject(err);
});
});
}
/**
* Presents an info dialog.
*
* @param options - Dialog options
* @returns A promise that resolves with the label of the chosen button.
*/
export function Info(options) { return dialog(DialogInfo, options); }
/**
* Presents a warning dialog.
*
* @param options - Dialog options.
* @returns A promise that resolves with the label of the chosen button.
*/
export function Warning(options) { return dialog(DialogWarning, options); }
/**
* Presents an error dialog.
*
* @param options - Dialog options.
* @returns A promise that resolves with the label of the chosen button.
*/
export function Error(options) { return dialog(DialogError, options); }
/**
* Presents a question dialog.
*
* @param options - Dialog options.
* @returns A promise that resolves with the label of the chosen button.
*/
export function Question(options) { return dialog(DialogQuestion, options); }
export function OpenFile(options) { var _a; return (_a = dialog(DialogOpenFile, options)) !== null && _a !== void 0 ? _a : []; }
/**
* Presents a file selection dialog to pick a file to save.
*
* @param options - Dialog options.
* @returns Selected file, or a blank string if no file has been selected.
*/
export function SaveFile(options) { return dialog(DialogSaveFile, options); }

View File

@@ -1,222 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { invoke, IsWindows } from "./system.js";
import { GetFlag } from "./flags.js";
import { canTrackButtons, eventTarget } from "./utils.js";
// Setup
let canDrag = false;
let dragging = false;
let resizable = false;
let canResize = false;
let resizing = false;
let resizeEdge = "";
let defaultCursor = "auto";
let buttons = 0;
const buttonsTracked = canTrackButtons();
window._wails = window._wails || {};
window._wails.setResizable = (value) => {
resizable = value;
if (!resizable) {
// Stop resizing if in progress.
canResize = resizing = false;
setResize();
}
};
window.addEventListener('mousedown', update, { capture: true });
window.addEventListener('mousemove', update, { capture: true });
window.addEventListener('mouseup', update, { capture: true });
for (const ev of ['click', 'contextmenu', 'dblclick']) {
window.addEventListener(ev, suppressEvent, { capture: true });
}
function suppressEvent(event) {
// Suppress click events while resizing or dragging.
if (dragging || resizing) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
}
}
// Use constants to avoid comparing strings multiple times.
const MouseDown = 0;
const MouseUp = 1;
const MouseMove = 2;
function update(event) {
// Windows suppresses mouse events at the end of dragging or resizing,
// so we need to be smart and synthesize button events.
let eventType, eventButtons = event.buttons;
switch (event.type) {
case 'mousedown':
eventType = MouseDown;
if (!buttonsTracked) {
eventButtons = buttons | (1 << event.button);
}
break;
case 'mouseup':
eventType = MouseUp;
if (!buttonsTracked) {
eventButtons = buttons & ~(1 << event.button);
}
break;
default:
eventType = MouseMove;
if (!buttonsTracked) {
eventButtons = buttons;
}
break;
}
let released = buttons & ~eventButtons;
let pressed = eventButtons & ~buttons;
buttons = eventButtons;
// Synthesize a release-press sequence if we detect a press of an already pressed button.
if (eventType === MouseDown && !(pressed & event.button)) {
released |= (1 << event.button);
pressed |= (1 << event.button);
}
// Suppress all button events during dragging and resizing,
// unless this is a mouseup event that is ending a drag action.
if (eventType !== MouseMove // Fast path for mousemove
&& resizing
|| (dragging
&& (eventType === MouseDown
|| event.button !== 0))) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
}
// Handle releases
if (released & 1) {
primaryUp(event);
}
// Handle presses
if (pressed & 1) {
primaryDown(event);
}
// Handle mousemove
if (eventType === MouseMove) {
onMouseMove(event);
}
;
}
function primaryDown(event) {
// Reset readiness state.
canDrag = false;
canResize = false;
// Ignore repeated clicks on macOS and Linux.
if (!IsWindows()) {
if (event.type === 'mousedown' && event.button === 0 && event.detail !== 1) {
return;
}
}
if (resizeEdge) {
// Ready to resize if the primary button was pressed for the first time.
canResize = true;
// Do not start drag operations when on resize edges.
return;
}
// Retrieve target element
const target = eventTarget(event);
// Ready to drag if the primary button was pressed for the first time on a draggable element.
// Ignore clicks on the scrollbar.
const style = window.getComputedStyle(target);
canDrag = (style.getPropertyValue("--wails-draggable").trim() === "drag"
&& (event.offsetX - parseFloat(style.paddingLeft) < target.clientWidth
&& event.offsetY - parseFloat(style.paddingTop) < target.clientHeight));
}
function primaryUp(event) {
// Stop dragging and resizing.
canDrag = false;
dragging = false;
canResize = false;
resizing = false;
}
const cursorForEdge = Object.freeze({
"se-resize": "nwse-resize",
"sw-resize": "nesw-resize",
"nw-resize": "nwse-resize",
"ne-resize": "nesw-resize",
"w-resize": "ew-resize",
"n-resize": "ns-resize",
"s-resize": "ns-resize",
"e-resize": "ew-resize",
});
function setResize(edge) {
if (edge) {
if (!resizeEdge) {
defaultCursor = document.body.style.cursor;
}
document.body.style.cursor = cursorForEdge[edge];
}
else if (!edge && resizeEdge) {
document.body.style.cursor = defaultCursor;
}
resizeEdge = edge || "";
}
function onMouseMove(event) {
if (canResize && resizeEdge) {
// Start resizing.
resizing = true;
invoke("wails:resize:" + resizeEdge);
}
else if (canDrag) {
// Start dragging.
dragging = true;
invoke("wails:drag");
}
if (dragging || resizing) {
// Either drag or resize is ongoing,
// reset readiness and stop processing.
canDrag = canResize = false;
return;
}
if (!resizable || !IsWindows()) {
if (resizeEdge) {
setResize();
}
return;
}
const resizeHandleHeight = GetFlag("system.resizeHandleHeight") || 5;
const resizeHandleWidth = GetFlag("system.resizeHandleWidth") || 5;
// Extra pixels for the corner areas.
const cornerExtra = GetFlag("resizeCornerExtra") || 10;
const rightBorder = (window.outerWidth - event.clientX) < resizeHandleWidth;
const leftBorder = event.clientX < resizeHandleWidth;
const topBorder = event.clientY < resizeHandleHeight;
const bottomBorder = (window.outerHeight - event.clientY) < resizeHandleHeight;
// Adjust for corner areas.
const rightCorner = (window.outerWidth - event.clientX) < (resizeHandleWidth + cornerExtra);
const leftCorner = event.clientX < (resizeHandleWidth + cornerExtra);
const topCorner = event.clientY < (resizeHandleHeight + cornerExtra);
const bottomCorner = (window.outerHeight - event.clientY) < (resizeHandleHeight + cornerExtra);
if (!leftCorner && !topCorner && !bottomCorner && !rightCorner) {
// Optimisation: out of all corner areas implies out of borders.
setResize();
}
// Detect corners.
else if (rightCorner && bottomCorner)
setResize("se-resize");
else if (leftCorner && bottomCorner)
setResize("sw-resize");
else if (leftCorner && topCorner)
setResize("nw-resize");
else if (topCorner && rightCorner)
setResize("ne-resize");
// Detect borders.
else if (leftBorder)
setResize("w-resize");
else if (topBorder)
setResize("n-resize");
else if (bottomBorder)
setResize("s-resize");
else if (rightBorder)
setResize("e-resize");
// Out of border area.
else
setResize();
}

View File

@@ -1,229 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export const Types = Object.freeze({
Windows: Object.freeze({
APMPowerSettingChange: "windows:APMPowerSettingChange",
APMPowerStatusChange: "windows:APMPowerStatusChange",
APMResumeAutomatic: "windows:APMResumeAutomatic",
APMResumeSuspend: "windows:APMResumeSuspend",
APMSuspend: "windows:APMSuspend",
ApplicationStarted: "windows:ApplicationStarted",
SystemThemeChanged: "windows:SystemThemeChanged",
WebViewNavigationCompleted: "windows:WebViewNavigationCompleted",
WindowActive: "windows:WindowActive",
WindowBackgroundErase: "windows:WindowBackgroundErase",
WindowClickActive: "windows:WindowClickActive",
WindowClosing: "windows:WindowClosing",
WindowDidMove: "windows:WindowDidMove",
WindowDidResize: "windows:WindowDidResize",
WindowDPIChanged: "windows:WindowDPIChanged",
WindowDragDrop: "windows:WindowDragDrop",
WindowDragEnter: "windows:WindowDragEnter",
WindowDragLeave: "windows:WindowDragLeave",
WindowDragOver: "windows:WindowDragOver",
WindowEndMove: "windows:WindowEndMove",
WindowEndResize: "windows:WindowEndResize",
WindowFullscreen: "windows:WindowFullscreen",
WindowHide: "windows:WindowHide",
WindowInactive: "windows:WindowInactive",
WindowKeyDown: "windows:WindowKeyDown",
WindowKeyUp: "windows:WindowKeyUp",
WindowKillFocus: "windows:WindowKillFocus",
WindowNonClientHit: "windows:WindowNonClientHit",
WindowNonClientMouseDown: "windows:WindowNonClientMouseDown",
WindowNonClientMouseLeave: "windows:WindowNonClientMouseLeave",
WindowNonClientMouseMove: "windows:WindowNonClientMouseMove",
WindowNonClientMouseUp: "windows:WindowNonClientMouseUp",
WindowPaint: "windows:WindowPaint",
WindowRestore: "windows:WindowRestore",
WindowSetFocus: "windows:WindowSetFocus",
WindowShow: "windows:WindowShow",
WindowStartMove: "windows:WindowStartMove",
WindowStartResize: "windows:WindowStartResize",
WindowUnFullscreen: "windows:WindowUnFullscreen",
WindowZOrderChanged: "windows:WindowZOrderChanged",
WindowMinimise: "windows:WindowMinimise",
WindowUnMinimise: "windows:WindowUnMinimise",
WindowMaximise: "windows:WindowMaximise",
WindowUnMaximise: "windows:WindowUnMaximise",
}),
Mac: Object.freeze({
ApplicationDidBecomeActive: "mac:ApplicationDidBecomeActive",
ApplicationDidChangeBackingProperties: "mac:ApplicationDidChangeBackingProperties",
ApplicationDidChangeEffectiveAppearance: "mac:ApplicationDidChangeEffectiveAppearance",
ApplicationDidChangeIcon: "mac:ApplicationDidChangeIcon",
ApplicationDidChangeOcclusionState: "mac:ApplicationDidChangeOcclusionState",
ApplicationDidChangeScreenParameters: "mac:ApplicationDidChangeScreenParameters",
ApplicationDidChangeStatusBarFrame: "mac:ApplicationDidChangeStatusBarFrame",
ApplicationDidChangeStatusBarOrientation: "mac:ApplicationDidChangeStatusBarOrientation",
ApplicationDidChangeTheme: "mac:ApplicationDidChangeTheme",
ApplicationDidFinishLaunching: "mac:ApplicationDidFinishLaunching",
ApplicationDidHide: "mac:ApplicationDidHide",
ApplicationDidResignActive: "mac:ApplicationDidResignActive",
ApplicationDidUnhide: "mac:ApplicationDidUnhide",
ApplicationDidUpdate: "mac:ApplicationDidUpdate",
ApplicationShouldHandleReopen: "mac:ApplicationShouldHandleReopen",
ApplicationWillBecomeActive: "mac:ApplicationWillBecomeActive",
ApplicationWillFinishLaunching: "mac:ApplicationWillFinishLaunching",
ApplicationWillHide: "mac:ApplicationWillHide",
ApplicationWillResignActive: "mac:ApplicationWillResignActive",
ApplicationWillTerminate: "mac:ApplicationWillTerminate",
ApplicationWillUnhide: "mac:ApplicationWillUnhide",
ApplicationWillUpdate: "mac:ApplicationWillUpdate",
MenuDidAddItem: "mac:MenuDidAddItem",
MenuDidBeginTracking: "mac:MenuDidBeginTracking",
MenuDidClose: "mac:MenuDidClose",
MenuDidDisplayItem: "mac:MenuDidDisplayItem",
MenuDidEndTracking: "mac:MenuDidEndTracking",
MenuDidHighlightItem: "mac:MenuDidHighlightItem",
MenuDidOpen: "mac:MenuDidOpen",
MenuDidPopUp: "mac:MenuDidPopUp",
MenuDidRemoveItem: "mac:MenuDidRemoveItem",
MenuDidSendAction: "mac:MenuDidSendAction",
MenuDidSendActionToItem: "mac:MenuDidSendActionToItem",
MenuDidUpdate: "mac:MenuDidUpdate",
MenuWillAddItem: "mac:MenuWillAddItem",
MenuWillBeginTracking: "mac:MenuWillBeginTracking",
MenuWillDisplayItem: "mac:MenuWillDisplayItem",
MenuWillEndTracking: "mac:MenuWillEndTracking",
MenuWillHighlightItem: "mac:MenuWillHighlightItem",
MenuWillOpen: "mac:MenuWillOpen",
MenuWillPopUp: "mac:MenuWillPopUp",
MenuWillRemoveItem: "mac:MenuWillRemoveItem",
MenuWillSendAction: "mac:MenuWillSendAction",
MenuWillSendActionToItem: "mac:MenuWillSendActionToItem",
MenuWillUpdate: "mac:MenuWillUpdate",
WebViewDidCommitNavigation: "mac:WebViewDidCommitNavigation",
WebViewDidFinishNavigation: "mac:WebViewDidFinishNavigation",
WebViewDidReceiveServerRedirectForProvisionalNavigation: "mac:WebViewDidReceiveServerRedirectForProvisionalNavigation",
WebViewDidStartProvisionalNavigation: "mac:WebViewDidStartProvisionalNavigation",
WindowDidBecomeKey: "mac:WindowDidBecomeKey",
WindowDidBecomeMain: "mac:WindowDidBecomeMain",
WindowDidBeginSheet: "mac:WindowDidBeginSheet",
WindowDidChangeAlpha: "mac:WindowDidChangeAlpha",
WindowDidChangeBackingLocation: "mac:WindowDidChangeBackingLocation",
WindowDidChangeBackingProperties: "mac:WindowDidChangeBackingProperties",
WindowDidChangeCollectionBehavior: "mac:WindowDidChangeCollectionBehavior",
WindowDidChangeEffectiveAppearance: "mac:WindowDidChangeEffectiveAppearance",
WindowDidChangeOcclusionState: "mac:WindowDidChangeOcclusionState",
WindowDidChangeOrderingMode: "mac:WindowDidChangeOrderingMode",
WindowDidChangeScreen: "mac:WindowDidChangeScreen",
WindowDidChangeScreenParameters: "mac:WindowDidChangeScreenParameters",
WindowDidChangeScreenProfile: "mac:WindowDidChangeScreenProfile",
WindowDidChangeScreenSpace: "mac:WindowDidChangeScreenSpace",
WindowDidChangeScreenSpaceProperties: "mac:WindowDidChangeScreenSpaceProperties",
WindowDidChangeSharingType: "mac:WindowDidChangeSharingType",
WindowDidChangeSpace: "mac:WindowDidChangeSpace",
WindowDidChangeSpaceOrderingMode: "mac:WindowDidChangeSpaceOrderingMode",
WindowDidChangeTitle: "mac:WindowDidChangeTitle",
WindowDidChangeToolbar: "mac:WindowDidChangeToolbar",
WindowDidDeminiaturize: "mac:WindowDidDeminiaturize",
WindowDidEndSheet: "mac:WindowDidEndSheet",
WindowDidEnterFullScreen: "mac:WindowDidEnterFullScreen",
WindowDidEnterVersionBrowser: "mac:WindowDidEnterVersionBrowser",
WindowDidExitFullScreen: "mac:WindowDidExitFullScreen",
WindowDidExitVersionBrowser: "mac:WindowDidExitVersionBrowser",
WindowDidExpose: "mac:WindowDidExpose",
WindowDidFocus: "mac:WindowDidFocus",
WindowDidMiniaturize: "mac:WindowDidMiniaturize",
WindowDidMove: "mac:WindowDidMove",
WindowDidOrderOffScreen: "mac:WindowDidOrderOffScreen",
WindowDidOrderOnScreen: "mac:WindowDidOrderOnScreen",
WindowDidResignKey: "mac:WindowDidResignKey",
WindowDidResignMain: "mac:WindowDidResignMain",
WindowDidResize: "mac:WindowDidResize",
WindowDidUpdate: "mac:WindowDidUpdate",
WindowDidUpdateAlpha: "mac:WindowDidUpdateAlpha",
WindowDidUpdateCollectionBehavior: "mac:WindowDidUpdateCollectionBehavior",
WindowDidUpdateCollectionProperties: "mac:WindowDidUpdateCollectionProperties",
WindowDidUpdateShadow: "mac:WindowDidUpdateShadow",
WindowDidUpdateTitle: "mac:WindowDidUpdateTitle",
WindowDidUpdateToolbar: "mac:WindowDidUpdateToolbar",
WindowDidZoom: "mac:WindowDidZoom",
WindowFileDraggingEntered: "mac:WindowFileDraggingEntered",
WindowFileDraggingExited: "mac:WindowFileDraggingExited",
WindowFileDraggingPerformed: "mac:WindowFileDraggingPerformed",
WindowHide: "mac:WindowHide",
WindowMaximise: "mac:WindowMaximise",
WindowUnMaximise: "mac:WindowUnMaximise",
WindowMinimise: "mac:WindowMinimise",
WindowUnMinimise: "mac:WindowUnMinimise",
WindowShouldClose: "mac:WindowShouldClose",
WindowShow: "mac:WindowShow",
WindowWillBecomeKey: "mac:WindowWillBecomeKey",
WindowWillBecomeMain: "mac:WindowWillBecomeMain",
WindowWillBeginSheet: "mac:WindowWillBeginSheet",
WindowWillChangeOrderingMode: "mac:WindowWillChangeOrderingMode",
WindowWillClose: "mac:WindowWillClose",
WindowWillDeminiaturize: "mac:WindowWillDeminiaturize",
WindowWillEnterFullScreen: "mac:WindowWillEnterFullScreen",
WindowWillEnterVersionBrowser: "mac:WindowWillEnterVersionBrowser",
WindowWillExitFullScreen: "mac:WindowWillExitFullScreen",
WindowWillExitVersionBrowser: "mac:WindowWillExitVersionBrowser",
WindowWillFocus: "mac:WindowWillFocus",
WindowWillMiniaturize: "mac:WindowWillMiniaturize",
WindowWillMove: "mac:WindowWillMove",
WindowWillOrderOffScreen: "mac:WindowWillOrderOffScreen",
WindowWillOrderOnScreen: "mac:WindowWillOrderOnScreen",
WindowWillResignMain: "mac:WindowWillResignMain",
WindowWillResize: "mac:WindowWillResize",
WindowWillUnfocus: "mac:WindowWillUnfocus",
WindowWillUpdate: "mac:WindowWillUpdate",
WindowWillUpdateAlpha: "mac:WindowWillUpdateAlpha",
WindowWillUpdateCollectionBehavior: "mac:WindowWillUpdateCollectionBehavior",
WindowWillUpdateCollectionProperties: "mac:WindowWillUpdateCollectionProperties",
WindowWillUpdateShadow: "mac:WindowWillUpdateShadow",
WindowWillUpdateTitle: "mac:WindowWillUpdateTitle",
WindowWillUpdateToolbar: "mac:WindowWillUpdateToolbar",
WindowWillUpdateVisibility: "mac:WindowWillUpdateVisibility",
WindowWillUseStandardFrame: "mac:WindowWillUseStandardFrame",
WindowZoomIn: "mac:WindowZoomIn",
WindowZoomOut: "mac:WindowZoomOut",
WindowZoomReset: "mac:WindowZoomReset",
}),
Linux: Object.freeze({
ApplicationStartup: "linux:ApplicationStartup",
SystemThemeChanged: "linux:SystemThemeChanged",
WindowDeleteEvent: "linux:WindowDeleteEvent",
WindowDidMove: "linux:WindowDidMove",
WindowDidResize: "linux:WindowDidResize",
WindowFocusIn: "linux:WindowFocusIn",
WindowFocusOut: "linux:WindowFocusOut",
WindowLoadChanged: "linux:WindowLoadChanged",
}),
Common: Object.freeze({
ApplicationOpenedWithFile: "common:ApplicationOpenedWithFile",
ApplicationStarted: "common:ApplicationStarted",
ThemeChanged: "common:ThemeChanged",
WindowClosing: "common:WindowClosing",
WindowDidMove: "common:WindowDidMove",
WindowDidResize: "common:WindowDidResize",
WindowDPIChanged: "common:WindowDPIChanged",
WindowFilesDropped: "common:WindowFilesDropped",
WindowFocus: "common:WindowFocus",
WindowFullscreen: "common:WindowFullscreen",
WindowHide: "common:WindowHide",
WindowLostFocus: "common:WindowLostFocus",
WindowMaximise: "common:WindowMaximise",
WindowMinimise: "common:WindowMinimise",
WindowRestore: "common:WindowRestore",
WindowRuntimeReady: "common:WindowRuntimeReady",
WindowShow: "common:WindowShow",
WindowUnFullscreen: "common:WindowUnFullscreen",
WindowUnMaximise: "common:WindowUnMaximise",
WindowUnMinimise: "common:WindowUnMinimise",
WindowZoom: "common:WindowZoom",
WindowZoomIn: "common:WindowZoomIn",
WindowZoomOut: "common:WindowZoomOut",
WindowZoomReset: "common:WindowZoomReset",
}),
});

View File

@@ -1,101 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
import { eventListeners, Listener, listenerOff } from "./listener.js";
// Setup
window._wails = window._wails || {};
window._wails.dispatchWailsEvent = dispatchWailsEvent;
const call = newRuntimeCaller(objectNames.Events);
const EmitMethod = 0;
export { Types } from "./event_types.js";
/**
* Represents a system event or a custom event emitted through wails-provided facilities.
*/
export class WailsEvent {
constructor(name, data = null) {
this.name = name;
this.data = data;
}
}
function dispatchWailsEvent(event) {
let listeners = eventListeners.get(event.name);
if (!listeners) {
return;
}
let wailsEvent = new WailsEvent(event.name, event.data);
if ('sender' in event) {
wailsEvent.sender = event.sender;
}
listeners = listeners.filter(listener => !listener.dispatch(wailsEvent));
if (listeners.length === 0) {
eventListeners.delete(event.name);
}
else {
eventListeners.set(event.name, listeners);
}
}
/**
* Register a callback function to be called multiple times for a specific event.
*
* @param eventName - The name of the event to register the callback for.
* @param callback - The callback function to be called when the event is triggered.
* @param maxCallbacks - The maximum number of times the callback can be called for the event. Once the maximum number is reached, the callback will no longer be called.
* @returns A function that, when called, will unregister the callback from the event.
*/
export function OnMultiple(eventName, callback, maxCallbacks) {
let listeners = eventListeners.get(eventName) || [];
const thisListener = new Listener(eventName, callback, maxCallbacks);
listeners.push(thisListener);
eventListeners.set(eventName, listeners);
return () => listenerOff(thisListener);
}
/**
* Registers a callback function to be executed when the specified event occurs.
*
* @param eventName - The name of the event to register the callback for.
* @param callback - The callback function to be called when the event is triggered.
* @returns A function that, when called, will unregister the callback from the event.
*/
export function On(eventName, callback) {
return OnMultiple(eventName, callback, -1);
}
/**
* Registers a callback function to be executed only once for the specified event.
*
* @param eventName - The name of the event to register the callback for.
* @param callback - The callback function to be called when the event is triggered.
* @returns A function that, when called, will unregister the callback from the event.
*/
export function Once(eventName, callback) {
return OnMultiple(eventName, callback, 1);
}
/**
* Removes event listeners for the specified event names.
*
* @param eventNames - The name of the events to remove listeners for.
*/
export function Off(...eventNames) {
eventNames.forEach(eventName => eventListeners.delete(eventName));
}
/**
* Removes all event listeners.
*/
export function OffAll() {
eventListeners.clear();
}
/**
* Emits the given event.
*
* @param event - The name of the event to emit.
* @returns A promise that will be fulfilled once the event has been emitted.
*/
export function Emit(event) {
return call(EmitMethod, event);
}

View File

@@ -1,23 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
/**
* Retrieves the value associated with the specified key from the flag map.
*
* @param key - The key to retrieve the value for.
* @return The value associated with the specified key.
*/
export function GetFlag(key) {
try {
return window._wails.flags[key];
}
catch (e) {
throw new Error("Unable to retrieve flag '" + key + "': " + e, { cause: e });
}
}

View File

@@ -1,38 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
// Setup
window._wails = window._wails || {};
import "./contextmenu.js";
import "./drag.js";
// Re-export public API
import * as Application from "./application.js";
import * as Browser from "./browser.js";
import * as Call from "./calls.js";
import * as Clipboard from "./clipboard.js";
import * as Create from "./create.js";
import * as Dialogs from "./dialogs.js";
import * as Events from "./events.js";
import * as Flags from "./flags.js";
import * as Screens from "./screens.js";
import * as System from "./system.js";
import Window from "./window.js";
import * as WML from "./wml.js";
export { Application, Browser, Call, Clipboard, Dialogs, Events, Flags, Screens, System, Window, WML };
/**
* An internal utility consumed by the binding generator.
*
* @ignore
* @internal
*/
export { Create };
export * from "./cancellable.js";
// Notify backend
window._wails.invoke = System.invoke;
System.invoke("wails:runtime:ready");

View File

@@ -1,44 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
// The following utilities have been factored out of ./events.ts
// for testing purposes.
export const eventListeners = new Map();
export class Listener {
constructor(eventName, callback, maxCallbacks) {
this.eventName = eventName;
this.callback = callback;
this.maxCallbacks = maxCallbacks || -1;
}
dispatch(data) {
try {
this.callback(data);
}
catch (err) {
console.error(err);
}
if (this.maxCallbacks === -1)
return false;
this.maxCallbacks -= 1;
return this.maxCallbacks === 0;
}
}
export function listenerOff(listener) {
let listeners = eventListeners.get(listener.eventName);
if (!listeners) {
return;
}
listeners = listeners.filter(l => l !== listener);
if (listeners.length === 0) {
eventListeners.delete(listener.eventName);
}
else {
eventListeners.set(listener.eventName, listeners);
}
}

View File

@@ -1,38 +0,0 @@
// Source: https://github.com/ai/nanoid
// The MIT License (MIT)
//
// Copyright 2017 Andrey Sitnik <andrey@sitnik.ru>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// This alphabet uses `A-Za-z0-9_-` symbols.
// The order of characters is optimized for better gzip and brotli compression.
// References to the same file (works both for gzip and brotli):
// `'use`, `andom`, and `rict'`
// References to the brotli default dictionary:
// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
export function nanoid(size = 21) {
let id = '';
// A compact alternative for `for (var i = 0; i < step; i++)`.
let i = size | 0;
while (i--) {
// `| 0` is more compact and faster than `Math.floor()`.
id += urlAlphabet[(Math.random() * 64) | 0];
}
return id;
}

View File

@@ -1,63 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { nanoid } from './nanoid.js';
const runtimeURL = window.location.origin + "/wails/runtime";
// Object Names
export const objectNames = Object.freeze({
Call: 0,
Clipboard: 1,
Application: 2,
Events: 3,
ContextMenu: 4,
Dialog: 5,
Window: 6,
Screens: 7,
System: 8,
Browser: 9,
CancelCall: 10,
});
export let clientId = nanoid();
/**
* Creates a new runtime caller with specified ID.
*
* @param object - The object to invoke the method on.
* @param windowName - The name of the window.
* @return The new runtime caller function.
*/
export function newRuntimeCaller(object, windowName = '') {
return function (method, args = null) {
return runtimeCallWithID(object, method, windowName, args);
};
}
async function runtimeCallWithID(objectID, method, windowName, args) {
var _a, _b;
let url = new URL(runtimeURL);
url.searchParams.append("object", objectID.toString());
url.searchParams.append("method", method.toString());
if (args) {
url.searchParams.append("args", JSON.stringify(args));
}
let headers = {
["x-wails-client-id"]: clientId
};
if (windowName) {
headers["x-wails-window-name"] = windowName;
}
let response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(await response.text());
}
if (((_b = (_a = response.headers.get("Content-Type")) === null || _a === void 0 ? void 0 : _a.indexOf("application/json")) !== null && _b !== void 0 ? _b : -1) !== -1) {
return response.json();
}
else {
return response.text();
}
}

View File

@@ -1,38 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const call = newRuntimeCaller(objectNames.Screens);
const getAll = 0;
const getPrimary = 1;
const getCurrent = 2;
/**
* Gets all screens.
*
* @returns A promise that resolves to an array of Screen objects.
*/
export function GetAll() {
return call(getAll);
}
/**
* Gets the primary screen.
*
* @returns A promise that resolves to the primary screen.
*/
export function GetPrimary() {
return call(getPrimary);
}
/**
* Gets the current active screen.
*
* @returns A promise that resolves with the current active screen.
*/
export function GetCurrent() {
return call(getCurrent);
}

View File

@@ -1,116 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const call = newRuntimeCaller(objectNames.System);
const SystemIsDarkMode = 0;
const SystemEnvironment = 1;
const _invoke = (function () {
var _a, _b, _c, _d, _e;
try {
if ((_b = (_a = window.chrome) === null || _a === void 0 ? void 0 : _a.webview) === null || _b === void 0 ? void 0 : _b.postMessage) {
return window.chrome.webview.postMessage.bind(window.chrome.webview);
}
else if ((_e = (_d = (_c = window.webkit) === null || _c === void 0 ? void 0 : _c.messageHandlers) === null || _d === void 0 ? void 0 : _d['external']) === null || _e === void 0 ? void 0 : _e.postMessage) {
return window.webkit.messageHandlers['external'].postMessage.bind(window.webkit.messageHandlers['external']);
}
}
catch (e) { }
console.warn('\n%c⚠ Browser Environment Detected %c\n\n%cOnly UI previews are available in the browser. For full functionality, please run the application in desktop mode.\nMore information at: https://v3.wails.io/learn/build/#using-a-browser-for-development\n', 'background: #ffffff; color: #000000; font-weight: bold; padding: 4px 8px; border-radius: 4px; border: 2px solid #000000;', 'background: transparent;', 'color: #ffffff; font-style: italic; font-weight: bold;');
return null;
})();
export function invoke(msg) {
_invoke === null || _invoke === void 0 ? void 0 : _invoke(msg);
}
/**
* Retrieves the system dark mode status.
*
* @returns A promise that resolves to a boolean value indicating if the system is in dark mode.
*/
export function IsDarkMode() {
return call(SystemIsDarkMode);
}
/**
* Fetches the capabilities of the application from the server.
*
* @returns A promise that resolves to an object containing the capabilities.
*/
export async function Capabilities() {
let response = await fetch("/wails/capabilities");
if (response.ok) {
return response.json();
}
else {
throw new Error("could not fetch capabilities: " + response.statusText);
}
}
/**
* Retrieves environment details.
*
* @returns A promise that resolves to an object containing OS and system architecture.
*/
export function Environment() {
return call(SystemEnvironment);
}
/**
* Checks if the current operating system is Windows.
*
* @return True if the operating system is Windows, otherwise false.
*/
export function IsWindows() {
return window._wails.environment.OS === "windows";
}
/**
* Checks if the current operating system is Linux.
*
* @returns Returns true if the current operating system is Linux, false otherwise.
*/
export function IsLinux() {
return window._wails.environment.OS === "linux";
}
/**
* Checks if the current environment is a macOS operating system.
*
* @returns True if the environment is macOS, false otherwise.
*/
export function IsMac() {
return window._wails.environment.OS === "darwin";
}
/**
* Checks if the current environment architecture is AMD64.
*
* @returns True if the current environment architecture is AMD64, false otherwise.
*/
export function IsAMD64() {
return window._wails.environment.Arch === "amd64";
}
/**
* Checks if the current architecture is ARM.
*
* @returns True if the current architecture is ARM, false otherwise.
*/
export function IsARM() {
return window._wails.environment.Arch === "arm";
}
/**
* Checks if the current environment is ARM64 architecture.
*
* @returns Returns true if the environment is ARM64 architecture, otherwise returns false.
*/
export function IsARM64() {
return window._wails.environment.Arch === "arm64";
}
/**
* Reports whether the app is being run in debug mode.
*
* @returns True if the app is being run in debug mode.
*/
export function IsDebug() {
return Boolean(window._wails.environment.Debug);
}

View File

@@ -1,95 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
/**
* Logs a message to the console with custom formatting.
*
* @param message - The message to be logged.
*/
export function debugLog(message) {
// eslint-disable-next-line
console.log('%c wails3 %c ' + message + ' ', 'background: #aa0000; color: #fff; border-radius: 3px 0px 0px 3px; padding: 1px; font-size: 0.7rem', 'background: #009900; color: #fff; border-radius: 0px 3px 3px 0px; padding: 1px; font-size: 0.7rem');
}
/**
* Checks whether the webview supports the {@link MouseEvent#buttons} property.
* Looking at you macOS High Sierra!
*/
export function canTrackButtons() {
return (new MouseEvent('mousedown')).buttons === 0;
}
/**
* Checks whether the browser supports removing listeners by triggering an AbortSignal
* (see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#signal).
*/
export function canAbortListeners() {
if (!EventTarget || !AbortSignal || !AbortController)
return false;
let result = true;
const target = new EventTarget();
const controller = new AbortController();
target.addEventListener('test', () => { result = false; }, { signal: controller.signal });
controller.abort();
target.dispatchEvent(new CustomEvent('test'));
return result;
}
/**
* Resolves the closest HTMLElement ancestor of an event's target.
*/
export function eventTarget(event) {
var _a;
if (event.target instanceof HTMLElement) {
return event.target;
}
else if (!(event.target instanceof HTMLElement) && event.target instanceof Node) {
return (_a = event.target.parentElement) !== null && _a !== void 0 ? _a : document.body;
}
else {
return document.body;
}
}
/***
This technique for proper load detection is taken from HTMX:
BSD 2-Clause License
Copyright (c) 2020, Big Sky Software
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***/
let isReady = false;
document.addEventListener('DOMContentLoaded', () => { isReady = true; });
export function whenReady(callback) {
if (isReady || document.readyState === 'complete') {
callback();
}
else {
document.addEventListener('DOMContentLoaded', callback);
}
}

View File

@@ -1,438 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { newRuntimeCaller, objectNames } from "./runtime.js";
const PositionMethod = 0;
const CenterMethod = 1;
const CloseMethod = 2;
const DisableSizeConstraintsMethod = 3;
const EnableSizeConstraintsMethod = 4;
const FocusMethod = 5;
const ForceReloadMethod = 6;
const FullscreenMethod = 7;
const GetScreenMethod = 8;
const GetZoomMethod = 9;
const HeightMethod = 10;
const HideMethod = 11;
const IsFocusedMethod = 12;
const IsFullscreenMethod = 13;
const IsMaximisedMethod = 14;
const IsMinimisedMethod = 15;
const MaximiseMethod = 16;
const MinimiseMethod = 17;
const NameMethod = 18;
const OpenDevToolsMethod = 19;
const RelativePositionMethod = 20;
const ReloadMethod = 21;
const ResizableMethod = 22;
const RestoreMethod = 23;
const SetPositionMethod = 24;
const SetAlwaysOnTopMethod = 25;
const SetBackgroundColourMethod = 26;
const SetFramelessMethod = 27;
const SetFullscreenButtonEnabledMethod = 28;
const SetMaxSizeMethod = 29;
const SetMinSizeMethod = 30;
const SetRelativePositionMethod = 31;
const SetResizableMethod = 32;
const SetSizeMethod = 33;
const SetTitleMethod = 34;
const SetZoomMethod = 35;
const ShowMethod = 36;
const SizeMethod = 37;
const ToggleFullscreenMethod = 38;
const ToggleMaximiseMethod = 39;
const UnFullscreenMethod = 40;
const UnMaximiseMethod = 41;
const UnMinimiseMethod = 42;
const WidthMethod = 43;
const ZoomMethod = 44;
const ZoomInMethod = 45;
const ZoomOutMethod = 46;
const ZoomResetMethod = 47;
// Private field names.
const callerSym = Symbol("caller");
class Window {
/**
* Initialises a window object with the specified name.
*
* @private
* @param name - The name of the target window.
*/
constructor(name = '') {
this[callerSym] = newRuntimeCaller(objectNames.Window, name);
// bind instance method to make them easily usable in event handlers
for (const method of Object.getOwnPropertyNames(Window.prototype)) {
if (method !== "constructor"
&& typeof this[method] === "function") {
this[method] = this[method].bind(this);
}
}
}
/**
* Gets the specified window.
*
* @param name - The name of the window to get.
* @returns The corresponding window object.
*/
Get(name) {
return new Window(name);
}
/**
* Returns the absolute position of the window.
*
* @returns The current absolute position of the window.
*/
Position() {
return this[callerSym](PositionMethod);
}
/**
* Centers the window on the screen.
*/
Center() {
return this[callerSym](CenterMethod);
}
/**
* Closes the window.
*/
Close() {
return this[callerSym](CloseMethod);
}
/**
* Disables min/max size constraints.
*/
DisableSizeConstraints() {
return this[callerSym](DisableSizeConstraintsMethod);
}
/**
* Enables min/max size constraints.
*/
EnableSizeConstraints() {
return this[callerSym](EnableSizeConstraintsMethod);
}
/**
* Focuses the window.
*/
Focus() {
return this[callerSym](FocusMethod);
}
/**
* Forces the window to reload the page assets.
*/
ForceReload() {
return this[callerSym](ForceReloadMethod);
}
/**
* Switches the window to fullscreen mode.
*/
Fullscreen() {
return this[callerSym](FullscreenMethod);
}
/**
* Returns the screen that the window is on.
*
* @returns The screen the window is currently on.
*/
GetScreen() {
return this[callerSym](GetScreenMethod);
}
/**
* Returns the current zoom level of the window.
*
* @returns The current zoom level.
*/
GetZoom() {
return this[callerSym](GetZoomMethod);
}
/**
* Returns the height of the window.
*
* @returns The current height of the window.
*/
Height() {
return this[callerSym](HeightMethod);
}
/**
* Hides the window.
*/
Hide() {
return this[callerSym](HideMethod);
}
/**
* Returns true if the window is focused.
*
* @returns Whether the window is currently focused.
*/
IsFocused() {
return this[callerSym](IsFocusedMethod);
}
/**
* Returns true if the window is fullscreen.
*
* @returns Whether the window is currently fullscreen.
*/
IsFullscreen() {
return this[callerSym](IsFullscreenMethod);
}
/**
* Returns true if the window is maximised.
*
* @returns Whether the window is currently maximised.
*/
IsMaximised() {
return this[callerSym](IsMaximisedMethod);
}
/**
* Returns true if the window is minimised.
*
* @returns Whether the window is currently minimised.
*/
IsMinimised() {
return this[callerSym](IsMinimisedMethod);
}
/**
* Maximises the window.
*/
Maximise() {
return this[callerSym](MaximiseMethod);
}
/**
* Minimises the window.
*/
Minimise() {
return this[callerSym](MinimiseMethod);
}
/**
* Returns the name of the window.
*
* @returns The name of the window.
*/
Name() {
return this[callerSym](NameMethod);
}
/**
* Opens the development tools pane.
*/
OpenDevTools() {
return this[callerSym](OpenDevToolsMethod);
}
/**
* Returns the relative position of the window to the screen.
*
* @returns The current relative position of the window.
*/
RelativePosition() {
return this[callerSym](RelativePositionMethod);
}
/**
* Reloads the page assets.
*/
Reload() {
return this[callerSym](ReloadMethod);
}
/**
* Returns true if the window is resizable.
*
* @returns Whether the window is currently resizable.
*/
Resizable() {
return this[callerSym](ResizableMethod);
}
/**
* Restores the window to its previous state if it was previously minimised, maximised or fullscreen.
*/
Restore() {
return this[callerSym](RestoreMethod);
}
/**
* Sets the absolute position of the window.
*
* @param x - The desired horizontal absolute position of the window.
* @param y - The desired vertical absolute position of the window.
*/
SetPosition(x, y) {
return this[callerSym](SetPositionMethod, { x, y });
}
/**
* Sets the window to be always on top.
*
* @param alwaysOnTop - Whether the window should stay on top.
*/
SetAlwaysOnTop(alwaysOnTop) {
return this[callerSym](SetAlwaysOnTopMethod, { alwaysOnTop });
}
/**
* Sets the background colour of the window.
*
* @param r - The desired red component of the window background.
* @param g - The desired green component of the window background.
* @param b - The desired blue component of the window background.
* @param a - The desired alpha component of the window background.
*/
SetBackgroundColour(r, g, b, a) {
return this[callerSym](SetBackgroundColourMethod, { r, g, b, a });
}
/**
* Removes the window frame and title bar.
*
* @param frameless - Whether the window should be frameless.
*/
SetFrameless(frameless) {
return this[callerSym](SetFramelessMethod, { frameless });
}
/**
* Disables the system fullscreen button.
*
* @param enabled - Whether the fullscreen button should be enabled.
*/
SetFullscreenButtonEnabled(enabled) {
return this[callerSym](SetFullscreenButtonEnabledMethod, { enabled });
}
/**
* Sets the maximum size of the window.
*
* @param width - The desired maximum width of the window.
* @param height - The desired maximum height of the window.
*/
SetMaxSize(width, height) {
return this[callerSym](SetMaxSizeMethod, { width, height });
}
/**
* Sets the minimum size of the window.
*
* @param width - The desired minimum width of the window.
* @param height - The desired minimum height of the window.
*/
SetMinSize(width, height) {
return this[callerSym](SetMinSizeMethod, { width, height });
}
/**
* Sets the relative position of the window to the screen.
*
* @param x - The desired horizontal relative position of the window.
* @param y - The desired vertical relative position of the window.
*/
SetRelativePosition(x, y) {
return this[callerSym](SetRelativePositionMethod, { x, y });
}
/**
* Sets whether the window is resizable.
*
* @param resizable - Whether the window should be resizable.
*/
SetResizable(resizable) {
return this[callerSym](SetResizableMethod, { resizable });
}
/**
* Sets the size of the window.
*
* @param width - The desired width of the window.
* @param height - The desired height of the window.
*/
SetSize(width, height) {
return this[callerSym](SetSizeMethod, { width, height });
}
/**
* Sets the title of the window.
*
* @param title - The desired title of the window.
*/
SetTitle(title) {
return this[callerSym](SetTitleMethod, { title });
}
/**
* Sets the zoom level of the window.
*
* @param zoom - The desired zoom level.
*/
SetZoom(zoom) {
return this[callerSym](SetZoomMethod, { zoom });
}
/**
* Shows the window.
*/
Show() {
return this[callerSym](ShowMethod);
}
/**
* Returns the size of the window.
*
* @returns The current size of the window.
*/
Size() {
return this[callerSym](SizeMethod);
}
/**
* Toggles the window between fullscreen and normal.
*/
ToggleFullscreen() {
return this[callerSym](ToggleFullscreenMethod);
}
/**
* Toggles the window between maximised and normal.
*/
ToggleMaximise() {
return this[callerSym](ToggleMaximiseMethod);
}
/**
* Un-fullscreens the window.
*/
UnFullscreen() {
return this[callerSym](UnFullscreenMethod);
}
/**
* Un-maximises the window.
*/
UnMaximise() {
return this[callerSym](UnMaximiseMethod);
}
/**
* Un-minimises the window.
*/
UnMinimise() {
return this[callerSym](UnMinimiseMethod);
}
/**
* Returns the width of the window.
*
* @returns The current width of the window.
*/
Width() {
return this[callerSym](WidthMethod);
}
/**
* Zooms the window.
*/
Zoom() {
return this[callerSym](ZoomMethod);
}
/**
* Increases the zoom level of the webview content.
*/
ZoomIn() {
return this[callerSym](ZoomInMethod);
}
/**
* Decreases the zoom level of the webview content.
*/
ZoomOut() {
return this[callerSym](ZoomOutMethod);
}
/**
* Resets the zoom level of the webview content.
*/
ZoomReset() {
return this[callerSym](ZoomResetMethod);
}
}
/**
* The window within which the script is running.
*/
const thisWindow = new Window('');
export default thisWindow;

View File

@@ -1,179 +0,0 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
import { OpenURL } from "./browser.js";
import { Question } from "./dialogs.js";
import { Emit, WailsEvent } from "./events.js";
import { canAbortListeners, whenReady } from "./utils.js";
import Window from "./window.js";
/**
* Sends an event with the given name and optional data.
*
* @param eventName - - The name of the event to send.
* @param [data=null] - - Optional data to send along with the event.
*/
function sendEvent(eventName, data = null) {
Emit(new WailsEvent(eventName, data));
}
/**
* Calls a method on a specified window.
*
* @param windowName - The name of the window to call the method on.
* @param methodName - The name of the method to call.
*/
function callWindowMethod(windowName, methodName) {
const targetWindow = Window.Get(windowName);
const method = targetWindow[methodName];
if (typeof method !== "function") {
console.error(`Window method '${methodName}' not found`);
return;
}
try {
method.call(targetWindow);
}
catch (e) {
console.error(`Error calling window method '${methodName}': `, e);
}
}
/**
* Responds to a triggering event by running appropriate WML actions for the current target.
*/
function onWMLTriggered(ev) {
const element = ev.currentTarget;
function runEffect(choice = "Yes") {
if (choice !== "Yes")
return;
const eventType = element.getAttribute('wml-event') || element.getAttribute('data-wml-event');
const targetWindow = element.getAttribute('wml-target-window') || element.getAttribute('data-wml-target-window') || "";
const windowMethod = element.getAttribute('wml-window') || element.getAttribute('data-wml-window');
const url = element.getAttribute('wml-openurl') || element.getAttribute('data-wml-openurl');
if (eventType !== null)
sendEvent(eventType);
if (windowMethod !== null)
callWindowMethod(targetWindow, windowMethod);
if (url !== null)
void OpenURL(url);
}
const confirm = element.getAttribute('wml-confirm') || element.getAttribute('data-wml-confirm');
if (confirm) {
Question({
Title: "Confirm",
Message: confirm,
Detached: false,
Buttons: [
{ Label: "Yes" },
{ Label: "No", IsDefault: true }
]
}).then(runEffect);
}
else {
runEffect();
}
}
// Private field names.
const controllerSym = Symbol("controller");
const triggerMapSym = Symbol("triggerMap");
const elementCountSym = Symbol("elementCount");
/**
* AbortControllerRegistry does not actually remember active event listeners: instead
* it ties them to an AbortSignal and uses an AbortController to remove them all at once.
*/
class AbortControllerRegistry {
constructor() {
this[controllerSym] = new AbortController();
}
/**
* Returns an options object for addEventListener that ties the listener
* to the AbortSignal from the current AbortController.
*
* @param element - An HTML element
* @param triggers - The list of active WML trigger events for the specified elements
*/
set(element, triggers) {
return { signal: this[controllerSym].signal };
}
/**
* Removes all registered event listeners and resets the registry.
*/
reset() {
this[controllerSym].abort();
this[controllerSym] = new AbortController();
}
}
/**
* WeakMapRegistry maps active trigger events to each DOM element through a WeakMap.
* This ensures that the mapping remains private to this module, while still allowing garbage
* collection of the involved elements.
*/
class WeakMapRegistry {
constructor() {
this[triggerMapSym] = new WeakMap();
this[elementCountSym] = 0;
}
/**
* Sets active triggers for the specified element.
*
* @param element - An HTML element
* @param triggers - The list of active WML trigger events for the specified element
*/
set(element, triggers) {
if (!this[triggerMapSym].has(element)) {
this[elementCountSym]++;
}
this[triggerMapSym].set(element, triggers);
return {};
}
/**
* Removes all registered event listeners.
*/
reset() {
if (this[elementCountSym] <= 0)
return;
for (const element of document.body.querySelectorAll('*')) {
if (this[elementCountSym] <= 0)
break;
const triggers = this[triggerMapSym].get(element);
if (triggers != null) {
this[elementCountSym]--;
}
for (const trigger of triggers || [])
element.removeEventListener(trigger, onWMLTriggered);
}
this[triggerMapSym] = new WeakMap();
this[elementCountSym] = 0;
}
}
const triggerRegistry = canAbortListeners() ? new AbortControllerRegistry() : new WeakMapRegistry();
/**
* Adds event listeners to the specified element.
*/
function addWMLListeners(element) {
const triggerRegExp = /\S+/g;
const triggerAttr = (element.getAttribute('wml-trigger') || element.getAttribute('data-wml-trigger') || "click");
const triggers = [];
let match;
while ((match = triggerRegExp.exec(triggerAttr)) !== null)
triggers.push(match[0]);
const options = triggerRegistry.set(element, triggers);
for (const trigger of triggers)
element.addEventListener(trigger, onWMLTriggered, options);
}
/**
* Schedules an automatic reload of WML to be performed as soon as the document is fully loaded.
*/
export function Enable() {
whenReady(Reload);
}
/**
* Reloads the WML page by adding necessary event listeners and browser listeners.
*/
export function Reload() {
triggerRegistry.reset();
document.body.querySelectorAll('[wml-event], [wml-window], [wml-openurl], [data-wml-event], [data-wml-window], [data-wml-openurl]').forEach(addWMLListeners);
}