initial commit

This commit is contained in:
2026-02-09 19:04:19 -08:00
commit f92b57c7b6
531 changed files with 196294 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2019-2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Application} from '../application.js';
import {HotkeyHandler} from '../input/hotkey-handler.js';
import {Frontend} from './frontend.js';
import {PopupFactory} from './popup-factory.js';
await Application.main(false, async (application) => {
const hotkeyHandler = new HotkeyHandler();
hotkeyHandler.prepare(application.crossFrame);
const popupFactory = new PopupFactory(application);
popupFactory.prepare();
const frontend = new Frontend({
application,
popupFactory,
depth: 0,
parentPopupId: null,
parentFrameId: null,
useProxyPopup: false,
pageType: 'web',
canUseWindowPopup: true,
allowRootFramePopupProxy: true,
childrenSupported: true,
hotkeyHandler,
});
await frontend.prepare();
});

View File

@@ -0,0 +1,23 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2019-2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
(async () => {
const src = chrome.runtime.getURL('js/app/content-script-main.js');
// eslint-disable-next-line no-unsanitized/method
await import(src);
})();

1054
vendor/yomitan/js/app/frontend.js vendored Normal file

File diff suppressed because it is too large Load Diff

418
vendor/yomitan/js/app/popup-factory.js vendored Normal file
View File

