Skip to content

Commit

Permalink
✅ Fix tests for tabs
Browse files Browse the repository at this point in the history
  • Loading branch information
trickypr committed Apr 13, 2024
1 parent ebbea46 commit d633117
Show file tree
Hide file tree
Showing 18 changed files with 241 additions and 46 deletions.
9 changes: 6 additions & 3 deletions apps/content/src/browser/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { registerEventBus } from './windowApi/eventBus.js'

// Handle window arguments
let rawArgs = window.arguments && window.arguments[0]
/** @type {Record<string, string>} */
/** @type {Record<string, string | string[]>} */
let args = {}

if (rawArgs && rawArgs instanceof Ci.nsISupports) {
Expand All @@ -19,8 +19,8 @@ if (rawArgs && rawArgs instanceof Ci.nsISupports) {
args = rawArgs
}

const initialUrls = args.initialUrl
? [args.initialUrl]
const initialUrls = args.initialUrls
? args.initialUrls
: ['https://google.com/', 'https://svelte.dev/']

WindowTabs.initialize(initialUrls)
Expand All @@ -30,3 +30,6 @@ registerEventBus()
new BrowserWindow({ target: document.body })

browserImports.WindowTracker.registerWindow(window)
window.addEventListener('unload', () =>
browserImports.WindowTracker.removeWindow(window),
)
9 changes: 9 additions & 0 deletions apps/content/src/browser/windowApi/WebsiteView.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export function create(uri) {
const view = {
windowBrowserId: nextWindowBrowserId++,
browser: createBrowser(uri),
uri,
websiteState: 'loading',

/** @type {import('mitt').Emitter<WebsiteViewEvents>} */
events: mitt(),
Expand All @@ -49,6 +51,12 @@ export function create(uri) {
registerViewThemeListener(view)
})

view.events.on('locationChange', (e) => (view.uri = e.aLocation))
view.events.on(
'loadingChange',
(e) => (view.websiteState = e ? 'loading' : 'complete'),
)

eventBus.on('iconUpdate', ({ browserId, iconUrl }) => {
if (view.browser.browserId === browserId) {
view.iconUrl = iconUrl
Expand Down Expand Up @@ -293,6 +301,7 @@ class TabProgressListener {
* @returns {void}
*/
onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
if (!aWebProgress || !aWebProgress.isTopLevel) return
this.view.events.emit('locationChange', {
aWebProgress,
aRequest,
Expand Down
2 changes: 1 addition & 1 deletion apps/extensions/lib/ext-browser.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"tabs": {
"schema": "chrome://bextensions/content/schemas/tabs.json",
"url": "chrome://bextensions/content/parent/ext-tabs.js",
"scopes": "addon_parent",
"scopes": ["addon_parent"],
"paths": [["tabs"]]
}
}
20 changes: 7 additions & 13 deletions apps/extensions/lib/parent/ext-tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
*/
function query(queryInfo) {
const windows = [...lazy.WindowTracker.registeredWindows.entries()]
console.log(queryInfo)

const urlMatchSet =
(queryInfo.url &&
Expand All @@ -25,17 +26,10 @@ function query(queryInfo) {
const tabs = window.windowTabs()
const activeTab = window.activeTab()

if (
typeof queryInfo.windowId !== 'undefined' &&
queryInfo.windowId != windowId
) {
return []
}

return tabs
.filter((tab) => {
const active =
typeof queryInfo.active !== 'undefined'
queryInfo.active !== null
? queryInfo.active
? tab === activeTab
: tab !== activeTab
Expand All @@ -46,9 +40,11 @@ function query(queryInfo) {
const url =
urlMatchSet === null
? true
: urlMatchSet.matches(tab.view.browser.browsingContext?.currentURI)
: urlMatchSet.matches(tab.view.uri.asciiSpec)
const window =
queryInfo.windowId === null ? true : queryInfo.windowId === windowId

return active && title && url
return active && title && url && window
})
.map(
/** @returns {[import("@browser/tabs").WindowTab, Window]} */ (tab) => [
Expand All @@ -75,9 +71,7 @@ const serialize =
active: window.activeTab() === tab,
highlighted: false, // TODO
title: hasTabPermission && tab.view.title,
url:
hasTabPermission &&
tab.view.browser.browsingContext?.currentURI.asciiSpec,
url: hasTabPermission && tab.view.uri.asciiSpec,
windowId: window.windowId,
}
}
Expand Down
5 changes: 5 additions & 0 deletions apps/extensions/lib/schemaTypes/tabs.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
//
// DO NOT MODIFY MANUALLY

declare module tabs__manifest {
type ApiGetterReturn = {
manifest: {}
}
}
declare module tabs__tabs {
type Tab = {
id?: number
Expand Down
15 changes: 15 additions & 0 deletions apps/extensions/lib/schemas/tabs.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,21 @@
// found in the LICENSE file.

[
{
"namespace": "manifest",
"types": [
{
"$extend": "OptionalPermission",
"id": "ExtraPerms1",
"choices": [
{
"type": "string",
"enum": ["tabs", "tabHide"]
}
]
}
]
},
{
"namespace": "tabs",
"description": "Provides access to information about currently open tabs",
Expand Down
21 changes: 12 additions & 9 deletions apps/extensions/scripts/buildTypes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @ts-check
import * as fs from 'node:fs'
import * as path from 'node:path'
Expand Down Expand Up @@ -138,14 +137,18 @@ for (const file of fs.readdirSync(schemaFolder)) {
* @returns {import('typescript').TypeAliasDeclaration[]}
*/
function generateTypes(types) {
return types.map((type) =>
factory.createTypeAliasDeclaration(
undefined,
type.id,
undefined,
generateTypeNode(type),
),
)
return types
.map((type) => {
if (type.$extend) return null

return factory.createTypeAliasDeclaration(
undefined,
type.id,
undefined,
generateTypeNode(type),
)
})
.filter(Boolean)
}

/**
Expand Down
5 changes: 4 additions & 1 deletion apps/modules/lib/BrowserWindowTracker.sys.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import mitt from 'resource://app/modules/mitt.sys.mjs'

/** @type {import('resource://app/modules/BrowserWindowTracker.sys.mjs')['WindowTracker']} */
export const WindowTracker = {
nextWindowId: 0,
/**
* 1 indexed to stop having a falsey window id
*/
nextWindowId: 1,

events: mitt(),

Expand Down
33 changes: 26 additions & 7 deletions apps/modules/lib/ExtensionTestUtils.sys.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @ts-check
import { lazyESModuleGetters } from 'resource://app/modules/TypedImportUtils.sys.mjs'

Expand Down Expand Up @@ -178,10 +177,8 @@ const objectMap = (obj, fn) =>
*/
class ExtensionTestUtilsImpl {
/**
* @template {import('resource://app/modules/zora.sys.mjs').IAssert} A
*
* @param {Partial<import("resource://app/modules/ExtensionTestUtils.sys.mjs").ExtManifest>} definition
* @param {import('resource://app/modules/ExtensionTestUtils.sys.mjs').AddonMiddleware<A>} assert
* @param {import('resource://app/modules/TestManager.sys.mjs').IDefaultAssert} assert
*
* @returns {import('resource://app/modules/ExtensionTestUtils.sys.mjs').ExtensionWrapper}
*/
Expand All @@ -193,8 +190,13 @@ class ExtensionTestUtilsImpl {
definition.background && serializeScript(definition.background),
})

let testCount = 0
/** @type {number | null} */
let expectedTestCount = null

function handleTestResults(kind, pass, msg, ...args) {
if (kind == 'test-eq') {
testCount += 1
let [expected, actual] = args
assert.ok(pass, `${msg} - Expected: ${expected}, Actual: ${actual}`)
} else if (kind == 'test-log') {
Expand Down Expand Up @@ -232,25 +234,42 @@ class ExtensionTestUtilsImpl {
/* Ignore */
}
await extension.startup()
return await startupPromise
await startupPromise
} catch (e) {
assert.fail(`Errored: ${e}`)
}

return this
},
async unload() {
await extension.shutdown()
return await extension._uninstallPromise
await extension._uninstallPromise

if (expectedTestCount && testCount !== expectedTestCount) {
assert.fail(
`Expected ${expectedTestCount} to execute. ${testCount} extecuted instead`,
)
}
},

/**
* @param {number} count
*/
testCount(count) {
expectedTestCount = count
return this
},
sendMsg(msg) {
extension.testMessage(msg)
return this
},
async awaitMsg(msg) {
const self = this
return new Promise((res) => {
const callback = (_, event) => {
if (event == msg) {
extension.off('test-message', callback)
res(void 0)
res(self)
}
}

Expand Down
6 changes: 3 additions & 3 deletions apps/modules/lib/TestManager.sys.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ class TestManagerSingleton {
}

/**
* @param {string} initialUrl
* @param {string[]} initialUrls
* @param {(win: Window) => Promise<void>} using
*/
async withBrowser(initialUrl, using) {
const args = { initialUrl }
async withBrowser(initialUrls, using) {
const args = { initialUrls }

/** @type {Window} */
// @ts-expect-error Incorrect type gen
Expand Down
1 change: 1 addition & 0 deletions apps/tests/integrations/_index.sys.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import './extensions/pageAction.mjs'
import './extensions/tabs.mjs'
4 changes: 2 additions & 2 deletions apps/tests/integrations/extensions/pageAction.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ async function spinLock(predicate) {
}
}

await TestManager.withBrowser('http://example.com/', async (window) => {
await TestManager.test('Extension Test', async (test) => {
await TestManager.withBrowser(['http://example.com/'], async (window) => {
await TestManager.test('pageAction - Icon & Panel', async (test) => {
const extension = ExtensionTestUtils.loadExtension(
{
manifest: {
Expand Down
Loading

0 comments on commit d633117

Please sign in to comment.