@@ -0,0 +1,418 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2019-2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {FrameOffsetForwarder} from '../comm/frame-offset-forwarder.js';
import {generateId} from '../core/utilities.js';
import {PopupProxy} from './popup-proxy.js';
import {PopupWindow} from './popup-window.js';
import {Popup} from './popup.js';
/**
* A class which is used to generate and manage popups.
*/
export class PopupFactory {
/**
* Creates a new instance.
* @param {import('../application.js').Application} application
*/
constructor(application) {
/** @type {import('../application.js').Application} */
this._application = application;
/** @type {FrameOffsetForwarder} */
this._frameOffsetForwarder = new FrameOffsetForwarder(application.crossFrame);
/** @type {Map<string, import('popup').PopupAny>} */
this._popups = new Map();
/** @type {Map<string, {popup: import('popup').PopupAny, token: string}[]>} */
this._allPopupVisibilityTokenMap = new Map();
}
/**
* Prepares the instance for use.
*/
prepare() {
this._frameOffsetForwarder.prepare();
/* eslint-disable @stylistic/no-multi-spaces */
this._application.crossFrame.registerHandlers([
['popupFactoryGetOrCreatePopup', this._onApiGetOrCreatePopup.bind(this)],
['popupFactorySetOptionsContext', this._onApiSetOptionsContext.bind(this)],
['popupFactoryHide', this._onApiHide.bind(this)],
['popupFactoryIsVisible', this._onApiIsVisibleAsync.bind(this)],
['popupFactorySetVisibleOverride', this._onApiSetVisibleOverride.bind(this)],
['popupFactoryClearVisibleOverride', this._onApiClearVisibleOverride.bind(this)],
['popupFactoryContainsPoint', this._onApiContainsPoint.bind(this)],
['popupFactoryShowContent', this._onApiShowContent.bind(this)],
['popupFactorySetCustomCss', this._onApiSetCustomCss.bind(this)],
['popupFactoryClearAutoPlayTimer', this._onApiClearAutoPlayTimer.bind(this)],
['popupFactorySetContentScale', this._onApiSetContentScale.bind(this)],
['popupFactoryUpdateTheme', this._onApiUpdateTheme.bind(this)],
['popupFactorySetCustomOuterCss', this._onApiSetCustomOuterCss.bind(this)],
['popupFactoryGetFrameSize', this._onApiGetFrameSize.bind(this)],
['popupFactorySetFrameSize', this._onApiSetFrameSize.bind(this)],
['popupFactoryIsPointerOver', this._onApiIsPointerOver.bind(this)],
]);
/* eslint-enable @stylistic/no-multi-spaces */
}
/**
* Gets or creates a popup based on a set of parameters
* @param {import('popup-factory').GetOrCreatePopupDetails} details Details about how to acquire the popup.
* @returns {Promise<import('popup').PopupAny>}
*/
async getOrCreatePopup({
frameId = null,
id = null,
parentPopupId = null,
depth = null,
popupWindow = false,
childrenSupported = false,
}) {
// Find by existing id
if (id !== null) {
const popup = this._popups.get(id);
if (typeof popup !== 'undefined') {
return popup;
}
}
// Find by existing parent id
let parent = null;
if (parentPopupId !== null) {
parent = this._popups.get(parentPopupId);
if (typeof parent !== 'undefined') {
const popup = parent.child;
if (popup !== null) {
return popup;
}
} else {
parent = null;
}
}
// Depth
if (parent !== null) {
if (depth !== null) {
throw new Error('Depth cannot be set when parent exists');
}
depth = parent.depth + 1;
} else if (depth === null) {
depth = 0;
}
const currentFrameId = this._application.frameId;
if (currentFrameId === null) { throw new Error('Cannot create popup: no frameId'); }
if (popupWindow) {
// New unique id
if (id === null) {
id = generateId(16);
}
const popup = new PopupWindow(
this._application,
id,
depth,
currentFrameId,
);
this._popups.set(id, popup);
return popup;
} else if (frameId === currentFrameId) {
// New unique id
if (id === null) {
id = generateId(16);
}
const popup = new Popup(
this._application,
id,
depth,
currentFrameId,
childrenSupported,
);
if (parent !== null) {
if (parent.child !== null) {
throw new Error('Parent popup already has a child');
}
popup.parent = /** @type {Popup} */ (parent);
parent.child = popup;
}
this._popups.set(id, popup);
popup.prepare();
return popup;
} else {
if (frameId === null) {
throw new Error('Invalid frameId');
}
const useFrameOffsetForwarder = (parentPopupId === null);
const info = await this._application.crossFrame.invoke(frameId, 'popupFactoryGetOrCreatePopup', {
id,
parentPopupId,
frameId,
childrenSupported,
});
id = info.id;
const popup = new PopupProxy(
this._application,
id,
info.depth,
info.frameId,
useFrameOffsetForwarder ? this._frameOffsetForwarder : null,
);
this._popups.set(id, popup);
return popup;
}
}
/**
* Force all popups to have a specific visibility value.
* @param {boolean} value Whether or not the popups should be visible.
* @param {number} priority The priority of the override.
* @returns {Promise<import('core').TokenString>} A token which can be passed to clearAllVisibleOverride.
* @throws An exception is thrown if any popup fails to have its visibiltiy overridden.
*/
async setAllVisibleOverride(value, priority) {
const promises = [];
for (const popup of this._popups.values()) {
const promise = this._setPopupVisibleOverrideReturnTuple(popup, value, priority);
promises.push(promise);
}
/** @type {undefined|Error} */
let error = void 0;
/** @type {{popup: import('popup').PopupAny, token: string}[]} */
const results = [];
for (const promise of promises) {
try {
const {popup, token} = await promise;
if (token !== null) {
results.push({popup, token});
}
} catch (e) {
if (typeof error === 'undefined') {
error = new Error(`Failed to set popup visibility override: ${e}`);
}
}
}
if (typeof error === 'undefined') {
const token = generateId(16);
this._allPopupVisibilityTokenMap.set(token, results);
return token;
}
// Revert on error
await this._revertPopupVisibilityOverrides(results);
throw error;
}
/**
* @param {import('popup').PopupAny} popup
* @param {boolean} value
* @param {number} priority
* @returns {Promise<{popup: import('popup').PopupAny, token: ?string}>}
*/
async _setPopupVisibleOverrideReturnTuple(popup, value, priority) {
const token = await popup.setVisibleOverride(value, priority);
return {popup, token};
}
/**
* Clears a visibility override that was generated by `setAllVisibleOverride`.
* @param {import('core').TokenString} token The token returned from `setAllVisibleOverride`.
* @returns {Promise<boolean>} `true` if the override existed and was removed, `false` otherwise.
*/
async clearAllVisibleOverride(token) {
const results = this._allPopupVisibilityTokenMap.get(token);
if (typeof results === 'undefined') { return false; }
this._allPopupVisibilityTokenMap.delete(token);
await this._revertPopupVisibilityOverrides(results);
return true;
}
// API message handlers
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryGetOrCreatePopup'>} */
async _onApiGetOrCreatePopup(details) {
const popup = await this.getOrCreatePopup(details);
return {
id: popup.id,
depth: popup.depth,
frameId: popup.frameId,
};
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetOptionsContext'>} */
async _onApiSetOptionsContext({id, optionsContext}) {
const popup = this._getPopup(id);
await popup.setOptionsContext(optionsContext);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryHide'>} */
async _onApiHide({id, changeFocus}) {
const popup = this._getPopup(id);
await popup.hide(changeFocus);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryIsVisible'>} */
async _onApiIsVisibleAsync({id}) {
const popup = this._getPopup(id);
return await popup.isVisible();
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetVisibleOverride'>} */
async _onApiSetVisibleOverride({id, value, priority}) {
const popup = this._getPopup(id);
return await popup.setVisibleOverride(value, priority);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryClearVisibleOverride'>} */
async _onApiClearVisibleOverride({id, token}) {
const popup = this._getPopup(id);
return await popup.clearVisibleOverride(token);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryContainsPoint'>} */
async _onApiContainsPoint({id, x, y}) {
const popup = this._getPopup(id);
const offset = this._getPopupOffset(popup);
x += offset.x;
y += offset.y;
return await popup.containsPoint(x, y);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryShowContent'>} */
async _onApiShowContent({id, details, displayDetails}) {
const popup = this._getPopup(id);
if (!this._popupCanShow(popup)) { return; }
const offset = this._getPopupOffset(popup);
const {sourceRects} = details;
for (const sourceRect of sourceRects) {
sourceRect.left += offset.x;
sourceRect.top += offset.y;
sourceRect.right += offset.x;
sourceRect.bottom += offset.y;
}
return await popup.showContent(details, displayDetails);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetCustomCss'>} */
async _onApiSetCustomCss({id, css}) {
const popup = this._getPopup(id);
await popup.setCustomCss(css);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryClearAutoPlayTimer'>} */
async _onApiClearAutoPlayTimer({id}) {
const popup = this._getPopup(id);
await popup.clearAutoPlayTimer();
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetContentScale'>} */
async _onApiSetContentScale({id, scale}) {
const popup = this._getPopup(id);
await popup.setContentScale(scale);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryUpdateTheme'>} */
async _onApiUpdateTheme({id}) {
const popup = this._getPopup(id);
await popup.updateTheme();
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetCustomOuterCss'>} */
async _onApiSetCustomOuterCss({id, css, useWebExtensionApi}) {
const popup = this._getPopup(id);
await popup.setCustomOuterCss(css, useWebExtensionApi);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryGetFrameSize'>} */
async _onApiGetFrameSize({id}) {
const popup = this._getPopup(id);
return await popup.getFrameSize();
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactorySetFrameSize'>} */
async _onApiSetFrameSize({id, width, height}) {
const popup = this._getPopup(id);
return await popup.setFrameSize(width, height);
}
/** @type {import('cross-frame-api').ApiHandler<'popupFactoryIsPointerOver'>} */
async _onApiIsPointerOver({id}) {
const popup = this._getPopup(id);
return popup.isPointerOver();
}
// Private functions
/**
* @param {string} id
* @returns {import('popup').PopupAny}
* @throws {Error}
*/
_getPopup(id) {
const popup = this._popups.get(id);
if (typeof popup === 'undefined') {
throw new Error(`Invalid popup ID ${id}`);
}
return popup;
}
/**
* @param {import('popup').PopupAny} popup
* @returns {{x: number, y: number}}
*/
_getPopupOffset(popup) {
const {parent} = popup;
if (parent !== null) {
const popupRect = parent.getFrameRect();
if (popupRect.valid) {
return {x: popupRect.left, y: popupRect.top};
}
}
return {x: 0, y: 0};
}
/**
* @param {import('popup').PopupAny} popup
* @returns {boolean}
*/
_popupCanShow(popup) {
const parent = popup.parent;
return parent === null || parent.isVisibleSync();
}
/**
* @param {{popup: import('popup').PopupAny, token: string}[]} overrides
* @returns {Promise<boolean[]>}
*/
async _revertPopupVisibilityOverrides(overrides) {
const promises = [];
for (const value of overrides) {
if (value === null) { continue; }
const {popup, token} = value;
const promise = popup.clearVisibleOverride(token)
.then(
(v) => v,
() => false,
);
promises.push(promise);
}
return await Promise.all(promises);
}
}

380
vendor/yomitan/js/app/popup-proxy.js vendored Normal file
View File

@@ -0,0 +1,380 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2019-2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EventDispatcher} from '../core/event-dispatcher.js';
import {log} from '../core/log.js';
/**
* This class is a proxy for a Popup that is hosted in a different frame.
* It effectively forwards all API calls to the underlying Popup.
* @augments EventDispatcher<import('popup').Events>
*/
export class PopupProxy extends EventDispatcher {
/**
* @param {import('../application.js').Application} application The main application instance.
* @param {string} id The identifier of the popup.
* @param {number} depth The depth of the popup.
* @param {number} frameId The frameId of the host frame.
* @param {?import('../comm/frame-offset-forwarder.js').FrameOffsetForwarder} frameOffsetForwarder A `FrameOffsetForwarder` instance which is used to determine frame positioning.
*/
constructor(application, id, depth, frameId, frameOffsetForwarder) {
super();
/** @type {import('../application.js').Application} */
this._application = application;
/** @type {string} */
this._id = id;
/** @type {number} */
this._depth = depth;
/** @type {number} */
this._frameId = frameId;
/** @type {?import('../comm/frame-offset-forwarder.js').FrameOffsetForwarder} */
this._frameOffsetForwarder = frameOffsetForwarder;
/** @type {number} */
this._frameOffsetX = 0;
/** @type {number} */
this._frameOffsetY = 0;
/** @type {?Promise<?[x: number, y: number]>} */
this._frameOffsetPromise = null;
/** @type {?number} */
this._frameOffsetUpdatedAt = null;
/** @type {number} */
this._frameOffsetExpireTimeout = 1000;
}
/**
* The ID of the popup.
* @type {string}
*/
get id() {
return this._id;
}
/**
* The parent of the popup, which is always `null` for `PopupProxy` instances,
* since any potential parent popups are in a different frame.
* @type {?import('./popup.js').Popup}
*/
get parent() {
return null;
}
/**
* Attempts to set the parent popup.
* @param {import('./popup.js').Popup} _value The parent to assign.
* @throws {Error} Throws an error, since this class doesn't support a direct parent.
*/
set parent(_value) {
throw new Error('Not supported on PopupProxy');
}
/**
* The popup child popup, which is always null for `PopupProxy` instances,
* since any potential child popups are in a different frame.
* @type {?import('./popup.js').Popup}
*/
get child() {
return null;
}
/**
* Attempts to set the child popup.
* @param {import('./popup.js').Popup} _child The child to assign.
* @throws {Error} Throws an error, since this class doesn't support children.
*/
set child(_child) {
throw new Error('Not supported on PopupProxy');
}
/**
* The depth of the popup.
* @type {number}
*/
get depth() {
return this._depth;
}
/**
* Gets the content window of the frame. This value is null,
* since the window is hosted in a different frame.
* @type {?Window}
*/
get frameContentWindow() {
return null;
}
/**
* Gets the DOM node that contains the frame.
* @type {?Element}
*/
get container() {
return null;
}
/**
* Gets the ID of the frame.
* @type {number}
*/
get frameId() {
return this._frameId;
}
/**
* Sets the options context for the popup.
* @param {import('settings').OptionsContext} optionsContext The options context object.
* @returns {Promise<void>}
*/
async setOptionsContext(optionsContext) {
await this._invokeSafe('popupFactorySetOptionsContext', {id: this._id, optionsContext}, void 0);
}
/**
* Hides the popup.
* @param {boolean} changeFocus Whether or not the parent popup or host frame should be focused.
* @returns {Promise<void>}
*/
async hide(changeFocus) {
await this._invokeSafe('popupFactoryHide', {id: this._id, changeFocus}, void 0);
}
/**
* Returns whether or not the popup is currently visible.
* @returns {Promise<boolean>} `true` if the popup is visible, `false` otherwise.
*/
isVisible() {
return this._invokeSafe('popupFactoryIsVisible', {id: this._id}, false);
}
/**
* Force assigns the visibility of the popup.
* @param {boolean} value Whether or not the popup should be visible.
* @param {number} priority The priority of the override.
* @returns {Promise<?import('core').TokenString>} A token used which can be passed to `clearVisibleOverride`,
* or null if the override wasn't assigned.
*/
setVisibleOverride(value, priority) {
return this._invokeSafe('popupFactorySetVisibleOverride', {id: this._id, value, priority}, null);
}
/**
* Clears a visibility override that was generated by `setVisibleOverride`.
* @param {import('core').TokenString} token The token returned from `setVisibleOverride`.
* @returns {Promise<boolean>} `true` if the override existed and was removed, `false` otherwise.
*/
clearVisibleOverride(token) {
return this._invokeSafe('popupFactoryClearVisibleOverride', {id: this._id, token}, false);
}
/**
* Checks whether a point is contained within the popup's rect.
* @param {number} x The x coordinate.
* @param {number} y The y coordinate.
* @returns {Promise<boolean>} `true` if the point is contained within the popup's rect, `false` otherwise.
*/
async containsPoint(x, y) {
if (this._frameOffsetForwarder !== null) {
await this._updateFrameOffset();
x += this._frameOffsetX;
y += this._frameOffsetY;
}
return await this._invokeSafe('popupFactoryContainsPoint', {id: this._id, x, y}, false);
}
/**
* Shows and updates the positioning and content of the popup.
* @param {import('popup').ContentDetails} details Settings for the outer popup.
* @param {?import('display').ContentDetails} displayDetails The details parameter passed to `Display.setContent`.
* @returns {Promise<void>}
*/
async showContent(details, displayDetails) {
if (this._frameOffsetForwarder !== null) {
const {sourceRects} = details;
await this._updateFrameOffset();
for (const sourceRect of sourceRects) {
sourceRect.left += this._frameOffsetX;
sourceRect.top += this._frameOffsetY;
sourceRect.right += this._frameOffsetX;
sourceRect.bottom += this._frameOffsetY;
}
}
await this._invokeSafe('popupFactoryShowContent', {id: this._id, details, displayDetails}, void 0);
}
/**
* Sets the custom styles for the popup content.
* @param {string} css The CSS rules.
* @returns {Promise<void>}
*/
async setCustomCss(css) {
await this._invokeSafe('popupFactorySetCustomCss', {id: this._id, css}, void 0);
}
/**
* Stops the audio auto-play timer, if one has started.
* @returns {Promise<void>}
*/
async clearAutoPlayTimer() {
await this._invokeSafe('popupFactoryClearAutoPlayTimer', {id: this._id}, void 0);
}
/**
* Sets the scaling factor of the popup content.
* @param {number} scale The scaling factor.
* @returns {Promise<void>}
*/
async setContentScale(scale) {
await this._invokeSafe('popupFactorySetContentScale', {id: this._id, scale}, void 0);
}
/**
* Returns whether or not the popup is currently visible, synchronously.
* @throws An exception is thrown for `PopupProxy` since it cannot synchronously detect visibility.
*/
isVisibleSync() {
throw new Error('Not supported on PopupProxy');
}
/**
* Updates the outer theme of the popup.
* @returns {Promise<void>}
*/
async updateTheme() {
await this._invokeSafe('popupFactoryUpdateTheme', {id: this._id}, void 0);
}
/**
* Sets the custom styles for the outer popup container.
* @param {string} css The CSS rules.
* @param {boolean} useWebExtensionApi Whether or not web extension APIs should be used to inject the rules.
* When web extension APIs are used, a DOM node is not generated, making it harder to detect the changes.
* @returns {Promise<void>}
*/
async setCustomOuterCss(css, useWebExtensionApi) {
await this._invokeSafe('popupFactorySetCustomOuterCss', {id: this._id, css, useWebExtensionApi}, void 0);
}
/**
* Gets the rectangle of the DOM frame, synchronously.
* @returns {import('popup').ValidRect} The rect.
* `valid` is `false` for `PopupProxy`, since the DOM node is hosted in a different frame.
*/
getFrameRect() {
return {left: 0, top: 0, right: 0, bottom: 0, valid: false};
}
/**
* Gets the size of the DOM frame.
* @returns {Promise<import('popup').ValidSize>} The size and whether or not it is valid.
*/
getFrameSize() {
return this._invokeSafe('popupFactoryGetFrameSize', {id: this._id}, {width: 0, height: 0, valid: false});
}
/**
* Sets the size of the DOM frame.
* @param {number} width The desired width of the popup.
* @param {number} height The desired height of the popup.
* @returns {Promise<boolean>} `true` if the size assignment was successful, `false` otherwise.
*/
setFrameSize(width, height) {
return this._invokeSafe('popupFactorySetFrameSize', {id: this._id, width, height}, false);
}
/**
* Checks if the pointer is over this popup.
* @returns {Promise<boolean>} Whether the pointer is over the popup
*/
isPointerOver() {
return this._invokeSafe('popupFactoryIsPointerOver', {id: this._id}, false);
}
// Private
/**
* @template {import('cross-frame-api').ApiNames} TName
* @param {TName} action
* @param {import('cross-frame-api').ApiParams<TName>} params
* @returns {Promise<import('cross-frame-api').ApiReturn<TName>>}
*/
_invoke(action, params) {
return this._application.crossFrame.invoke(this._frameId, action, params);
}
/**
* @template {import('cross-frame-api').ApiNames} TName
* @template [TReturnDefault=unknown]
* @param {TName} action
* @param {import('cross-frame-api').ApiParams<TName>} params
* @param {TReturnDefault} defaultReturnValue
* @returns {Promise<import('cross-frame-api').ApiReturn<TName>|TReturnDefault>}
*/
async _invokeSafe(action, params, defaultReturnValue) {
try {
return await this._invoke(action, params);
} catch (e) {
if (!this._application.webExtension.unloaded) { throw e; }
return defaultReturnValue;
}
}
/**
* @returns {Promise<void>}
*/
async _updateFrameOffset() {
const now = Date.now();
const firstRun = this._frameOffsetUpdatedAt === null;
const expired = firstRun || /** @type {number} */ (this._frameOffsetUpdatedAt) < now - this._frameOffsetExpireTimeout;
if (this._frameOffsetPromise === null && !expired) { return; }
if (this._frameOffsetPromise !== null) {
if (firstRun) {
await this._frameOffsetPromise;
}
return;
}
const promise = this._updateFrameOffsetInner(now);
if (firstRun) {
await promise;
}
}
/**
* @param {number} now
*/
async _updateFrameOffsetInner(now) {
this._frameOffsetPromise = /** @type {import('../comm/frame-offset-forwarder.js').FrameOffsetForwarder} */ (this._frameOffsetForwarder).getOffset();
try {
const offset = await this._frameOffsetPromise;
if (offset !== null) {
this._frameOffsetX = offset[0];
this._frameOffsetY = offset[1];
} else {
this._frameOffsetX = 0;
this._frameOffsetY = 0;
this.trigger('offsetNotFound', {});
return;
}
this._frameOffsetUpdatedAt = now;
} catch (e) {
log.error(e);
} finally {
this._frameOffsetPromise = null;
}
}
}

320
vendor/yomitan/js/app/popup-window.js vendored Normal file
View File

@@ -0,0 +1,320 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2020-2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EventDispatcher} from '../core/event-dispatcher.js';
/**
* This class represents a popup that is hosted in a new native window.
* @augments EventDispatcher<import('popup').Events>
*/
export class PopupWindow extends EventDispatcher {
/**
* @param {import('../application.js').Application} application The main application instance.
* @param {string} id The identifier of the popup.
* @param {number} depth The depth of the popup.
* @param {number} frameId The frameId of the host frame.
*/
constructor(application, id, depth, frameId) {
super();
/** @type {import('../application.js').Application} */
this._application = application;
/** @type {string} */
this._id = id;
/** @type {number} */
this._depth = depth;
/** @type {number} */
this._frameId = frameId;
/** @type {?number} */
this._popupTabId = null;
}
/**
* The ID of the popup.
* @type {string}
*/
get id() {
return this._id;
}
/**
* @type {?import('./popup.js').Popup}
*/
get parent() {
return null;
}
/**
* The parent of the popup, which is always `null` for `PopupWindow` instances,
* since any potential parent popups are in a different frame.
* @param {import('./popup.js').Popup} _value The parent to assign.
* @throws {Error} Throws an error, since this class doesn't support children.
*/
set parent(_value) {
throw new Error('Not supported on PopupWindow');
}
/**
* The popup child popup, which is always null for `PopupWindow` instances,
* since any potential child popups are in a different frame.
* @type {?import('./popup.js').Popup}
*/
get child() {
return null;
}
/**
* Attempts to set the child popup.
* @param {import('./popup.js').Popup} _value The child to assign.
* @throws Throws an error, since this class doesn't support children.
*/
set child(_value) {
throw new Error('Not supported on PopupWindow');
}
/**
* The depth of the popup.
* @type {number}
*/
get depth() {
return this._depth;
}
/**
* Gets the content window of the frame. This value is null,
* since the window is hosted in a different frame.
* @type {?Window}
*/
get frameContentWindow() {
return null;
}
/**
* Gets the DOM node that contains the frame.
* @type {?Element}
*/
get container() {
return null;
}
/**
* Gets the ID of the frame.
* @type {number}
*/
get frameId() {
return this._frameId;
}
/**
* Sets the options context for the popup.
* @param {import('settings').OptionsContext} optionsContext The options context object.
* @returns {Promise<void>}
*/
async setOptionsContext(optionsContext) {
await this._invoke(false, 'displaySetOptionsContext', {optionsContext});
}
/**
* Hides the popup. This does nothing for `PopupWindow`.
* @param {boolean} _changeFocus Whether or not the parent popup or host frame should be focused.
*/
hide(_changeFocus) {
// NOP
}
/**
* Returns whether or not the popup is currently visible.
* @returns {Promise<boolean>} `true` if the popup is visible, `false` otherwise.
*/
async isVisible() {
return (this._popupTabId !== null && await this._application.api.isTabSearchPopup(this._popupTabId));
}
/**
* Force assigns the visibility of the popup.
* @param {boolean} _value Whether or not the popup should be visible.
* @param {number} _priority The priority of the override.
* @returns {Promise<?import('core').TokenString>} A token used which can be passed to `clearVisibleOverride`,
* or null if the override wasn't assigned.
*/
async setVisibleOverride(_value, _priority) {
return null;
}
/**
* Clears a visibility override that was generated by `setVisibleOverride`.
* @param {import('core').TokenString} _token The token returned from `setVisibleOverride`.
* @returns {Promise<boolean>} `true` if the override existed and was removed, `false` otherwise.
*/
async clearVisibleOverride(_token) {
return false;
}
/**
* Checks whether a point is contained within the popup's rect.
* @param {number} _x The x coordinate.
* @param {number} _y The y coordinate.
* @returns {Promise<boolean>} `true` if the point is contained within the popup's rect, `false` otherwise.
*/
async containsPoint(_x, _y) {
return false;
}
/**
* Shows and updates the positioning and content of the popup.
* @param {import('popup').ContentDetails} _details Settings for the outer popup.
* @param {?import('display').ContentDetails} displayDetails The details parameter passed to `Display.setContent`.
* @returns {Promise<void>}
*/
async showContent(_details, displayDetails) {
if (displayDetails === null) { return; }
await this._invoke(true, 'displaySetContent', {details: displayDetails});
}
/**
* Sets the custom styles for the popup content.
* @param {string} css The CSS rules.
* @returns {Promise<void>}
*/
async setCustomCss(css) {
await this._invoke(false, 'displaySetCustomCss', {css});
}
/**
* Stops the audio auto-play timer, if one has started.
* @returns {Promise<void>}
*/
async clearAutoPlayTimer() {
await this._invoke(false, 'displayAudioClearAutoPlayTimer', void 0);
}
/**
* Sets the scaling factor of the popup content.
* @param {number} _scale The scaling factor.
*/
async setContentScale(_scale) {
// NOP
}
/**
* Returns whether or not the popup is currently visible, synchronously.
* @throws An exception is thrown for `PopupWindow` since it cannot synchronously detect visibility.
*/
isVisibleSync() {
throw new Error('Not supported on PopupWindow');
}
/**
* Updates the outer theme of the popup.
*/
async updateTheme() {
// NOP
}
/**
* Sets the custom styles for the outer popup container.
* This does nothing for `PopupWindow`.
* @param {string} _css The CSS rules.
* @param {boolean} _useWebExtensionApi Whether or not web extension APIs should be used to inject the rules.
* When web extension APIs are used, a DOM node is not generated, making it harder to detect the changes.
*/
async setCustomOuterCss(_css, _useWebExtensionApi) {
// NOP
}
/**
* Gets the rectangle of the DOM frame, synchronously.
* @returns {import('popup').ValidRect} The rect.
* `valid` is `false` for `PopupProxy`, since the DOM node is hosted in a different frame.
*/
getFrameRect() {
return {left: 0, top: 0, right: 0, bottom: 0, valid: false};
}
/**
* Gets the size of the DOM frame.
* @returns {Promise<import('popup').ValidSize>} The size and whether or not it is valid.
*/
async getFrameSize() {
return {width: 0, height: 0, valid: false};
}
/**
* Sets the size of the DOM frame.
* @param {number} _width The desired width of the popup.
* @param {number} _height The desired height of the popup.
* @returns {Promise<boolean>} `true` if the size assignment was successful, `false` otherwise.
*/
async setFrameSize(_width, _height) {
return false;
}
/**
* @returns {Promise<boolean>}
*/
async isPointerOver() {
return false;
}
// Private
/**
* @template {import('display').DirectApiNames} TName
* @param {boolean} open
* @param {TName} action
* @param {import('display').DirectApiParams<TName>} params
* @returns {Promise<import('display').DirectApiReturn<TName>|undefined>}
*/
async _invoke(open, action, params) {
if (this._application.webExtension.unloaded) {
return void 0;
}
const message = /** @type {import('display').DirectApiMessageAny} */ ({action, params});
const frameId = 0;
if (this._popupTabId !== null) {
try {
return /** @type {import('display').DirectApiReturn<TName>} */ (await this._application.crossFrame.invokeTab(
this._popupTabId,
frameId,
'displayPopupMessage2',
message,
));
} catch (e) {
if (this._application.webExtension.unloaded) {
open = false;
}
}
this._popupTabId = null;
}
if (!open) {
return void 0;
}
const {tabId} = await this._application.api.getOrCreateSearchPopup({focus: 'ifCreated'});
this._popupTabId = tabId;
return /** @type {import('display').DirectApiReturn<TName>} */ (await this._application.crossFrame.invokeTab(
this._popupTabId,
frameId,
'displayPopupMessage2',
message,
));
}
}

1249
vendor/yomitan/js/app/popup.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,220 @@
/*
* Copyright (C) 2023-2025 Yomitan Authors
* Copyright (C) 2022 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* This class is used to control theme attributes on DOM elements.
*/
export class ThemeController {
/**
* Creates a new instance of the class.
* @param {?HTMLElement} element A DOM element which theme properties are applied to.
*/
constructor(element) {
/** @type {?HTMLElement} */
this._element = element;
/** @type {import("settings.js").PopupTheme} */
this._theme = 'site';
/** @type {import("settings.js").PopupOuterTheme} */
this._outerTheme = 'site';
/** @type {?('dark'|'light')} */
this._siteTheme = null;
/** @type {'dark'|'light'} */
this._browserTheme = 'light';
/** @type {boolean} */
this.siteOverride = false;
}
/**
* Gets the DOM element which theme properties are applied to.
* @type {?Element}
*/
get element() {
return this._element;
}
/**
* Sets the DOM element which theme properties are applied to.
* @param {?HTMLElement} value The DOM element to assign.
*/
set element(value) {
this._element = value;
}
/**
* Gets the main theme for the content.
* @type {import("settings.js").PopupTheme}
*/
get theme() {
return this._theme;
}
/**
* Sets the main theme for the content.
* @param {import("settings.js").PopupTheme} value The theme value to assign.
*/
set theme(value) {
this._theme = value;
}
/**
* Gets the outer theme for the content.
* @type {import("settings.js").PopupOuterTheme}
*/
get outerTheme() {
return this._outerTheme;
}
/**
* Sets the outer theme for the content.
* @param {import("settings.js").PopupOuterTheme} value The outer theme value to assign.
*/
set outerTheme(value) {
this._outerTheme = value;
}
/**
* Gets the override value for the site theme.
* If this value is `null`, the computed value will be used.
* @type {?('dark'|'light')}
*/
get siteTheme() {
return this._siteTheme;
}
/**
* Sets the override value for the site theme.
* If this value is `null`, the computed value will be used.
* @param {?('dark'|'light')} value The site theme value to assign.
*/
set siteTheme(value) {
this._siteTheme = value;
}
/**
* Gets the browser's preferred color theme.
* The value can be either 'light' or 'dark'.
* @type {'dark'|'light'}
*/
get browserTheme() {
return this._browserTheme;
}
/**
* Prepares the instance for use and applies the theme settings.
*/
prepare() {
const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
mediaQueryList.addEventListener('change', this._onPrefersColorSchemeDarkChange.bind(this));
this._onPrefersColorSchemeDarkChange(mediaQueryList);
}
/**
* Updates the theme attributes on the target element.
* If the site theme value isn't overridden, the current site theme is recomputed.
*/
updateTheme() {
if (this._element === null) { return; }
const computedSiteTheme = this._siteTheme !== null ? this._siteTheme : this.computeSiteTheme();
const data = this._element.dataset;
data.theme = this._resolveThemeValue(this._theme, computedSiteTheme);
data.outerTheme = this._resolveThemeValue(this._outerTheme, computedSiteTheme);
data.siteTheme = computedSiteTheme;
data.browserTheme = this._browserTheme;
data.themeRaw = this._theme;
data.outerThemeRaw = this._outerTheme;
}
/**
* Computes the current site theme based on the background color.
* @returns {'light'|'dark'} The theme of the site.
*/
computeSiteTheme() {
const color = [255, 255, 255];
const {documentElement, body} = document;
if (documentElement !== null) {
this._addColor(color, window.getComputedStyle(documentElement).backgroundColor);
}
if (body !== null) {
this._addColor(color, window.getComputedStyle(body).backgroundColor);
}
const dark = (color[0] < 128 && color[1] < 128 && color[2] < 128);
return dark ? 'dark' : 'light';
}
/**
* Event handler for when the preferred browser theme changes.
* @param {MediaQueryList|MediaQueryListEvent} detail The object containing event details.
*/
_onPrefersColorSchemeDarkChange({matches}) {
this._browserTheme = (matches ? 'dark' : 'light');
this.updateTheme();
}
/**
* Resolves a settings theme value to the actual value which should be used.
* @param {string} theme The theme value to resolve.
* @param {string} computedSiteTheme The computed site theme value to use for when the theme value is `'auto'`.
* @returns {string} The resolved theme value.
*/
_resolveThemeValue(theme, computedSiteTheme) {
switch (theme) {
case 'site': return this.siteOverride ? this._browserTheme : computedSiteTheme;
case 'browser': return this._browserTheme;
default: return theme;
}
}
/**
* Adds the value of a CSS color to an accumulation target.
* @param {number[]} target The target color buffer to accumulate into, as an array of [r, g, b].
* @param {string|*} cssColor The CSS color value to add to the target. If this value is not a string,
* the target will not be modified.
*/
_addColor(target, cssColor) {
if (typeof cssColor !== 'string') { return; }
const color = this._getColorInfo(cssColor);
if (color === null) { return; }
const a = color[3];
if (a <= 0) { return; }
const aInv = 1 - a;
for (let i = 0; i < 3; ++i) {
target[i] = target[i] * aInv + color[i] * a;
}
}
/**
* Decomposes a CSS color string into its RGBA values.
* @param {string} cssColor The color value to decompose. This value is expected to be in the form RGB(r, g, b) or RGBA(r, g, b, a).
* @returns {?number[]} The color and alpha values as [r, g, b, a]. The color component values range from [0, 255], and the alpha ranges from [0, 1].
*/
_getColorInfo(cssColor) {
const m = /^\s*rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)\s*$/.exec(cssColor);
if (m === null) { return null; }
const m4 = m[4];
return [
Number.parseInt(m[1], 10),
Number.parseInt(m[2], 10),
Number.parseInt(m[3], 10),
m4 ? Math.max(0, Math.min(1, Number.parseFloat(m4))) : 1,
];
}
}