Merge autoland to mozilla-central. a=merge

This commit is contained in:
Bogdan Szekely 2022-07-06 12:39:26 +03:00
Родитель 67abf7dc22 c3aa2f7ca2
Коммит f816e52d85
233 изменённых файлов: 1844 добавлений и 2628 удалений

Просмотреть файл

@ -1403,7 +1403,7 @@ TextLeafPoint TextLeafPoint::FindTextAttrsStart(nsDirection aDirection,
LayoutDeviceIntRect TextLeafPoint::CharBounds() {
if (mAcc && !mAcc->IsText()) {
// If we're dealing with an empty embedded object, return the
// If we're dealing with an empty container, return the
// accessible's non-text bounds.
return mAcc->Bounds();
}
@ -1426,4 +1426,14 @@ LayoutDeviceIntRect TextLeafPoint::CharBounds() {
return LayoutDeviceIntRect();
}
bool TextLeafPoint::ContainsPoint(int32_t aX, int32_t aY) {
if (mAcc && !mAcc->IsText()) {
// If we're dealing with an empty embedded object, use the
// accessible's non-text bounds.
return mAcc->Bounds().Contains(aX, aY);
}
return CharBounds().Contains(aX, aY);
}
} // namespace mozilla::a11y

Просмотреть файл

@ -168,6 +168,15 @@ class TextLeafPoint final {
*/
LayoutDeviceIntRect CharBounds();
/**
* Returns true if the given point (in screen coords) is contained
* in the char bounds of the current TextLeafPoint. Returns false otherwise.
* If the current point is an empty container, we use the acc's bounds instead
* of char bounds. Because this depends on CharBounds, this function only
* works on remote accessibles, and assumes caching is enabled.
*/
bool ContainsPoint(int32_t aX, int32_t aY);
bool IsLineFeedChar() const { return GetChar() == '\n'; }
bool IsSpace() const;

Просмотреть файл

@ -247,6 +247,33 @@ LayoutDeviceIntRect HyperTextAccessibleBase::TextBounds(int32_t aStartOffset,
return result;
}
int32_t HyperTextAccessibleBase::OffsetAtPoint(int32_t aX, int32_t aY,
uint32_t aCoordType) {
Accessible* thisAcc = Acc();
LayoutDeviceIntPoint coords =
nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordType, thisAcc);
if (!thisAcc->Bounds().Contains(coords.x, coords.y)) {
// The requested point does not exist in this accessible.
return -1;
}
TextLeafPoint point = ToTextLeafPoint(0, false);
// As with TextBounds, we walk to the very end of the text contained in this
// hypertext and then step backwards to make our endPoint inclusive.
TextLeafPoint endPoint =
ToTextLeafPoint(static_cast<int32_t>(CharacterCount()), true);
endPoint =
endPoint.FindBoundary(nsIAccessibleText::BOUNDARY_CHAR, eDirPrevious,
/* aIncludeOrigin */ false);
// XXX: We should create a TextLeafRange object for this hypertext and move
// this search inside the TextLeafRange class.
for (; !point.ContainsPoint(coords.x, coords.y) && point != endPoint;
point = point.FindBoundary(nsIAccessibleText::BOUNDARY_CHAR, eDirNext,
/* aIncludeOrigin */ false)) {
};
return point.ContainsPoint(coords.x, coords.y) ? point.mOffset : -1;
}
TextLeafPoint HyperTextAccessibleBase::ToTextLeafPoint(int32_t aOffset,
bool aDescendToEnd) {
Accessible* thisAcc = Acc();

Просмотреть файл

@ -115,6 +115,11 @@ class HyperTextAccessibleBase {
int32_t aEndOffset,
uint32_t aCoordType);
/**
* Return the offset of the char that contains the given coordinates.
*/
virtual int32_t OffsetAtPoint(int32_t aX, int32_t aY, uint32_t aCoordType);
/**
* Get a TextLeafPoint for a given offset in this HyperTextAccessible.
* If the offset points to an embedded object and aDescendToEnd is true,

Просмотреть файл

@ -171,7 +171,7 @@ class HyperTextAccessible : public AccessibleWrap,
/**
* Return an offset at the given point.
*/
int32_t OffsetAtPoint(int32_t aX, int32_t aY, uint32_t aCoordType);
int32_t OffsetAtPoint(int32_t aX, int32_t aY, uint32_t aCoordType) override;
LayoutDeviceIntRect TextBounds(
int32_t aStartOffset, int32_t aEndOffset,

Просмотреть файл

@ -484,15 +484,18 @@ void RemoteAccessibleBase<Derived>::ApplyScrollOffset(nsRect& aBounds) const {
template <class Derived>
nsRect RemoteAccessibleBase<Derived>::BoundsInAppUnits() const {
dom::CanonicalBrowsingContext* cbc =
static_cast<dom::BrowserParent*>(mDoc->Manager())
->GetBrowsingContext()
->Top();
dom::BrowserParent* bp = cbc->GetBrowserParent();
nsPresContext* presContext =
bp->GetOwnerElement()->OwnerDoc()->GetPresContext();
return LayoutDeviceIntRect::ToAppUnits(Bounds(),
presContext->AppUnitsPerDevPixel());
if (dom::CanonicalBrowsingContext* cbc = mDoc->GetBrowsingContext()->Top()) {
if (dom::BrowserParent* bp = cbc->GetBrowserParent()) {
DocAccessibleParent* topDoc = bp->GetTopLevelDocAccessible();
if (topDoc && topDoc->mCachedFields) {
auto appUnitsPerDevPixel = topDoc->mCachedFields->GetAttribute<int32_t>(
nsGkAtoms::_moz_device_pixel_ratio);
MOZ_ASSERT(appUnitsPerDevPixel);
return LayoutDeviceIntRect::ToAppUnits(Bounds(), *appUnitsPerDevPixel);
}
}
}
return LayoutDeviceIntRect::ToAppUnits(Bounds(), AppUnitsPerCSSPixel());
}
template <class Derived>

Просмотреть файл

@ -90,7 +90,8 @@ virtual void TextBeforeOffset(int32_t aOffset,
char16_t CharAt(int32_t aOffset);
int32_t OffsetAtPoint(int32_t aX, int32_t aY, uint32_t aCoordType);
virtual int32_t OffsetAtPoint(int32_t aX, int32_t aY,
uint32_t aCoordType) override;
bool SetSelectionBoundsAt(int32_t aSelectionNum, int32_t aStartOffset,
int32_t aEndOffset);

Просмотреть файл

@ -309,6 +309,12 @@ LayoutDeviceIntRect RemoteAccessible::CharBounds(int32_t aOffset,
int32_t RemoteAccessible::OffsetAtPoint(int32_t aX, int32_t aY,
uint32_t aCoordType) {
if (StaticPrefs::accessibility_cache_enabled_AtStartup()) {
MOZ_ASSERT(IsHyperText(), "is not hypertext?");
return RemoteAccessibleBase<RemoteAccessible>::OffsetAtPoint(aX, aY,
aCoordType);
}
int32_t retVal = -1;
Unused << mDoc->SendOffsetAtPoint(mID, aX, aY, aCoordType, &retVal);
return retVal;

Просмотреть файл

@ -517,6 +517,11 @@ static IA2TextBoundaryType GetIA2TextBoundary(
int32_t RemoteAccessible::OffsetAtPoint(int32_t aX, int32_t aY,
uint32_t aCoordinateType) {
if (StaticPrefs::accessibility_cache_enabled_AtStartup()) {
return RemoteAccessibleBase<RemoteAccessible>::OffsetAtPoint(
aX, aY, aCoordinateType);
}
RefPtr<IAccessibleText> acc = QueryInterface<IAccessibleText>(this);
if (!acc) {
return -1;

Просмотреть файл

@ -17,7 +17,10 @@ const Layout = {
*/
zoomDocument(doc, zoom) {
const bc = BrowsingContext.getFromWindow(doc.defaultView);
bc.fullZoom = zoom;
// To mirror the behaviour of the UI, we set the zoom
// value on the top level browsing context. This value automatically
// propagates down to iframes.
bc.top.fullZoom = zoom;
},
/**

Просмотреть файл

@ -72,4 +72,3 @@ skip-if = true # Failing due to incorrect index of test container children on do
[browser_obj_group.js]
skip-if = os == 'win' # Only supported with cache enabled
[browser_caching_position.js]
[browser_caching_hittest.js]

Просмотреть файл

@ -1,187 +0,0 @@
/* 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/. */
"use strict";
const { Layout } = ChromeUtils.import(
"chrome://mochitests/content/browser/accessible/tests/browser/Layout.jsm"
);
const { CommonUtils } = ChromeUtils.import(
"chrome://mochitests/content/browser/accessible/tests/browser/Common.jsm"
);
function getChildAtPoint(container, x, y, findDeepestChild) {
try {
const child = findDeepestChild
? container.getDeepestChildAtPoint(x, y)
: container.getChildAtPoint(x, y);
info(`Got child with role: ${roleToString(child.role)}`);
return child;
} catch (e) {
// Failed to get child at point.
}
return null;
}
async function testChildAtPoint(dpr, x, y, container, child, grandChild) {
const [containerX, containerY] = Layout.getBounds(container, dpr);
x += containerX;
y += containerY;
await untilCacheIs(
() => getChildAtPoint(container, x, y, false),
child,
`Wrong direct child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${child ? roleToString(child.role) : "unknown"}`
);
await untilCacheIs(
() => getChildAtPoint(container, x, y, true),
grandChild,
`Wrong deepest child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${grandChild ? roleToString(grandChild.role) : "unknown"}`
);
}
async function hitTest(browser, container, child, grandChild) {
const [childX, childY] = await getContentBoundsForDOMElm(
browser,
getAccessibleDOMNodeID(child)
);
const x = childX + 1;
const y = childY + 1;
await untilCacheIs(
() => getChildAtPoint(container, x, y, false),
child,
`Wrong direct child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${child ? roleToString(child.role) : "unknown"}`
);
await untilCacheIs(
() => getChildAtPoint(container, x, y, true),
grandChild,
`Wrong deepest child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${grandChild ? roleToString(grandChild.role) : "unknown"}`
);
}
async function runTests(browser, accDoc) {
await waitForImageMap(browser, accDoc);
const dpr = await getContentDPR(browser);
await testChildAtPoint(
dpr,
3,
3,
findAccessibleChildByID(accDoc, "list"),
findAccessibleChildByID(accDoc, "listitem"),
findAccessibleChildByID(accDoc, "inner").firstChild
);
todo(
false,
"Bug 746974 - children must match on all platforms. On Windows, " +
"ChildAtPoint with eDeepestChild is incorrectly ignoring MustPrune " +
"for the graphic."
);
const txt = findAccessibleChildByID(accDoc, "txt");
await testChildAtPoint(dpr, 1, 1, txt, txt, txt);
info(
"::MustPrune case, point is outside of textbox accessible but is in document."
);
await testChildAtPoint(dpr, -1, -1, txt, null, null);
info("::MustPrune case, point is outside of root accessible.");
await testChildAtPoint(dpr, -10000, -10000, txt, null, null);
info("Not specific case, point is inside of btn accessible.");
const btn = findAccessibleChildByID(accDoc, "btn");
await testChildAtPoint(dpr, 1, 1, btn, btn, btn);
info("Not specific case, point is outside of btn accessible.");
await testChildAtPoint(dpr, -1, -1, btn, null, null);
info(
"Out of flow accessible testing, do not return out of flow accessible " +
"because it's not a child of the accessible even though visually it is."
);
await invokeContentTask(browser, [], () => {
// We have to reimprot CommonUtils in this scope -- eslint thinks this is
// wrong, but if you remove it, things will break.
/* eslint-disable no-shadow */
const { CommonUtils } = ChromeUtils.import(
"chrome://mochitests/content/browser/accessible/tests/browser/Common.jsm"
);
/* eslint-enable no-shadow */
const doc = content.document;
const rectArea = CommonUtils.getNode("area", doc).getBoundingClientRect();
const outOfFlow = CommonUtils.getNode("outofflow", doc);
outOfFlow.style.left = rectArea.left + "px";
outOfFlow.style.top = rectArea.top + "px";
});
const area = findAccessibleChildByID(accDoc, "area");
await testChildAtPoint(dpr, 1, 1, area, area, area);
info("Test image maps. Their children are not in the layout tree.");
const imgmap = findAccessibleChildByID(accDoc, "imgmap");
const theLetterA = imgmap.firstChild;
await hitTest(browser, imgmap, theLetterA, theLetterA);
await hitTest(
browser,
findAccessibleChildByID(accDoc, "container"),
imgmap,
theLetterA
);
info("hit testing for element contained by zero-width element");
const container2Input = findAccessibleChildByID(accDoc, "container2_input");
await hitTest(
browser,
findAccessibleChildByID(accDoc, "container2"),
container2Input,
container2Input
);
}
addAccessibleTask(
`
<div role="list" id="list">
<div role="listitem" id="listitem"><span title="foo" id="inner">inner</span>item</div>
</div>
<span role="button">button1</span><span role="button" id="btn">button2</span>
<span role="textbox">textbox1</span><span role="textbox" id="txt">textbox2</span>
<div id="outofflow" style="width: 10px; height: 10px; position: absolute; left: 0px; top: 0px; background-color: yellow;">
</div>
<div id="area" style="width: 100px; height: 100px; background-color: blue;"></div>
<map name="atoz_map">
<area id="thelettera" href="http://www.bbc.co.uk/radio4/atoz/index.shtml#a"
coords="0,0,15,15" alt="thelettera" shape="rect"/>
</map>
<div id="container">
<img id="imgmap" width="447" height="15" usemap="#atoz_map" src="http://example.com/a11y/accessible/tests/mochitest/letters.gif"/>
</div>
<div id="container2" style="width: 0px">
<input id="container2_input">
</div>
`,
runTests,
{
iframe: true,
remoteIframe: true,
// Ensure that all hittest elements are in view.
iframeAttrs: { style: "width: 600px; height: 600px; padding: 10px;" },
}
);

Просмотреть файл

@ -8,8 +8,7 @@ async function runTests(browser, accDoc) {
await waitForImageMap(browser, accDoc);
const dpr = await getContentDPR(browser);
info("Not specific case, child and deepchild testing.");
testChildAtPoint(
await testChildAtPoint(
dpr,
3,
3,
@ -24,27 +23,23 @@ async function runTests(browser, accDoc) {
"for the graphic."
);
info(
"::MustPrune case (in this case childAtPoint doesn't look inside a " +
"textbox), point is inside of textbox."
);
const txt = findAccessibleChildByID(accDoc, "txt");
testChildAtPoint(dpr, 1, 1, txt, txt, txt);
await testChildAtPoint(dpr, 1, 1, txt, txt, txt);
info(
"::MustPrune case, point is outside of textbox accessible but is in document."
);
testChildAtPoint(dpr, -1, -1, txt, null, null);
await testChildAtPoint(dpr, -1, -1, txt, null, null);
info("::MustPrune case, point is outside of root accessible.");
testChildAtPoint(dpr, -10000, -10000, txt, null, null);
await testChildAtPoint(dpr, -10000, -10000, txt, null, null);
info("Not specific case, point is inside of btn accessible.");
const btn = findAccessibleChildByID(accDoc, "btn");
testChildAtPoint(dpr, 1, 1, btn, btn, btn);
await testChildAtPoint(dpr, 1, 1, btn, btn, btn);
info("Not specific case, point is outside of btn accessible.");
testChildAtPoint(dpr, -1, -1, btn, null, null);
await testChildAtPoint(dpr, -1, -1, btn, null, null);
info(
"Out of flow accessible testing, do not return out of flow accessible " +
@ -54,7 +49,6 @@ async function runTests(browser, accDoc) {
const { CommonUtils } = ChromeUtils.import(
"chrome://mochitests/content/browser/accessible/tests/browser/Common.jsm"
);
const doc = content.document;
const rectArea = CommonUtils.getNode("area", doc).getBoundingClientRect();
const outOfFlow = CommonUtils.getNode("outofflow", doc);
@ -63,7 +57,7 @@ async function runTests(browser, accDoc) {
});
const area = findAccessibleChildByID(accDoc, "area");
testChildAtPoint(dpr, 1, 1, area, area, area);
await testChildAtPoint(dpr, 1, 1, area, area, area);
info("Test image maps. Their children are not in the layout tree.");
const imgmap = findAccessibleChildByID(accDoc, "imgmap");
@ -118,6 +112,6 @@ addAccessibleTask(
iframe: true,
remoteIframe: true,
// Ensure that all hittest elements are in view.
iframeAttrs: { style: "width: 600px; height: 600px;" },
iframeAttrs: { style: "width: 600px; height: 600px; padding: 10px;" },
}
);

Просмотреть файл

@ -7,7 +7,7 @@
async function runTests(browser, accDoc) {
const dpr = await getContentDPR(browser);
let componentAcc = findAccessibleChildByID(accDoc, "component1");
testChildAtPoint(
await testChildAtPoint(
dpr,
1,
1,
@ -17,7 +17,7 @@ async function runTests(browser, accDoc) {
);
componentAcc = findAccessibleChildByID(accDoc, "component2");
testChildAtPoint(
await testChildAtPoint(
dpr,
1,
1,

Просмотреть файл

@ -7,9 +7,9 @@
/**
* Test if getOffsetAtPoint returns the given text offset at given coordinates.
*/
function testOffsetAtPoint(hyperText, x, y, coordType, expectedOffset) {
is(
hyperText.getOffsetAtPoint(x, y, coordType),
async function testOffsetAtPoint(hyperText, x, y, coordType, expectedOffset) {
await untilCacheIs(
() => hyperText.getOffsetAtPoint(x, y, coordType),
expectedOffset,
`Wrong offset at given point (${x}, ${y}) for ${prettyName(hyperText)}`
);
@ -21,8 +21,7 @@ async function runTests(browser, accDoc) {
"chrome://mochitests/content/browser/accessible/tests/browser/Common.jsm"
);
const hyperText = CommonUtils.getNode("paragraph", content.document);
return hyperText.textContent.length / 2;
return Math.floor(hyperText.textContent.length / 2);
});
const hyperText = findAccessibleChildByID(accDoc, "paragraph", [
Ci.nsIAccessibleText,
@ -34,7 +33,7 @@ async function runTests(browser, accDoc) {
await getContentDPR(browser)
);
testOffsetAtPoint(
await testOffsetAtPoint(
hyperText,
x + width / 2,
y + height / 2,
@ -56,7 +55,7 @@ async function runTests(browser, accDoc) {
await getContentDPR(browser)
);
testOffsetAtPoint(
await testOffsetAtPoint(
hyperText,
x + width / 2,
y + height / 2,
@ -66,7 +65,7 @@ async function runTests(browser, accDoc) {
}
addAccessibleTask(
`<p id="paragraph" style="font-family: monospace;">Болтали две сороки</p>`,
`<p id="paragraph" style="font-family: monospace;">hello world hello world</p>`,
runTests,
{
iframe: true,

Просмотреть файл

@ -41,25 +41,23 @@ function getChildAtPoint(container, x, y, findDeepestChild) {
return null;
}
function testChildAtPoint(dpr, x, y, container, child, grandChild) {
async function testChildAtPoint(dpr, x, y, container, child, grandChild) {
const [containerX, containerY] = Layout.getBounds(container, dpr);
x += containerX;
y += containerY;
CommonUtils.isObject(
getChildAtPoint(container, x, y, false),
await untilCacheIs(
() => getChildAtPoint(container, x, y, false),
child,
`Wrong direct child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}`
)}, sought ${child ? roleToString(child.role) : "unknown"}`
);
CommonUtils.isObject(
getChildAtPoint(container, x, y, true),
await untilCacheIs(
() => getChildAtPoint(container, x, y, true),
grandChild,
`Wrong deepest child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}`
)}, sought ${grandChild ? roleToString(grandChild.role) : "unknown"}`
);
}
@ -75,15 +73,18 @@ async function hitTest(browser, container, child, grandChild) {
const x = childX + 1;
const y = childY + 1;
CommonUtils.isObject(
getChildAtPoint(container, x, y, false),
await untilCacheIs(
() => getChildAtPoint(container, x, y, false),
child,
`Wrong direct child of ${prettyName(container)}`
`Wrong direct child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${child ? roleToString(child.role) : "unknown"}`
);
CommonUtils.isObject(
getChildAtPoint(container, x, y, true),
await untilCacheIs(
() => getChildAtPoint(container, x, y, true),
grandChild,
`Wrong deepest child of ${prettyName(container)}`
`Wrong deepest child accessible at the point (${x}, ${y}) of ${CommonUtils.prettyName(
container
)}, sought ${grandChild ? roleToString(grandChild.role) : "unknown"}`
);
}

Просмотреть файл

@ -489,6 +489,16 @@ static already_AddRefed<IDispatch> GetProxiedAccessibleInSubtree(
return disp.forget();
}
static bool IsInclusiveDescendantOf(DocAccessible* aAncestor,
DocAccessible* aDescendant) {
for (DocAccessible* doc = aDescendant; doc; doc = doc->ParentDocument()) {
if (doc == aAncestor) {
return true;
}
}
return false;
}
already_AddRefed<IAccessible> MsaaAccessible::GetIAccessibleFor(
const VARIANT& aVarChild, bool* aIsDefunct) {
if (aVarChild.vt != VT_I4) return nullptr;
@ -602,9 +612,8 @@ already_AddRefed<IAccessible> MsaaAccessible::GetIAccessibleFor(
}
for (DocAccessibleParent* remoteDoc : *remoteDocs) {
LocalAccessible* outerDoc = remoteDoc->OuterDocOfRemoteBrowser();
if (!outerDoc || outerDoc->Document() != localDoc) {
// The OuterDoc isn't inside our document, so this isn't a
// descendant.
if (!outerDoc ||
!IsInclusiveDescendantOf(localDoc, outerDoc->Document())) {
continue;
}
child = GetAccessibleInSubtree(remoteDoc, id);

Просмотреть файл

@ -3,6 +3,8 @@
* 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/. */
#include "mozilla/a11y/DocAccessibleParent.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/WindowsVersion.h"
#include "MsaaRootAccessible.h"
#include "Relation.h"
@ -129,12 +131,11 @@ MsaaRootAccessible::get_accFocus(
if (StaticPrefs::accessibility_cache_enabled_AtStartup()) {
return S_FALSE;
}
// Get the document in the active tab.
RootAccessible* rootAcc = RootAcc();
if (!rootAcc) {
return CO_E_OBJNOTCONNECTED;
dom::BrowserParent* browser = dom::BrowserParent::GetFocused();
if (!browser) {
return hr;
}
RemoteAccessible* docProxy = rootAcc->GetPrimaryRemoteTopLevelContentDoc();
DocAccessibleParent* docProxy = browser->GetTopLevelDocAccessible();
if (!docProxy) {
return hr;
}

Просмотреть файл

@ -1526,8 +1526,6 @@ pref("browser.newtabpage.activity-stream.discoverystream.hardcoded-basic-layout"
pref("browser.newtabpage.activity-stream.discoverystream.hybridLayout.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.hideCardBackground.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.fourCardLayout.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.loadMore.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.lastCardMessage.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.newFooterSection.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.saveToPocketCard.enabled", false);
pref("browser.newtabpage.activity-stream.discoverystream.hideDescriptions.enabled", false);

Просмотреть файл

@ -225,8 +225,6 @@ export class _DiscoveryStreamBase extends React.PureComponent {
essentialReadsHeader={component.properties.essentialReadsHeader}
editorsPicksHeader={component.properties.editorsPicksHeader}
readTime={component.properties.readTime}
loadMore={component.loadMore}
lastCardMessageEnabled={component.lastCardMessageEnabled}
saveToPocketCard={component.saveToPocketCard}
cta_variant={component.cta_variant}
pocket_button_enabled={component.pocketButtonEnabled}

Просмотреть файл

@ -2,11 +2,7 @@
* 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 {
DSCard,
PlaceholderDSCard,
LastCardMessage,
} from "../DSCard/DSCard.jsx";
import { DSCard, PlaceholderDSCard } from "../DSCard/DSCard.jsx";
import { DSEmptyState } from "../DSEmptyState/DSEmptyState.jsx";
import { TopicsWidget } from "../TopicsWidget/TopicsWidget.jsx";
import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
@ -181,45 +177,18 @@ export function RecentSavesContainer({
}
export class _CardGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = { moreLoaded: false };
this.loadMoreClicked = this.loadMoreClicked.bind(this);
}
loadMoreClicked() {
this.props.dispatch(
ac.UserEvent({
event: "CLICK",
source: "DS_LOAD_MORE_BUTTON",
})
);
this.setState({ moreLoaded: true });
}
get showLoadMore() {
const { loadMore, data, loadMoreThreshold } = this.props;
return (
loadMore &&
data.recommendations.length > loadMoreThreshold &&
!this.state.moreLoaded
);
}
renderCards() {
let { items } = this.props;
const { DiscoveryStream } = this.props;
const prefs = this.props.Prefs.values;
const { recentSavesEnabled } = DiscoveryStream;
const showRecentSaves = prefs.showRecentSaves && recentSavesEnabled;
const {
items,
hybridLayout,
hideCardBackground,
fourCardLayout,
hideDescriptions,
lastCardMessageEnabled,
saveToPocketCard,
loadMoreThreshold,
compactGrid,
compactImages,
imageGradient,
@ -231,12 +200,6 @@ export class _CardGrid extends React.PureComponent {
editorsPicksHeader,
widgets,
} = this.props;
let showLastCardMessage = lastCardMessageEnabled;
if (this.showLoadMore) {
items = loadMoreThreshold;
// We don't want to show this until after load more has been clicked.
showLastCardMessage = false;
}
const recs = this.props.data.recommendations.slice(0, items);
const cards = [];
@ -291,15 +254,6 @@ export class _CardGrid extends React.PureComponent {
);
}
// Replace last card with "you are all caught up card"
if (showLastCardMessage) {
cards.splice(
cards.length - 1,
1,
<LastCardMessage key={`dscard-last-${cards.length - 1}`} />
);
}
if (widgets?.positions?.length && widgets?.data?.length) {
let positionIndex = 0;
const source = "CARDGRID_WIDGET";
@ -444,13 +398,6 @@ export class _CardGrid extends React.PureComponent {
) : (
this.renderCards()
)}
{this.showLoadMore && (
<button
className="ASRouterButton primary ds-card-grid-load-more-button"
onClick={this.loadMoreClicked}
data-l10n-id="newtab-pocket-load-more-stories-button"
/>
)}
</div>
);
}
@ -460,9 +407,7 @@ _CardGrid.defaultProps = {
border: `border`,
items: 4, // Number of stories to display
enable_video_playheads: false,
lastCardMessageEnabled: false,
saveToPocketCard: false,
loadMoreThreshold: 12,
};
export const CardGrid = connect(state => ({

Просмотреть файл

@ -160,7 +160,6 @@ $col4-header-font-size: 14;
}
.source,
.ds-last-card-desc,
.story-sponsored-label,
.status-message .story-context-label {
color: var(--newtab-text-secondary-color);
@ -168,7 +167,6 @@ $col4-header-font-size: 14;
}
.source,
.ds-last-card-desc,
.story-sponsored-label {
font-size: 13px;
}
@ -271,12 +269,6 @@ $col4-header-font-size: 14;
.img-wrapper .img img {
border-radius: 8px;
box-shadow: $shadow-card;
&.last-card-message-image {
background: transparent;
box-shadow: none;
object-fit: contain;
}
}
.meta {
@ -311,12 +303,4 @@ $col4-header-font-size: 14;
}
}
}
.ds-card-grid-load-more-button {
display: block;
margin: 32px auto 0;
font-size: 13px;
line-height: 16px;
border-radius: 4px;
}
}

Просмотреть файл

@ -380,34 +380,6 @@ export class _DSCard extends React.PureComponent {
);
}
if (this.props.lastCard) {
return (
<div className="ds-card last-card-message">
<div className="img-wrapper">
<picture className="ds-image img loaded">
<img
data-l10n-id="newtab-pocket-last-card-image"
className="last-card-message-image"
src="chrome://activity-stream/content/data/content/assets/caught-up-illustration.svg"
alt="Youre all caught up"
/>
</picture>
</div>
<div className="meta">
<div className="info-wrap">
<header
className="title clamp"
data-l10n-id="newtab-pocket-last-card-title"
/>
<p
className="ds-last-card-desc"
data-l10n-id="newtab-pocket-last-card-desc"
/>
</div>
</div>
</div>
);
}
const isButtonCTA = this.props.cta_variant === "button";
const {
@ -585,4 +557,3 @@ export const DSCard = connect(state => ({
}))(_DSCard);
export const PlaceholderDSCard = props => <DSCard placeholder={true} />;
export const LastCardMessage = props => <DSCard lastCard={true} />;

Просмотреть файл

@ -196,24 +196,6 @@ $ds-card-image-gradient-solid: rgba(0, 0, 0, 1);
margin-top: 4px;
}
&.last-card-message {
.ds-last-card-desc {
font-size: 13px;
color: var(--newtab-text-secondary-color);
}
.ds-last-card-desc,
.title {
text-align: center;
}
.last-card-message-image {
object-fit: contain;
background: transparent;
box-shadow: none;
}
}
.meta {
display: flex;
flex-direction: column;

Просмотреть файл

@ -2762,14 +2762,12 @@ main.has-snippet {
margin-top: 8px;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2816,29 +2814,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2871,29 +2861,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2936,12 +2918,6 @@ main.has-snippet {
border-radius: 8px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image {
background: transparent;
box-shadow: none;
object-fit: contain;
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta {
padding: 12px 0 0;
@ -2968,13 +2944,6 @@ main.has-snippet {
.ds-layout .ds-sub-header .section-sub-link:active {
color: var(--newtab-primary-element-active-color);
}
.ds-layout .ds-card-grid-load-more-button {
display: block;
margin: 32px auto 0;
font-size: 13px;
line-height: 16px;
border-radius: 4px;
}
.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
margin: 15px 0 0;
@ -3506,19 +3475,6 @@ main.has-snippet {
.ds-card.video-card .meta {
margin-top: 4px;
}
.ds-card.last-card-message .ds-last-card-desc {
font-size: 13px;
color: var(--newtab-text-secondary-color);
}
.ds-card.last-card-message .ds-last-card-desc,
.ds-card.last-card-message .title {
text-align: center;
}
.ds-card.last-card-message .last-card-message-image {
object-fit: contain;
background: transparent;
box-shadow: none;
}
.ds-card .meta {
display: flex;
flex-direction: column;

Просмотреть файл

@ -2766,14 +2766,12 @@ main.has-snippet {
margin-top: 8px;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2820,29 +2818,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2875,29 +2865,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2940,12 +2922,6 @@ main.has-snippet {
border-radius: 8px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image {
background: transparent;
box-shadow: none;
object-fit: contain;
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta {
padding: 12px 0 0;
@ -2972,13 +2948,6 @@ main.has-snippet {
.ds-layout .ds-sub-header .section-sub-link:active {
color: var(--newtab-primary-element-active-color);
}
.ds-layout .ds-card-grid-load-more-button {
display: block;
margin: 32px auto 0;
font-size: 13px;
line-height: 16px;
border-radius: 4px;
}
.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
margin: 15px 0 0;
@ -3510,19 +3479,6 @@ main.has-snippet {
.ds-card.video-card .meta {
margin-top: 4px;
}
.ds-card.last-card-message .ds-last-card-desc {
font-size: 13px;
color: var(--newtab-text-secondary-color);
}
.ds-card.last-card-message .ds-last-card-desc,
.ds-card.last-card-message .title {
text-align: center;
}
.ds-card.last-card-message .last-card-message-image {
object-fit: contain;
background: transparent;
box-shadow: none;
}
.ds-card .meta {
display: flex;
flex-direction: column;

Просмотреть файл

@ -2762,14 +2762,12 @@ main.has-snippet {
margin-top: 8px;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .ds-last-card-desc,
.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2816,29 +2814,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2871,29 +2861,21 @@ main.has-snippet {
margin-top: 8px;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
color: var(--newtab-text-secondary-color);
-webkit-line-clamp: 2;
}
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .ds-last-card-desc,
.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
font-size: 13px;
}
@ -2936,12 +2918,6 @@ main.has-snippet {
border-radius: 8px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img.last-card-message-image {
background: transparent;
box-shadow: none;
object-fit: contain;
}
.outer-wrapper .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta,
.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background.ds-card-grid-border .ds-card:not(.placeholder) .meta {
padding: 12px 0 0;
@ -2968,13 +2944,6 @@ main.has-snippet {
.ds-layout .ds-sub-header .section-sub-link:active {
color: var(--newtab-primary-element-active-color);
}
.ds-layout .ds-card-grid-load-more-button {
display: block;
margin: 32px auto 0;
font-size: 13px;
line-height: 16px;
border-radius: 4px;
}
.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
margin: 15px 0 0;
@ -3506,19 +3475,6 @@ main.has-snippet {
.ds-card.video-card .meta {
margin-top: 4px;
}
.ds-card.last-card-message .ds-last-card-desc {
font-size: 13px;
color: var(--newtab-text-secondary-color);
}
.ds-card.last-card-message .ds-last-card-desc,
.ds-card.last-card-message .title {
text-align: center;
}
.ds-card.last-card-message .last-card-message-image {
object-fit: contain;
background: transparent;
box-shadow: none;
}
.ds-card .meta {
display: flex;
flex-direction: column;

Просмотреть файл

@ -7750,31 +7750,6 @@ class _DSCard extends (external_React_default()).PureComponent {
});
}
if (this.props.lastCard) {
return /*#__PURE__*/external_React_default().createElement("div", {
className: "ds-card last-card-message"
}, /*#__PURE__*/external_React_default().createElement("div", {
className: "img-wrapper"
}, /*#__PURE__*/external_React_default().createElement("picture", {
className: "ds-image img loaded"
}, /*#__PURE__*/external_React_default().createElement("img", {
"data-l10n-id": "newtab-pocket-last-card-image",
className: "last-card-message-image",
src: "chrome://activity-stream/content/data/content/assets/caught-up-illustration.svg",
alt: "You\u2019re all caught up"
}))), /*#__PURE__*/external_React_default().createElement("div", {
className: "meta"
}, /*#__PURE__*/external_React_default().createElement("div", {
className: "info-wrap"
}, /*#__PURE__*/external_React_default().createElement("header", {
className: "title clamp",
"data-l10n-id": "newtab-pocket-last-card-title"
}), /*#__PURE__*/external_React_default().createElement("p", {
className: "ds-last-card-desc",
"data-l10n-id": "newtab-pocket-last-card-desc"
}))));
}
const isButtonCTA = this.props.cta_variant === "button";
const {
is_video,
@ -7919,9 +7894,6 @@ const DSCard = (0,external_ReactRedux_namespaceObject.connect)(state => ({
const PlaceholderDSCard = props => /*#__PURE__*/external_React_default().createElement(DSCard, {
placeholder: true
});
const LastCardMessage = props => /*#__PURE__*/external_React_default().createElement(DSCard, {
lastCard: true
});
;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx
/* 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,
@ -8313,39 +8285,9 @@ function RecentSavesContainer({
}, recentSavesCards));
}
class _CardGrid extends (external_React_default()).PureComponent {
constructor(props) {
super(props);
this.state = {
moreLoaded: false
};
this.loadMoreClicked = this.loadMoreClicked.bind(this);
}
loadMoreClicked() {
this.props.dispatch(actionCreators.UserEvent({
event: "CLICK",
source: "DS_LOAD_MORE_BUTTON"
}));
this.setState({
moreLoaded: true
});
}
get showLoadMore() {
const {
loadMore,
data,
loadMoreThreshold
} = this.props;
return loadMore && data.recommendations.length > loadMoreThreshold && !this.state.moreLoaded;
}
renderCards() {
var _widgets$positions, _widgets$data, _essentialReadsCards, _editorsPicksCards;
let {
items
} = this.props;
const {
DiscoveryStream
} = this.props;
@ -8355,13 +8297,12 @@ class _CardGrid extends (external_React_default()).PureComponent {
} = DiscoveryStream;
const showRecentSaves = prefs.showRecentSaves && recentSavesEnabled;
const {
items,
hybridLayout,
hideCardBackground,
fourCardLayout,
hideDescriptions,
lastCardMessageEnabled,
saveToPocketCard,
loadMoreThreshold,
compactGrid,
compactImages,
imageGradient,
@ -8373,14 +8314,6 @@ class _CardGrid extends (external_React_default()).PureComponent {
editorsPicksHeader,
widgets
} = this.props;
let showLastCardMessage = lastCardMessageEnabled;
if (this.showLoadMore) {
items = loadMoreThreshold; // We don't want to show this until after load more has been clicked.
showLastCardMessage = false;
}
const recs = this.props.data.recommendations.slice(0, items);
const cards = [];
let essentialReadsCards = [];
@ -8428,13 +8361,6 @@ class _CardGrid extends (external_React_default()).PureComponent {
is_video: this.props.enable_video_playheads && rec.is_video,
is_collection: this.props.is_collection
}));
} // Replace last card with "you are all caught up card"
if (showLastCardMessage) {
cards.splice(cards.length - 1, 1, /*#__PURE__*/external_React_default().createElement(LastCardMessage, {
key: `dscard-last-${cards.length - 1}`
}));
}
if (widgets !== null && widgets !== void 0 && (_widgets$positions = widgets.positions) !== null && _widgets$positions !== void 0 && _widgets$positions.length && widgets !== null && widgets !== void 0 && (_widgets$data = widgets.data) !== null && _widgets$data !== void 0 && _widgets$data.length) {
@ -8541,11 +8467,7 @@ class _CardGrid extends (external_React_default()).PureComponent {
status: data.status,
dispatch: this.props.dispatch,
feed: this.props.feed
})) : this.renderCards(), this.showLoadMore && /*#__PURE__*/external_React_default().createElement("button", {
className: "ASRouterButton primary ds-card-grid-load-more-button",
onClick: this.loadMoreClicked,
"data-l10n-id": "newtab-pocket-load-more-stories-button"
}));
})) : this.renderCards());
}
}
@ -8554,9 +8476,7 @@ _CardGrid.defaultProps = {
items: 4,
// Number of stories to display
enable_video_playheads: false,
lastCardMessageEnabled: false,
saveToPocketCard: false,
loadMoreThreshold: 12
saveToPocketCard: false
};
const CardGrid = (0,external_ReactRedux_namespaceObject.connect)(state => ({
Prefs: state.Prefs,
@ -13932,8 +13852,6 @@ class _DiscoveryStreamBase extends (external_React_default()).PureComponent {
essentialReadsHeader: component.properties.essentialReadsHeader,
editorsPicksHeader: component.properties.editorsPicksHeader,
readTime: component.properties.readTime,
loadMore: component.loadMore,
lastCardMessageEnabled: component.lastCardMessageEnabled,
saveToPocketCard: component.saveToPocketCard,
cta_variant: component.cta_variant,
pocket_button_enabled: component.pocketButtonEnabled,

Просмотреть файл

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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/. -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 124.3 100.9" xml:space="preserve">
<path class="st0" d="M119 90.7C119 94 82.8 99 55.6 99S13.1 89 13.1 85.6s18.8-5.6 46-5.6 60 7.2 60 10.7z" fill="#FCB643"></path>
<path class="st1" d="m73 14.5-51 11c-.2 0-.3.2-.2.4l13.8 67c0 .2.2.3.3.3l50.3-9.9c.1 0 .3-.2.2-.4l-13-68.1c0-.2-.2-.3-.4-.3z" fill="#fff"></path>
<path d="M74.3 14.6a1.3 1.3 0 0 0-1.5-1l-51 11c-.7 0-1.2.8-1 1.5l13.8 67c.1.7.7 1.1 1.3 1.1h.3l50.2-10c.7 0 1.1-.7 1-1.5l-13-68.1zm11.9 68.7L36 93.2h-.1c-.1 0-.3-.1-.3-.3L21.8 26c0-.2 0-.4.2-.4l51-11c.2 0 .3 0 .4.3l13 68.1c0 .2 0 .4-.2.4z"></path>
<path class="st1" d="m93.3 19.2-52-2.6c-.2 0-.4.1-.4.3l-4 68.3c0 .2 0 .4.3.4l51 3.5c.2 0 .3-.2.4-.3l5-69.3v-.2l-.3-.1z" fill="#fff"></path>
<path d="m93.4 18.2-52.1-2.6c-.8 0-1.3.5-1.4 1.2l-4 68.4c0 .7.5 1.3 1.2 1.4L88 90h.1c.7 0 1.3-.5 1.4-1.2l5-69.3c0-.7-.5-1.4-1.2-1.4zm-5.2 70.9-51-3.5a.3.3 0 0 1-.3-.4l4-68.3c0-.2.2-.3.3-.3l52.1 2.6.3.1v.3l-5 69.2c0 .2-.2.3-.4.3z"></path>
<path class="st1" d="M109 26.6 58 15.1c-.1 0-.3.1-.3.3L42 82c0 .2.1.4.3.4L92 94.6c.2 0 .3 0 .4-.3L109.2 27v-.3h-.3z" fill="#fff"></path>
<path d="M91.8 95.6h.3c.6 0 1.1-.4 1.3-1l16.8-67.3c.1-.8-.3-1.5-1-1.7L58.3 14.2H58c-.6 0-1.1.4-1.3 1L41.1 81.8c-.2.7.2 1.4 1 1.6l49.7 12.2zm.3-1H92L42.3 82.4a.3.3 0 0 1-.3-.4l15.7-66.6c0-.2.2-.3.3-.3l51 11.5.1.2s.1.1 0 .2L92.5 94.4l-.3.2z"></path>
<path class="st2" d="M101.7 31.5 62 22.7c-1-.2-2 .4-2.2 1.4l-3 12c-.2 1 .4 1.9 1.4 2.1L98 47.8c1 .2 2-.4 2.1-1.4l3-12.7c.2-1-.4-2-1.4-2.2zm-9.5 40.9-11.9-2.6a1 1 0 0 0-1.1.7L76 82c-.1.5.2 1 .7 1.1l12.2 3.3c.5.1 1-.2 1.2-.7l2.9-12a1 1 0 0 0-.8-1.2z" fill="#EF4056"></path>
<path d="M97.3 52.3c-1.8-.4-3 .6-4 1.4-.8.7-1.3 1.1-2 1-.9-.3-1.2-.8-1.6-1.9-.5-1.1-1-2.5-2.9-3-1.8-.3-3 .6-3.9 1.4-.8.7-1.4 1.1-2.1 1-.8-.2-1.1-.8-1.5-1.8-.5-1.2-1.1-2.6-3-3s-2.9.6-3.8 1.4c-.9.7-1.4 1-2.2 1-.7-.3-1-.9-1.5-1.9-.5-1.1-1-2.5-2.9-3-1.7-.4-3 .6-3.9 1.4-.8.7-1.3 1.1-2.1 1-.8-.2-1-.8-1.5-1.9-.5-1-1-2.5-2.9-3a1 1 0 0 0-1.2.8c-.1.6.2 1.1.8 1.2.7.2 1 .8 1.5 1.8.4 1.2 1 2.6 2.8 3 1.8.4 3-.6 4-1.4.8-.7 1.3-1 2.1-.9s1 .8 1.5 1.8c.5 1.1 1 2.5 2.9 3 1.8.4 3-.6 3.9-1.4.8-.7 1.4-1.1 2.1-1s1 .8 1.5 1.9c.5 1 1.1 2.5 3 3 1.7.3 2.9-.7 3.8-1.4.9-.8 1.4-1.2 2.2-1 .7.2 1 .8 1.5 1.8.5 1.1 1 2.5 2.9 3h.8c1.3 0 2.3-.7 3-1.4 1-.7 1.4-1.1 2.2-1a1 1 0 1 0 .5-1.9zM95 61.7c-1.7-.4-3 .6-3.9 1.4-.8.7-1.3 1.1-2.1 1s-1-.8-1.5-1.9c-.5-1-1.1-2.5-2.9-3-1.8-.3-3 .7-3.9 1.4-.9.8-1.4 1.2-2.2 1-.7-.2-1-.8-1.5-1.8-.4-1.1-1-2.5-2.8-3-1.8-.4-3 .6-4 1.4-.8.7-1.3 1.1-2 1-.9-.3-1.1-.8-1.6-1.9-.5-1.1-1-2.5-2.9-3-1.8-.4-3 .6-3.9 1.4-.8.7-1.3 1.1-2.1 1s-1-.8-1.5-1.8c-.5-1.2-1.1-2.6-2.9-3a1 1 0 1 0-.4 2c.7.1 1 .7 1.5 1.8.4 1 1 2.5 2.8 3 1.8.3 3-.7 4-1.4.8-.8 1.3-1.2 2-1 .9.2 1.1.8 1.6 1.8.5 1.1 1 2.5 2.9 3 1.8.4 3-.6 3.9-1.4.8-.7 1.3-1.1 2.1-1 .8.3 1 .8 1.5 1.9.5 1.1 1.1 2.5 2.9 3 1.8.4 3-.6 3.9-1.4.8-.7 1.4-1.1 2.1-1s1.1.8 1.6 1.8c.4 1.2 1 2.6 2.8 3h.9c1.3 0 2.3-.7 3-1.4.9-.7 1.4-1.1 2.2-1 .5.2 1-.1 1.2-.7s-.2-1-.8-1.2zM76.3 71c-.7-.2-1-.8-1.5-1.8-.4-1.1-1-2.5-2.8-3-1.8-.4-3 .6-4 1.4-.8.7-1.3 1.1-2 1-.9-.2-1.1-.8-1.6-1.9-.5-1.1-1-2.5-2.9-3-1.8-.3-3 .6-3.9 1.4-.8.8-1.3 1.2-2.1 1-.8-.2-1-.8-1.5-1.8-.5-1.2-1.1-2.6-2.9-3a1 1 0 1 0-.4 2c.7.1 1 .7 1.5 1.8.4 1 1 2.5 2.8 3 1.8.3 3-.6 4-1.4.8-.8 1.3-1.2 2-1s1.1.8 1.6 1.8c.5 1.2 1 2.6 2.9 3 1.8.4 3-.6 3.9-1.4.8-.7 1.3-1.1 2.1-1s1 .9 1.5 1.9c.5 1.1 1.1 2.5 2.9 3h.2a1 1 0 0 0 .3-2zm-2.2 9.4c-.7-.2-1-.8-1.5-1.8-.4-1.1-1-2.5-2.8-3-1.8-.4-3 .6-4 1.4-.8.7-1.3 1.1-2 1-.9-.2-1.1-.8-1.6-1.9-.5-1.1-1-2.5-2.9-3-1.8-.3-3 .6-3.9 1.4-.8.8-1.3 1.2-2.1 1-.8-.2-1-.8-1.5-1.8-.5-1.2-1.1-2.6-2.9-3a1 1 0 0 0-1.2.8c-.1.5.2 1 .7 1.2.8.1 1.1.7 1.5 1.8.5 1 1.1 2.5 3 3 1.7.3 2.9-.6 3.8-1.4.9-.8 1.4-1.2 2.2-1s1 .8 1.5 1.8c.5 1.2 1 2.6 2.9 3 1.8.4 3-.6 3.9-1.4.8-.7 1.3-1.1 2.1-1 .8.3 1 .9 1.5 1.9.5 1.1 1.1 2.5 2.9 3h.2a1 1 0 0 0 .2-2z"></path>
<path class="st3" fill="#1CB0A8" d="M176.8 13.9h5.8v5.8h-5.8zM1 28.4 3 23l5.4 2-2 5.4zM34.3 4.2l6.7-3 3 6.5-6.6 3.3z"></path>
<path class="st2" d="M19.6 8a3 3 0 1 0 0 6.2 3 3 0 0 0 0-6.2zm47.5-4.6a3.3 3.3 0 1 0 0 6.6 3.3 3.3 0 0 0 0-6.6z" fill="#EF4056"></path>
<circle class="st2" cx="120.1" cy="31.3" r="2.2" fill="#EF4056"></circle>
<path class="st0" fill="#FCB643" d="m14.3 51.3 1.6 3.8 1.7 3.8 2.5-3.4 2.4-3.3-4.1-.5zm98.1-41.8-3.5 1.5 3.1 2.3 3.1 2.3.4-3.9.4-3.8zm-7.5 64.2 4.3 3.2 4.4 3.2.6-5.4.6-5.4-5 2.2z"></path>
<path class="st3" d="M46 22.7a2 2 0 0 0-2 1.7l-1 11.7c-.1.4 0 1 .3 1.3.4.4.8.6 1.4.7l6.5.6L54.9 23l-8.9-.3zm-1.3 21.8a2 2 0 0 0-2 1.7l-1 11.7c-.1.5 0 1 .3 1.3.4.4.8.6 1.4.7l2.8.3 3.6-15.5-5-.2zM44.5 67h-1.1a2 2 0 0 0-2 1.7l-1 11.6a1.8 1.8 0 0 0 .7 1.6v-.1L44.5 67z" fill="#1CB0A8"></path>
<path d="M37.8 30.6c-1.8.4-2.4 1.8-3 2.9-.4 1-.7 1.6-1.5 1.8s-1.3-.3-2-1c-1-.9-2.1-1.9-4-1.5a1 1 0 0 0 .5 2c.7-.2 1.2.2 2 1 .9.7 1.8 1.5 3.2 1.5h.7c1.8-.4 2.5-1.8 3-3 .5-1 .8-1.6 1.5-1.7h.8l.1-2h-1.3zm-1 12.3c-.4 1-.7 1.6-1.5 1.8-.8.1-1.3-.3-2.1-1-1-.9-2.1-1.9-4-1.5a1 1 0 0 0 .5 2c.8-.2 1.3.2 2.1 1 .8.6 1.7 1.5 3.1 1.5h.8a4 4 0 0 0 2.6-2.3l.2-3.8c-.9.6-1.3 1.5-1.7 2.3z"></path>
<path class="st0" d="M32.8 54c-.8.2-1.3 1-1.1 1.7l4.6 23 1.5-26-5 1.3zm6.6 33 1.6-.2-2.8-.2c.3.3.7.5 1.2.5z" fill="#FCB643"></path>
</svg>

До

Ширина:  |  Высота:  |  Размер: 5.3 KiB

Просмотреть файл

@ -682,25 +682,6 @@ This reports the user's interaction with those Pocket tiles.
}
```
### Load more button ping
```js
{
"event": "CLICK",
"source": "DS_LOAD_MORE_BUTTON",
// Basic metadata
"action": "activity_stream_event",
"page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
"client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
"session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
"browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
"addon_version": "20180710100040",
"locale": "en-US",
"user_prefs": 7
}
```
## Save to Pocket button pings
Right now the save to Pocket button, while technically outside of newtab, has some similarities with the newtab telemetry.

Просмотреть файл

@ -572,8 +572,6 @@ class DiscoveryStreamFeed {
hybridLayout: pocketConfig.hybridLayout,
hideCardBackground: pocketConfig.hideCardBackground,
fourCardLayout: pocketConfig.fourCardLayout,
loadMore: pocketConfig.loadMore,
lastCardMessageEnabled: pocketConfig.lastCardMessageEnabled,
pocketButtonEnabled,
saveToPocketCard: pocketButtonEnabled && pocketConfig.saveToPocketCard,
newFooterSection: pocketConfig.newFooterSection,
@ -1977,8 +1975,6 @@ class DiscoveryStreamFeed {
`hybridLayout` Changes cards to smaller more compact cards only for specific breakpoints.
`hideCardBackground` Removes Pocket card background and borders.
`fourCardLayout` Enable four Pocket cards per row.
`loadMore` Hide half the Pocket stories behind a load more button.
`lastCardMessageEnabled` Shows a message card at the end of the feed.
`newFooterSection` Changes the layout of the topics section.
`pocketButtonEnabled` Removes Pocket context menu items from cards.
`saveToPocketCard` Cards have a save to Pocket button over their thumbnail on hover.
@ -2001,8 +1997,6 @@ getHardcodedLayout = ({
hybridLayout = false,
hideCardBackground = false,
fourCardLayout = false,
loadMore = false,
lastCardMessageEnabled = false,
newFooterSection = false,
pocketButtonEnabled = false,
saveToPocketCard = false,
@ -2112,8 +2106,6 @@ getHardcodedLayout = ({
}),
data: widgetData,
},
loadMore,
lastCardMessageEnabled,
pocketButtonEnabled,
saveToPocketCard,
cta_variant: "link",

Просмотреть файл

@ -10,7 +10,6 @@ import { Provider } from "react-redux";
import {
DSCard,
PlaceholderDSCard,
LastCardMessage,
} from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
import { TopicsWidget } from "content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget";
import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
@ -128,56 +127,6 @@ describe("<CardGrid>", () => {
assert.ok(!wrapper.find(".ds-card-grid-include-descriptions").exists());
});
it("should show last card and more loaded state", () => {
const dispatch = sinon.stub();
wrapper.setProps({
dispatch,
compact: true,
loadMore: true,
lastCardMessageEnabled: true,
loadMoreThreshold: 2,
data: {
recommendations: [{}, {}, {}],
},
});
const loadMoreButton = wrapper.find(".ds-card-grid-load-more-button");
assert.ok(loadMoreButton.exists());
loadMoreButton.simulate("click", { preventDefault: () => {} });
assert.calledOnce(dispatch);
assert.calledWith(
dispatch,
ac.UserEvent({
event: "CLICK",
source: "DS_LOAD_MORE_BUTTON",
})
);
const lastCard = wrapper.find(LastCardMessage);
assert.ok(lastCard.exists());
});
it("should only show load more with more than threshold number of stories", () => {
wrapper.setProps({
loadMore: true,
loadMoreThreshold: 2,
data: {
recommendations: [{}, {}, {}],
},
});
let loadMoreButton = wrapper.find(".ds-card-grid-load-more-button");
assert.ok(loadMoreButton.exists());
wrapper.setProps({
loadMoreThreshold: 3,
});
loadMoreButton = wrapper.find(".ds-card-grid-load-more-button");
assert.ok(!loadMoreButton.exists());
});
it("should create a widget card", () => {
wrapper.setProps({
widgets: {

Просмотреть файл

@ -11,7 +11,8 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
DevToolsShim: "chrome://devtools-startup/content/DevToolsShim.jsm",
UrlbarProviderQuickActions:
@ -22,7 +23,7 @@ const BASE_URL = Services.urlFormatter.formatURLPref("app.support.baseURL");
let openUrlFun = url => () => openUrl(url);
let openUrl = url => {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gBrowser.loadOneTab(url, {
inBackground: false,
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
@ -37,7 +38,7 @@ let openUrl = url => {
let currentPageIsWebContentFilter = () =>
currentBrowser().currentURI.spec.startsWith("about:");
let currentBrowser = () =>
BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
lazy.BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
const DEFAULT_ACTIONS = {
clear: {
@ -65,7 +66,7 @@ const DEFAULT_ACTIONS = {
label: "quickactions-print",
isActive: currentPageIsWebContentFilter,
onPick: () => {
BrowserWindowTracker.getTopWindow()
lazy.BrowserWindowTracker.getTopWindow()
.document.getElementById("cmd_print")
.doCommand();
},
@ -113,8 +114,8 @@ const DEFAULT_ACTIONS = {
function openInspector() {
// TODO: This is supposed to be called with an element to start inspecting.
DevToolsShim.inspectNode(
BrowserWindowTracker.getTopWindow().gBrowser.selectedTab
lazy.DevToolsShim.inspectNode(
lazy.BrowserWindowTracker.getTopWindow().gBrowser.selectedTab
);
}
@ -150,7 +151,7 @@ function restartBrowser() {
class QuickActionsLoaderDefault {
static load() {
for (const key in DEFAULT_ACTIONS) {
UrlbarProviderQuickActions.addAction(key, DEFAULT_ACTIONS[key]);
lazy.UrlbarProviderQuickActions.addAction(key, DEFAULT_ACTIONS[key]);
}
}
}

Просмотреть файл

@ -13,7 +13,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
FormHistory: "resource://gre/modules/FormHistory.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
@ -87,7 +88,7 @@ class UrlbarController {
this.input = options.input;
this.browserWindow = options.input.window;
this.manager = options.manager || UrlbarProvidersManager;
this.manager = options.manager || lazy.UrlbarProvidersManager;
this._listeners = new Set();
this._userSelectionBehavior = "none";
@ -369,7 +370,7 @@ class UrlbarController {
this.view.selectBy(
event.keyCode == KeyEvent.DOM_VK_PAGE_DOWN ||
event.keyCode == KeyEvent.DOM_VK_PAGE_UP
? UrlbarUtils.PAGE_UP_DOWN_DELTA
? lazy.UrlbarUtils.PAGE_UP_DOWN_DELTA
: 1,
{
reverse:
@ -448,7 +449,7 @@ class UrlbarController {
if (!this.input || context.isPrivate || !context.results.length) {
return;
}
let { url } = UrlbarUtils.getUrlFromResult(result);
let { url } = lazy.UrlbarUtils.getUrlFromResult(result);
if (!url) {
return;
}
@ -460,22 +461,25 @@ class UrlbarController {
(result == context.results[0] && result.heuristic) ||
result.autofill
) {
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
// Speculative connect only if search suggestions are enabled.
if (
UrlbarPrefs.get("suggest.searches") &&
UrlbarPrefs.get("browser.search.suggest.enabled")
lazy.UrlbarPrefs.get("suggest.searches") &&
lazy.UrlbarPrefs.get("browser.search.suggest.enabled")
) {
let engine = Services.search.getEngineByName(
result.payload.engine
);
UrlbarUtils.setupSpeculativeConnection(
lazy.UrlbarUtils.setupSpeculativeConnection(
engine,
this.browserWindow
);
}
} else if (result.autofill) {
UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
lazy.UrlbarUtils.setupSpeculativeConnection(
url,
this.browserWindow
);
}
}
return;
@ -483,7 +487,7 @@ class UrlbarController {
case "mousedown": {
// On mousedown, connect only to http/https urls.
if (url.startsWith("http")) {
UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
lazy.UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
}
return;
}
@ -526,7 +530,7 @@ class UrlbarController {
// will happen when you press the Enter key. Treat it as no selection.
selectedResult = resultIndex > 0 || !result.heuristic ? resultIndex : -1;
}
BrowserSearchTelemetry.recordSearchSuggestionSelectionMethod(
lazy.BrowserSearchTelemetry.recordSearchSuggestionSelectionMethod(
event,
"urlbar",
selectedResult,
@ -553,7 +557,7 @@ class UrlbarController {
let telemetryType =
result.providerName == "UrlbarProviderTopSites"
? "topsite"
: UrlbarUtils.telemetryTypeFromResult(result);
: lazy.UrlbarUtils.telemetryTypeFromResult(result);
Services.telemetry.keyedScalarAdd(
`urlbar.picked.${telemetryType}`,
resultIndex,
@ -608,7 +612,7 @@ class UrlbarController {
}
// First call `provider.blockResult()`.
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
if (!provider) {
Cu.reportError(`Provider not found: ${result.providerName}`);
}
@ -622,7 +626,7 @@ class UrlbarController {
// is from history.
if (
!blockedByProvider &&
result.source != UrlbarUtils.RESULT_SOURCE.HISTORY
result.source != lazy.UrlbarUtils.RESULT_SOURCE.HISTORY
) {
return false;
}
@ -641,15 +645,15 @@ class UrlbarController {
}
// Form history or url restyled as search.
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
if (!queryContext.formHistoryName) {
return false;
}
// Generate the search url to remove it from browsing history.
let { url } = UrlbarUtils.getUrlFromResult(result);
PlacesUtils.history.remove(url).catch(Cu.reportError);
let { url } = lazy.UrlbarUtils.getUrlFromResult(result);
lazy.PlacesUtils.history.remove(url).catch(Cu.reportError);
// Now remove form history.
FormHistory.update(
lazy.FormHistory.update(
{
op: "remove",
fieldname: queryContext.formHistoryName,
@ -665,7 +669,7 @@ class UrlbarController {
}
// Remove browsing history entries from Places.
PlacesUtils.history.remove(result.payload.url).catch(Cu.reportError);
lazy.PlacesUtils.history.remove(result.payload.url).catch(Cu.reportError);
return true;
}
@ -761,7 +765,9 @@ class TelemetryEvent {
if (event.interactionType) {
interactionType = event.interactionType;
} else if (event.type == "input") {
interactionType = UrlbarUtils.isPasteEvent(event) ? "pasted" : "typed";
interactionType = lazy.UrlbarUtils.isPasteEvent(event)
? "pasted"
: "typed";
} else if (event.type == "drop") {
interactionType = "dropped";
} else if (searchString) {
@ -864,7 +870,7 @@ class TelemetryEvent {
// Rather than listening to the pref, just update status when we record an
// event, if the pref changed from the last time.
let recordingEnabled = UrlbarPrefs.get("eventTelemetry.enabled");
let recordingEnabled = lazy.UrlbarPrefs.get("eventTelemetry.enabled");
if (this._eventRecordingEnabled != recordingEnabled) {
this._eventRecordingEnabled = recordingEnabled;
Services.telemetry.setEventRecordingEnabled("urlbar", recordingEnabled);
@ -878,7 +884,7 @@ class TelemetryEvent {
numChars: details.searchString.length.toString(),
numWords: details.searchString
.trim()
.split(UrlbarTokenizer.REGEXP_SPACES)
.split(lazy.UrlbarTokenizer.REGEXP_SPACES)
.filter(t => t)
.length.toString(),
};
@ -909,7 +915,9 @@ class TelemetryEvent {
if (method === "engagement" && queryContext.results?.[0].autofill) {
// Record autofill impressions upon engagement.
const type = UrlbarUtils.telemetryTypeFromResult(queryContext.results[0]);
const type = lazy.UrlbarUtils.telemetryTypeFromResult(
queryContext.results[0]
);
Services.telemetry.scalarAdd(`urlbar.impression.${type}`, 1);
}
@ -946,7 +954,7 @@ class TelemetryEvent {
if (row.result && row.result.providerName != "UrlbarProviderTopSites") {
// Element handlers go here.
if (element.classList.contains("urlbarView-button-help")) {
return row.result.type == UrlbarUtils.RESULT_TYPE.TIP
return row.result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP
? "tiphelp"
: "help";
}
@ -955,6 +963,6 @@ class TelemetryEvent {
}
}
// Now handle the result.
return UrlbarUtils.telemetryTypeFromResult(row.result);
return lazy.UrlbarUtils.telemetryTypeFromResult(row.result);
}
}

Просмотреть файл

@ -13,14 +13,15 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
clearTimeout: "resource://gre/modules/Timer.jsm",
setTimeout: "resource://gre/modules/Timer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "EventBufferer" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "EventBufferer" })
);
// Maximum time events can be deferred for. In automation providers can be quite
@ -100,7 +101,7 @@ class UrlbarEventBufferer {
context: queryContext,
};
if (this._deferringTimeout) {
clearTimeout(this._deferringTimeout);
lazy.clearTimeout(this._deferringTimeout);
this._deferringTimeout = null;
}
}
@ -126,12 +127,12 @@ class UrlbarEventBufferer {
*/
handleEvent(event) {
if (event.type == "blur") {
logger.debug("Clearing queue on blur");
lazy.logger.debug("Clearing queue on blur");
// The input field was blurred, pending events don't matter anymore.
// Clear the timeout and the queue.
this._eventsQueue.length = 0;
if (this._deferringTimeout) {
clearTimeout(this._deferringTimeout);
lazy.clearTimeout(this._deferringTimeout);
this._deferringTimeout = null;
}
}
@ -172,7 +173,7 @@ class UrlbarEventBufferer {
if (event.urlbarDeferred) {
throw new Error(`Event ${event.type}:${event.keyCode} already deferred!`);
}
logger.debug(`Deferring ${event.type}:${event.keyCode} event`);
lazy.logger.debug(`Deferring ${event.type}:${event.keyCode} event`);
// Mark the event as deferred.
event.urlbarDeferred = true;
// Also store the current search string, as an added safety check. If the
@ -183,7 +184,7 @@ class UrlbarEventBufferer {
if (!this._deferringTimeout) {
let elapsed = Cu.now() - this._lastQuery.startDate;
let remaining = DEFERRING_TIMEOUT_MS - elapsed;
this._deferringTimeout = setTimeout(() => {
this._deferringTimeout = lazy.setTimeout(() => {
this.replayDeferredEvents(false);
this._deferringTimeout = null;
}, Math.max(0, remaining));

Просмотреть файл

@ -14,7 +14,9 @@ const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
@ -40,7 +42,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -70,7 +72,7 @@ class UrlbarInput {
this.textbox = options.textbox;
this.window = this.textbox.ownerGlobal;
this.isPrivate = PrivateBrowsingUtils.isWindowPrivate(this.window);
this.isPrivate = lazy.PrivateBrowsingUtils.isWindowPrivate(this.window);
this.document = this.window.document;
// Create the panel to contain results.
@ -94,16 +96,16 @@ class UrlbarInput {
);
this.panel = this.textbox.querySelector(".urlbarView");
this.searchButton = UrlbarPrefs.get("experimental.searchButton");
this.searchButton = lazy.UrlbarPrefs.get("experimental.searchButton");
if (this.searchButton) {
this.textbox.classList.add("searchButton");
}
this.controller = new UrlbarController({
this.controller = new lazy.UrlbarController({
input: this,
eventTelemetryCategory: options.eventTelemetryCategory,
});
this.view = new UrlbarView(this);
this.view = new lazy.UrlbarView(this);
this.valueIsTyped = false;
this.formHistoryName = DEFAULT_FORM_HISTORY_NAME;
this.lastQueryContextPromise = Promise.resolve();
@ -199,7 +201,7 @@ class UrlbarInput {
this._toolbar = this.textbox.closest("toolbar");
XPCOMUtils.defineLazyGetter(this, "valueFormatter", () => {
return new UrlbarValueFormatter(this);
return new lazy.UrlbarValueFormatter(this);
});
XPCOMUtils.defineLazyGetter(this, "addSearchEngineHelper", () => {
@ -217,7 +219,7 @@ class UrlbarInput {
// muscle memory; for example quickly pressing DOWN+ENTER should end up
// on a predictable result, regardless of the search status. The event
// bufferer will invoke the handling code at the right time.
this.eventBufferer = new UrlbarEventBufferer(this);
this.eventBufferer = new lazy.UrlbarEventBufferer(this);
this._inputFieldEvents = [
"compositionstart",
@ -268,7 +270,7 @@ class UrlbarInput {
this._initPasteAndGo();
// Tracks IME composition.
this._compositionState = UrlbarUtils.COMPOSITION.NONE;
this._compositionState = lazy.UrlbarUtils.COMPOSITION.NONE;
this._compositionClosedPopup = false;
this.editor.newlineHandling =
@ -346,7 +348,7 @@ class UrlbarInput {
// only if there's no opener (bug 370555).
if (
this.window.isInitialPage(uri) &&
BrowserUIUtils.checkEmptyPageOrigin(
lazy.BrowserUIUtils.checkEmptyPageOrigin(
this.window.gBrowser.selectedBrowser,
uri
)
@ -369,7 +371,9 @@ class UrlbarInput {
uri.schemeIs("moz-extension"));
} else if (
this.window.isInitialPage(value) &&
BrowserUIUtils.checkEmptyPageOrigin(this.window.gBrowser.selectedBrowser)
lazy.BrowserUIUtils.checkEmptyPageOrigin(
this.window.gBrowser.selectedBrowser
)
) {
value = "";
valid = true;
@ -443,7 +447,7 @@ class UrlbarInput {
makeURIReadable(uri) {
// Avoid copying 'about:reader?url=', and always provide the original URI:
// Reader mode ensures we call createExposableURI itself.
let readerStrippedURI = ReaderMode.getOriginalUrlObjectForDisplay(
let readerStrippedURI = lazy.ReaderMode.getOriginalUrlObjectForDisplay(
uri.displaySpec
);
if (readerStrippedURI) {
@ -537,7 +541,7 @@ class UrlbarInput {
// when the view is open.
let selectedPrivateResult =
result &&
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.inPrivateWindow;
let selectedPrivateEngineResult =
selectedPrivateResult && result.payload.isPrivateEngine;
@ -552,7 +556,7 @@ class UrlbarInput {
// Use the hidden heuristic if it exists and there's no selection.
if (
UrlbarPrefs.get("experimental.hideHeuristic") &&
lazy.UrlbarPrefs.get("experimental.hideHeuristic") &&
!element &&
!isComposing &&
!oneOffParams?.engine &&
@ -584,13 +588,13 @@ class UrlbarInput {
let searchString =
(result && (result.payload.suggestion || result.payload.query)) ||
this._lastSearchString;
[url, openParams.postData] = UrlbarUtils.getSearchQueryUrl(
[url, openParams.postData] = lazy.UrlbarUtils.getSearchQueryUrl(
oneOffParams.engine,
searchString
);
this._recordSearch(oneOffParams.engine, event, { url });
UrlbarUtils.addToFormHistory(
lazy.UrlbarUtils.addToFormHistory(
this,
searchString,
oneOffParams.engine.name
@ -664,7 +668,7 @@ class UrlbarInput {
// the appropriate engine submission url.
let browser = this.window.gBrowser.selectedBrowser;
let lastLocationChange = browser.lastLocationChange;
UrlbarUtils.getHeuristicResultFor(url)
lazy.UrlbarUtils.getHeuristicResultFor(url)
.then(newResult => {
// Because this happens asynchronously, we must verify that the browser
// location did not change in the meanwhile.
@ -729,7 +733,7 @@ class UrlbarInput {
*/
handoff(searchString, searchEngine, newtabSessionId) {
this._handoffSession = newtabSessionId;
if (UrlbarPrefs.get("shouldHandOffToSearchMode") && searchEngine) {
if (lazy.UrlbarPrefs.get("shouldHandOffToSearchMode") && searchEngine) {
this.search(searchString, {
searchEngine,
searchModeEntry: "handoff",
@ -802,7 +806,7 @@ class UrlbarInput {
if (
urlOverride &&
result.type != UrlbarUtils.RESULT_TYPE.TIP &&
result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP &&
where == "current"
) {
// Open non-tip help links in a new tab unless the user held a modifier.
@ -830,11 +834,11 @@ class UrlbarInput {
let { url, postData } = urlOverride
? { url: urlOverride, postData: null }
: UrlbarUtils.getUrlFromResult(result);
: lazy.UrlbarUtils.getUrlFromResult(result);
openParams.postData = postData;
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.URL: {
case lazy.UrlbarUtils.RESULT_TYPE.URL: {
// Bug 1578856: both the provider and the docshell run heuristics to
// decide how to handle a non-url string, either fixing it to a url, or
// searching for it.
@ -855,20 +859,20 @@ class UrlbarInput {
// the urifixup prefs.
if (
result.heuristic &&
UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
lazy.UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
lazy.UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
) {
url = originalUntrimmedValue;
}
break;
}
case UrlbarUtils.RESULT_TYPE.KEYWORD: {
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD: {
// If this result comes from a bookmark keyword, let it inherit the
// current document's principal, otherwise bookmarklets would break.
openParams.allowInheritPrincipal = true;
break;
}
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH: {
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH: {
if (this.hasAttribute("actionoverride")) {
where = "current";
break;
@ -877,7 +881,7 @@ class UrlbarInput {
this.handleRevert();
let prevTab = this.window.gBrowser.selectedTab;
let loadOpts = {
adoptIntoActiveWindow: UrlbarPrefs.get(
adoptIntoActiveWindow: lazy.UrlbarPrefs.get(
"switchTabs.adoptIntoActiveWindow"
),
};
@ -903,14 +907,14 @@ class UrlbarInput {
if (switched && !this.isPrivate && !result.heuristic) {
// We don't await for this, because a rejection should not interrupt
// the load. Just reportError it.
UrlbarUtils.addToInputHistory(url, searchString).catch(
lazy.UrlbarUtils.addToInputHistory(url, searchString).catch(
Cu.reportError
);
}
return;
}
case UrlbarUtils.RESULT_TYPE.SEARCH: {
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH: {
if (result.payload.providesSearchMode) {
let searchModeParams = this._searchModeForResult(result);
if (searchModeParams) {
@ -924,12 +928,12 @@ class UrlbarInput {
!this.searchMode &&
result.heuristic &&
// If we asked the DNS earlier, avoid the post-facto check.
!UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
!lazy.UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
// TODO (bug 1642623): for now there is no smart heuristic to skip the
// DNS lookup, so any value above 0 will run it.
UrlbarPrefs.get("dnsResolveSingleWordsAfterSearch") > 0 &&
lazy.UrlbarPrefs.get("dnsResolveSingleWordsAfterSearch") > 0 &&
this.window.gKeywordURIFixup &&
UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
lazy.UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
) {
// When fixing a single word to a search, the docShell would also
// query the DNS and if resolved ask the user whether they would
@ -954,7 +958,8 @@ class UrlbarInput {
const actionDetails = {
isSuggestion: !!result.payload.suggestion,
isFormHistory: result.source == UrlbarUtils.RESULT_SOURCE.HISTORY,
isFormHistory:
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY,
alias: result.payload.keyword,
url,
};
@ -962,7 +967,7 @@ class UrlbarInput {
this._recordSearch(engine, event, actionDetails);
if (!result.payload.inPrivateWindow) {
UrlbarUtils.addToFormHistory(
lazy.UrlbarUtils.addToFormHistory(
this,
result.payload.suggestion || result.payload.query,
engine.name
@ -970,7 +975,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.TIP: {
case lazy.UrlbarUtils.RESULT_TYPE.TIP: {
let scalarName;
if (element.classList.contains("urlbarView-button-help")) {
url = result.payload.helpUrl;
@ -991,7 +996,7 @@ class UrlbarInput {
selType: "tip",
provider: result.providerName,
});
let provider = UrlbarProvidersManager.getProvider(
let provider = lazy.UrlbarProvidersManager.getProvider(
result.providerName
);
if (!provider) {
@ -1003,7 +1008,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.DYNAMIC: {
case lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC: {
url = result.payload.url;
// Do not revert the Urlbar if we're going to navigate. We want the URL
// populated so we can navigate to it.
@ -1011,7 +1016,9 @@ class UrlbarInput {
this.handleRevert();
}
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(
result.providerName
);
if (!provider) {
Cu.reportError(`Provider not found: ${result.providerName}`);
return;
@ -1030,7 +1037,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.OMNIBOX: {
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX: {
this.controller.engagementEvent.record(event, {
searchString: this._lastSearchString,
selIndex,
@ -1047,7 +1054,7 @@ class UrlbarInput {
// We pass the keyword and content, that actually is the retrieved value
// prefixed by the keyword. ExtensionSearchHandler uses this keyword
// redundancy as a sanity check.
ExtensionSearchHandler.handleInputEntered(
lazy.ExtensionSearchHandler.handleInputEntered(
result.payload.keyword,
result.payload.content,
where
@ -1072,7 +1079,7 @@ class UrlbarInput {
if (input !== undefined) {
// We don't await for this, because a rejection should not interrupt
// the load. Just reportError it.
UrlbarUtils.addToInputHistory(url, input).catch(Cu.reportError);
lazy.UrlbarUtils.addToInputHistory(url, input).catch(Cu.reportError);
}
}
@ -1084,7 +1091,7 @@ class UrlbarInput {
});
if (result.payload.sendAttributionRequest) {
PartnerLinkAttribution.makeRequest({
lazy.PartnerLinkAttribution.makeRequest({
targetURL: result.payload.url,
source: "urlbar",
campaignID: Services.prefs.getStringPref(
@ -1099,7 +1106,7 @@ class UrlbarInput {
`urlbar_${position}`,
1
);
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
position,
source: "urlbar",
@ -1107,7 +1114,7 @@ class UrlbarInput {
reporting_url: result.payload.sponsoredClickUrl,
advertiser: result.payload.title.toLocaleLowerCase(),
},
CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_SELECTION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_SELECTION
);
}
}
@ -1177,10 +1184,10 @@ class UrlbarInput {
this._setValue(value, allowTrim);
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
this.setAttribute("actiontype", "switchtab");
break;
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
this.setAttribute("actiontype", "extension");
break;
}
@ -1226,12 +1233,12 @@ class UrlbarInput {
// it would end up executing a search instead of visiting it.
let allowTrim = true;
if (
(urlOverride || result.type == UrlbarUtils.RESULT_TYPE.URL) &&
UrlbarPrefs.get("trimURLs")
(urlOverride || result.type == lazy.UrlbarUtils.RESULT_TYPE.URL) &&
lazy.UrlbarPrefs.get("trimURLs")
) {
let url = urlOverride || result.payload.url;
if (url.startsWith(BrowserUIUtils.trimURLProtocol)) {
let fixupInfo = this._getURIFixupInfo(BrowserUIUtils.trimURL(url));
if (url.startsWith(lazy.BrowserUIUtils.trimURLProtocol)) {
let fixupInfo = this._getURIFixupInfo(lazy.BrowserUIUtils.trimURL(url));
if (fixupInfo?.keywordAsSent) {
allowTrim = false;
}
@ -1398,7 +1405,7 @@ class UrlbarInput {
let options = {
allowAutofill,
isPrivate: this.isPrivate,
maxResults: UrlbarPrefs.get("maxRichResults"),
maxResults: lazy.UrlbarPrefs.get("maxRichResults"),
searchString,
userContextId: this.window.gBrowser.selectedBrowser.getAttribute(
"usercontextid"
@ -1407,8 +1414,9 @@ class UrlbarInput {
formHistoryName: this.formHistoryName,
prohibitRemoteResults:
event &&
UrlbarUtils.isPasteEvent(event) &&
UrlbarPrefs.get("maxCharsForSearchSuggestions") < event.data?.length,
lazy.UrlbarUtils.isPasteEvent(event) &&
lazy.UrlbarPrefs.get("maxCharsForSearchSuggestions") <
event.data?.length,
};
if (this.searchMode) {
@ -1423,7 +1431,7 @@ class UrlbarInput {
// tests are not listening for completion when starting a query through
// other methods than startQuery (input events for example).
this.lastQueryContextPromise = this.controller.startQuery(
new UrlbarQueryContext(options)
new lazy.UrlbarQueryContext(options)
);
}
@ -1448,10 +1456,10 @@ class UrlbarInput {
this.focus();
}
let trimmedValue = value.trim();
let end = trimmedValue.search(UrlbarTokenizer.REGEXP_SPACES);
let end = trimmedValue.search(lazy.UrlbarTokenizer.REGEXP_SPACES);
let firstToken = end == -1 ? trimmedValue : trimmedValue.substring(0, end);
// Enter search mode if the string starts with a restriction token.
let searchMode = UrlbarUtils.searchModeForToken(firstToken);
let searchMode = lazy.UrlbarUtils.searchModeForToken(firstToken);
let firstTokenIsRestriction = !!searchMode;
if (!searchMode && searchEngine) {
searchMode = { engineName: searchEngine.name };
@ -1466,16 +1474,18 @@ class UrlbarInput {
// in search mode.
value = value.replace(firstToken, "");
}
if (UrlbarTokenizer.REGEXP_SPACES.test(value[0])) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(value[0])) {
// If there was a trailing space after the restriction token/alias,
// remove it.
value = value.slice(1);
}
this._revertOnBlurValue = value;
} else if (Object.values(UrlbarTokenizer.RESTRICT).includes(firstToken)) {
} else if (
Object.values(lazy.UrlbarTokenizer.RESTRICT).includes(firstToken)
) {
this.searchMode = null;
// If the entire value is a restricted token, append a space.
if (Object.values(UrlbarTokenizer.RESTRICT).includes(value)) {
if (Object.values(lazy.UrlbarTokenizer.RESTRICT).includes(value)) {
value += " ";
}
this._revertOnBlurValue = value;
@ -1584,7 +1594,7 @@ class UrlbarInput {
let currentSearchMode = this.getSearchMode(browser);
let areSearchModesSame =
(!currentSearchMode && !searchMode) ||
ObjectUtils.deepEqual(currentSearchMode, searchMode);
lazy.ObjectUtils.deepEqual(currentSearchMode, searchMode);
// Exit search mode if the passed-in engine is invalid or hidden.
let engine;
@ -1613,10 +1623,10 @@ class UrlbarInput {
// History results for general-purpose search engines are often not
// useful, so we hide them in search mode. See bug 1658646 for
// discussion.
searchMode.source = UrlbarUtils.RESULT_SOURCE.SEARCH;
searchMode.source = lazy.UrlbarUtils.RESULT_SOURCE.SEARCH;
}
} else if (source) {
let sourceName = UrlbarUtils.getResultSourceName(source);
let sourceName = lazy.UrlbarUtils.getResultSourceName(source);
if (sourceName) {
searchMode = { source };
} else {
@ -1626,7 +1636,7 @@ class UrlbarInput {
if (searchMode) {
searchMode.isPreview = isPreview;
if (UrlbarUtils.SEARCH_MODE_ENTRY.has(entry)) {
if (lazy.UrlbarUtils.SEARCH_MODE_ENTRY.has(entry)) {
searchMode.entry = entry;
} else {
// If we see this value showing up in telemetry, we should review
@ -1658,7 +1668,7 @@ class UrlbarInput {
this.valueIsTyped = true;
if (!searchMode.isPreview && !areSearchModesSame) {
try {
BrowserSearchTelemetry.recordSearchMode(searchMode);
lazy.BrowserSearchTelemetry.recordSearchMode(searchMode);
} catch (ex) {
Cu.reportError(ex);
}
@ -1684,8 +1694,8 @@ class UrlbarInput {
// We restrict to search results when entering search mode from this
// shortcut to honor historical behaviour.
this.searchMode = {
source: UrlbarUtils.RESULT_SOURCE.SEARCH,
engineName: UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
source: lazy.UrlbarUtils.RESULT_SOURCE.SEARCH,
engineName: lazy.UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
entry: "shortcut",
};
// The searchMode setter clears the input if pageproxystate is valid, so
@ -1781,7 +1791,7 @@ class UrlbarInput {
}
if (Cu.isInAutomation) {
if (UrlbarPrefs.get("disableExtendForTests")) {
if (lazy.UrlbarPrefs.get("disableExtendForTests")) {
this.setAttribute("breakout-extend-disabled", "true");
return;
}
@ -1908,10 +1918,10 @@ class UrlbarInput {
observe(subject, topic, data) {
switch (topic) {
case SearchUtils.TOPIC_ENGINE_MODIFIED: {
case lazy.SearchUtils.TOPIC_ENGINE_MODIFIED: {
switch (data) {
case SearchUtils.MODIFIED_TYPE.CHANGED:
case SearchUtils.MODIFIED_TYPE.REMOVED: {
case lazy.SearchUtils.MODIFIED_TYPE.CHANGED:
case lazy.SearchUtils.MODIFIED_TYPE.REMOVED: {
let searchMode = this.searchMode;
let engine = subject.QueryInterface(Ci.nsISearchEngine);
if (searchMode?.engineName == engine.name) {
@ -1929,7 +1939,11 @@ class UrlbarInput {
// Private methods below.
_addObservers() {
Services.obs.addObserver(this, SearchUtils.TOPIC_ENGINE_MODIFIED, true);
Services.obs.addObserver(
this,
lazy.SearchUtils.TOPIC_ENGINE_MODIFIED,
true
);
}
_getURIFixupInfo(searchString) {
@ -2009,7 +2023,7 @@ class UrlbarInput {
_setValue(val, allowTrim) {
// Don't expose internal about:reader URLs to the user.
let originalUrl = ReaderMode.getOriginalUrlObjectForDisplay(val);
let originalUrl = lazy.ReaderMode.getOriginalUrlObjectForDisplay(val);
if (originalUrl) {
val = originalUrl.displaySpec;
}
@ -2035,9 +2049,9 @@ class UrlbarInput {
_getValueFromResult(result, urlOverride = null) {
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
return result.payload.input;
case UrlbarUtils.RESULT_TYPE.SEARCH: {
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH: {
let value = "";
if (result.payload.keyword) {
value += result.payload.keyword + " ";
@ -2045,9 +2059,9 @@ class UrlbarInput {
value += result.payload.suggestion || result.payload.query;
return value;
}
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
return result.payload.content;
case UrlbarUtils.RESULT_TYPE.DYNAMIC:
case lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC:
return result.payload.input || "";
}
@ -2090,7 +2104,7 @@ class UrlbarInput {
let allowAutofill =
this.selectionEnd == value.length &&
!this.searchMode?.engineName &&
this.searchMode?.source != UrlbarUtils.RESULT_SOURCE.SEARCH;
this.searchMode?.source != lazy.UrlbarUtils.RESULT_SOURCE.SEARCH;
if (!allowAutofill) {
this._autofillPlaceholder = null;
return false;
@ -2113,7 +2127,7 @@ class UrlbarInput {
.toLocaleLowerCase()
.startsWith(value.toLocaleLowerCase());
} else {
canAutofillPlaceholder = UrlbarUtils.canAutofillURL(
canAutofillPlaceholder = lazy.UrlbarUtils.canAutofillURL(
this._autofillPlaceholder.value,
value
);
@ -2263,7 +2277,7 @@ class UrlbarInput {
this.value == selectedVal &&
!uri.schemeIs("javascript") &&
!uri.schemeIs("data") &&
!UrlbarPrefs.get("decodeURLsOnCopy")
!lazy.UrlbarPrefs.get("decodeURLsOnCopy")
) {
return displaySpec;
}
@ -2272,18 +2286,18 @@ class UrlbarInput {
// url. First check for a trimmed value.
if (
!selectedVal.startsWith(BrowserUIUtils.trimURLProtocol) &&
!selectedVal.startsWith(lazy.BrowserUIUtils.trimURLProtocol) &&
// Note _trimValue may also trim a trailing slash, thus we can't just do
// a straight string compare to tell if the protocol was trimmed.
!displaySpec.startsWith(this._trimValue(displaySpec))
) {
selectedVal = BrowserUIUtils.trimURLProtocol + selectedVal;
selectedVal = lazy.BrowserUIUtils.trimURLProtocol + selectedVal;
}
// If selection starts from the beginning and part or all of the URL
// is selected, we check for decoded characters and encode them.
// Unless decodeURLsOnCopy is set. Do not encode data: URIs.
if (!UrlbarPrefs.get("decodeURLsOnCopy") && !uri.schemeIs("data")) {
if (!lazy.UrlbarPrefs.get("decodeURLsOnCopy") && !uri.schemeIs("data")) {
try {
new URL(selectedVal);
// Use encodeURI instead of URL.href because we don't want
@ -2363,7 +2377,7 @@ class UrlbarInput {
source = "urlbar-searchmode";
}
BrowserSearchTelemetry.recordSearch(
lazy.BrowserSearchTelemetry.recordSearch(
this.window.gBrowser.selectedBrowser,
engine,
source,
@ -2384,7 +2398,9 @@ class UrlbarInput {
* The trimmed string
*/
_trimValue(val) {
return UrlbarPrefs.get("trimURLs") ? BrowserUIUtils.trimURL(val) : val;
return lazy.UrlbarPrefs.get("trimURLs")
? lazy.BrowserUIUtils.trimURL(val)
: val;
}
/**
@ -2405,7 +2421,7 @@ class UrlbarInput {
!KeyboardEvent.isInstance(event) ||
event._disableCanonization ||
!event.ctrlKey ||
!UrlbarPrefs.get("ctrlCanonizesURLs") ||
!lazy.UrlbarPrefs.get("ctrlCanonizesURLs") ||
!/^\s*[^.:\/\s]+(?:\/.*|\s*)$/i.test(value)
) {
return null;
@ -2526,7 +2542,7 @@ class UrlbarInput {
}
try {
UrlbarUtils.addToUrlbarHistory(url, this.window);
lazy.UrlbarUtils.addToUrlbarHistory(url, this.window);
} catch (ex) {
// Things may go wrong when adding url to session history,
// but don't let that interfere with the loading of the url.
@ -2632,7 +2648,7 @@ class UrlbarInput {
} else if (
isKeyboardEvent &&
event.ctrlKey &&
UrlbarPrefs.get("ctrlCanonizesURLs")
lazy.UrlbarPrefs.get("ctrlCanonizesURLs")
) {
// If we're allowing canonization, and this is a key event with ctrl
// pressed, open in current tab to allow ctrl-enter to canonize URL.
@ -2640,7 +2656,7 @@ class UrlbarInput {
} else {
where = this.window.whereToOpenLink(event, false, false);
}
if (UrlbarPrefs.get("openintab")) {
if (lazy.UrlbarPrefs.get("openintab")) {
if (where == "current") {
where = "tab";
} else if (where == "tab") {
@ -2745,7 +2761,9 @@ class UrlbarInput {
return null;
}
let searchMode = UrlbarUtils.searchModeForToken(result.payload.keyword);
let searchMode = lazy.UrlbarUtils.searchModeForToken(
result.payload.keyword
);
// If result.originalEngine is set, then the user is Alt+Tabbing
// through the one-offs, so the keyword doesn't match the engine.
if (
@ -2829,7 +2847,7 @@ class UrlbarInput {
{ name: engineName }
);
} else if (source) {
let sourceName = UrlbarUtils.getResultSourceName(source);
let sourceName = lazy.UrlbarUtils.getResultSourceName(source);
let l10nID = `urlbar-search-mode-${sourceName}`;
this.document.l10n.setAttributes(this._searchModeIndicatorTitle, l10nID);
this.document.l10n.setAttributes(this._searchModeLabel, l10nID);
@ -2858,7 +2876,7 @@ class UrlbarInput {
_maybeSelectAll() {
if (
!this._preventClickSelectsAll &&
this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING &&
this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING &&
this.document.activeElement == this.inputField &&
this.inputField.selectionStart == this.inputField.selectionEnd
) {
@ -2917,13 +2935,13 @@ class UrlbarInput {
// The extension input sessions depends more on blur than on the fact we
// actually cancel a running query, so we do it here.
if (ExtensionSearchHandler.hasActiveInputSession()) {
ExtensionSearchHandler.handleInputCancelled();
if (lazy.ExtensionSearchHandler.hasActiveInputSession()) {
lazy.ExtensionSearchHandler.handleInputCancelled();
}
// Respect the autohide preference for easier inspecting/debugging via
// the browser toolbox.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
@ -3032,7 +3050,7 @@ class UrlbarInput {
}
_on_draggableregionleftmousedown(event) {
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
}
@ -3073,7 +3091,7 @@ class UrlbarInput {
if (event.target.id == SEARCH_BUTTON_ID) {
this._preventClickSelectsAll = true;
this.search(UrlbarTokenizer.RESTRICT.SEARCH);
this.search(lazy.UrlbarTokenizer.RESTRICT.SEARCH);
} else {
// Do not suppress the focus border if we are already focused. If we
// did, we'd hide the focus border briefly then show it again if the
@ -3098,7 +3116,7 @@ class UrlbarInput {
// might not automatically remove focus from the input.
// Respect the autohide preference for easier inspecting/debugging via
// the browser toolbox.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
break;
@ -3121,8 +3139,8 @@ class UrlbarInput {
let compositionClosedPopup = this._compositionClosedPopup;
// Clear composition values if we're no more composing.
if (this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING) {
this._compositionState = UrlbarUtils.COMPOSITION.NONE;
if (this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
this._compositionState = lazy.UrlbarUtils.COMPOSITION.NONE;
this._compositionClosedPopup = false;
}
@ -3142,7 +3160,7 @@ class UrlbarInput {
if (!this.view.isOpen) {
this.view.clear();
} else if (!value && !UrlbarPrefs.get("suggest.topsites")) {
} else if (!value && !lazy.UrlbarPrefs.get("suggest.topsites")) {
this.view.clear();
if (!this.searchMode || !this.view.oneOffSearchButtons.hasView) {
this.view.close();
@ -3161,9 +3179,9 @@ class UrlbarInput {
// We should do nothing during composition or if composition was canceled
// and we didn't close the popup on composition start.
if (
!UrlbarPrefs.get("keepPanelOpenDuringImeComposition") &&
(compositionState == UrlbarUtils.COMPOSITION.COMPOSING ||
(compositionState == UrlbarUtils.COMPOSITION.CANCELED &&
!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition") &&
(compositionState == lazy.UrlbarUtils.COMPOSITION.COMPOSING ||
(compositionState == lazy.UrlbarUtils.COMPOSITION.CANCELED &&
!compositionClosedPopup))
) {
return;
@ -3172,10 +3190,10 @@ class UrlbarInput {
// Autofill only when text is inserted (i.e., event.data is not empty) and
// it's not due to pasting.
const allowAutofill =
(!UrlbarPrefs.get("keepPanelOpenDuringImeComposition") ||
compositionState !== UrlbarUtils.COMPOSITION.COMPOSING) &&
(!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition") ||
compositionState !== lazy.UrlbarUtils.COMPOSITION.COMPOSING) &&
!!event.data &&
!UrlbarUtils.isPasteEvent(event) &&
!lazy.UrlbarUtils.isPasteEvent(event) &&
this._maybeAutofillPlaceholder(value);
this.startQuery({
@ -3214,7 +3232,7 @@ class UrlbarInput {
return;
}
ClipboardHelper.copyStringToClipboard(
lazy.ClipboardHelper.copyStringToClipboard(
val,
Services.clipboard.kSelectionClipboard
);
@ -3281,7 +3299,7 @@ class UrlbarInput {
? originalPasteData.replace(/[\r\n]/g, "")
: originalPasteData.replace(/\s/g, " ");
pasteData = UrlbarUtils.stripUnsafeProtocolOnPaste(pasteData);
pasteData = lazy.UrlbarUtils.stripUnsafeProtocolOnPaste(pasteData);
if (originalPasteData != pasteData) {
// Unfortunately we're not allowed to set the bits being pasted
@ -3326,7 +3344,7 @@ class UrlbarInput {
if (this._keyDownEnterDeferred) {
this._keyDownEnterDeferred.reject();
}
this._keyDownEnterDeferred = PromiseUtils.defer();
this._keyDownEnterDeferred = lazy.PromiseUtils.defer();
event._disableCanonization = this._isKeyDownWithCtrl;
} else if (event.keyCode !== KeyEvent.DOM_VK_CONTROL && event.ctrlKey) {
this._isKeyDownWithCtrl = true;
@ -3385,12 +3403,12 @@ class UrlbarInput {
}
_on_compositionstart(event) {
if (this._compositionState == UrlbarUtils.COMPOSITION.COMPOSING) {
if (this._compositionState == lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
throw new Error("Trying to start a nested composition?");
}
this._compositionState = UrlbarUtils.COMPOSITION.COMPOSING;
this._compositionState = lazy.UrlbarUtils.COMPOSITION.COMPOSING;
if (UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
if (lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
return;
}
@ -3416,11 +3434,11 @@ class UrlbarInput {
}
_on_compositionend(event) {
if (this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING) {
if (this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
throw new Error("Trying to stop a non existing composition?");
}
if (!UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
if (!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
// Clear the selection and the cached result, since they refer to the
// state before this composition. A new input even will be generated
// after this.
@ -3431,8 +3449,8 @@ class UrlbarInput {
// We can't yet retrieve the committed value from the editor, since it isn't
// completely committed yet. We'll handle it at the next input event.
this._compositionState = event.data
? UrlbarUtils.COMPOSITION.COMMIT
: UrlbarUtils.COMPOSITION.CANCELED;
? lazy.UrlbarUtils.COMPOSITION.COMMIT
: lazy.UrlbarUtils.COMPOSITION.CANCELED;
}
_on_dragstart(event) {
@ -3535,7 +3553,7 @@ function getDroppableData(event) {
if (links.length && links[0].url) {
event.preventDefault();
let href = links[0].url;
if (UrlbarUtils.stripUnsafeProtocolOnPaste(href) != href) {
if (lazy.UrlbarUtils.stripUnsafeProtocolOnPaste(href) != href) {
// We may have stripped an unsafe protocol like javascript: and if so
// there's no point in handling a partial drop.
event.stopImmediatePropagation();
@ -3700,7 +3718,7 @@ class CopyCutController {
urlbar.inputField.dispatchEvent(event);
}
ClipboardHelper.copyString(val);
lazy.ClipboardHelper.copyString(val);
}
/**
@ -3772,7 +3790,7 @@ class AddSearchEngineHelper {
if (engines1?.length != engines2?.length) {
return false;
}
return ObjectUtils.deepEqual(
return lazy.ObjectUtils.deepEqual(
engines1.map(e => e.title),
engines2.map(e => e.title)
);
@ -3861,7 +3879,7 @@ class AddSearchEngineHelper {
}
async _onCommand(event) {
let added = await SearchUIUtils.addOpenSearchEngine(
let added = await lazy.SearchUIUtils.addOpenSearchEngine(
event.target.getAttribute("uri"),
event.target.getAttribute("image"),
this.browsingContext

Просмотреть файл

@ -14,18 +14,23 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarMuxer, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProviderQuickSuggest:
"resource:///modules/UrlbarProviderQuickSuggest.jsm",
UrlbarProviderTabToSearch:
"resource:///modules/UrlbarProviderTabToSearch.jsm",
UrlbarMuxer: "resource:///modules/UrlbarUtils.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
UrlbarUtils.getLogger({ prefix: "MuxerUnifiedComplete" })
);
@ -116,7 +121,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
);
}
if (state.maxHeuristicResultSpan) {
if (UrlbarPrefs.get("experimental.hideHeuristic")) {
if (lazy.UrlbarPrefs.get("experimental.hideHeuristic")) {
// The heuristic is hidden. The muxer will include it but the view will
// hide it. Increase the available span to compensate so that the total
// visible span accurately reflects `context.maxResults`.
@ -134,9 +139,9 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// Determine the result groups to use for this sort. In search mode with
// an engine, show search suggestions first.
let rootGroup = context.searchMode?.engineName
? UrlbarPrefs.makeResultGroups({ showSearchSuggestionsFirst: true })
: UrlbarPrefs.get("resultGroups");
logger.debug(`Groups: ${rootGroup}`);
? lazy.UrlbarPrefs.makeResultGroups({ showSearchSuggestionsFirst: true })
: lazy.UrlbarPrefs.get("resultGroups");
lazy.logger.debug(`Groups: ${rootGroup}`);
// Fill the root group.
let [sortedResults] = this._fillGroup(
@ -536,7 +541,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
while (summedFillableLimit != fillableLimit) {
if (!fractionalDataArray.length) {
// This shouldn't happen, but don't let it break us.
logger.error("fractionalDataArray is empty!");
lazy.logger.error("fractionalDataArray is empty!");
break;
}
let data = flexDataArray[fractionalDataArray.shift().index];
@ -583,7 +588,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// are ignored and we use the flex defined on the form history group.
if (
groupConst == UrlbarUtils.RESULT_GROUP.FORM_HISTORY &&
!UrlbarPrefs.get("maxHistoricalSearchSuggestions")
!lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions")
) {
// Create a new `limits` object so we don't modify the caller's.
limits = { ...limits };
@ -641,7 +646,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
_canAddResult(result, state) {
// Never discard quick suggest results. We may want to change this logic at
// some point, but for all current use cases, they should always be shown.
if (result.providerName == UrlbarProviderQuickSuggest.name) {
if (result.providerName == lazy.UrlbarProviderQuickSuggest.name) {
return true;
}
@ -699,7 +704,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
!result.autofill &&
state.context.heuristicResult.payload?.url == result.payload.url &&
state.context.heuristicResult.type == result.type &&
!UrlbarPrefs.get("experimental.hideHeuristic")
!lazy.UrlbarPrefs.get("experimental.hideHeuristic")
) {
return false;
}
@ -714,7 +719,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
return false;
}
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
// Discard the result if a tab-to-search result was added already.
if (!state.canAddTabToSearch) {
return false;
@ -843,7 +848,10 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
submission.terms
);
if (
UrlbarSearchUtils.serpsAreEquivalent(result.payload.url, newSerpURL)
lazy.UrlbarSearchUtils.serpsAreEquivalent(
result.payload.url,
newSerpURL
)
) {
return false;
}
@ -858,7 +866,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.context.searchMode.engineName
);
if (engine) {
let searchModeRootDomain = UrlbarSearchUtils.getRootDomainFromEngine(
let searchModeRootDomain = lazy.UrlbarSearchUtils.getRootDomainFromEngine(
engine
);
let resultUrl = new URL(result.payload.url);
@ -877,7 +885,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.quickSuggestResult &&
!result.heuristic &&
result.type == UrlbarUtils.RESULT_TYPE.URL &&
UrlbarProviderQuickSuggest.isURLEquivalentToResultURL(
lazy.UrlbarProviderQuickSuggest.isURLEquivalentToResultURL(
result.payload.url,
state.quickSuggestResult
)
@ -966,7 +974,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
this._canAddResult(result, state)
) {
let span = UrlbarUtils.getSpanForResult(result);
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
state.maxTabToSearchResultSpan = Math.max(
state.maxTabToSearchResultSpan,
span
@ -984,7 +992,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
(result.type == UrlbarUtils.RESULT_TYPE.URL ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
result.payload.url &&
(!result.heuristic || !UrlbarPrefs.get("experimental.hideHeuristic"))
(!result.heuristic || !lazy.UrlbarPrefs.get("experimental.hideHeuristic"))
) {
let [strippedUrl, prefix] = UrlbarUtils.stripPrefixAndTrim(
result.payload.url,
@ -1006,7 +1014,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// the quick suggest: The URL is added to history and later both a
// history result and the quick suggest may match a query.
(topPrefixRank == prefixRank &&
result.providerName == UrlbarProviderQuickSuggest.name)
result.providerName == lazy.UrlbarProviderQuickSuggest.name)
) {
// strippedUrl => { prefix, title, rank, providerName }
state.strippedUrlToTopPrefixAndTitle.set(strippedUrl, {
@ -1041,7 +1049,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.canShowTailSuggestions = false;
}
if (result.providerName == UrlbarProviderQuickSuggest.name) {
if (result.providerName == lazy.UrlbarProviderQuickSuggest.name) {
state.quickSuggestResult = result;
}
@ -1066,7 +1074,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.query &&
!UrlbarPrefs.get("experimental.hideHeuristic")
!lazy.UrlbarPrefs.get("experimental.hideHeuristic")
) {
let query = result.payload.query.trim().toLocaleLowerCase();
if (query) {
@ -1100,17 +1108,17 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// Avoid multiple tab-to-search results.
// TODO (Bug 1670185): figure out better strategies to manage this case.
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
state.canAddTabToSearch = false;
// We want to record in urlbar.tips once per engagement per engine. Since
// whether these results are shown is dependent on the Muxer, we must
// add to `enginesShown` here.
if (result.payload.dynamicType) {
UrlbarProviderTabToSearch.enginesShown.onboarding.add(
lazy.UrlbarProviderTabToSearch.enginesShown.onboarding.add(
result.payload.engine
);
} else {
UrlbarProviderTabToSearch.enginesShown.regular.add(
lazy.UrlbarProviderTabToSearch.enginesShown.regular.add(
result.payload.engine
);
}
@ -1183,16 +1191,16 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// If same suggestedIndex, change the displaying order along to following
// provider priority.
// TabToSearch > QuickSuggest > Other providers
if (a.providerName === UrlbarProviderTabToSearch.name) {
if (a.providerName === lazy.UrlbarProviderTabToSearch.name) {
return 1;
}
if (b.providerName === UrlbarProviderTabToSearch.name) {
if (b.providerName === lazy.UrlbarProviderTabToSearch.name) {
return -1;
}
if (a.providerName === UrlbarProviderQuickSuggest.name) {
if (a.providerName === lazy.UrlbarProviderQuickSuggest.name) {
return 1;
}
if (b.providerName === UrlbarProviderQuickSuggest.name) {
if (b.providerName === lazy.UrlbarProviderQuickSuggest.name) {
return -1;
}

Просмотреть файл

@ -17,7 +17,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
Region: "resource://gre/modules/Region.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
@ -436,22 +438,22 @@ function makeResultGroups({ showSearchSuggestionsFirst }) {
{
maxResultCount: 1,
children: [
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_TEST },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_EXTENSION },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_SEARCH_TIP },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_OMNIBOX },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_ENGINE_ALIAS },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_BOOKMARK_KEYWORD },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_AUTOFILL },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_PRELOADED },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_TOKEN_ALIAS_ENGINE },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_FALLBACK },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_TEST },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_EXTENSION },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_SEARCH_TIP },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_OMNIBOX },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_ENGINE_ALIAS },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_BOOKMARK_KEYWORD },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_AUTOFILL },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_PRELOADED },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_TOKEN_ALIAS_ENGINE },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_FALLBACK },
],
},
// extensions using the omnibox API
{
group: UrlbarUtils.RESULT_GROUP.OMNIBOX,
availableSpan: UrlbarUtils.MAX_OMNIBOX_RESULT_COUNT - 1,
group: lazy.UrlbarUtils.RESULT_GROUP.OMNIBOX,
availableSpan: lazy.UrlbarUtils.MAX_OMNIBOX_RESULT_COUNT - 1,
},
],
};
@ -470,52 +472,52 @@ function makeResultGroups({ showSearchSuggestionsFirst }) {
// If `maxHistoricalSearchSuggestions` == 0, the muxer forces
// `maxResultCount` to be zero and flex is ignored, per query.
flex: 2,
group: UrlbarUtils.RESULT_GROUP.FORM_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.FORM_HISTORY,
},
{
flex: 4,
group: UrlbarUtils.RESULT_GROUP.REMOTE_SUGGESTION,
group: lazy.UrlbarUtils.RESULT_GROUP.REMOTE_SUGGESTION,
},
],
},
{
group: UrlbarUtils.RESULT_GROUP.TAIL_SUGGESTION,
group: lazy.UrlbarUtils.RESULT_GROUP.TAIL_SUGGESTION,
},
],
},
// general
{
group: UrlbarUtils.RESULT_GROUP.GENERAL_PARENT,
group: lazy.UrlbarUtils.RESULT_GROUP.GENERAL_PARENT,
children: [
{
availableSpan: 3,
group: UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
},
{
flexChildren: true,
children: [
{
flex: 1,
group: UrlbarUtils.RESULT_GROUP.REMOTE_TAB,
group: lazy.UrlbarUtils.RESULT_GROUP.REMOTE_TAB,
},
{
flex: 2,
group: UrlbarUtils.RESULT_GROUP.GENERAL,
group: lazy.UrlbarUtils.RESULT_GROUP.GENERAL,
},
{
// We show relatively many about-page results because they're
// only added for queries starting with "about:".
flex: 2,
group: UrlbarUtils.RESULT_GROUP.ABOUT_PAGES,
group: lazy.UrlbarUtils.RESULT_GROUP.ABOUT_PAGES,
},
{
flex: 1,
group: UrlbarUtils.RESULT_GROUP.PRELOADED,
group: lazy.UrlbarUtils.RESULT_GROUP.PRELOADED,
},
],
},
{
group: UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
},
],
},
@ -570,7 +572,7 @@ class Preferences {
// prevent re-entry due to pref observers.
this._updatingFirefoxSuggestScenario = false;
NimbusFeatures.urlbar.onUpdate(() => this._onNimbusUpdate());
lazy.NimbusFeatures.urlbar.onUpdate(() => this._onNimbusUpdate());
}
/**
@ -693,8 +695,8 @@ class Preferences {
// depend on them. Also note that pref migrations may depend on the
// scenario, and since each migration is performed only once, at startup,
// prefs can end up wrong if their migrations use the wrong scenario.
await Region.init();
await NimbusFeatures.urlbar.ready();
await lazy.Region.init();
await lazy.NimbusFeatures.urlbar.ready();
this._clearNimbusCache();
this._updateFirefoxSuggestScenarioHelper(isStartup, testOverrides);
@ -848,7 +850,7 @@ class Preferences {
let scenario = this._nimbus.quickSuggestScenario;
if (!scenario) {
if (
Region.home == "US" &&
lazy.Region.home == "US" &&
Services.locale.appLocaleAsBCP47.substring(0, 2) == "en"
) {
// offline rollout for en locales in the US region
@ -1296,7 +1298,7 @@ class Preferences {
get _nimbus() {
if (!this.__nimbus) {
this.__nimbus = NimbusFeatures.urlbar.getAllVariables({
this.__nimbus = lazy.NimbusFeatures.urlbar.getAllVariables({
defaultValues: NIMBUS_DEFAULTS,
});
}

Просмотреть файл

@ -13,11 +13,16 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderAboutPages"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutPagesUtils: "resource://gre/modules/AboutPagesUtils.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -62,12 +67,12 @@ class ProviderAboutPages extends UrlbarProvider {
*/
startQuery(queryContext, addCallback) {
let searchString = queryContext.trimmedSearchString.toLowerCase();
for (const aboutUrl of AboutPagesUtils.visibleAboutUrls) {
for (const aboutUrl of lazy.AboutPagesUtils.visibleAboutUrls) {
if (aboutUrl.startsWith(searchString)) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
url: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(aboutUrl),

Просмотреть файл

@ -14,12 +14,17 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderAliasEngines"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -52,7 +57,7 @@ class ProviderAliasEngines extends UrlbarProvider {
isActive(queryContext) {
return (
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.SEARCH) &&
queryContext.restrictSource == lazy.UrlbarTokenizer.RESTRICT.SEARCH) &&
!queryContext.searchMode &&
queryContext.tokens.length
);
@ -67,7 +72,7 @@ class ProviderAliasEngines extends UrlbarProvider {
async startQuery(queryContext, addCallback) {
let instance = this.queryInstance;
let alias = queryContext.tokens[0]?.value;
let engine = await UrlbarSearchUtils.engineForAlias(
let engine = await lazy.UrlbarSearchUtils.engineForAlias(
alias,
queryContext.searchString
);
@ -75,10 +80,10 @@ class ProviderAliasEngines extends UrlbarProvider {
return;
}
let query = UrlbarUtils.substringAfter(queryContext.searchString, alias);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: engine.name,
keyword: alias,
query: query.trimStart(),

Просмотреть файл

@ -13,15 +13,20 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderAutofill"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutPagesUtils: "resource://gre/modules/AboutPagesUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
// AutoComplete query type constants.
@ -299,7 +304,7 @@ class ProviderAutofill extends UrlbarProvider {
this._autofillData = null;
// First of all, check for the autoFill pref.
if (!UrlbarPrefs.get("autoFill")) {
if (!lazy.UrlbarPrefs.get("autoFill")) {
return false;
}
@ -329,8 +334,8 @@ class ProviderAutofill extends UrlbarProvider {
if (
queryContext.tokens.some(
t =>
t.type == UrlbarTokenizer.TYPE.RESTRICT_TAG ||
t.type == UrlbarTokenizer.TYPE.RESTRICT_TITLE
t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG ||
t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE
)
) {
return false;
@ -345,7 +350,7 @@ class ProviderAutofill extends UrlbarProvider {
// This may confuse completeDefaultIndex cause the AUTOCOMPLETE_MATCH
// tokenizer ends up trimming the search string and returning a value
// that doesn't match it, or is even shorter.
if (UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
return false;
}
@ -422,10 +427,10 @@ class ProviderAutofill extends UrlbarProvider {
* @resolves {string} The top matching host, or null if not found.
*/
async getTopHostOverThreshold(queryContext, hosts) {
let db = await PlacesUtils.promiseLargeCacheDBConnection();
let db = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
let conditions = [];
// Pay attention to the order of params, since they are not named.
let params = [UrlbarPrefs.get("autoFill.stddevMultiplier"), ...hosts];
let params = [lazy.UrlbarPrefs.get("autoFill.stddevMultiplier"), ...hosts];
let sources = queryContext.sources;
if (
sources.includes(UrlbarUtils.RESULT_SOURCE.HISTORY) &&
@ -494,7 +499,7 @@ class ProviderAutofill extends UrlbarProvider {
let opts = {
query_type: QUERYTYPE.AUTOFILL_ORIGIN,
searchString: searchStr.toLowerCase(),
stddevMultiplier: UrlbarPrefs.get("autoFill.stddevMultiplier"),
stddevMultiplier: lazy.UrlbarPrefs.get("autoFill.stddevMultiplier"),
};
if (this._strippedPrefix) {
opts.prefix = this._strippedPrefix;
@ -646,7 +651,7 @@ class ProviderAutofill extends UrlbarProvider {
const params = {
queryType: QUERYTYPE.AUTOFILL_ADAPTIVE,
searchString: queryContext.searchString.toLowerCase(),
useCountThreshold: UrlbarPrefs.get(
useCountThreshold: lazy.UrlbarPrefs.get(
"autoFillAdaptiveHistoryUseCountThreshold"
),
};
@ -803,10 +808,10 @@ class ProviderAutofill extends UrlbarProvider {
title = [autofilled, UrlbarUtils.HIGHLIGHT.TYPED];
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title,
url: [finalCompleteValue, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(finalCompleteValue),
@ -852,17 +857,17 @@ class ProviderAutofill extends UrlbarProvider {
return null;
}
for (const aboutUrl of AboutPagesUtils.visibleAboutUrls) {
for (const aboutUrl of lazy.AboutPagesUtils.visibleAboutUrls) {
if (aboutUrl.startsWith(`about:${this._searchString.toLowerCase()}`)) {
let [trimmedUrl] = UrlbarUtils.stripPrefixAndTrim(aboutUrl, {
stripHttp: true,
trimEmptyQuery: true,
trimSlash: !this._searchString.includes("/"),
});
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [trimmedUrl, UrlbarUtils.HIGHLIGHT.TYPED],
url: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(aboutUrl),
@ -884,15 +889,15 @@ class ProviderAutofill extends UrlbarProvider {
}
async _matchKnownUrl(queryContext) {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
if (!conn) {
return null;
}
// We try to autofill with adaptive history first.
if (
UrlbarPrefs.get("autoFillAdaptiveHistoryEnabled") &&
UrlbarPrefs.get("autoFillAdaptiveHistoryMinCharsThreshold") <=
lazy.UrlbarPrefs.get("autoFillAdaptiveHistoryEnabled") &&
lazy.UrlbarPrefs.get("autoFillAdaptiveHistoryMinCharsThreshold") <=
queryContext.searchString.length
) {
const [query, params] = this._getAdaptiveHistoryQuery(queryContext);
@ -918,7 +923,7 @@ class ProviderAutofill extends UrlbarProvider {
// at the end, we still treat it as an URL.
let query, params;
if (
UrlbarTokenizer.looksLikeOrigin(this._searchString, {
lazy.UrlbarTokenizer.looksLikeOrigin(this._searchString, {
ignoreKnownDomains: true,
})
) {
@ -939,7 +944,7 @@ class ProviderAutofill extends UrlbarProvider {
async _matchSearchEngineDomain(queryContext) {
if (
!UrlbarPrefs.get("autoFill.searchEngines") ||
!lazy.UrlbarPrefs.get("autoFill.searchEngines") ||
!this._searchString.length
) {
return null;
@ -956,14 +961,18 @@ class ProviderAutofill extends UrlbarProvider {
}
// If the search string looks more like a url than a domain, bail out.
if (
!UrlbarTokenizer.looksLikeOrigin(searchStr, { ignoreKnownDomains: true })
!lazy.UrlbarTokenizer.looksLikeOrigin(searchStr, {
ignoreKnownDomains: true,
})
) {
return null;
}
// Since we are autofilling, we can only pick one matching engine. Use the
// first.
let engine = (await UrlbarSearchUtils.enginesForDomainPrefix(searchStr))[0];
let engine = (
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(searchStr)
)[0];
if (!engine) {
return null;
}
@ -984,10 +993,10 @@ class ProviderAutofill extends UrlbarProvider {
let value =
this._strippedPrefix + domain.substr(domain.indexOf(searchStr)) + "/";
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
})

Просмотреть файл

@ -13,12 +13,17 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderBookmarkKeywords"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -51,7 +56,8 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
isActive(queryContext) {
return (
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.BOOKMARK) &&
queryContext.restrictSource ==
lazy.UrlbarTokenizer.RESTRICT.BOOKMARK) &&
!queryContext.searchMode &&
queryContext.tokens.length
);
@ -70,7 +76,7 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
queryContext.searchString,
keyword
).trim();
let { entry, url, postData } = await KeywordUtils.getBindableKeyword(
let { entry, url, postData } = await lazy.KeywordUtils.getBindableKeyword(
keyword,
searchString
);
@ -96,10 +102,10 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
title = UrlbarUtils.unEscapeURIForUI(url);
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.KEYWORD,
UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [keyword, UrlbarUtils.HIGHLIGHT.TYPED],

Просмотреть файл

@ -10,16 +10,20 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
UrlbarView: "resource:///modules/UrlbarView.jsm",
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -68,8 +72,8 @@ const MIN_EXPRESSION_LENGTH = 3;
class ProviderCalculator extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -98,7 +102,7 @@ class ProviderCalculator extends UrlbarProvider {
return (
queryContext.trimmedSearchString &&
!queryContext.searchMode &&
UrlbarPrefs.get(ENABLED_PREF)
lazy.UrlbarPrefs.get(ENABLED_PREF)
);
}
@ -119,7 +123,7 @@ class ProviderCalculator extends UrlbarProvider {
return;
}
let value = Calculator.evaluatePostfix(postfix);
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -155,7 +159,7 @@ class ProviderCalculator extends UrlbarProvider {
}
async pickResult({ payload }) {
ClipboardHelper.copyString(payload.value);
lazy.ClipboardHelper.copyString(payload.value);
}
}

Просмотреть файл

@ -15,14 +15,18 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -52,10 +56,10 @@ class UrlbarProviderExtension extends UrlbarProvider {
* The provider.
*/
static getOrCreate(name) {
let provider = UrlbarProvidersManager.getProvider(name);
let provider = lazy.UrlbarProvidersManager.getProvider(name);
if (!provider) {
provider = new UrlbarProviderExtension(name);
UrlbarProvidersManager.registerProvider(provider);
lazy.UrlbarProvidersManager.registerProvider(provider);
}
return provider;
}
@ -155,7 +159,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
} else {
this._eventListeners.delete(eventName);
if (!this._eventListeners.size) {
UrlbarProvidersManager.unregisterProvider(this);
lazy.UrlbarProvidersManager.unregisterProvider(this);
}
}
}
@ -291,7 +295,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
// so that we're not stuck waiting forever.
let timer = new SkippableTimer({
name: "UrlbarProviderExtension notification timer",
time: UrlbarPrefs.get("extension.timeout"),
time: lazy.UrlbarPrefs.get("extension.timeout"),
reportErrorOnTimeout: true,
logger: this.logger,
});
@ -328,7 +332,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
engine = Services.search.getEngineByName(extResult.payload.engine);
} else if (extResult.payload.keyword) {
// Look up the engine by its alias.
engine = await UrlbarSearchUtils.engineForAlias(
engine = await lazy.UrlbarSearchUtils.engineForAlias(
extResult.payload.keyword
);
} else if (extResult.payload.url) {
@ -338,7 +342,9 @@ class UrlbarProviderExtension extends UrlbarProvider {
host = new URL(extResult.payload.url).hostname;
} catch (err) {}
if (host) {
engine = (await UrlbarSearchUtils.enginesForDomainPrefix(host))[0];
engine = (
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(host)
)[0];
}
}
if (!engine) {
@ -353,10 +359,10 @@ class UrlbarProviderExtension extends UrlbarProvider {
extResult.payload.type = extResult.payload.type || "extension";
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarProviderExtension.RESULT_TYPES[extResult.type],
UrlbarProviderExtension.SOURCE_TYPES[extResult.source],
...UrlbarResult.payloadAndSimpleHighlights(
...lazy.UrlbarResult.payloadAndSimpleHighlights(
context.tokens,
extResult.payload || {}
)

Просмотреть файл

@ -16,13 +16,18 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -90,12 +95,12 @@ class ProviderHeuristicFallback extends UrlbarProvider {
new URL(str);
} catch (ex) {
if (
UrlbarPrefs.get("keyword.enabled") &&
(UrlbarTokenizer.looksLikeOrigin(str, {
lazy.UrlbarPrefs.get("keyword.enabled") &&
(lazy.UrlbarTokenizer.looksLikeOrigin(str, {
noIp: true,
noPort: true,
}) ||
UrlbarTokenizer.REGEXP_COMMON_EMAIL.test(str))
lazy.UrlbarTokenizer.REGEXP_COMMON_EMAIL.test(str))
) {
let searchResult = this._engineSearchResult(queryContext);
if (instance != this.queryInstance) {
@ -132,7 +137,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
// restriction token was typed.
if (
queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH ||
UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(
lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(
queryContext.restrictToken?.value
) ||
queryContext.searchMode
@ -155,12 +160,12 @@ class ProviderHeuristicFallback extends UrlbarProvider {
if (queryContext.fixupError) {
if (
queryContext.fixupError == Cr.NS_ERROR_MALFORMED_URI &&
!UrlbarPrefs.get("keyword.enabled")
!lazy.UrlbarPrefs.get("keyword.enabled")
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [searchUrl, UrlbarUtils.HIGHLIGHT.NONE],
url: [searchUrl, UrlbarUtils.HIGHLIGHT.NONE],
})
@ -215,10 +220,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
iconUri = `page-icon:${prePath}/`;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [displayURL, UrlbarUtils.HIGHLIGHT.NONE],
url: [escapedURL, UrlbarUtils.HIGHLIGHT.NONE],
icon: iconUri,
@ -234,7 +239,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
}
let firstToken = queryContext.tokens[0].value;
if (!UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(firstToken)) {
if (!lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(firstToken)) {
return null;
}
@ -260,7 +265,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
queryContext.searchString,
firstToken
);
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
@ -268,10 +273,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
if (queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH) {
result = this._engineSearchResult(queryContext, firstToken);
} else {
result = new UrlbarResult(
result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
query: [query.trimStart(), UrlbarUtils.HIGHLIGHT.NONE],
keyword: [firstToken, UrlbarUtils.HIGHLIGHT.NONE],
})
@ -288,7 +293,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
queryContext.searchMode.engineName
);
} else {
engine = UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
engine = lazy.UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
}
if (!engine) {
@ -302,7 +307,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
let query = queryContext.searchString;
if (
queryContext.tokens[0] &&
queryContext.tokens[0].value === UrlbarTokenizer.RESTRICT.SEARCH
queryContext.tokens[0].value === lazy.UrlbarTokenizer.RESTRICT.SEARCH
) {
query = UrlbarUtils.substringAfter(
query,
@ -310,10 +315,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
).trim();
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
query: [query, UrlbarUtils.HIGHLIGHT.NONE],

Просмотреть файл

@ -16,13 +16,18 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderInputHistory"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProviderOpenTabs: "resource:///modules/UrlbarProviderOpenTabs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
// Sqlite result row index constants.
@ -99,9 +104,9 @@ class ProviderInputHistory extends UrlbarProvider {
*/
isActive(queryContext) {
return (
(UrlbarPrefs.get("suggest.history") ||
UrlbarPrefs.get("suggest.bookmark") ||
UrlbarPrefs.get("suggest.openpage")) &&
(lazy.UrlbarPrefs.get("suggest.history") ||
lazy.UrlbarPrefs.get("suggest.bookmark") ||
lazy.UrlbarPrefs.get("suggest.openpage")) &&
!queryContext.searchMode
);
}
@ -117,7 +122,7 @@ class ProviderInputHistory extends UrlbarProvider {
async startQuery(queryContext, addCallback) {
let instance = this.queryInstance;
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
if (instance != this.queryInstance) {
return;
}
@ -139,15 +144,15 @@ class ProviderInputHistory extends UrlbarProvider {
const tags = row.getResultByIndex(QUERYINDEX.TAGS) || "";
let resultTitle = historyTitle;
if (openPageCount > 0 && UrlbarPrefs.get("suggest.openpage")) {
if (openPageCount > 0 && lazy.UrlbarPrefs.get("suggest.openpage")) {
if (url == queryContext.currentPage) {
// Don't suggest switching to the current page.
continue;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [resultTitle, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -158,10 +163,10 @@ class ProviderInputHistory extends UrlbarProvider {
}
let resultSource;
if (bookmarked && UrlbarPrefs.get("suggest.bookmark")) {
if (bookmarked && lazy.UrlbarPrefs.get("suggest.bookmark")) {
resultSource = UrlbarUtils.RESULT_SOURCE.BOOKMARKS;
resultTitle = bookmarkTitle || historyTitle;
} else if (UrlbarPrefs.get("suggest.history")) {
} else if (lazy.UrlbarPrefs.get("suggest.history")) {
resultSource = UrlbarUtils.RESULT_SOURCE.HISTORY;
} else {
continue;
@ -178,10 +183,10 @@ class ProviderInputHistory extends UrlbarProvider {
})
.sort();
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
resultSource,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [resultTitle, UrlbarUtils.HIGHLIGHT.TYPED],
tags: [resultTags, UrlbarUtils.HIGHLIGHT.TYPED],
@ -204,11 +209,11 @@ class ProviderInputHistory extends UrlbarProvider {
return [
SQL_ADAPTIVE_QUERY,
{
parent: PlacesUtils.tagsFolderId,
parent: lazy.PlacesUtils.tagsFolderId,
search_string: queryContext.searchString.toLowerCase(),
matchBehavior: Ci.mozIPlacesAutoComplete.MATCH_ANYWHERE,
searchBehavior: UrlbarPrefs.get("defaultBehavior"),
userContextId: UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
searchBehavior: lazy.UrlbarPrefs.get("defaultBehavior"),
userContextId: lazy.UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
queryContext.userContextId,
queryContext.isPrivate
),

Просмотреть файл

@ -5,27 +5,30 @@
"use strict";
var EXPORTED_SYMBOLS = ["UrlbarProviderInterventions", "QueryScorer"];
var gGlobalScope = this;
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppUpdater: "resource:///modules/AppUpdater.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
NLP: "resource://gre/modules/NLP.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
ResetProfile: "resource://gre/modules/ResetProfile.jsm",
Sanitizer: "resource:///modules/Sanitizer.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "appUpdater", () => new AppUpdater());
XPCOMUtils.defineLazyGetter(lazy, "appUpdater", () => new lazy.AppUpdater());
// The possible tips to show. These names (except NONE) are used in the names
// of keys in the `urlbar.tips` keyed scalar telemetry (see telemetry.rst).
@ -358,7 +361,7 @@ class QueryScorer {
// Compare each word in the node to the current query word.
let queryWord = queryWords[queryWordsIndex];
for (let [childWord, child] of node.childrenByWord) {
let distance = NLP.levenshtein(queryWord, childWord);
let distance = lazy.NLP.levenshtein(queryWord, childWord);
if (distance <= this._distanceThreshold) {
// The word represented by this child node matches the current query
// word. Recurse into the child node.
@ -490,7 +493,9 @@ class ProviderInterventions extends UrlbarProvider {
if (
!queryContext.searchString ||
queryContext.searchString.length > UrlbarUtils.MAX_TEXT_LENGTH ||
UrlbarTokenizer.REGEXP_LIKE_PROTOCOL.test(queryContext.searchString) ||
lazy.UrlbarTokenizer.REGEXP_LIKE_PROTOCOL.test(
queryContext.searchString
) ||
!EN_LOCALE_MATCH.test(Services.locale.appLocaleAsBCP47) ||
!Services.policies.isAllowed("urlbarinterventions")
) {
@ -519,8 +524,8 @@ class ProviderInterventions extends UrlbarProvider {
if (topDocIDs.has("update")) {
this._setCurrentTipFromAppUpdaterStatus();
} else if (topDocIDs.has("clear")) {
let window = BrowserWindowTracker.getTopWindow();
if (!PrivateBrowsingUtils.isWindowPrivate(window)) {
let window = lazy.BrowserWindowTracker.getTopWindow();
if (!lazy.PrivateBrowsingUtils.isWindowPrivate(window)) {
this.currentTip = TIPS.CLEAR;
}
} else if (topDocIDs.has("refresh")) {
@ -551,27 +556,27 @@ class ProviderInterventions extends UrlbarProvider {
}
// There are several update tips. Figure out which one to show.
switch (appUpdater.status) {
case AppUpdater.STATUS.READY_FOR_RESTART:
switch (lazy.appUpdater.status) {
case lazy.AppUpdater.STATUS.READY_FOR_RESTART:
// Prompt the user to restart.
this.currentTip = TIPS.UPDATE_RESTART;
break;
case AppUpdater.STATUS.DOWNLOAD_AND_INSTALL:
case lazy.AppUpdater.STATUS.DOWNLOAD_AND_INSTALL:
// There's an update available, but the user's pref says we should ask
// them to download and apply it.
this.currentTip = TIPS.UPDATE_ASK;
break;
case AppUpdater.STATUS.NO_UPDATES_FOUND:
case lazy.AppUpdater.STATUS.NO_UPDATES_FOUND:
// We show a special refresh tip when the browser is up to date.
this.currentTip = TIPS.UPDATE_REFRESH;
break;
case AppUpdater.STATUS.CHECKING:
case lazy.AppUpdater.STATUS.CHECKING:
// This will be the case the first time we check. See startQuery for
// how this special tip is handled.
this.currentTip = TIPS.UPDATE_CHECKING;
break;
case AppUpdater.STATUS.NO_UPDATER:
case AppUpdater.STATUS.UPDATE_DISABLED_BY_POLICY:
case lazy.AppUpdater.STATUS.NO_UPDATER:
case lazy.AppUpdater.STATUS.UPDATE_DISABLED_BY_POLICY:
// If the updater is disabled at build time or at runtime, either by
// policy or because we're in a package, do not select any update tips.
this.currentTip = TIPS.NONE;
@ -616,11 +621,11 @@ class ProviderInterventions extends UrlbarProvider {
// The updater is still checking, so wait for it to finish.
await new Promise(resolve => {
this._appUpdaterListener = () => {
appUpdater.removeListener(this._appUpdaterListener);
lazy.appUpdater.removeListener(this._appUpdaterListener);
delete this._appUpdaterListener;
resolve();
};
appUpdater.addListener(this._appUpdaterListener);
lazy.appUpdater.addListener(this._appUpdaterListener);
});
if (instance != this.queryInstance) {
// The query was canceled before the check finished.
@ -638,7 +643,7 @@ class ProviderInterventions extends UrlbarProvider {
// At this point, this.currentTip != TIPS.UPDATE_CHECKING because we
// returned early above if it was.
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TIP,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -668,7 +673,7 @@ class ProviderInterventions extends UrlbarProvider {
// If we're waiting for appUpdater to finish its update check,
// this._appUpdaterListener will be defined. We can stop listening now.
if (this._appUpdaterListener) {
appUpdater.removeListener(this._appUpdaterListener);
lazy.appUpdater.removeListener(this._appUpdaterListener);
delete this._appUpdaterListener;
}
}
@ -698,7 +703,7 @@ class ProviderInterventions extends UrlbarProvider {
restartBrowser();
break;
case TIPS.UPDATE_WEB:
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gBrowser.selectedTab = window.gBrowser.addWebTab(
"https://www.mozilla.org/firefox/new/"
);
@ -729,7 +734,7 @@ class ProviderInterventions extends UrlbarProvider {
Date.now() - this._lastUpdateCheckTime >= UPDATE_CHECK_PERIOD_MS
) {
this._lastUpdateCheckTime = Date.now();
appUpdater.check();
lazy.appUpdater.check();
}
}
@ -739,8 +744,8 @@ class ProviderInterventions extends UrlbarProvider {
*/
resetAppUpdater() {
// Reset only if the object has already been initialized.
if (!Object.getOwnPropertyDescriptor(gGlobalScope, "appUpdater").get) {
appUpdater = new AppUpdater();
if (!Object.getOwnPropertyDescriptor(lazy, "appUpdater").get) {
lazy.appUpdater = new lazy.AppUpdater();
}
}
}
@ -752,7 +757,7 @@ var UrlbarProviderInterventions = new ProviderInterventions();
*/
function installBrowserUpdateAndRestart() {
if (appUpdater.status != AppUpdater.STATUS.DOWNLOAD_AND_INSTALL) {
if (lazy.appUpdater.status != lazy.AppUpdater.STATUS.DOWNLOAD_AND_INSTALL) {
return Promise.resolve();
}
return new Promise(resolve => {
@ -760,30 +765,30 @@ function installBrowserUpdateAndRestart() {
// Once we call startDownload, there are two possible end
// states: DOWNLOAD_FAILED and READY_FOR_RESTART.
if (
appUpdater.status != AppUpdater.STATUS.READY_FOR_RESTART &&
appUpdater.status != AppUpdater.STATUS.DOWNLOAD_FAILED
lazy.appUpdater.status != lazy.AppUpdater.STATUS.READY_FOR_RESTART &&
lazy.appUpdater.status != lazy.AppUpdater.STATUS.DOWNLOAD_FAILED
) {
return;
}
appUpdater.removeListener(listener);
if (appUpdater.status == AppUpdater.STATUS.READY_FOR_RESTART) {
lazy.appUpdater.removeListener(listener);
if (lazy.appUpdater.status == lazy.AppUpdater.STATUS.READY_FOR_RESTART) {
restartBrowser();
}
resolve();
};
appUpdater.addListener(listener);
appUpdater.startDownload();
lazy.appUpdater.addListener(listener);
lazy.appUpdater.startDownload();
});
}
function openClearHistoryDialog() {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// The behaviour of the Clear Recent History dialog in PBM does
// not have the expected effect (bug 463607).
if (PrivateBrowsingUtils.isWindowPrivate(window)) {
if (lazy.PrivateBrowsingUtils.isWindowPrivate(window)) {
return;
}
Sanitizer.showUI(window);
lazy.Sanitizer.showUI(window);
}
function restartBrowser() {
@ -811,9 +816,9 @@ function restartBrowser() {
}
function resetBrowser() {
if (!ResetProfile.resetSupported()) {
if (!lazy.ResetProfile.resetSupported()) {
return;
}
let window = BrowserWindowTracker.getTopWindow();
ResetProfile.openConfirmationDialog(window);
let window = lazy.BrowserWindowTracker.getTopWindow();
lazy.ResetProfile.openConfirmationDialog(window);
}

Просмотреть файл

@ -14,12 +14,16 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderOmnibox"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ExtensionSearchHandler: "resource://gre/modules/ExtensionSearchHandler.jsm",
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
// After this time, we'll give up waiting for the extension to return matches.
@ -65,7 +69,7 @@ class ProviderOmnibox extends UrlbarProvider {
if (
queryContext.tokens[0] &&
queryContext.tokens[0].value.length &&
ExtensionSearchHandler.isKeywordRegistered(
lazy.ExtensionSearchHandler.isKeywordRegistered(
queryContext.tokens[0].value
) &&
UrlbarUtils.substringAfter(
@ -80,8 +84,8 @@ class ProviderOmnibox extends UrlbarProvider {
// query but cancelQuery can be called multiple times per query.
// The frequent cancels can cause the extension's state to drift from the
// provider's state.
if (ExtensionSearchHandler.hasActiveInputSession()) {
ExtensionSearchHandler.handleInputCancelled();
if (lazy.ExtensionSearchHandler.hasActiveInputSession()) {
lazy.ExtensionSearchHandler.handleInputCancelled();
}
return false;
@ -113,11 +117,11 @@ class ProviderOmnibox extends UrlbarProvider {
// Fetch heuristic result.
let keyword = queryContext.tokens[0].value;
let description = ExtensionSearchHandler.getDescription(keyword);
let heuristicResult = new UrlbarResult(
let description = lazy.ExtensionSearchHandler.getDescription(keyword);
let heuristicResult = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.OMNIBOX,
UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [queryContext.searchString, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [queryContext.tokens[0].value, UrlbarUtils.HIGHLIGHT.TYPED],
@ -133,7 +137,7 @@ class ProviderOmnibox extends UrlbarProvider {
text: queryContext.searchString,
inPrivateWindow: queryContext.isPrivate,
};
this._resultsPromise = ExtensionSearchHandler.handleSearch(
this._resultsPromise = lazy.ExtensionSearchHandler.handleSearch(
data,
suggestions => {
if (instance != this.queryInstance) {
@ -144,18 +148,21 @@ class ProviderOmnibox extends UrlbarProvider {
if (content == heuristicResult.payload.content) {
continue;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.OMNIBOX,
UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [suggestion.description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [content, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [
queryContext.tokens[0].value,
UrlbarUtils.HIGHLIGHT.TYPED,
],
icon: UrlbarUtils.ICON.EXTENSION,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
title: [suggestion.description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [content, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [
queryContext.tokens[0].value,
UrlbarUtils.HIGHLIGHT.TYPED,
],
icon: UrlbarUtils.ICON.EXTENSION,
}
)
);
addCallback(this, result);
}

Просмотреть файл

@ -14,12 +14,17 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderOpenTabs"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
const PRIVATE_USER_CONTEXT_ID = -1;
@ -101,7 +106,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
* Copy over cached open tabs to the memory table once the Urlbar
* connection has been initialized.
*/
static promiseDBPopulated = PlacesUtils.largeCacheDBConnDeferred.promise.then(
static promiseDBPopulated = lazy.PlacesUtils.largeCacheDBConnDeferred.promise.then(
async () => {
// Must be set before populating.
UrlbarProviderOpenTabs.memoryTableInitialized = true;
@ -169,7 +174,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
// TODO:
// * properly search and handle tokens, this is just a mock for now.
let instance = this.queryInstance;
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await UrlbarProviderOpenTabs.promiseDBPopulated;
await conn.executeCached(
`
@ -184,7 +189,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
}
addCallback(
this,
new UrlbarResult(
new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
{
@ -208,8 +213,8 @@ async function addToMemoryTable(url, userContextId) {
if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
return;
}
await UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await conn.executeCached(
`
INSERT OR REPLACE INTO moz_openpages_temp (url, userContextId, open_count)
@ -238,8 +243,8 @@ async function removeFromMemoryTable(url, userContextId) {
if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
return;
}
await UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await conn.executeCached(
`
UPDATE moz_openpages_temp

Просмотреть файл

@ -103,20 +103,24 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
Sqlite: "resource://gre/modules/Sqlite.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProviderOpenTabs: "resource:///modules/UrlbarProviderOpenTabs.jsm",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
function setTimeout(callback, ms) {
@ -126,19 +130,19 @@ function setTimeout(callback, ms) {
}
// Maps restriction character types to textual behaviors.
XPCOMUtils.defineLazyGetter(this, "typeToBehaviorMap", () => {
XPCOMUtils.defineLazyGetter(lazy, "typeToBehaviorMap", () => {
return new Map([
[UrlbarTokenizer.TYPE.RESTRICT_HISTORY, "history"],
[UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK, "bookmark"],
[UrlbarTokenizer.TYPE.RESTRICT_TAG, "tag"],
[UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE, "openpage"],
[UrlbarTokenizer.TYPE.RESTRICT_SEARCH, "search"],
[UrlbarTokenizer.TYPE.RESTRICT_TITLE, "title"],
[UrlbarTokenizer.TYPE.RESTRICT_URL, "url"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY, "history"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK, "bookmark"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG, "tag"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE, "openpage"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH, "search"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE, "title"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_URL, "url"],
]);
});
XPCOMUtils.defineLazyGetter(this, "sourceToBehaviorMap", () => {
XPCOMUtils.defineLazyGetter(lazy, "sourceToBehaviorMap", () => {
return new Map([
[UrlbarUtils.RESULT_SOURCE.HISTORY, "history"],
[UrlbarUtils.RESULT_SOURCE.BOOKMARKS, "bookmark"],
@ -163,7 +167,7 @@ XPCOMUtils.defineLazyGetter(this, "sourceToBehaviorMap", () => {
*/
function makeKeyForMatch(match) {
let key, prefix;
let action = PlacesUtils.parseActionUrl(match.value);
let action = lazy.PlacesUtils.parseActionUrl(match.value);
if (!action) {
[key, prefix] = UrlbarUtils.stripPrefixAndTrim(match.value, {
stripHttp: true,
@ -279,16 +283,16 @@ function convertLegacyMatches(context, matches, urls) {
* @returns {object} an UrlbarResult
*/
function makeUrlbarResult(tokens, info) {
let action = PlacesUtils.parseActionUrl(info.url);
let action = lazy.PlacesUtils.parseActionUrl(info.url);
if (action) {
switch (action.type) {
case "searchengine": {
if (action.params.isSearchHistory) {
// Return a form history result.
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
engine: action.params.engineName,
suggestion: [
action.params.searchSuggestion,
@ -299,10 +303,10 @@ function makeUrlbarResult(tokens, info) {
);
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
engine: [action.params.engineName, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [
action.params.searchSuggestion,
@ -319,20 +323,20 @@ function makeUrlbarResult(tokens, info) {
);
}
case "switchtab":
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
url: [action.params.url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [info.comment, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
})
);
case "visiturl":
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
title: [info.comment, UrlbarUtils.HIGHLIGHT.TYPED],
url: [action.params.url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
@ -384,10 +388,10 @@ function makeUrlbarResult(tokens, info) {
.sort();
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
source,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
url: [info.url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
title: [comment, UrlbarUtils.HIGHLIGHT.TYPED],
@ -424,7 +428,7 @@ function Search(queryContext, listener, provider) {
this._matchBehavior = Ci.mozIPlacesAutoComplete.MATCH_BOUNDARY;
// Set the default behavior for this search.
this._behavior = this._searchString
? UrlbarPrefs.get("defaultBehavior")
? lazy.UrlbarPrefs.get("defaultBehavior")
: this._emptySearchDefaultBehavior;
this._inPrivateWindow = queryContext.isPrivate;
@ -440,14 +444,14 @@ function Search(queryContext, listener, provider) {
this._filterOnHost = engine.getResultDomain();
}
this._userContextId = UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
this._userContextId = lazy.UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
this._userContextId,
this._inPrivateWindow
);
// Use the original string here, not the stripped one, so the tokenizer can
// properly recognize token types.
let { tokens } = UrlbarTokenizer.tokenize({
let { tokens } = lazy.UrlbarTokenizer.tokenize({
searchString: unescapedSearchString,
trimmedSearchString: unescapedSearchString.trim(),
});
@ -456,9 +460,9 @@ function Search(queryContext, listener, provider) {
this._leadingRestrictionToken = null;
if (tokens.length) {
if (
UrlbarTokenizer.isRestrictionToken(tokens[0]) &&
lazy.UrlbarTokenizer.isRestrictionToken(tokens[0]) &&
(tokens.length > 1 ||
tokens[0].type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
tokens[0].type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
) {
this._leadingRestrictionToken = tokens[0].value;
}
@ -484,11 +488,11 @@ function Search(queryContext, listener, provider) {
if (
queryContext &&
queryContext.restrictSource &&
sourceToBehaviorMap.has(queryContext.restrictSource)
lazy.sourceToBehaviorMap.has(queryContext.restrictSource)
) {
this._behavior = 0;
this.setBehavior("restrict");
let behavior = sourceToBehaviorMap.get(queryContext.restrictSource);
let behavior = lazy.sourceToBehaviorMap.get(queryContext.restrictSource);
this.setBehavior(behavior);
// When we are in restrict mode, all the tokens are valid for searching, so
@ -509,7 +513,7 @@ function Search(queryContext, listener, provider) {
// Set the right JavaScript behavior based on our preference. Note that the
// preference is whether or not we should filter JavaScript, and the
// behavior is if we should search it or not.
if (!UrlbarPrefs.get("filter.javascript")) {
if (!lazy.UrlbarPrefs.get("filter.javascript")) {
this.setBehavior("javascript");
}
@ -565,11 +569,11 @@ Search.prototype = {
// Set the proper behavior while filtering tokens.
let filtered = [];
for (let token of tokens) {
if (!UrlbarTokenizer.isRestrictionToken(token)) {
if (!lazy.UrlbarTokenizer.isRestrictionToken(token)) {
filtered.push(token);
continue;
}
let behavior = typeToBehaviorMap.get(token.type);
let behavior = lazy.typeToBehaviorMap.get(token.type);
if (!behavior) {
throw new Error(`Unknown token type ${token.type}`);
}
@ -630,7 +634,7 @@ Search.prototype = {
// Used by stop() to interrupt an eventual running statement.
this.interrupt = () => {
// Interrupt any ongoing statement to run the search sooner.
if (!UrlbarProvidersManager.interruptLevel) {
if (!lazy.UrlbarProvidersManager.interruptLevel) {
conn.interrupt();
}
};
@ -641,7 +645,7 @@ Search.prototype = {
// If the query is simply "@" and we have tokenAliasEngines then return
// early. UrlbarProviderTokenAliasEngines will add engine results.
let tokenAliasEngines = await UrlbarSearchUtils.tokenAliasEngines();
let tokenAliasEngines = await lazy.UrlbarSearchUtils.tokenAliasEngines();
if (this._trimmedOriginalSearchString == "@" && tokenAliasEngines.length) {
this._provider.finishSearch(true);
return;
@ -661,7 +665,7 @@ Search.prototype = {
// UrlbarProviderSearchSuggestions will handle suggestions, if any.
let emptySearchRestriction =
this._trimmedOriginalSearchString.length <= 3 &&
this._leadingRestrictionToken == UrlbarTokenizer.RESTRICT.SEARCH &&
this._leadingRestrictionToken == lazy.UrlbarTokenizer.RESTRICT.SEARCH &&
/\s*\S?$/.test(this._trimmedOriginalSearchString);
if (
emptySearchRestriction ||
@ -712,7 +716,7 @@ Search.prototype = {
return false;
}
let aliasEngine = await UrlbarSearchUtils.engineForAlias(
let aliasEngine = await lazy.UrlbarSearchUtils.engineForAlias(
this._heuristicToken,
this._originalSearchString
);
@ -721,7 +725,7 @@ Search.prototype = {
return true;
}
let { entry } = await KeywordUtils.getBindableKeyword(
let { entry } = await lazy.KeywordUtils.getBindableKeyword(
this._heuristicToken,
this._originalSearchString
);
@ -844,7 +848,7 @@ Search.prototype = {
// already checked that the typed query is a subset of the search history
// query above with this._searchTokens.every(...).
if (
!UrlbarSearchUtils.serpsAreEquivalent(
!lazy.UrlbarSearchUtils.serpsAreEquivalent(
historyUrl,
generatedSuggestionUrl,
[parseResult.termsParameterName]
@ -887,10 +891,13 @@ Search.prototype = {
// Restyle past searches, unless they are bookmarks or special results.
if (
match.style == "favicon" &&
(UrlbarPrefs.get("restyleSearches") || this._searchModeEngine)
(lazy.UrlbarPrefs.get("restyleSearches") || this._searchModeEngine)
) {
let restyled = this._maybeRestyleSearchMatch(match);
if (restyled && UrlbarPrefs.get("maxHistoricalSearchSuggestions") == 0) {
if (
restyled &&
lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions") == 0
) {
// The user doesn't want search history.
return;
}
@ -933,7 +940,7 @@ Search.prototype = {
let [urlMapKey, prefix, action] = makeKeyForMatch(match);
if (
(match.placeId && this._usedPlaceIds.has(match.placeId)) ||
this._usedURLs.some(e => ObjectUtils.deepEqual(e.key, urlMapKey))
this._usedURLs.some(e => lazy.ObjectUtils.deepEqual(e.key, urlMapKey))
) {
let isDupe = true;
if (action && ["switchtab", "remotetab"].includes(action.type)) {
@ -941,7 +948,7 @@ Search.prototype = {
// among current matches.
for (let i = 0; i < this._usedURLs.length; ++i) {
let { key: matchKey, action: matchAction } = this._usedURLs[i];
if (ObjectUtils.deepEqual(matchKey, urlMapKey)) {
if (lazy.ObjectUtils.deepEqual(matchKey, urlMapKey)) {
isDupe = true;
if (!matchAction || action.type == "switchtab") {
this._usedURLs[i] = {
@ -972,7 +979,7 @@ Search.prototype = {
let { key: existingKey, prefix: existingPrefix } = this._usedURLs[i];
let existingPrefixRank = UrlbarUtils.getPrefixRank(existingPrefix);
if (ObjectUtils.deepEqual(existingKey, urlMapKey)) {
if (lazy.ObjectUtils.deepEqual(existingKey, urlMapKey)) {
isDupe = true;
if (prefix == existingPrefix) {
@ -1025,7 +1032,7 @@ Search.prototype = {
let index = 0;
if (!this._groups) {
this._groups = [];
this._makeGroups(UrlbarPrefs.get("resultGroups"), this._maxResults);
this._makeGroups(lazy.UrlbarPrefs.get("resultGroups"), this._maxResults);
}
let replace = 0;
@ -1178,7 +1185,7 @@ Search.prototype = {
// This means removing less interesting urls, like redirects or
// non-bookmarked title-less pages.
if (UrlbarPrefs.get("restyleSearches") || this._searchModeEngine) {
if (lazy.UrlbarPrefs.get("restyleSearches") || this._searchModeEngine) {
// If restyle is enabled, we want to filter out redirect targets,
// because sources are urls built using search engines definitions that
// we can reverse-parse.
@ -1247,9 +1254,9 @@ Search.prototype = {
// Otherwise, it is bookmarks, if they are enabled. If both history and
// bookmarks are disabled, it defaults to open pages.
let val = Ci.mozIPlacesAutoComplete.BEHAVIOR_RESTRICT;
if (UrlbarPrefs.get("suggest.history")) {
if (lazy.UrlbarPrefs.get("suggest.history")) {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_HISTORY;
} else if (UrlbarPrefs.get("suggest.bookmark")) {
} else if (lazy.UrlbarPrefs.get("suggest.bookmark")) {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_BOOKMARK;
} else {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_OPENPAGE;
@ -1280,7 +1287,7 @@ Search.prototype = {
*/
get _searchQuery() {
let params = {
parent: PlacesUtils.tagsFolderId,
parent: lazy.PlacesUtils.tagsFolderId,
query_type: QUERYTYPE_FILTERED,
matchBehavior: this._matchBehavior,
searchBehavior: this._behavior,
@ -1395,10 +1402,10 @@ class ProviderPlaces extends UrlbarProvider {
getDatabaseHandle() {
if (!this._promiseDatabase) {
this._promiseDatabase = (async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
// We don't catch exceptions here as it is too late to block shutdown.
Sqlite.shutdown.addBlocker("UrlbarProviderPlaces closing", () => {
lazy.Sqlite.shutdown.addBlocker("UrlbarProviderPlaces closing", () => {
// Break a possible cycle through the
// previous result, the controller and
// ourselves.
@ -1425,7 +1432,7 @@ class ProviderPlaces extends UrlbarProvider {
if (
!queryContext.trimmedSearchString &&
queryContext.searchMode?.engineName &&
UrlbarPrefs.get("update2.emptySearchBehavior") < 2
lazy.UrlbarPrefs.get("update2.emptySearchBehavior") < 2
) {
return false;
}
@ -1503,7 +1510,7 @@ class ProviderPlaces extends UrlbarProvider {
}
_startLegacyQuery(queryContext, callback) {
let deferred = PromiseUtils.defer();
let deferred = lazy.PromiseUtils.defer();
let listener = (matches, searchOngoing) => {
callback(matches);
if (!searchOngoing) {

Просмотреть файл

@ -17,13 +17,17 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ProfileAge: "resource://gre/modules/ProfileAge.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
const MS_PER_DAY = 86400000; // 24 * 60 * 60 * 1000
@ -42,7 +46,7 @@ function PreloadedSite(url, title) {
* populate(sites) : populates the storage with array of [url,title]
* sites[]: resulting array of sites (PreloadedSite objects)
*/
XPCOMUtils.defineLazyGetter(this, "PreloadedSiteStorage", () =>
XPCOMUtils.defineLazyGetter(lazy, "PreloadedSiteStorage", () =>
Object.seal({
sites: [],
@ -60,8 +64,8 @@ XPCOMUtils.defineLazyGetter(this, "PreloadedSiteStorage", () =>
})
);
XPCOMUtils.defineLazyGetter(this, "ProfileAgeCreatedPromise", async () => {
let times = await ProfileAge();
XPCOMUtils.defineLazyGetter(lazy, "ProfileAgeCreatedPromise", async () => {
let times = await lazy.ProfileAge();
return times.created;
});
@ -72,10 +76,10 @@ class ProviderPreloadedSites extends UrlbarProvider {
constructor() {
super();
if (UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
fetch("chrome://browser/content/urlbar/preloaded-top-urls.json")
.then(response => response.json())
.then(sites => PreloadedSiteStorage.populate(sites))
.then(sites => lazy.PreloadedSiteStorage.populate(sites))
.catch(ex => this.logger.error(ex));
}
}
@ -117,12 +121,12 @@ class ProviderPreloadedSites extends UrlbarProvider {
return false;
}
if (!UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (!lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
return false;
}
if (
!UrlbarPrefs.get("autoFill") ||
!lazy.UrlbarPrefs.get("autoFill") ||
!queryContext.allowAutofill ||
queryContext.tokens.length != 1
) {
@ -146,7 +150,7 @@ class ProviderPreloadedSites extends UrlbarProvider {
// As an optimization, don't try to autofill if the search term includes any
// whitespace.
if (UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
return false;
}
@ -183,17 +187,17 @@ class ProviderPreloadedSites extends UrlbarProvider {
}
// Now, add non-autofill preloaded sites.
for (let site of PreloadedSiteStorage.sites) {
for (let site of lazy.PreloadedSiteStorage.sites) {
let url = site.uri.spec;
if (
(!this._strippedPrefix || url.startsWith(this._strippedPrefix)) &&
(site.uri.host.includes(this._lowerCaseSearchString) ||
site._matchTitle.includes(this._lowerCaseSearchString))
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [site.title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -222,11 +226,11 @@ class ProviderPreloadedSites extends UrlbarProvider {
* the format.
*/
populatePreloadedSiteStorage(list) {
PreloadedSiteStorage.populate(list);
lazy.PreloadedSiteStorage.populate(list);
}
async _getAutofillResult(queryContext) {
let matchedSite = PreloadedSiteStorage.sites.find(site => {
let matchedSite = lazy.PreloadedSiteStorage.sites.find(site => {
return (
(!this._strippedPrefix ||
site.uri.spec.startsWith(this._strippedPrefix)) &&
@ -246,10 +250,10 @@ class ProviderPreloadedSites extends UrlbarProvider {
trimSlash: !this._searchString.includes("/"),
});
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -272,15 +276,15 @@ class ProviderPreloadedSites extends UrlbarProvider {
}
async _checkPreloadedSitesExpiry() {
if (!UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (!lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
return;
}
let profileCreationDate = await ProfileAgeCreatedPromise;
let profileCreationDate = await lazy.ProfileAgeCreatedPromise;
let daysSinceProfileCreation =
(Date.now() - profileCreationDate) / MS_PER_DAY;
if (
daysSinceProfileCreation >
UrlbarPrefs.get("usepreloadedtopurls.expire_days")
lazy.UrlbarPrefs.get("usepreloadedtopurls.expire_days")
) {
Services.prefs.setBoolPref(
"browser.urlbar.usepreloadedtopurls.enabled",

Просмотреть файл

@ -14,13 +14,17 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -58,7 +62,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
*/
isActive(queryContext) {
return (
UrlbarSearchUtils.separatePrivateDefaultUIEnabled &&
lazy.UrlbarSearchUtils.separatePrivateDefaultUIEnabled &&
!queryContext.isPrivate &&
queryContext.tokens.length
);
@ -75,7 +79,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
let searchString = queryContext.trimmedSearchString;
if (
queryContext.tokens.some(
t => t.type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH
t => t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH
)
) {
if (queryContext.tokens.length == 1) {
@ -84,7 +88,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
}
// Remove the restriction char from the search string.
searchString = queryContext.tokens
.filter(t => t.type != UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
.filter(t => t.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
.map(t => t.value)
.join(" ");
}
@ -95,7 +99,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
? Services.search.getEngineByName(queryContext.searchMode.engineName)
: await Services.search.getDefaultPrivate();
let isPrivateEngine =
UrlbarSearchUtils.separatePrivateDefault &&
lazy.UrlbarSearchUtils.separatePrivateDefault &&
engine != (await Services.search.getDefault());
this.logger.info(`isPrivateEngine: ${isPrivateEngine}`);
@ -113,10 +117,10 @@ class ProviderPrivateSearch extends UrlbarProvider {
return;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
query: [searchString, UrlbarUtils.HIGHLIGHT.NONE],
icon: engine.iconURI?.spec,

Просмотреть файл

@ -10,17 +10,17 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { UrlbarProvider } = ChromeUtils.import(
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
QuickActionsLoaderDefault:
"resource:///modules/QuickActionsLoaderDefault.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
// These prefs are relative to the `browser.urlbar` branch.
@ -44,9 +44,9 @@ const SUGGESTED_INDEX = 1;
class ProviderQuickActions extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_TYPE_NAME);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_TYPE_NAME);
Services.tm.idleDispatchToMainThread(() =>
QuickActionsLoaderDefault.load()
lazy.QuickActionsLoaderDefault.load()
);
}
@ -81,9 +81,9 @@ class ProviderQuickActions extends UrlbarProvider {
*/
isActive(queryContext) {
return (
UrlbarPrefs.get(ENABLED_PREF) &&
lazy.UrlbarPrefs.get(ENABLED_PREF) &&
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.ACTIONS) &&
queryContext.restrictSource == lazy.UrlbarTokenizer.RESTRICT.ACTIONS) &&
!queryContext.searchMode
);
}
@ -118,7 +118,7 @@ class ProviderQuickActions extends UrlbarProvider {
results.length = ACTIONS_SHOWN_FOCUS;
}
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.ACTIONS,
{

Просмотреть файл

@ -11,7 +11,16 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const {
SkippableTimer,
TaskQueue,
UrlbarProvider,
UrlbarUtils,
} = ChromeUtils.import("resource:///modules/UrlbarUtils.jsm");
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
clearInterval: "resource://gre/modules/Timer.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
@ -19,13 +28,9 @@ XPCOMUtils.defineLazyModuleGetters(this, {
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
PartnerLinkAttribution: "resource:///modules/PartnerLinkAttribution.jsm",
setInterval: "resource://gre/modules/Timer.jsm",
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
TaskQueue: "resource:///modules/UrlbarUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarQuickSuggest: "resource:///modules/UrlbarQuickSuggest.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
const TIMESTAMP_TEMPLATE = "%YYYYMMDDHH%";
@ -105,19 +110,21 @@ class ProviderQuickSuggest extends UrlbarProvider {
constructor(...args) {
super(...args);
UrlbarQuickSuggest.init();
UrlbarQuickSuggest.on("config-set", () => this._validateImpressionStats());
lazy.UrlbarQuickSuggest.init();
lazy.UrlbarQuickSuggest.on("config-set", () =>
this._validateImpressionStats()
);
this._updateFeatureState();
NimbusFeatures.urlbar.onUpdate(() => this._updateFeatureState());
lazy.NimbusFeatures.urlbar.onUpdate(() => this._updateFeatureState());
UrlbarPrefs.addObserver(this);
lazy.UrlbarPrefs.addObserver(this);
// Periodically record impression counters reset telemetry.
this._setImpressionCountersResetInterval();
// On shutdown, record any final impression counters reset telemetry.
AsyncShutdown.profileChangeTeardown.addBlocker(
lazy.AsyncShutdown.profileChangeTeardown.addBlocker(
"UrlbarProviderQuickSuggest: Record impression counters reset telemetry",
() => this._resetElapsedImpressionCounters()
);
@ -206,10 +213,10 @@ class ProviderQuickSuggest extends UrlbarProvider {
queryContext.trimmedSearchString &&
!queryContext.searchMode &&
!queryContext.isPrivate &&
UrlbarPrefs.get("quickSuggestEnabled") &&
(UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
UrlbarPrefs.get("suggest.quicksuggest.sponsored") ||
UrlbarPrefs.get("quicksuggest.dataCollection.enabled"))
lazy.UrlbarPrefs.get("quickSuggestEnabled") &&
(lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored") ||
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled"))
);
}
@ -231,14 +238,14 @@ class ProviderQuickSuggest extends UrlbarProvider {
// There are two sources for quick suggest: remote settings (from
// `UrlbarQuickSuggest`) and Merino.
let promises = [];
if (UrlbarPrefs.get("quickSuggestRemoteSettingsEnabled")) {
if (lazy.UrlbarPrefs.get("quickSuggestRemoteSettingsEnabled")) {
promises.push(
this._fetchRemoteSettingsSuggestions(queryContext, searchString)
);
}
if (
UrlbarPrefs.get("merinoEnabled") &&
UrlbarPrefs.get("quicksuggest.dataCollection.enabled") &&
lazy.UrlbarPrefs.get("merinoEnabled") &&
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled") &&
queryContext.allowRemoteResults()
) {
promises.push(this._fetchMerinoSuggestions(queryContext, searchString));
@ -295,8 +302,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
let isSuggestionBestMatch = false;
if (typeof suggestion._test_is_best_match == "boolean") {
isSuggestionBestMatch = suggestion._test_is_best_match;
} else if (UrlbarQuickSuggest.config.best_match) {
let { best_match } = UrlbarQuickSuggest.config;
} else if (lazy.UrlbarQuickSuggest.config.best_match) {
let { best_match } = lazy.UrlbarQuickSuggest.config;
isSuggestionBestMatch =
best_match.min_search_string_length <= searchString.length &&
!best_match.blocked_suggestion_ids.includes(suggestion.block_id);
@ -305,8 +312,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Determine if the urlbar result should be a best match.
let isResultBestMatch =
isSuggestionBestMatch &&
UrlbarPrefs.get("bestMatchEnabled") &&
UrlbarPrefs.get("suggest.bestmatch");
lazy.UrlbarPrefs.get("bestMatchEnabled") &&
lazy.UrlbarPrefs.get("suggest.bestmatch");
if (isResultBestMatch) {
// Show the result as a best match. Best match titles don't include the
// `full_keyword`, and the user's search string is highlighted.
@ -321,10 +328,13 @@ class ProviderQuickSuggest extends UrlbarProvider {
];
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, payload)
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
payload
)
);
if (isResultBestMatch) {
@ -332,12 +342,12 @@ class ProviderQuickSuggest extends UrlbarProvider {
result.suggestedIndex = 1;
} else if (
!isNaN(suggestion.position) &&
UrlbarPrefs.get("quickSuggestAllowPositionInSuggestions")
lazy.UrlbarPrefs.get("quickSuggestAllowPositionInSuggestions")
) {
result.suggestedIndex = suggestion.position;
} else {
result.isSuggestedIndexRelativeToGroup = true;
result.suggestedIndex = UrlbarPrefs.get(
result.suggestedIndex = lazy.UrlbarPrefs.get(
suggestion.is_sponsored
? "quickSuggestSponsoredIndex"
: "quickSuggestNonSponsoredIndex"
@ -361,18 +371,18 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Else if the user is not in a modal experiment:
// Record the event
if (
UrlbarPrefs.get("isBestMatchExperiment") ||
UrlbarPrefs.get("experimentType") === "best-match"
lazy.UrlbarPrefs.get("isBestMatchExperiment") ||
lazy.UrlbarPrefs.get("experimentType") === "best-match"
) {
if (
isSuggestionBestMatch &&
(!UrlbarPrefs.get("bestMatchEnabled") ||
UrlbarPrefs.get("suggest.bestmatch"))
(!lazy.UrlbarPrefs.get("bestMatchEnabled") ||
lazy.UrlbarPrefs.get("suggest.bestmatch"))
) {
UrlbarQuickSuggest.ensureExposureEventRecorded();
lazy.UrlbarQuickSuggest.ensureExposureEventRecorded();
}
} else if (UrlbarPrefs.get("experimentType") !== "modal") {
UrlbarQuickSuggest.ensureExposureEventRecorded();
} else if (lazy.UrlbarPrefs.get("experimentType") !== "modal") {
lazy.UrlbarQuickSuggest.ensureExposureEventRecorded();
}
}
@ -391,8 +401,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
blockResult(queryContext, result) {
if (
(!result.isBestMatch &&
!UrlbarPrefs.get("quickSuggestBlockingEnabled")) ||
(result.isBestMatch && !UrlbarPrefs.get("bestMatchBlockingEnabled"))
!lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled")) ||
(result.isBestMatch && !lazy.UrlbarPrefs.get("bestMatchBlockingEnabled"))
) {
this.logger.info("Blocking disabled, ignoring block");
return false;
@ -420,7 +430,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
let json = JSON.stringify([...this._blockedDigests]);
this._updatingBlockedDigests = true;
try {
UrlbarPrefs.set("quicksuggest.blockedDigests", json);
lazy.UrlbarPrefs.set("quicksuggest.blockedDigests", json);
} finally {
this._updatingBlockedDigests = false;
}
@ -456,7 +466,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
await this._blockTaskQueue.queue(() => {
this.logger.info(`Clearing all blocked suggestions`);
this._blockedDigests.clear();
UrlbarPrefs.clear("quicksuggest.blockedDigests");
lazy.UrlbarPrefs.clear("quicksuggest.blockedDigests");
});
}
@ -628,7 +638,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Always use lowercase to make the reporting consistent
advertiser: result.payload.sponsoredAdvertiser.toLocaleLowerCase(),
block_id: result.payload.sponsoredBlockId,
improve_suggest_experience_checked: UrlbarPrefs.get(
improve_suggest_experience_checked: lazy.UrlbarPrefs.get(
"quicksuggest.dataCollection.enabled"
),
position: telemetryResultIndex,
@ -636,34 +646,34 @@ class ProviderQuickSuggest extends UrlbarProvider {
};
// impression
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
is_clicked,
reporting_url: result.payload.sponsoredImpressionUrl,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_IMPRESSION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_IMPRESSION
);
// click
if (is_clicked) {
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
reporting_url: result.payload.sponsoredClickUrl,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_SELECTION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_SELECTION
);
}
// block
if (selType == "block") {
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
iab_category: result.payload.sponsoredIabCategory,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_BLOCK
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_BLOCK
);
}
}
@ -694,29 +704,29 @@ class ProviderQuickSuggest extends UrlbarProvider {
}
break;
case "quicksuggest.dataCollection.enabled":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"data_collect_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
case "suggest.quicksuggest.nonsponsored":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"enable_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
case "suggest.quicksuggest.sponsored":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"sponsored_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
@ -812,7 +822,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
let suggestions;
TelemetryStopwatch.start(TELEMETRY_REMOTE_SETTINGS_LATENCY, queryContext);
try {
suggestions = await UrlbarQuickSuggest.query(searchString);
suggestions = await lazy.UrlbarQuickSuggest.query(searchString);
TelemetryStopwatch.finish(
TELEMETRY_REMOTE_SETTINGS_LATENCY,
queryContext
@ -863,7 +873,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Get the endpoint URL. It's empty by default when running tests so they
// don't hit the network.
let endpointString = UrlbarPrefs.get("merino.endpointURL");
let endpointString = lazy.UrlbarPrefs.get("merino.endpointURL");
if (!endpointString) {
return null;
}
@ -881,17 +891,17 @@ class ProviderQuickSuggest extends UrlbarProvider {
this._merinoSequenceNumber
);
let clientVariants = UrlbarPrefs.get("merino.clientVariants");
let clientVariants = lazy.UrlbarPrefs.get("merino.clientVariants");
if (clientVariants) {
url.searchParams.set(MERINO_PARAMS.CLIENT_VARIANTS, clientVariants);
}
let providers = UrlbarPrefs.get("merino.providers");
let providers = lazy.UrlbarPrefs.get("merino.providers");
if (providers) {
url.searchParams.set(MERINO_PARAMS.PROVIDERS, providers);
} else if (
!UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") &&
!UrlbarPrefs.get("suggest.quicksuggest.sponsored")
!lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") &&
!lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")
) {
// Data collection is enabled but suggestions are not. Set the providers
// param to an empty string to tell Merino not to fetch any suggestions.
@ -907,7 +917,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
};
// Set up the timeout timer.
let timeout = UrlbarPrefs.get("merinoTimeoutMs");
let timeout = lazy.UrlbarPrefs.get("merinoTimeoutMs");
let timer = (this._merinoTimeoutTimer = new SkippableTimer({
name: "Merino timeout",
time: timeout,
@ -1033,9 +1043,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Return false if suggestions are disabled.
if (
(suggestion.is_sponsored &&
!UrlbarPrefs.get("suggest.quicksuggest.sponsored")) ||
!lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")) ||
(!suggestion.is_sponsored &&
!UrlbarPrefs.get("suggest.quicksuggest.nonsponsored"))
!lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored"))
) {
this.logger.info("Suggestions disabled, not adding suggestion");
return false;
@ -1044,9 +1054,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Return false if an impression cap has been hit.
if (
(suggestion.is_sponsored &&
UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
lazy.UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
(!suggestion.is_sponsored &&
UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
lazy.UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
) {
this._resetElapsedImpressionCounters();
let type = suggestion.is_sponsored ? "sponsored" : "nonsponsored";
@ -1127,16 +1137,16 @@ class ProviderQuickSuggest extends UrlbarProvider {
JSON.stringify({
isSponsored,
currentStats: this._impressionStats,
impression_caps: UrlbarQuickSuggest.config.impression_caps,
impression_caps: lazy.UrlbarQuickSuggest.config.impression_caps,
})
);
// Don't bother recording anything if caps are disabled.
if (
(isSponsored &&
!UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
!lazy.UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
(!isSponsored &&
!UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
!lazy.UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
) {
this.logger.info("Impression caps disabled, skipping update");
return;
@ -1172,7 +1182,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Save the stats.
this._updatingImpressionStats = true;
try {
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
"quicksuggest.impressionCaps.stats",
JSON.stringify(this._impressionStats)
);
@ -1188,7 +1198,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* Loads and validates impression stats.
*/
_loadImpressionStats() {
let json = UrlbarPrefs.get("quicksuggest.impressionCaps.stats");
let json = lazy.UrlbarPrefs.get("quicksuggest.impressionCaps.stats");
if (!json) {
this._impressionStats = {};
} else {
@ -1215,7 +1225,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* for more info.
*/
_validateImpressionStats() {
let { impression_caps } = UrlbarQuickSuggest.config;
let { impression_caps } = lazy.UrlbarQuickSuggest.config;
this.logger.info("Validating impression stats");
this.logger.debug(
@ -1336,7 +1346,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
this.logger.debug(
JSON.stringify({
currentStats: this._impressionStats,
impression_caps: UrlbarQuickSuggest.config.impression_caps,
impression_caps: lazy.UrlbarQuickSuggest.config.impression_caps,
})
);
@ -1459,9 +1469,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
ms = IMPRESSION_COUNTERS_RESET_INTERVAL_MS
) {
if (this._impressionCountersResetInterval) {
clearInterval(this._impressionCountersResetInterval);
lazy.clearInterval(this._impressionCountersResetInterval);
}
this._impressionCountersResetInterval = setInterval(
this._impressionCountersResetInterval = lazy.setInterval(
() => this._resetElapsedImpressionCounters(),
ms
);
@ -1486,7 +1496,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
this.logger.debug(`Queueing _loadBlockedDigests`);
await this._blockTaskQueue.queue(() => {
this.logger.info(`Loading blocked suggestion digests`);
let json = UrlbarPrefs.get("quicksuggest.blockedDigests");
let json = lazy.UrlbarPrefs.get("quicksuggest.blockedDigests");
this.logger.debug(
`browser.urlbar.quicksuggest.blockedDigests value: ${json}`
);
@ -1524,7 +1534,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* Updates state based on the `browser.urlbar.quicksuggest.enabled` pref.
*/
_updateFeatureState() {
let enabled = UrlbarPrefs.get("quickSuggestEnabled");
let enabled = lazy.UrlbarPrefs.get("quickSuggestEnabled");
if (enabled == this._quickSuggestEnabled) {
// This method is a Nimbus `onUpdate()` callback, which means it's called
// each time any pref is changed that is a fallback for a Nimbus variable.

Просмотреть файл

@ -14,14 +14,19 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
SyncedTabs: "resource://services-sync/SyncedTabs.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
let _cache = null;
@ -31,7 +36,7 @@ let _cache = null;
// are found.
const RECENT_REMOTE_TAB_THRESHOLD_MS = 72 * 60 * 60 * 1000; // 72 hours.
XPCOMUtils.defineLazyGetter(this, "weaveXPCService", function() {
XPCOMUtils.defineLazyGetter(lazy, "weaveXPCService", function() {
try {
return Cc["@mozilla.org/weave/service;1"].getService(
Ci.nsISupports
@ -43,21 +48,21 @@ XPCOMUtils.defineLazyGetter(this, "weaveXPCService", function() {
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"showRemoteIconsPref",
"services.sync.syncedTabs.showRemoteIcons",
true
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"showRemoteTabsPref",
"services.sync.syncedTabs.showRemoteTabs",
true
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"syncUsernamePref",
"services.sync.username"
);
@ -100,13 +105,13 @@ class ProviderRemoteTabs extends UrlbarProvider {
*/
isActive(queryContext) {
return (
syncUsernamePref &&
showRemoteTabsPref &&
UrlbarPrefs.get("suggest.remotetab") &&
lazy.syncUsernamePref &&
lazy.showRemoteTabsPref &&
lazy.UrlbarPrefs.get("suggest.remotetab") &&
queryContext.sources.includes(UrlbarUtils.RESULT_SOURCE.TABS) &&
weaveXPCService &&
weaveXPCService.ready &&
weaveXPCService.enabled
lazy.weaveXPCService &&
lazy.weaveXPCService.ready &&
lazy.weaveXPCService.enabled
);
}
@ -134,30 +139,30 @@ class ProviderRemoteTabs extends UrlbarProvider {
for (let { tab, client } of tabsData) {
if (
!searchString ||
searchString == UrlbarTokenizer.RESTRICT.OPENPAGE ||
searchString == lazy.UrlbarTokenizer.RESTRICT.OPENPAGE ||
re.test(tab.url) ||
(tab.title && re.test(tab.title))
) {
if (showRemoteIconsPref) {
if (lazy.showRemoteIconsPref) {
if (!tab.icon) {
// It's rare that Sync supplies the icon for the page. If it does, it is a
// string URL.
tab.icon = UrlbarUtils.getIconForUrl(tab.url);
} else {
tab.icon = PlacesUtils.favicons.getFaviconLinkForIcon(
tab.icon = lazy.PlacesUtils.favicons.getFaviconLinkForIcon(
Services.io.newURI(tab.icon)
).spec;
}
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.REMOTE_TAB,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [tab.url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [tab.title, UrlbarUtils.HIGHLIGHT.TYPED],
device: client.name,
icon: showRemoteIconsPref ? tab.icon : "",
icon: lazy.showRemoteIconsPref ? tab.icon : "",
lastUsed: (tab.lastUsed || 0) * 1000,
})
);
@ -205,9 +210,9 @@ class ProviderRemoteTabs extends UrlbarProvider {
// being signed in), don't reach in to Weave.Service as that may initialize
// Sync unnecessarily - we'll get an observer notification later when it
// becomes ready and has synced a list of tabs.
if (weaveXPCService.ready) {
let clients = await SyncedTabs.getTabClients();
SyncedTabs.sortTabClientsByLastUsed(clients);
if (lazy.weaveXPCService.ready) {
let clients = await lazy.SyncedTabs.getTabClients();
lazy.SyncedTabs.sortTabClientsByLastUsed(clients);
for (let client of clients) {
for (let tab of client.tabs) {
tabsData.push({ tab, client });

Просмотреть файл

@ -14,16 +14,20 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
SearchSuggestionController:
"resource://gre/modules/SearchSuggestionController.jsm",
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -36,7 +40,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
function looksLikeUrl(str, ignoreAlphanumericHosts = false) {
// Single word including special chars.
return (
!UrlbarTokenizer.REGEXP_SPACES.test(str) &&
!lazy.UrlbarTokenizer.REGEXP_SPACES.test(str) &&
(["/", "@", ":", "["].some(c => str.includes(c)) ||
(ignoreAlphanumericHosts
? /^([\[\]A-Z0-9-]+\.){3,}[^.]+$/i.test(str)
@ -100,9 +104,9 @@ class ProviderSearchSuggestions extends UrlbarProvider {
}
let wantsLocalSuggestions =
UrlbarPrefs.get("maxHistoricalSearchSuggestions") &&
lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions") &&
(queryContext.trimmedSearchString ||
UrlbarPrefs.get("update2.emptySearchBehavior") != 0);
lazy.UrlbarPrefs.get("update2.emptySearchBehavior") != 0);
return wantsLocalSuggestions || this._allowRemoteSuggestions(queryContext);
}
@ -121,7 +125,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
(queryContext.restrictSource &&
queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH) ||
queryContext.tokens.some(
t => t.type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH
t => t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH
) ||
(queryContext.searchMode &&
queryContext.sources.includes(UrlbarUtils.RESULT_SOURCE.SEARCH))
@ -141,11 +145,11 @@ class ProviderSearchSuggestions extends UrlbarProvider {
if (
// If the user typed a restriction token or token alias, we ignore the
// pref to disable suggestions in the Urlbar.
(!UrlbarPrefs.get("suggest.searches") &&
(!lazy.UrlbarPrefs.get("suggest.searches") &&
!this._isTokenOrRestrictionPresent(queryContext)) ||
!UrlbarPrefs.get("browser.search.suggest.enabled") ||
!lazy.UrlbarPrefs.get("browser.search.suggest.enabled") ||
(queryContext.isPrivate &&
!UrlbarPrefs.get("browser.search.suggest.enabled.private"))
!lazy.UrlbarPrefs.get("browser.search.suggest.enabled.private"))
) {
return false;
}
@ -229,9 +233,10 @@ class ProviderSearchSuggestions extends UrlbarProvider {
let leadingRestrictionToken = null;
if (
UrlbarTokenizer.isRestrictionToken(queryContext.tokens[0]) &&
lazy.UrlbarTokenizer.isRestrictionToken(queryContext.tokens[0]) &&
(queryContext.tokens.length > 1 ||
queryContext.tokens[0].type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
queryContext.tokens[0].type ==
lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
) {
leadingRestrictionToken = queryContext.tokens[0].value;
}
@ -240,7 +245,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// when the search shortcut is used and it's not user typed. Don't strip
// other restriction chars, so that it's possible to search for things
// including one of those (e.g. "c#").
if (leadingRestrictionToken === UrlbarTokenizer.RESTRICT.SEARCH) {
if (leadingRestrictionToken === lazy.UrlbarTokenizer.RESTRICT.SEARCH) {
query = UrlbarUtils.substringAfter(query, leadingRestrictionToken).trim();
}
@ -253,7 +258,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
queryContext.searchMode.engineName
);
} else {
engine = UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
engine = lazy.UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
}
if (!engine) {
@ -302,7 +307,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
return null;
}
this._suggestionsController = new SearchSuggestionController();
this._suggestionsController = new lazy.SearchSuggestionController();
this._suggestionsController.formHistoryParam = queryContext.formHistoryName;
// If there's a form history entry that equals the search string, the search
@ -345,7 +350,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// show form history at all. With the introduction of flexed result
// groups, we now use it only as a boolean: Zero means don't show form
// history at all (as before), non-zero means show it.
if (UrlbarPrefs.get("maxHistoricalSearchSuggestions")) {
if (lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions")) {
for (let entry of fetchData.local) {
results.push(makeFormHistoryResult(queryContext, engine, entry));
}
@ -357,7 +362,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
if (
allowRemote &&
!fetchData.remote.length &&
searchString.length > UrlbarPrefs.get("maxCharsForSearchSuggestions")
searchString.length > lazy.UrlbarPrefs.get("maxCharsForSearchSuggestions")
) {
this._lastLowResultsSearchSuggestion = searchString;
}
@ -388,7 +393,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
let tailPrefix = entry.matchPrefix;
// Skip tail suggestions if the pref is disabled.
if (tail && !UrlbarPrefs.get("richSuggestions.tail")) {
if (tail && !lazy.UrlbarPrefs.get("richSuggestions.tail")) {
continue;
}
@ -398,20 +403,26 @@ class ProviderSearchSuggestions extends UrlbarProvider {
try {
results.push(
new UrlbarResult(
new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),
tailPrefix,
tail: [tail, UrlbarUtils.HIGHLIGHT.SUGGESTED],
tailOffsetIndex: tail ? entry.tailOffsetIndex : undefined,
keyword: [alias ? alias : undefined, UrlbarUtils.HIGHLIGHT.TYPED],
query: [searchString.trim(), UrlbarUtils.HIGHLIGHT.NONE],
icon: !entry.value ? engine.iconURI?.spec : undefined,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),
tailPrefix,
tail: [tail, UrlbarUtils.HIGHLIGHT.SUGGESTED],
tailOffsetIndex: tail ? entry.tailOffsetIndex : undefined,
keyword: [
alias ? alias : undefined,
UrlbarUtils.HIGHLIGHT.TYPED,
],
query: [searchString.trim(), UrlbarUtils.HIGHLIGHT.NONE],
icon: !entry.value ? engine.iconURI?.spec : undefined,
}
)
)
);
} catch (err) {
@ -455,12 +466,14 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// Match an alias only when it has a space after it. If there's no trailing
// space, then continue to treat it as part of the search string.
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
// Check if the user entered an engine alias directly.
let engineMatch = await UrlbarSearchUtils.engineForAlias(possibleAlias);
let engineMatch = await lazy.UrlbarSearchUtils.engineForAlias(
possibleAlias
);
if (engineMatch) {
return {
engine: engineMatch,
@ -474,10 +487,10 @@ class ProviderSearchSuggestions extends UrlbarProvider {
}
function makeFormHistoryResult(queryContext, engine, entry) {
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: engine.name,
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),

Просмотреть файл

@ -16,20 +16,24 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
DefaultBrowserCheck: "resource:///modules/BrowserGlue.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
ProfileAge: "resource://gre/modules/ProfileAge.jsm",
setTimeout: "resource://gre/modules/Timer.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProviderTopSites: "resource:///modules/UrlbarProviderTopSites.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "updateManager", () => {
XPCOMUtils.defineLazyGetter(lazy, "updateManager", () => {
return (
Cc["@mozilla.org/updates/update-manager;1"] &&
Cc["@mozilla.org/updates/update-manager;1"].getService(Ci.nsIUpdateManager)
@ -37,7 +41,7 @@ XPCOMUtils.defineLazyGetter(this, "updateManager", () => {
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"cfrFeaturesUserPref",
"browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
true
@ -97,7 +101,10 @@ class ProviderSearchTips extends UrlbarProvider {
// example because a tip was already shown.
this.disableTipsForCurrentSession = true;
for (let tip of Object.values(TIPS)) {
if (tip && UrlbarPrefs.get(`tipShownCount.${tip}`) < MAX_SHOWN_COUNT) {
if (
tip &&
lazy.UrlbarPrefs.get(`tipShownCount.${tip}`) < MAX_SHOWN_COUNT
) {
this.disableTipsForCurrentSession = false;
break;
}
@ -119,7 +126,7 @@ class ProviderSearchTips extends UrlbarProvider {
get PRIORITY() {
// Search tips are prioritized over the Places and top sites providers.
return UrlbarProviderTopSites.PRIORITY + 1;
return lazy.UrlbarProviderTopSites.PRIORITY + 1;
}
/**
@ -145,7 +152,7 @@ class ProviderSearchTips extends UrlbarProvider {
* @returns {boolean} Whether this provider should be invoked for the search.
*/
isActive(queryContext) {
return this.currentTip && cfrFeaturesUserPref;
return this.currentTip && lazy.cfrFeaturesUserPref;
}
/**
@ -174,7 +181,7 @@ class ProviderSearchTips extends UrlbarProvider {
let defaultEngine = await Services.search.getDefault();
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TIP,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -220,7 +227,7 @@ class ProviderSearchTips extends UrlbarProvider {
* The result that was picked.
*/
pickResult(result) {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gURLBar.value = "";
window.gURLBar.setPageProxyState("invalid");
window.gURLBar.removeAttribute("suppress-focus-border");
@ -253,7 +260,7 @@ class ProviderSearchTips extends UrlbarProvider {
// engaged with the urlbar while the tip was showing. We treat both as the
// user's acknowledgment of the tip, and we don't show tips again in any
// session. Set the shown count to the max.
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
`tipShownCount.${this.showedTipTypeInCurrentEngagement}`,
MAX_SHOWN_COUNT
);
@ -316,9 +323,9 @@ class ProviderSearchTips extends UrlbarProvider {
// Check if we are supposed to show a tip for the current session.
if (
!cfrFeaturesUserPref ||
!lazy.cfrFeaturesUserPref ||
(this.disableTipsForCurrentSession &&
!UrlbarPrefs.get("searchTips.test.ignoreShowLimits"))
!lazy.UrlbarPrefs.get("searchTips.test.ignoreShowLimits"))
) {
return;
}
@ -352,11 +359,13 @@ class ProviderSearchTips extends UrlbarProvider {
return;
}
let ignoreShowLimits = UrlbarPrefs.get("searchTips.test.ignoreShowLimits");
let ignoreShowLimits = lazy.UrlbarPrefs.get(
"searchTips.test.ignoreShowLimits"
);
// If we've shown this type of tip the maximum number of times over all
// sessions, don't show it again.
let shownCount = UrlbarPrefs.get(`tipShownCount.${tip}`);
let shownCount = lazy.UrlbarPrefs.get(`tipShownCount.${tip}`);
if (shownCount >= MAX_SHOWN_COUNT && !ignoreShowLimits) {
return;
}
@ -368,12 +377,12 @@ class ProviderSearchTips extends UrlbarProvider {
}
// Start a search.
setTimeout(async () => {
lazy.setTimeout(async () => {
if (this._maybeShowTipForUrlInstance != instance) {
return;
}
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// We don't want to interrupt a user's typed query with a Search Tip.
// See bugs 1613662 and 1619547.
if (
@ -396,7 +405,7 @@ class ProviderSearchTips extends UrlbarProvider {
this.disableTipsForCurrentSession = true;
// Store the new shown count.
UrlbarPrefs.set(`tipShownCount.${tip}`, shownCount + 1);
lazy.UrlbarPrefs.set(`tipShownCount.${tip}`, shownCount + 1);
this.currentTip = tip;
window.gURLBar.search("", { focus: tip == TIPS.ONBOARD });
@ -405,7 +414,7 @@ class ProviderSearchTips extends UrlbarProvider {
}
async function isBrowserShowingNotification() {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// urlbar view and notification box (info bar)
if (
@ -418,9 +427,9 @@ async function isBrowserShowingNotification() {
// app menu notification doorhanger
if (
AppMenuNotifications.activeNotification &&
!AppMenuNotifications.activeNotification.dismissed &&
!AppMenuNotifications.activeNotification.options.badgeOnly
lazy.AppMenuNotifications.activeNotification &&
!lazy.AppMenuNotifications.activeNotification.dismissed &&
!lazy.AppMenuNotifications.activeNotification.options.badgeOnly
) {
return true;
}
@ -465,7 +474,7 @@ async function isBrowserShowingNotification() {
// On startup, the default browser check normally opens after the Search Tip.
// As a result, we can't check for the prompt's presence, but we can check if
// it plans on opening.
const willPrompt = await DefaultBrowserCheck.willCheckDefaultBrowser(
const willPrompt = await lazy.DefaultBrowserCheck.willCheckDefaultBrowser(
/* isStartupCheck */ false
);
if (willPrompt) {
@ -516,12 +525,12 @@ async function lastBrowserUpdateDate() {
// Get the newest update in the update history. This isn't perfect
// because these dates are when updates are applied, not when the
// user restarts with the update. See bug 1595328.
if (updateManager && updateManager.getUpdateCount()) {
let update = updateManager.getUpdateAt(0);
if (lazy.updateManager && lazy.updateManager.getUpdateCount()) {
let update = lazy.updateManager.getUpdateAt(0);
return update.installDate;
}
// Fall back to the profile age.
let age = await ProfileAge();
let age = await lazy.ProfileAge();
return (await age.firstUse) || age.created;
}

Просмотреть файл

@ -15,15 +15,20 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarView: "resource:///modules/UrlbarView.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProviderAutofill: "resource:///modules/UrlbarProviderAutofill.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
const DYNAMIC_RESULT_TYPE = "onboardTabToSearch";
@ -93,8 +98,8 @@ const VIEW_TEMPLATE = {
* of the provider singleton.
*/
function initializeDynamicResult() {
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -137,7 +142,7 @@ class ProviderTabToSearch extends UrlbarProvider {
queryContext.searchString &&
queryContext.tokens.length == 1 &&
!queryContext.searchMode &&
UrlbarPrefs.get("suggest.engines")
lazy.UrlbarPrefs.get("suggest.engines")
);
}
@ -232,12 +237,12 @@ class ProviderTabToSearch extends UrlbarProvider {
(!this.onboardingInteractionAtTime ||
this.onboardingInteractionAtTime < Date.now() - 1000 * 60 * 5)
) {
let interactionsLeft = UrlbarPrefs.get(
let interactionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
if (interactionsLeft > 0) {
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
"tabToSearch.onboard.interactionsLeft",
--interactionsLeft
);
@ -272,7 +277,7 @@ class ProviderTabToSearch extends UrlbarProvider {
try {
// urlbar.tabtosearch.* is prerelease-only/opt-in for now. See bug 1686330.
for (let engine of this.enginesShown.regular) {
let scalarKey = UrlbarSearchUtils.getSearchModeScalarKey({
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
@ -282,7 +287,7 @@ class ProviderTabToSearch extends UrlbarProvider {
);
}
for (let engine of this.enginesShown.onboarding) {
let scalarKey = UrlbarSearchUtils.getSearchModeScalarKey({
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
@ -352,7 +357,7 @@ class ProviderTabToSearch extends UrlbarProvider {
);
// Skip any string that cannot be an origin.
if (
!UrlbarTokenizer.looksLikeOrigin(searchStr, {
!lazy.UrlbarTokenizer.looksLikeOrigin(searchStr, {
ignoreKnownDomains: true,
noIp: true,
})
@ -366,15 +371,18 @@ class ProviderTabToSearch extends UrlbarProvider {
}
// Add all matching engines.
let engines = await UrlbarSearchUtils.enginesForDomainPrefix(searchStr, {
matchAllDomainLevels: true,
onlyEnabled: true,
});
let engines = await lazy.UrlbarSearchUtils.enginesForDomainPrefix(
searchStr,
{
matchAllDomainLevels: true,
onlyEnabled: true,
}
);
if (!engines.length) {
return;
}
const onboardingInteractionsLeft = UrlbarPrefs.get(
const onboardingInteractionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
@ -424,7 +432,7 @@ class ProviderTabToSearch extends UrlbarProvider {
}
}
if (partialMatchEnginesByHost.size) {
let host = await UrlbarProviderAutofill.getTopHostOverThreshold(
let host = await lazy.UrlbarProviderAutofill.getTopHostOverThreshold(
queryContext,
Array.from(partialMatchEnginesByHost.keys())
);
@ -445,7 +453,7 @@ function makeOnboardingResult(engine, satisfiesAutofillThreshold = false) {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.SEARCH,
{
@ -467,10 +475,10 @@ function makeResult(context, engine, satisfiesAutofillThreshold = false) {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(context.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(context.tokens, {
engine: engine.name,
isGeneralPurposeEngine: engine.isGeneralPurposeEngine,
url,

Просмотреть файл

@ -13,13 +13,18 @@ var EXPORTED_SYMBOLS = ["UrlbarProviderTokenAliasEngines"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
/**
@ -81,7 +86,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
return false;
}
this._engines = await UrlbarSearchUtils.tokenAliasEngines();
this._engines = await lazy.UrlbarSearchUtils.tokenAliasEngines();
if (!this._engines.length) {
return false;
}
@ -96,7 +101,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
}
// If the user is typing a potential engine name, autofill it.
if (UrlbarPrefs.get("autoFill") && queryContext.allowAutofill) {
if (lazy.UrlbarPrefs.get("autoFill") && queryContext.allowAutofill) {
let result = this._getAutofillResult(queryContext);
if (result) {
this._autofillData = { result, instance };
@ -130,10 +135,10 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
tokenAliases[0].startsWith(queryContext.trimmedSearchString) &&
engine.name != this._autofillData?.result.payload.engine
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [tokenAliases[0], UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
@ -180,7 +185,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
// alias followed by a space. We enter search mode at that point.
if (
lowerCaseSearchString.startsWith(alias) &&
UrlbarTokenizer.REGEXP_SPACES_START.test(
lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(
lowerCaseSearchString.substring(alias.length)
)
) {
@ -193,16 +198,19 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
queryContext.searchString +
alias.substr(queryContext.searchString.length);
let value = aliasPreservingUserCase + " ";
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [aliasPreservingUserCase, UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
providesSearchMode: true,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [aliasPreservingUserCase, UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
providesSearchMode: true,
}
)
);
// We set suggestedIndex = 0 instead of the heuristic because we

Просмотреть файл

@ -15,18 +15,22 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutNewTab: "resource:///modules/AboutNewTab.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
"resource:///modules/PartnerLinkAttribution.jsm",
PartnerLinkAttribution: "resource:///modules/PartnerLinkAttribution.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarProviderOpenTabs: "resource:///modules/UrlbarProviderOpenTabs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
TOP_SITES_MAX_SITES_PER_ROW: "resource://activity-stream/common/Reducers.jsm",
TOP_SITES_DEFAULT_ROWS: "resource://activity-stream/common/Reducers.jsm",
});
@ -124,7 +128,7 @@ class ProviderTopSites extends UrlbarProvider {
return;
}
let sites = AboutNewTab.getTopSites();
let sites = lazy.AboutNewTab.getTopSites();
let instance = this.queryInstance;
@ -132,7 +136,7 @@ class ProviderTopSites extends UrlbarProvider {
// on about:newtab.
sites = sites.filter(site => site);
if (!UrlbarPrefs.get("sponsoredTopSites")) {
if (!lazy.UrlbarPrefs.get("sponsoredTopSites")) {
sites = sites.filter(site => !site.sponsored_position);
}
@ -144,7 +148,7 @@ class ProviderTopSites extends UrlbarProvider {
this,
"topSitesRows",
"browser.newtabpage.activity-stream.topSitesRows",
TOP_SITES_DEFAULT_ROWS
lazy.TOP_SITES_DEFAULT_ROWS
);
}
@ -152,8 +156,8 @@ class ProviderTopSites extends UrlbarProvider {
// Sites greater than what is visible in the New Tab Page, because the
// additional ones couldn't be managed from the page.
let numTopSites = Math.min(
UrlbarPrefs.get("maxRichResults"),
TOP_SITES_MAX_SITES_PER_ROW * this.topSitesRows
lazy.UrlbarPrefs.get("maxRichResults"),
lazy.TOP_SITES_MAX_SITES_PER_ROW * this.topSitesRows
);
sites = sites.slice(0, numTopSites);
@ -214,18 +218,18 @@ class ProviderTopSites extends UrlbarProvider {
sponsoredClickUrl: site.sponsoredClickUrl,
};
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
payload
)
);
let tabs;
if (UrlbarPrefs.get("suggest.openpage")) {
tabs = UrlbarProviderOpenTabs.getOpenTabs(
if (lazy.UrlbarPrefs.get("suggest.openpage")) {
tabs = lazy.UrlbarProviderOpenTabs.getOpenTabs(
queryContext.userContextId || 0,
queryContext.isPrivate
);
@ -234,8 +238,8 @@ class ProviderTopSites extends UrlbarProvider {
if (tabs && tabs.includes(site.url.replace(/#.*$/, ""))) {
result.type = UrlbarUtils.RESULT_TYPE.TAB_SWITCH;
result.source = UrlbarUtils.RESULT_SOURCE.TABS;
} else if (UrlbarPrefs.get("suggest.bookmark")) {
let bookmark = await PlacesUtils.bookmarks.fetch({
} else if (lazy.UrlbarPrefs.get("suggest.bookmark")) {
let bookmark = await lazy.PlacesUtils.bookmarks.fetch({
url: new URL(result.payload.url),
});
if (bookmark) {
@ -252,7 +256,7 @@ class ProviderTopSites extends UrlbarProvider {
break;
}
case "search": {
let engine = await UrlbarSearchUtils.engineForAlias(site.title);
let engine = await lazy.UrlbarSearchUtils.engineForAlias(site.title);
if (!engine && site.url) {
// Look up the engine by its domain.
@ -262,7 +266,7 @@ class ProviderTopSites extends UrlbarProvider {
} catch (err) {}
if (host) {
engine = (
await UrlbarSearchUtils.enginesForDomainPrefix(host)
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(host)
)[0];
}
}
@ -276,18 +280,21 @@ class ProviderTopSites extends UrlbarProvider {
break;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: site.title,
keyword: site.title,
providesSearchMode: true,
engine: engine.name,
query: "",
icon: site.favicon,
isPinned: site.isPinned,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
title: site.title,
keyword: site.title,
providesSearchMode: true,
engine: engine.name,
query: "",
icon: site.favicon,
isPinned: site.isPinned,
}
)
);
addCallback(this, result);
break;
@ -325,7 +332,7 @@ class ProviderTopSites extends UrlbarProvider {
`urlbar_${site.position}`,
1
);
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
source: "urlbar",
tile_id: site.sponsoredTileId || -1,
@ -333,7 +340,7 @@ class ProviderTopSites extends UrlbarProvider {
reporting_url: site.sponsoredImpressionUrl,
advertiser: site.title.toLocaleLowerCase(),
},
CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_IMPRESSION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_IMPRESSION
);
}
}

Просмотреть файл

@ -13,19 +13,30 @@ const EXPORTED_SYMBOLS = ["UrlbarProviderUnitConversion"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
UnitConverterSimple: "resource:///modules/UnitConverterSimple.jsm",
UnitConverterTemperature: "resource:///modules/UnitConverterTemperature.jsm",
UnitConverterTimezone: "resource:///modules/UnitConverterTimezone.jsm",
const { UnitConverterSimple } = ChromeUtils.import(
"resource:///modules/UnitConverterSimple.jsm"
);
const { UnitConverterTemperature } = ChromeUtils.import(
"resource:///modules/UnitConverterTemperature.jsm"
);
const { UnitConverterTimezone } = ChromeUtils.import(
"resource:///modules/UnitConverterTimezone.jsm"
);
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
UrlbarView: "resource:///modules/UrlbarView.jsm",
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -75,8 +86,8 @@ const VIEW_TEMPLATE = {
class ProviderUnitConversion extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -106,7 +117,7 @@ class ProviderUnitConversion extends UrlbarProvider {
* Whether this provider should be invoked for the search.
*/
isActive({ searchString }) {
if (!UrlbarPrefs.get("unitConversion.enabled")) {
if (!lazy.UrlbarPrefs.get("unitConversion.enabled")) {
return false;
}
@ -154,7 +165,7 @@ class ProviderUnitConversion extends UrlbarProvider {
* The callback invoked by this method to add each result.
*/
startQuery(queryContext, addCallback) {
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -163,7 +174,9 @@ class ProviderUnitConversion extends UrlbarProvider {
input: queryContext.searchString,
}
);
result.suggestedIndex = UrlbarPrefs.get("unitConversion.suggestedIndex");
result.suggestedIndex = lazy.UrlbarPrefs.get(
"unitConversion.suggestedIndex"
);
addCallback(this, result);
}
@ -172,7 +185,7 @@ class ProviderUnitConversion extends UrlbarProvider {
const { textContent } = element.querySelector(
".urlbarView-dynamic-unitConversion-output"
);
ClipboardHelper.copyString(textContent);
lazy.ClipboardHelper.copyString(textContent);
}
}

Просмотреть файл

@ -14,7 +14,8 @@ var EXPORTED_SYMBOLS = ["UrlbarProvidersManager"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
@ -26,8 +27,8 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "ProvidersManager" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "ProvidersManager" })
);
// List of available local providers, each is implemented in its own jsm module
@ -117,19 +118,21 @@ class ProvidersManager {
* @param {object} provider
*/
registerProvider(provider) {
if (!provider || !(provider instanceof UrlbarProvider)) {
if (!provider || !(provider instanceof lazy.UrlbarProvider)) {
throw new Error(`Trying to register an invalid provider`);
}
if (!Object.values(UrlbarUtils.PROVIDER_TYPE).includes(provider.type)) {
if (
!Object.values(lazy.UrlbarUtils.PROVIDER_TYPE).includes(provider.type)
) {
throw new Error(`Unknown provider type ${provider.type}`);
}
logger.info(`Registering provider ${provider.name}`);
lazy.logger.info(`Registering provider ${provider.name}`);
let index = -1;
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
// Keep heuristic providers in order at the front of the array. Find the
// first non-heuristic provider and insert the new provider there.
index = this.providers.findIndex(
p => p.type != UrlbarUtils.PROVIDER_TYPE.HEURISTIC
p => p.type != lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC
);
}
if (index < 0) {
@ -143,7 +146,7 @@ class ProvidersManager {
* @param {object} provider
*/
unregisterProvider(provider) {
logger.info(`Unregistering provider ${provider.name}`);
lazy.logger.info(`Unregistering provider ${provider.name}`);
let index = this.providers.findIndex(p => p.name == provider.name);
if (index != -1) {
this.providers.splice(index, 1);
@ -164,10 +167,10 @@ class ProvidersManager {
* @param {object} muxer a UrlbarMuxer object
*/
registerMuxer(muxer) {
if (!muxer || !(muxer instanceof UrlbarMuxer)) {
if (!muxer || !(muxer instanceof lazy.UrlbarMuxer)) {
throw new Error(`Trying to register an invalid muxer`);
}
logger.info(`Registering muxer ${muxer.name}`);
lazy.logger.info(`Registering muxer ${muxer.name}`);
this.muxers.set(muxer.name, muxer);
}
@ -177,7 +180,7 @@ class ProvidersManager {
*/
unregisterMuxer(muxer) {
let muxerName = typeof muxer == "string" ? muxer : muxer.name;
logger.info(`Unregistering muxer ${muxerName}`);
lazy.logger.info(`Unregistering muxer ${muxerName}`);
this.muxers.delete(muxerName);
}
@ -187,11 +190,11 @@ class ProvidersManager {
* @param {object} [controller] a UrlbarController instance
*/
async startQuery(queryContext, controller = null) {
logger.info(`Query start ${queryContext.searchString}`);
lazy.logger.info(`Query start ${queryContext.searchString}`);
// Define the muxer to use.
let muxerName = queryContext.muxer || DEFAULT_MUXER;
logger.info(`Using muxer ${muxerName}`);
lazy.logger.info(`Using muxer ${muxerName}`);
let muxer = this.muxers.get(muxerName);
if (!muxer) {
throw new Error(`Muxer with name ${muxerName} not found`);
@ -204,7 +207,7 @@ class ProvidersManager {
: this.providers;
// Apply tokenization.
UrlbarTokenizer.tokenize(queryContext);
lazy.UrlbarTokenizer.tokenize(queryContext);
// If there's a single source, we are in restriction mode.
if (queryContext.sources && queryContext.sources.length == 1) {
@ -221,11 +224,11 @@ class ProvidersManager {
queryContext.restrictToken = restrictToken;
// If the restriction token has an equivalent source, then set it as
// restrictSource.
if (UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(restrictToken.value)) {
if (lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(restrictToken.value)) {
queryContext.restrictSource = queryContext.sources[0];
}
}
logger.debug(`Context sources ${queryContext.sources}`);
lazy.logger.debug(`Context sources ${queryContext.sources}`);
let query = new Query(queryContext, controller, muxer, providers);
this.queries.set(queryContext, query);
@ -233,7 +236,7 @@ class ProvidersManager {
// The muxer and many providers depend on the search service and our search
// utils. Make sure they're initialized now (via UrlbarSearchUtils) so that
// all query-related urlbar modules don't need to do it.
await UrlbarSearchUtils.init();
await lazy.UrlbarSearchUtils.init();
if (query.canceled) {
return;
}
@ -242,7 +245,7 @@ class ProvidersManager {
let updateBehaviorPromises = [];
for (let provider of this.providers) {
if (
provider.type == UrlbarUtils.PROVIDER_TYPE.EXTENSION &&
provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.EXTENSION &&
provider.name != "Omnibox"
) {
updateBehaviorPromises.push(
@ -265,7 +268,7 @@ class ProvidersManager {
* @param {object} queryContext
*/
cancelQuery(queryContext) {
logger.info(`Query cancel "${queryContext.searchString}"`);
lazy.logger.info(`Query cancel "${queryContext.searchString}"`);
let query = this.queries.get(queryContext);
if (!query) {
throw new Error("Couldn't find a matching query for the given context");
@ -273,7 +276,7 @@ class ProvidersManager {
query.cancel();
if (!this.interruptLevel) {
try {
let db = PlacesUtils.promiseLargeCacheDBConnection();
let db = lazy.PlacesUtils.promiseLargeCacheDBConnection();
db.interrupt();
} catch (ex) {}
}
@ -407,7 +410,7 @@ class Query {
}
}
})
.catch(ex => logger.error(ex))
.catch(ex => lazy.logger.error(ex))
);
}
@ -436,7 +439,7 @@ class Query {
let queryPromises = [];
for (let provider of activeProviders) {
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
this.context.pendingHeuristicProviders.add(provider.name);
queryPromises.push(startQuery(provider));
continue;
@ -445,9 +448,9 @@ class Query {
// Tracks the delay timer. We will fire (in this specific case, cancel
// would do the same, since the callback is empty) the timer when the
// search is canceled, unblocking start().
this._sleepTimer = new SkippableTimer({
this._sleepTimer = new lazy.SkippableTimer({
name: "Query provider timer",
time: UrlbarPrefs.get("delay"),
time: lazy.UrlbarPrefs.get("delay"),
logger: provider.logger,
});
}
@ -458,7 +461,7 @@ class Query {
);
}
logger.info(`Queried ${queryPromises.length} providers`);
lazy.logger.info(`Queried ${queryPromises.length} providers`);
await Promise.all(queryPromises);
// All the providers are done returning results, so we can stop chunking.
@ -494,13 +497,13 @@ class Query {
provider.tryMethod("cancelQuery", this.context);
}
if (this._heuristicProviderTimer) {
this._heuristicProviderTimer.cancel().catch(ex => logger.error(ex));
this._heuristicProviderTimer.cancel().catch(ex => lazy.logger.error(ex));
}
if (this._chunkTimer) {
this._chunkTimer.cancel().catch(ex => logger.error(ex));
this._chunkTimer.cancel().catch(ex => lazy.logger.error(ex));
}
if (this._sleepTimer) {
this._sleepTimer.fire().catch(ex => logger.error(ex));
this._sleepTimer.fire().catch(ex => lazy.logger.error(ex));
}
}
@ -510,7 +513,7 @@ class Query {
* @param {object} result
*/
add(provider, result) {
if (!(provider instanceof UrlbarProvider)) {
if (!(provider instanceof lazy.UrlbarProvider)) {
throw new Error("Invalid provider passed to the add callback");
}
@ -545,9 +548,9 @@ class Query {
!this.acceptableSources.includes(result.source) &&
!result.heuristic &&
// Treat form history as searches for the purpose of acceptableSources.
(result.type != UrlbarUtils.RESULT_TYPE.SEARCH ||
result.source != UrlbarUtils.RESULT_SOURCE.HISTORY ||
!this.acceptableSources.includes(UrlbarUtils.RESULT_SOURCE.SEARCH))
(result.type != lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.source != lazy.UrlbarUtils.RESULT_SOURCE.HISTORY ||
!this.acceptableSources.includes(lazy.UrlbarUtils.RESULT_SOURCE.SEARCH))
) {
return;
}
@ -555,11 +558,11 @@ class Query {
// Filter out javascript results for safety. The provider is supposed to do
// it, but we don't want to risk leaking these out.
if (
result.type != UrlbarUtils.RESULT_TYPE.KEYWORD &&
result.type != lazy.UrlbarUtils.RESULT_TYPE.KEYWORD &&
result.payload.url &&
result.payload.url.startsWith("javascript:") &&
!this.context.searchString.startsWith("javascript:") &&
UrlbarPrefs.get("filter.javascript")
lazy.UrlbarPrefs.get("filter.javascript")
) {
return;
}
@ -579,9 +582,9 @@ class Query {
// If the timer fires first, we stop waiting on the remaining heuristic
// providers.
// Both timers are used to reduce UI flicker.
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (!this._heuristicProviderTimer) {
this._heuristicProviderTimer = new SkippableTimer({
this._heuristicProviderTimer = new lazy.SkippableTimer({
name: "Heuristic provider timer",
callback: () => this._notifyResults(),
time: CHUNK_RESULTS_DELAY_MS,
@ -589,7 +592,7 @@ class Query {
});
}
} else if (!this._chunkTimer) {
this._chunkTimer = new SkippableTimer({
this._chunkTimer = new lazy.SkippableTimer({
name: "Query chunk timer",
callback: () => this._notifyResults(),
time: CHUNK_RESULTS_DELAY_MS,
@ -602,7 +605,7 @@ class Query {
this._heuristicProviderTimer &&
!this.context.pendingHeuristicProviders.size
) {
this._heuristicProviderTimer.fire().catch(ex => logger.error(ex));
this._heuristicProviderTimer.fire().catch(ex => lazy.logger.error(ex));
}
}
@ -610,12 +613,12 @@ class Query {
this.muxer.sort(this.context);
if (this._heuristicProviderTimer) {
this._heuristicProviderTimer.cancel().catch(ex => logger.error(ex));
this._heuristicProviderTimer.cancel().catch(ex => lazy.logger.error(ex));
this._heuristicProviderTimer = null;
}
if (this._chunkTimer) {
this._chunkTimer.cancel().catch(ex => logger.error(ex));
this._chunkTimer.cancel().catch(ex => lazy.logger.error(ex));
this._chunkTimer = null;
}
@ -631,7 +634,7 @@ class Query {
return;
}
this.context.firstResultChanged = !ObjectUtils.deepEqual(
this.context.firstResultChanged = !lazy.ObjectUtils.deepEqual(
this.context.firstResult,
this.context.results[0]
);
@ -657,52 +660,52 @@ function updateSourcesIfEmpty(context) {
// There can be only one restrict token per query.
let restrictToken = context.tokens.find(t =>
[
UrlbarTokenizer.TYPE.RESTRICT_HISTORY,
UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK,
UrlbarTokenizer.TYPE.RESTRICT_TAG,
UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE,
UrlbarTokenizer.TYPE.RESTRICT_SEARCH,
UrlbarTokenizer.TYPE.RESTRICT_TITLE,
UrlbarTokenizer.TYPE.RESTRICT_URL,
UrlbarTokenizer.TYPE.RESTRICT_ACTION,
lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY,
lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK,
lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG,
lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE,
lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH,
lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE,
lazy.UrlbarTokenizer.TYPE.RESTRICT_URL,
lazy.UrlbarTokenizer.TYPE.RESTRICT_ACTION,
].includes(t.type)
);
// RESTRICT_TITLE and RESTRICT_URL do not affect query sources.
let restrictTokenType =
restrictToken &&
restrictToken.type != UrlbarTokenizer.TYPE.RESTRICT_TITLE &&
restrictToken.type != UrlbarTokenizer.TYPE.RESTRICT_URL
restrictToken.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE &&
restrictToken.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_URL
? restrictToken.type
: undefined;
for (let source of Object.values(UrlbarUtils.RESULT_SOURCE)) {
for (let source of Object.values(lazy.UrlbarUtils.RESULT_SOURCE)) {
// Skip sources that the context doesn't care about.
if (context.sources && !context.sources.includes(source)) {
continue;
}
// Check prefs and restriction tokens.
switch (source) {
case UrlbarUtils.RESULT_SOURCE.BOOKMARKS:
case lazy.UrlbarUtils.RESULT_SOURCE.BOOKMARKS:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK ||
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_TAG ||
(!restrictTokenType && UrlbarPrefs.get("suggest.bookmark"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK ||
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.bookmark"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.HISTORY:
case lazy.UrlbarUtils.RESULT_SOURCE.HISTORY:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_HISTORY ||
(!restrictTokenType && UrlbarPrefs.get("suggest.history"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.history"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.SEARCH:
case lazy.UrlbarUtils.RESULT_SOURCE.SEARCH:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_SEARCH ||
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH ||
!restrictTokenType
) {
// We didn't check browser.urlbar.suggest.searches here, because it
@ -713,20 +716,20 @@ function updateSourcesIfEmpty(context) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.TABS:
case lazy.UrlbarUtils.RESULT_SOURCE.TABS:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE ||
(!restrictTokenType && UrlbarPrefs.get("suggest.openpage"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.openpage"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK:
case lazy.UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK:
if (!context.isPrivate && !restrictTokenType) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL:
case lazy.UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL:
default:
if (!restrictTokenType) {
acceptedSources.push(source);

Просмотреть файл

@ -11,9 +11,14 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const { EventEmitter } = ChromeUtils.import(
"resource://gre/modules/EventEmitter.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
EventEmitter: "resource://gre/modules/EventEmitter.jsm",
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
QUICK_SUGGEST_SOURCE: "resource:///modules/UrlbarProviderQuickSuggest.jsm",
RemoteSettings: "resource://services-settings/remote-settings.js",
@ -25,7 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
const log = console.createInstance({
prefix: "QuickSuggest",
maxLogLevel: UrlbarPrefs.get("quicksuggest.log") ? "All" : "Warn",
maxLogLevel: lazy.UrlbarPrefs.get("quicksuggest.log") ? "All" : "Warn",
});
const RS_COLLECTION = "quicksuggest";
@ -71,8 +76,8 @@ const ADD_RESULTS_CHUNK_SIZE = 1000;
*/
class QuickSuggest extends EventEmitter {
init() {
UrlbarPrefs.addObserver(this);
NimbusFeatures.urlbar.onUpdate(() => this._queueSettingsSetup());
lazy.UrlbarPrefs.addObserver(this);
lazy.NimbusFeatures.urlbar.onUpdate(() => this._queueSettingsSetup());
this._settingsTaskQueue.queue(() => {
return new Promise(resolve => {
@ -171,7 +176,7 @@ class QuickSuggest extends EventEmitter {
typeof result.score == "number"
? result.score
: DEFAULT_SUGGESTION_SCORE,
source: QUICK_SUGGEST_SOURCE.REMOTE_SETTINGS,
source: lazy.QUICK_SUGGEST_SOURCE.REMOTE_SETTINGS,
icon: icons.shift(),
position: result.position,
_test_is_best_match: result._test_is_best_match,
@ -190,7 +195,7 @@ class QuickSuggest extends EventEmitter {
if (!this._recordedExposureEvent) {
this._recordedExposureEvent = true;
Services.tm.idleDispatchToMainThread(() =>
NimbusFeatures.urlbar.recordExposureEvent({ once: true })
lazy.NimbusFeatures.urlbar.recordExposureEvent({ once: true })
);
}
}
@ -265,54 +270,54 @@ class QuickSuggest extends EventEmitter {
// The call to this method races scenario initialization on startup, and the
// Nimbus variables we rely on below depend on the scenario, so wait for it
// to be initialized.
await UrlbarPrefs.firefoxSuggestScenarioStartupPromise;
await lazy.UrlbarPrefs.firefoxSuggestScenarioStartupPromise;
// If the feature is disabled, the user has already seen the dialog, or the
// user has already opted in, don't show the onboarding.
if (
!UrlbarPrefs.get(FEATURE_AVAILABLE) ||
UrlbarPrefs.get(SEEN_DIALOG_PREF) ||
UrlbarPrefs.get("quicksuggest.dataCollection.enabled")
!lazy.UrlbarPrefs.get(FEATURE_AVAILABLE) ||
lazy.UrlbarPrefs.get(SEEN_DIALOG_PREF) ||
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled")
) {
return false;
}
// Wait a number of restarts before showing the dialog.
let restartsSeen = UrlbarPrefs.get(RESTARTS_PREF);
let restartsSeen = lazy.UrlbarPrefs.get(RESTARTS_PREF);
if (
restartsSeen <
UrlbarPrefs.get("quickSuggestShowOnboardingDialogAfterNRestarts")
lazy.UrlbarPrefs.get("quickSuggestShowOnboardingDialogAfterNRestarts")
) {
UrlbarPrefs.set(RESTARTS_PREF, restartsSeen + 1);
lazy.UrlbarPrefs.set(RESTARTS_PREF, restartsSeen + 1);
return false;
}
let win = BrowserWindowTracker.getTopWindow();
let win = lazy.BrowserWindowTracker.getTopWindow();
// Don't show the dialog on top of about:welcome for new users.
if (win.gBrowser?.currentURI?.spec == "about:welcome") {
return false;
}
if (UrlbarPrefs.get("experimentType") === "modal") {
if (lazy.UrlbarPrefs.get("experimentType") === "modal") {
this.ensureExposureEventRecorded();
}
if (!UrlbarPrefs.get("quickSuggestShouldShowOnboardingDialog")) {
if (!lazy.UrlbarPrefs.get("quickSuggestShouldShowOnboardingDialog")) {
return false;
}
let variationType;
try {
// An error happens if the pref is not in user prefs.
variationType = UrlbarPrefs.get(DIALOG_VARIATION_PREF).toLowerCase();
variationType = lazy.UrlbarPrefs.get(DIALOG_VARIATION_PREF).toLowerCase();
} catch (e) {}
let params = { choice: undefined, variationType, visitedMain: false };
await win.gDialogBox.open(ONBOARDING_URI, params);
UrlbarPrefs.set(SEEN_DIALOG_PREF, true);
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(SEEN_DIALOG_PREF, true);
lazy.UrlbarPrefs.set(
DIALOG_VERSION_PREF,
JSON.stringify({ version: 1, variation: variationType })
);
@ -321,12 +326,12 @@ class QuickSuggest extends EventEmitter {
// so it will retain its user-branch value regardless of what the particular
// default was at the time.
let optedIn = params.choice == ONBOARDING_CHOICE.ACCEPT_2;
UrlbarPrefs.set("quicksuggest.dataCollection.enabled", optedIn);
lazy.UrlbarPrefs.set("quicksuggest.dataCollection.enabled", optedIn);
switch (params.choice) {
case ONBOARDING_CHOICE.LEARN_MORE_1:
case ONBOARDING_CHOICE.LEARN_MORE_2:
win.openTrustedLinkIn(UrlbarProviderQuickSuggest.helpUrl, "tab", {
win.openTrustedLinkIn(lazy.UrlbarProviderQuickSuggest.helpUrl, "tab", {
fromChrome: true,
});
break;
@ -343,7 +348,7 @@ class QuickSuggest extends EventEmitter {
break;
}
UrlbarPrefs.set("quicksuggest.onboardingDialogChoice", params.choice);
lazy.UrlbarPrefs.set("quicksuggest.onboardingDialogChoice", params.choice);
Services.telemetry.recordEvent(
"contextservices.quicksuggest",
@ -380,7 +385,7 @@ class QuickSuggest extends EventEmitter {
// overlap, and happen only one at a time. It also lets clients, especially
// tests, use this class without having to worry about whether a settings sync
// or initialization is ongoing; see `readyPromise`.
_settingsTaskQueue = new TaskQueue();
_settingsTaskQueue = new lazy.TaskQueue();
// Configuration data synced from remote settings. See the `config` getter.
_config = {};
@ -404,12 +409,12 @@ class QuickSuggest extends EventEmitter {
_queueSettingsSetup() {
this._settingsTaskQueue.queue(() => {
let enabled =
UrlbarPrefs.get(FEATURE_AVAILABLE) &&
(UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
UrlbarPrefs.get("suggest.quicksuggest.sponsored"));
lazy.UrlbarPrefs.get(FEATURE_AVAILABLE) &&
(lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored"));
if (enabled && !this._rs) {
this._onSettingsSync = (...args) => this._queueSettingsSync(...args);
this._rs = RemoteSettings(RS_COLLECTION);
this._rs = lazy.RemoteSettings(RS_COLLECTION);
this._rs.on("sync", this._onSettingsSync);
} else if (!enabled && this._rs) {
this._rs.off("sync", this._onSettingsSync);
@ -443,7 +448,7 @@ class QuickSuggest extends EventEmitter {
);
}
let dataType = UrlbarPrefs.get("quickSuggestRemoteSettingsDataType");
let dataType = lazy.UrlbarPrefs.get("quickSuggestRemoteSettingsDataType");
log.debug("Loading data with type:", dataType);
let [configArray, data] = await Promise.all([

Просмотреть файл

@ -17,7 +17,8 @@ var EXPORTED_SYMBOLS = ["UrlbarResult"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
JsonSchemaValidator:
"resource://gre/modules/components-utils/JsonSchemaValidator.jsm",
@ -45,14 +46,14 @@ class UrlbarResult {
constructor(resultType, resultSource, payload, payloadHighlights = {}) {
// Type describes the payload and visualization that should be used for
// this result.
if (!Object.values(UrlbarUtils.RESULT_TYPE).includes(resultType)) {
if (!Object.values(lazy.UrlbarUtils.RESULT_TYPE).includes(resultType)) {
throw new Error("Invalid result type");
}
this.type = resultType;
// Source describes which data has been used to derive this result. In case
// multiple sources are involved, use the more privacy restricted.
if (!Object.values(UrlbarUtils.RESULT_SOURCE).includes(resultSource)) {
if (!Object.values(lazy.UrlbarUtils.RESULT_SOURCE).includes(resultSource)) {
throw new Error("Invalid result source");
}
this.source = resultSource;
@ -108,11 +109,11 @@ class UrlbarResult {
*/
get _titleAndHighlights() {
switch (this.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case UrlbarUtils.RESULT_TYPE.URL:
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.URL:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
if (this.payload.qsSuggestion) {
return [
// We will initially only be targetting en-US users with this experiment
@ -124,7 +125,7 @@ class UrlbarResult {
return this.payload.title
? [this.payload.title, this.payloadHighlights.title]
: [this.payload.url || "", this.payloadHighlights.url || []];
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
if (this.payload.providesSearchMode) {
return ["", []];
}
@ -165,14 +166,14 @@ class UrlbarResult {
* @returns {object} `payload` if it's valid.
*/
validatePayload(payload) {
let schema = UrlbarUtils.getPayloadSchema(this.type);
let schema = lazy.UrlbarUtils.getPayloadSchema(this.type);
if (!schema) {
throw new Error(`Unrecognized result type: ${this.type}`);
}
let result = JsonSchemaValidator.validate(payload, schema, {
let result = lazy.JsonSchemaValidator.validate(payload, schema, {
allowExplicitUndefinedProperties: true,
allowNullAsUndefinedProperties: true,
allowExtraProperties: this.type == UrlbarUtils.RESULT_TYPE.DYNAMIC,
allowExtraProperties: this.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC,
});
if (!result.valid) {
throw result.error;
@ -227,7 +228,7 @@ class UrlbarResult {
// have a domain.
payloadInfo.title = payloadInfo.title || [
"",
UrlbarUtils.HIGHLIGHT.TYPED,
lazy.UrlbarUtils.HIGHLIGHT.TYPED,
];
try {
payloadInfo.title[0] = new URL(payloadInfo.url[0]).host;
@ -238,8 +239,8 @@ class UrlbarResult {
// For display purposes we need to unescape the url.
payloadInfo.displayUrl = [...payloadInfo.url];
let url = payloadInfo.displayUrl[0];
if (url && UrlbarPrefs.get("trimURLs")) {
url = BrowserUIUtils.removeSingleTrailingSlashFromURL(url);
if (url && lazy.UrlbarPrefs.get("trimURLs")) {
url = lazy.BrowserUIUtils.removeSingleTrailingSlashFromURL(url);
if (url.startsWith("https://")) {
url = url.substring(8);
if (url.startsWith("www.")) {
@ -247,7 +248,7 @@ class UrlbarResult {
}
}
}
payloadInfo.displayUrl[0] = UrlbarUtils.unEscapeURIForUI(url);
payloadInfo.displayUrl[0] = lazy.UrlbarUtils.unEscapeURIForUI(url);
}
// For performance reasons limit excessive string lengths, to reduce the
@ -256,7 +257,10 @@ class UrlbarResult {
for (let prop of ["displayUrl", "title", "suggestion"]) {
let val = payloadInfo[prop]?.[0];
if (typeof val == "string") {
payloadInfo[prop][0] = val.substring(0, UrlbarUtils.MAX_TEXT_LENGTH);
payloadInfo[prop][0] = val.substring(
0,
lazy.UrlbarUtils.MAX_TEXT_LENGTH
);
}
}
@ -269,9 +273,9 @@ class UrlbarResult {
entries.reduce((highlights, [name, [val, highlightType]]) => {
if (highlightType) {
highlights[name] = !Array.isArray(val)
? UrlbarUtils.getTokenMatches(tokens, val || "", highlightType)
? lazy.UrlbarUtils.getTokenMatches(tokens, val || "", highlightType)
: val.map(subval =>
UrlbarUtils.getTokenMatches(tokens, subval, highlightType)
lazy.UrlbarUtils.getTokenMatches(tokens, subval, highlightType)
);
}
return highlights;

Просмотреть файл

@ -10,8 +10,14 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
SearchOneOffs: "resource:///modules/SearchOneOffs.jsm",
const { SearchOneOffs } = ChromeUtils.import(
"resource:///modules/SearchOneOffs.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
@ -30,7 +36,7 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
super(view.panel.querySelector(".search-one-offs"));
this.view = view;
this.input = view.input;
UrlbarPrefs.addObserver(this);
lazy.UrlbarPrefs.addObserver(this);
// Override the SearchOneOffs.jsm value for the Address Bar.
this.disableOneOffsHorizontalKeyNavigation = true;
this._webEngines = [];
@ -195,7 +201,7 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
let startQueryParams = {
allowAutofill:
!searchMode.engineName &&
searchMode.source != UrlbarUtils.RESULT_SOURCE.SEARCH,
searchMode.source != lazy.UrlbarUtils.RESULT_SOURCE.SEARCH,
event,
};
@ -294,7 +300,11 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
// We need to call super.willHide() even when we return false below because
// it has the necessary side effect of creating this._engineInfo.
let superWillHide = await super.willHide();
if (UrlbarUtils.LOCAL_SEARCH_MODES.some(m => UrlbarPrefs.get(m.pref))) {
if (
lazy.UrlbarUtils.LOCAL_SEARCH_MODES.some(m =>
lazy.UrlbarPrefs.get(m.pref)
)
) {
return false;
}
return superWillHide;
@ -311,7 +321,9 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
// Invalidate the engine cache when the local-one-offs-related prefs change
// so that the one-offs rebuild themselves the next time the view opens.
if (
[...UrlbarUtils.LOCAL_SEARCH_MODES.map(m => m.pref)].includes(changedPref)
[...lazy.UrlbarUtils.LOCAL_SEARCH_MODES.map(m => m.pref)].includes(
changedPref
)
) {
this.invalidateCache();
}
@ -337,11 +349,12 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
_rebuildEngineList(engines, addEngines) {
super._rebuildEngineList(engines, addEngines);
for (let { source, pref, restrict } of UrlbarUtils.LOCAL_SEARCH_MODES) {
if (!UrlbarPrefs.get(pref)) {
for (let { source, pref, restrict } of lazy.UrlbarUtils
.LOCAL_SEARCH_MODES) {
if (!lazy.UrlbarPrefs.get(pref)) {
continue;
}
let name = UrlbarUtils.getResultSourceName(source);
let name = lazy.UrlbarUtils.getResultSourceName(source);
let button = this.document.createXULElement("button");
button.id = `urlbar-engine-one-off-item-${name}`;
button.setAttribute("class", "searchbar-engine-one-off-item");

Просмотреть файл

@ -18,7 +18,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
@ -161,10 +163,10 @@ class SearchUtils {
await Promise.all([this.init(), this._refreshEnginesByAliasPromise]);
let engine = this._enginesByAlias.get(alias.toLocaleLowerCase());
if (engine && searchString) {
let query = UrlbarUtils.substringAfter(searchString, alias);
let query = lazy.UrlbarUtils.substringAfter(searchString, alias);
// Match an alias only when it has a space after it. If there's no trailing
// space, then continue to treat it as part of the search string.
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
}
@ -254,7 +256,8 @@ class SearchUtils {
scalarKey = searchMode.engineName;
}
} else if (searchMode.source) {
scalarKey = UrlbarUtils.getResultSourceName(searchMode.source) || "other";
scalarKey =
lazy.UrlbarUtils.getResultSourceName(searchMode.source) || "other";
}
return scalarKey;

Просмотреть файл

@ -16,12 +16,13 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "Tokenizer" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "Tokenizer" })
);
var UrlbarTokenizer = {
@ -127,7 +128,7 @@ var UrlbarTokenizer = {
}
let path = slashIndex != -1 ? token.slice(slashIndex) : "";
logger.debug("path", path);
lazy.logger.debug("path", path);
if (requirePath && !path) {
return false;
}
@ -196,8 +197,8 @@ var UrlbarTokenizer = {
let userinfo = atIndex != -1 ? token.slice(0, atIndex) : "";
let hostPort = atIndex != -1 ? token.slice(atIndex + 1) : token;
let hasPort = this.REGEXP_HAS_PORT.test(hostPort);
logger.debug("userinfo", userinfo);
logger.debug("hostPort", hostPort);
lazy.logger.debug("userinfo", userinfo);
lazy.logger.debug("hostPort", hostPort);
if (noPort && hasPort) {
return false;
}
@ -241,7 +242,7 @@ var UrlbarTokenizer = {
* tokens property.
*/
tokenize(queryContext) {
logger.info("Tokenizing", queryContext);
lazy.logger.info("Tokenizing", queryContext);
if (!queryContext.trimmedSearchString) {
queryContext.tokens = [];
return queryContext;
@ -407,6 +408,6 @@ function filterTokens(tokens) {
}
}
logger.info("Filtered Tokens", tokens);
lazy.logger.info("Filtered Tokens", tokens);
return filtered;
}

Просмотреть файл

@ -23,7 +23,8 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
FormHistory: "resource://gre/modules/FormHistory.jsm",
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
@ -219,25 +220,25 @@ var UrlbarUtils = {
return [
{
source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
restrict: UrlbarTokenizer.RESTRICT.BOOKMARK,
restrict: lazy.UrlbarTokenizer.RESTRICT.BOOKMARK,
icon: "chrome://browser/skin/bookmark.svg",
pref: "shortcuts.bookmarks",
},
{
source: UrlbarUtils.RESULT_SOURCE.TABS,
restrict: UrlbarTokenizer.RESTRICT.OPENPAGE,
restrict: lazy.UrlbarTokenizer.RESTRICT.OPENPAGE,
icon: "chrome://browser/skin/tab.svg",
pref: "shortcuts.tabs",
},
{
source: UrlbarUtils.RESULT_SOURCE.HISTORY,
restrict: UrlbarTokenizer.RESTRICT.HISTORY,
restrict: lazy.UrlbarTokenizer.RESTRICT.HISTORY,
icon: "chrome://browser/skin/history.svg",
pref: "shortcuts.history",
},
{
source: UrlbarUtils.RESULT_SOURCE.ACTIONS,
restrict: UrlbarTokenizer.RESTRICT.ACTION,
restrict: lazy.UrlbarTokenizer.RESTRICT.ACTION,
icon: "chrome://devtools/skin/images/command-console.svg",
pref: "shortcuts.quickactions",
},
@ -263,13 +264,13 @@ var UrlbarUtils = {
*/
addToUrlbarHistory(url, window) {
if (
!PrivateBrowsingUtils.isWindowPrivate(window) &&
!lazy.PrivateBrowsingUtils.isWindowPrivate(window) &&
url &&
!url.includes(" ") &&
// eslint-disable-next-line no-control-regex
!/[\x00-\x1F]/.test(url)
) {
PlacesUIUtils.markPageAsTyped(url);
lazy.PlacesUIUtils.markPageAsTyped(url);
}
},
@ -308,7 +309,7 @@ var UrlbarUtils = {
// from the location bar.
let entry = null;
try {
entry = await PlacesUtils.keywords.fetch(keyword);
entry = await lazy.PlacesUtils.keywords.fetch(keyword);
} catch (ex) {
Cu.reportError(`Unable to fetch Places keyword "${keyword}": ${ex}`);
}
@ -318,7 +319,7 @@ var UrlbarUtils = {
}
try {
[url, postData] = await KeywordUtils.parseUrlAndPostData(
[url, postData] = await lazy.KeywordUtils.parseUrlAndPostData(
entry.url.href,
entry.postData,
param
@ -698,9 +699,10 @@ var UrlbarUtils = {
* setSearchMode documentation for details.
*/
searchModeForToken(token) {
if (token == UrlbarTokenizer.RESTRICT.SEARCH) {
if (token == lazy.UrlbarTokenizer.RESTRICT.SEARCH) {
return {
engineName: UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
engineName: lazy.UrlbarSearchUtils.getDefaultEngine(this.isPrivate)
.name,
};
}
@ -722,7 +724,7 @@ var UrlbarUtils = {
* initialized, it will be a no-op.
*/
setupSpeculativeConnection(urlOrEngine, window) {
if (!UrlbarPrefs.get("speculativeConnect.enabled")) {
if (!lazy.UrlbarPrefs.get("speculativeConnect.enabled")) {
return;
}
if (urlOrEngine instanceof Ci.nsISearchEngine) {
@ -860,7 +862,7 @@ var UrlbarUtils = {
},
async addToInputHistory(url, input) {
await PlacesUtils.withConnectionWrapper("addToInputHistory", db => {
await lazy.PlacesUtils.withConnectionWrapper("addToInputHistory", db => {
// use_count will asymptotically approach the max of 10.
return db.executeCached(
`
@ -944,7 +946,7 @@ var UrlbarUtils = {
* then [prefix, remainder]. Otherwise, ["", str].
*/
stripURLPrefix(str) {
let match = UrlbarTokenizer.REGEXP_PREFIX.exec(str);
let match = lazy.UrlbarTokenizer.REGEXP_PREFIX.exec(str);
if (!match) {
return ["", str];
}
@ -973,7 +975,7 @@ var UrlbarUtils = {
*/
async getHeuristicResultFor(
searchString,
window = BrowserWindowTracker.getTopWindow()
window = lazy.BrowserWindowTracker.getTopWindow()
) {
if (!searchString) {
throw new Error("Must pass a non-null search string");
@ -981,7 +983,7 @@ var UrlbarUtils = {
let options = {
allowAutofill: false,
isPrivate: PrivateBrowsingUtils.isWindowPrivate(window),
isPrivate: lazy.PrivateBrowsingUtils.isWindowPrivate(window),
maxResults: 1,
searchString,
userContextId: window.gBrowser.selectedBrowser.getAttribute(
@ -998,7 +1000,7 @@ var UrlbarUtils = {
}
}
let context = new UrlbarQueryContext(options);
await UrlbarProvidersManager.startQuery(context);
await lazy.UrlbarProvidersManager.startQuery(context);
if (!context.heuristicResult) {
throw new Error("There should always be an heuristic result");
}
@ -1014,17 +1016,17 @@ var UrlbarUtils = {
*/
getLogger({ prefix = "" } = {}) {
if (!this._logger) {
this._logger = Log.repository.getLogger("urlbar");
this._logger = lazy.Log.repository.getLogger("urlbar");
this._logger.manageLevelFromPref("browser.urlbar.loglevel");
this._logger.addAppender(
new Log.ConsoleAppender(new Log.BasicFormatter())
new lazy.Log.ConsoleAppender(new lazy.Log.BasicFormatter())
);
}
if (prefix) {
// This is not an early return because it is necessary to invoke getLogger
// at least once before getLoggerWithMessagePrefix; it replaces a
// method of the original logger, rather than using an actual Proxy.
return Log.repository.getLoggerWithMessagePrefix(
return lazy.Log.repository.getLoggerWithMessagePrefix(
"urlbar",
prefix + " :: "
);
@ -1068,12 +1070,13 @@ var UrlbarUtils = {
if (
!value ||
input.isPrivate ||
value.length > SearchSuggestionController.SEARCH_HISTORY_MAX_VALUE_LENGTH
value.length >
lazy.SearchSuggestionController.SEARCH_HISTORY_MAX_VALUE_LENGTH
) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
FormHistory.update(
lazy.FormHistory.update(
{
op: "bump",
fieldname: input.formHistoryName,
@ -1113,10 +1116,10 @@ var UrlbarUtils = {
// Create `URL` objects to make the logic below easier. The strings must
// include schemes for this to work.
if (!UrlbarTokenizer.REGEXP_PREFIX.test(url)) {
if (!lazy.UrlbarTokenizer.REGEXP_PREFIX.test(url)) {
url = "http://" + url;
}
if (!UrlbarTokenizer.REGEXP_PREFIX.test(candidate)) {
if (!lazy.UrlbarTokenizer.REGEXP_PREFIX.test(candidate)) {
candidate = "http://" + candidate;
}
try {
@ -1236,7 +1239,7 @@ var UrlbarUtils = {
};
XPCOMUtils.defineLazyGetter(UrlbarUtils.ICON, "DEFAULT", () => {
return PlacesUtils.favicons.defaultFavicon.spec;
return lazy.PlacesUtils.favicons.defaultFavicon.spec;
});
XPCOMUtils.defineLazyGetter(UrlbarUtils, "strings", () => {
@ -1726,7 +1729,7 @@ class UrlbarQueryContext {
// mozilla.o, because the fixup check below can't validate them.
if (
this.tokens.length == 1 &&
this.tokens[0].type == UrlbarTokenizer.TYPE.POSSIBLE_ORIGIN
this.tokens[0].type == lazy.UrlbarTokenizer.TYPE.POSSIBLE_ORIGIN
) {
return false;
}

Просмотреть файл

@ -11,7 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
@ -148,7 +150,7 @@ class UrlbarValueFormatter {
let flags =
Services.uriFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |
Services.uriFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;
if (PrivateBrowsingUtils.isWindowPrivate(this.window)) {
if (lazy.PrivateBrowsingUtils.isWindowPrivate(this.window)) {
flags |= Services.uriFixup.FIXUP_FLAG_PRIVATE_CONTEXT;
}
let uriInfo;
@ -262,7 +264,7 @@ class UrlbarValueFormatter {
url,
} = urlMetaData;
// We strip http, so we should not show the scheme box for it.
if (!UrlbarPrefs.get("trimURLs") || schemeWSlashes != "http://") {
if (!lazy.UrlbarPrefs.get("trimURLs") || schemeWSlashes != "http://") {
this.scheme.value = schemeWSlashes;
this.inputField.style.setProperty(
"--urlbar-scheme-size",
@ -272,7 +274,7 @@ class UrlbarValueFormatter {
this._ensureFormattedHostVisible(urlMetaData);
if (!UrlbarPrefs.get("formatting.enabled")) {
if (!lazy.UrlbarPrefs.get("formatting.enabled")) {
return false;
}
@ -369,7 +371,7 @@ class UrlbarValueFormatter {
* True if formatting was applied and false if not.
*/
_formatSearchAlias() {
if (!UrlbarPrefs.get("formatting.enabled")) {
if (!lazy.UrlbarPrefs.get("formatting.enabled")) {
return false;
}
@ -459,7 +461,7 @@ class UrlbarValueFormatter {
if (
this._selectedResult &&
this._selectedResult.type == UrlbarUtils.RESULT_TYPE.SEARCH
this._selectedResult.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH
) {
return this._selectedResult.payload.keyword || null;
}

Просмотреть файл

@ -10,7 +10,8 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
L10nCache: "resource:///modules/UrlbarUtils.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
@ -23,7 +24,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"styleSheetService",
"@mozilla.org/content/style-sheet-service;1",
"nsIStyleSheetService"
@ -83,7 +84,7 @@ class UrlbarView {
this._queryContextCache = new QueryContextCache(5);
// We cache l10n strings to avoid Fluent's async lookup.
this._l10nCache = new L10nCache(this.document.l10n);
this._l10nCache = new lazy.L10nCache(this.document.l10n);
for (let viewTemplate of UrlbarView.dynamicViewTemplatesByName.values()) {
if (viewTemplate.stylesheet) {
@ -94,7 +95,7 @@ class UrlbarView {
get oneOffSearchButtons() {
if (!this._oneOffSearchButtons) {
this._oneOffSearchButtons = new UrlbarSearchOneOffs(this);
this._oneOffSearchButtons = new lazy.UrlbarSearchOneOffs(this);
this._oneOffSearchButtons.addEventListener(
"SelectedOneOffButtonChanged",
this
@ -355,7 +356,7 @@ class UrlbarView {
selectedElt?.result?.providerName == "TabToSearch" &&
!this._announceTabToSearchOnSelection &&
userPressedTab &&
UrlbarPrefs.get("accessibility.tabToSearch.announceResults");
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults");
if (skipAnnouncement) {
// Once we skip setting aria-activedescendant once, we should not skip
// it again if the user returns to that result.
@ -655,7 +656,7 @@ class UrlbarView {
queryContext.trimmedSearchString) &&
queryContext.trimmedSearchString[0] != "@" &&
(queryContext.trimmedSearchString[0] !=
UrlbarTokenizer.RESTRICT.SEARCH ||
lazy.UrlbarTokenizer.RESTRICT.SEARCH ||
queryContext.trimmedSearchString.length != 1)
);
}
@ -692,7 +693,7 @@ class UrlbarView {
let secondResult = queryContext.results[1];
if (
secondResult?.providerName == "TabToSearch" &&
UrlbarPrefs.get("accessibility.tabToSearch.announceResults") &&
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults") &&
this._previousTabToSearchEngine != secondResult.payload.engine
) {
let engine = secondResult.payload.engine;
@ -847,7 +848,7 @@ class UrlbarView {
static addDynamicViewTemplate(name, viewTemplate) {
this.dynamicViewTemplatesByName.set(name, viewTemplate);
if (viewTemplate.stylesheet) {
for (let window of BrowserWindowTracker.orderedWindows) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
addDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
@ -867,7 +868,7 @@ class UrlbarView {
}
this.dynamicViewTemplatesByName.delete(name);
if (viewTemplate.stylesheet) {
for (let window of BrowserWindowTracker.orderedWindows) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
removeDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
@ -906,8 +907,8 @@ class UrlbarView {
throw new Error("A heuristic result must be given");
}
return (
!UrlbarPrefs.get("experimental.hideHeuristic") ||
result.type == UrlbarUtils.RESULT_TYPE.TIP
!lazy.UrlbarPrefs.get("experimental.hideHeuristic") ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP
);
}
@ -919,7 +920,7 @@ class UrlbarView {
_resultIsSearchSuggestion(result) {
return Boolean(
result &&
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.suggestion
);
}
@ -994,7 +995,7 @@ class UrlbarView {
) {
let row = this._rows.children[rowIndex];
if (this._isElementVisible(row)) {
visibleSpanCount += UrlbarUtils.getSpanForResult(row.result);
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
// Continue updating rows as long as we haven't encountered a new
// suggestedIndex result that couldn't replace a current result.
@ -1026,7 +1027,7 @@ class UrlbarView {
let row = this._rows.children[rowIndex];
row.setAttribute("stale", "true");
if (this._isElementVisible(row)) {
visibleSpanCount += UrlbarUtils.getSpanForResult(row.result);
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
}
@ -1061,7 +1062,7 @@ class UrlbarView {
}
}
let newVisibleSpanCount =
visibleSpanCount + UrlbarUtils.getSpanForResult(result);
visibleSpanCount + lazy.UrlbarUtils.getSpanForResult(result);
if (
newVisibleSpanCount <= queryContext.maxResults &&
!seenMisplacedResult
@ -1155,7 +1156,7 @@ class UrlbarView {
// only when necessary.
if (
result.providerName == "UrlbarProviderQuickSuggest" &&
UrlbarPrefs.get("quickSuggestBlockingEnabled")
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled")
) {
this._addRowButton(item, "block", "firefox-suggest-urlbar-block");
}
@ -1209,7 +1210,7 @@ class UrlbarView {
_createRowContentForDynamicType(item, result) {
let { dynamicType } = result.payload;
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewTemplate =
provider.getViewTemplate?.(result) ||
UrlbarView.dynamicViewTemplatesByName.get(dynamicType);
@ -1297,7 +1298,7 @@ class UrlbarView {
body.appendChild(bottom);
item._elements.set("bottom", bottom);
if (UrlbarPrefs.get("bestMatchBlockingEnabled")) {
if (lazy.UrlbarPrefs.get("bestMatchBlockingEnabled")) {
this._addRowButton(item, "block", "firefox-suggest-urlbar-block");
}
if (result.payload.helpUrl) {
@ -1335,19 +1336,19 @@ class UrlbarView {
_updateRow(item, result) {
let oldResult = item.result;
let oldResultType = item.result && item.result.type;
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
item.result = result;
item.removeAttribute("stale");
item.id = getUniqueId("urlbarView-row-");
let needsNewContent =
oldResultType === undefined ||
(oldResultType == UrlbarUtils.RESULT_TYPE.TIP) !=
(result.type == UrlbarUtils.RESULT_TYPE.TIP) ||
(oldResultType == UrlbarUtils.RESULT_TYPE.DYNAMIC) !=
(result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) ||
(oldResultType == UrlbarUtils.RESULT_TYPE.DYNAMIC &&
result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC &&
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.TIP) !=
(result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) !=
(result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
oldResult.payload.dynamicType != result.payload.dynamicType) ||
// Dynamic results that implement getViewTemplate will
// always need updating.
@ -1355,11 +1356,11 @@ class UrlbarView {
oldResult.isBestMatch != result.isBestMatch ||
!!result.payload.helpUrl != item._buttons.has("help") ||
(result.isBestMatch &&
UrlbarPrefs.get("bestMatchBlockingEnabled") !=
lazy.UrlbarPrefs.get("bestMatchBlockingEnabled") !=
item._buttons.has("block")) ||
(!result.isBestMatch &&
result.providerName == "UrlbarProviderQuickSuggest" &&
UrlbarPrefs.get("quickSuggestBlockingEnabled") !=
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled") !=
item._buttons.has("block"));
if (needsNewContent) {
@ -1372,9 +1373,9 @@ class UrlbarView {
item._content.className = "urlbarView-row-inner";
item.appendChild(item._content);
item.removeAttribute("dynamicType");
if (item.result.type == UrlbarUtils.RESULT_TYPE.TIP) {
if (item.result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) {
this._createRowContentForTip(item);
} else if (item.result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) {
} else if (item.result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
this._createRowContentForDynamicType(item, result);
} else if (item.result.isBestMatch) {
this._createRowContentForBestMatch(item, result);
@ -1385,22 +1386,22 @@ class UrlbarView {
item._content.id = item.id + "-inner";
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
!result.payload.providesSearchMode &&
!result.payload.inPrivateWindow
) {
item.setAttribute("type", "search");
} else if (result.type == UrlbarUtils.RESULT_TYPE.REMOTE_TAB) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB) {
item.setAttribute("type", "remotetab");
} else if (result.type == UrlbarUtils.RESULT_TYPE.TAB_SWITCH) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH) {
item.setAttribute("type", "switchtab");
} else if (result.type == UrlbarUtils.RESULT_TYPE.TIP) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) {
item.setAttribute("type", "tip");
this._updateRowForTip(item, result);
return;
} else if (result.source == UrlbarUtils.RESULT_SOURCE.BOOKMARKS) {
} else if (result.source == lazy.UrlbarUtils.RESULT_SOURCE.BOOKMARKS) {
item.setAttribute("type", "bookmark");
} else if (result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
item.setAttribute("type", "dynamic");
this._updateRowForDynamicType(item, result);
return;
@ -1416,12 +1417,12 @@ class UrlbarView {
let favicon = item._elements.get("favicon");
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD
) {
favicon.src = this._iconForResult(result);
} else {
favicon.src = result.payload.icon || UrlbarUtils.ICON.DEFAULT;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.DEFAULT;
}
let title = item._elements.get("title");
@ -1463,7 +1464,7 @@ class UrlbarView {
let isVisitAction = false;
let setURL = false;
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
actionSetter = () => {
this._setElementL10n(action, {
id: "urlbar-result-action-switch-tab",
@ -1471,14 +1472,14 @@ class UrlbarView {
};
setURL = true;
break;
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
actionSetter = () => {
this._removeElementL10n(action);
action.textContent = result.payload.device;
};
setURL = true;
break;
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
if (result.payload.inPrivateWindow) {
if (result.payload.isPrivateEngine) {
actionSetter = () => {
@ -1512,10 +1513,10 @@ class UrlbarView {
};
}
break;
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
isVisitAction = result.payload.input.trim() == result.payload.keyword;
break;
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
actionSetter = () => {
this._removeElementL10n(action);
action.textContent = result.payload.content;
@ -1544,7 +1545,7 @@ class UrlbarView {
if (
result.payload.isSponsored &&
result.type != UrlbarUtils.RESULT_TYPE.TAB_SWITCH
result.type != lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH
) {
item.toggleAttribute("sponsored", true);
actionSetter = () => {
@ -1618,22 +1619,22 @@ class UrlbarView {
_iconForResult(result, iconUrlOverride = null) {
return (
(result.source == UrlbarUtils.RESULT_SOURCE.HISTORY &&
(result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
UrlbarUtils.ICON.HISTORY) ||
(result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY &&
(result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD) &&
lazy.UrlbarUtils.ICON.HISTORY) ||
iconUrlOverride ||
result.payload.icon ||
((result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
UrlbarUtils.ICON.SEARCH_GLASS) ||
UrlbarUtils.ICON.DEFAULT
((result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD) &&
lazy.UrlbarUtils.ICON.SEARCH_GLASS) ||
lazy.UrlbarUtils.ICON.DEFAULT
);
}
_updateRowForTip(item, result) {
let favicon = item._elements.get("favicon");
favicon.src = result.payload.icon || UrlbarUtils.ICON.TIP;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.TIP;
favicon.id = item.id + "-icon";
let title = item._elements.get("title");
@ -1701,7 +1702,7 @@ class UrlbarView {
}
// Get the view update from the result's provider.
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewUpdate = await provider.getViewUpdate(result, idsByName);
// Update each node in the view by name.
@ -1822,7 +1823,7 @@ class UrlbarView {
if (visible) {
label = this._rowLabel(item, currentLabel);
if (label) {
if (ObjectUtils.deepEqual(label, currentLabel)) {
if (lazy.ObjectUtils.deepEqual(label, currentLabel)) {
label = null;
} else {
currentLabel = label;
@ -1873,7 +1874,7 @@ class UrlbarView {
_rowLabel(row, currentLabel) {
// Labels aren't shown for top sites, i.e., when the search string is empty.
if (
UrlbarPrefs.get("groupLabels.enabled") &&
lazy.UrlbarPrefs.get("groupLabels.enabled") &&
this._queryContext?.searchString &&
!row.result.heuristic
) {
@ -1881,12 +1882,12 @@ class UrlbarView {
return { id: "urlbar-group-best-match" };
}
switch (row.result.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case UrlbarUtils.RESULT_TYPE.URL:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.URL:
return { id: "urlbar-group-firefox-suggest" };
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
// Show "{ $engine } suggestions" if it's not the first label.
if (currentLabel && row.result.payload.suggestion) {
let engineName =
@ -1906,8 +1907,8 @@ class UrlbarView {
row.style.display = visible ? "" : "none";
if (
!visible &&
row.result.type != UrlbarUtils.RESULT_TYPE.TIP &&
row.result.type != UrlbarUtils.RESULT_TYPE.DYNAMIC
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP &&
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC
) {
// Reset the overflow state of elements that can overflow in case their
// content changes while they're hidden. When making the row visible
@ -1994,7 +1995,9 @@ class UrlbarView {
this.input.setResultForCurrentValue(result);
}
let provider = UrlbarProvidersManager.getProvider(result?.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(
result?.providerName
);
if (provider) {
provider.tryMethod("onSelection", result, element);
}
@ -2283,7 +2286,7 @@ class UrlbarView {
return false;
}
let result = this._queryContext.results[0];
if (result.type != UrlbarUtils.RESULT_TYPE.TIP) {
if (result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP) {
return false;
}
let tipButton = this._rows.firstElementChild.querySelector(
@ -2318,19 +2321,19 @@ class UrlbarView {
{ id: "urlbar-result-action-visit" },
];
if (UrlbarPrefs.get("groupLabels.enabled")) {
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push({ id: "urlbar-group-firefox-suggest" });
if (
UrlbarPrefs.get("bestMatchEnabled") &&
UrlbarPrefs.get("suggest.bestmatch")
lazy.UrlbarPrefs.get("bestMatchEnabled") &&
lazy.UrlbarPrefs.get("suggest.bestmatch")
) {
idArgs.push({ id: "urlbar-group-best-match" });
}
}
if (
UrlbarPrefs.get("quickSuggestEnabled") &&
UrlbarPrefs.get("suggest.quicksuggest.sponsored")
lazy.UrlbarPrefs.get("quickSuggestEnabled") &&
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")
) {
idArgs.push({ id: "urlbar-result-action-sponsored" });
}
@ -2382,7 +2385,7 @@ class UrlbarView {
idArgs.push(...engineNames.map(name => ({ id, args: { engine: name } })));
}
if (UrlbarPrefs.get("groupLabels.enabled")) {
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push(
...engineNames.map(name => ({
id: "urlbar-group-search-suggestions",
@ -2457,7 +2460,7 @@ class UrlbarView {
let localSearchMode;
if (source) {
localSearchMode = UrlbarUtils.LOCAL_SEARCH_MODES.find(
localSearchMode = lazy.UrlbarUtils.LOCAL_SEARCH_MODES.find(
m => m.source == source
);
}
@ -2468,8 +2471,8 @@ class UrlbarView {
let isPrivateSearchWithoutPrivateEngine =
result.payload.inPrivateWindow && !result.payload.isPrivateEngine;
let isSearchHistory =
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.source == UrlbarUtils.RESULT_SOURCE.HISTORY;
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY;
let isSearchSuggestion = result.payload.suggestion && !isSearchHistory;
// For one-off buttons having a source, we update the action for the
@ -2515,7 +2518,7 @@ class UrlbarView {
// If an engine is selected, update search results to use that engine.
// Otherwise, restore their original engines.
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
if (engine) {
if (!result.payload.originalEngine) {
result.payload.originalEngine = result.payload.engine;
@ -2549,7 +2552,7 @@ class UrlbarView {
// Update result action text.
if (localSearchMode) {
// Update the result action text for a local one-off.
let name = UrlbarUtils.getResultSourceName(localSearchMode.source);
let name = lazy.UrlbarUtils.getResultSourceName(localSearchMode.source);
this._setElementL10n(action, {
id: `urlbar-result-action-search-${name}`,
});
@ -2568,7 +2571,7 @@ class UrlbarView {
if (item._originalActionSetter) {
item._originalActionSetter();
if (result.heuristic) {
favicon.src = result.payload.icon || UrlbarUtils.ICON.DEFAULT;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.DEFAULT;
}
} else {
Cu.reportError("An item is missing the action setter");
@ -2581,7 +2584,7 @@ class UrlbarView {
if (!iconOverride && (localSearchMode || engine)) {
// For one-offs without an icon, do not allow restyled URL results to
// use their own icons.
iconOverride = UrlbarUtils.ICON.SEARCH_GLASS;
iconOverride = lazy.UrlbarUtils.ICON.SEARCH_GLASS;
}
if (
result.heuristic ||
@ -2600,7 +2603,7 @@ class UrlbarView {
// If the view is open without the input being focused, it will not close
// automatically when the window loses focus. We might be in this state
// after a Search Tip is shown on an engine homepage.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.close();
}
}
@ -2682,7 +2685,7 @@ class QueryContextCache {
// and therefore shouldn't be evicted except when the top sites change.
this._topSitesContext = null;
this._topSitesListener = () => (this._topSitesContext = null);
UrlbarProviderTopSites.addTopSitesListener(this._topSitesListener);
lazy.UrlbarProviderTopSites.addTopSitesListener(this._topSitesListener);
}
/**
@ -2718,7 +2721,8 @@ class QueryContextCache {
// use it too, like search mode. If the first result is from the top-sites
// provider, assume the context is top sites.
if (
queryContext.results?.[0]?.providerName == UrlbarProviderTopSites.name
queryContext.results?.[0]?.providerName ==
lazy.UrlbarProviderTopSites.name
) {
this._topSitesContext = queryContext;
}
@ -2757,7 +2761,7 @@ async function addDynamicStylesheet(window, stylesheetURL) {
// won't break the whole urlbar.
try {
let uri = Services.io.newURI(stylesheetURL);
let sheet = await styleSheetService.preloadSheetAsync(
let sheet = await lazy.styleSheetService.preloadSheetAsync(
uri,
Ci.nsIStyleSheetService.AGENT_SHEET
);

Просмотреть файл

@ -13,7 +13,13 @@ const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AddonTestUtils: "resource://testing-common/AddonTestUtils.jsm",
BrowserTestUtils: "resource://testing-common/BrowserTestUtils.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
@ -24,9 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
TestUtils: "resource://testing-common/TestUtils.jsm",
UrlbarController: "resource:///modules/UrlbarController.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvider: "resource:///modules/UrlbarUtils.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
var UrlbarTestUtils = {
@ -121,8 +125,8 @@ var UrlbarTestUtils = {
// Using the value setter in some cases may trim and fetch unexpected
// results, then pick an alternate path.
if (
UrlbarPrefs.get("trimURLs") &&
value != BrowserUIUtils.trimURL(value)
lazy.UrlbarPrefs.get("trimURLs") &&
value != lazy.BrowserUIUtils.trimURL(value)
) {
window.gURLBar.inputField.value = value;
fireInputEvent = true;
@ -343,7 +347,7 @@ var UrlbarTestUtils = {
if (!httpserver) {
throw new Error("Must provide an http server");
}
return BrowserTestUtils.waitForCondition(
return lazy.BrowserTestUtils.waitForCondition(
() => httpserver.connectionNumber == count,
"Waiting for speculative connection setup"
);
@ -412,7 +416,7 @@ var UrlbarTestUtils = {
async withContextMenu(win, task) {
let textBox = win.gURLBar.querySelector("moz-input-box");
let cxmenu = textBox.menupopup;
let openPromise = BrowserTestUtils.waitForEvent(cxmenu, "popupshown");
let openPromise = lazy.BrowserTestUtils.waitForEvent(cxmenu, "popupshown");
this.EventUtils.synthesizeMouseAtCenter(
win.gURLBar.inputField,
{
@ -429,7 +433,10 @@ var UrlbarTestUtils = {
} finally {
// Close the context menu if the task didn't pick anything.
if (cxmenu.state == "open" || cxmenu.state == "showing") {
let closePromise = BrowserTestUtils.waitForEvent(cxmenu, "popuphidden");
let closePromise = lazy.BrowserTestUtils.waitForEvent(
cxmenu,
"popuphidden"
);
cxmenu.hidePopup();
await closePromise;
}
@ -470,7 +477,7 @@ var UrlbarTestUtils = {
// Check the input's placeholder.
const prefName =
"browser.urlbar.placeholderName" +
(PrivateBrowsingUtils.isWindowPrivate(window) ? ".private" : "");
(lazy.PrivateBrowsingUtils.isWindowPrivate(window) ? ".private" : "");
let engineName = Services.prefs.getStringPref(prefName, "");
this.Assert.deepEqual(
window.document.l10n.getAttributes(window.gURLBar.inputField),
@ -593,7 +600,7 @@ var UrlbarTestUtils = {
let engine = Services.search.getEngineByName(
expectedSearchMode.engineName
);
let engineRootDomain = UrlbarSearchUtils.getRootDomainFromEngine(
let engineRootDomain = lazy.UrlbarSearchUtils.getRootDomainFromEngine(
engine
);
let resultUrl = new URL(result.url);
@ -624,7 +631,7 @@ var UrlbarTestUtils = {
// Ensure the the one-offs are finished rebuilding and visible.
let oneOffs = this.getOneOffSearchButtons(window);
await TestUtils.waitForCondition(
await lazy.TestUtils.waitForCondition(
() => !oneOffs._rebuilding,
"Waiting for one-offs to finish rebuilding"
);
@ -768,7 +775,7 @@ var UrlbarTestUtils = {
* @returns {UrlbarController} A new controller.
*/
newMockController(options = {}) {
return new UrlbarController(
return new lazy.UrlbarController(
Object.assign(
{
input: {
@ -802,7 +809,7 @@ var UrlbarTestUtils = {
// This is necessary because UrlbarMuxerUnifiedComplete.sort calls
// Services.search.parseSubmissionURL, so we need engines.
try {
await AddonTestUtils.promiseStartupManager();
await lazy.AddonTestUtils.promiseStartupManager();
} catch (error) {
if (!error.message.includes("already started")) {
throw error;
@ -821,9 +828,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
add(values = [], window = BrowserWindowTracker.getTopWindow()) {
add(values = [], window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.add(fieldname, values);
return lazy.FormHistoryTestUtils.add(fieldname, values);
},
/**
@ -836,9 +843,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
remove(values = [], window = BrowserWindowTracker.getTopWindow()) {
remove(values = [], window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.remove(fieldname, values);
return lazy.FormHistoryTestUtils.remove(fieldname, values);
},
/**
@ -849,9 +856,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
clear(window = BrowserWindowTracker.getTopWindow()) {
clear(window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.clear(fieldname);
return lazy.FormHistoryTestUtils.clear(fieldname);
},
/**
@ -864,9 +871,9 @@ UrlbarTestUtils.formHistory = {
* @returns {Promise}
* A promise resolved with an array of found form history entries.
*/
search(criteria = {}, window = BrowserWindowTracker.getTopWindow()) {
search(criteria = {}, window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.search(fieldname, criteria);
return lazy.FormHistoryTestUtils.search(fieldname, criteria);
},
/**
@ -878,7 +885,7 @@ UrlbarTestUtils.formHistory = {
* Resolved on the next specified form history change.
*/
promiseChanged(change = null) {
return TestUtils.topicObserved(
return lazy.TestUtils.topicObserved(
"satchel-storage-changed",
(subject, data) => !change || data == "formhistory-" + change
);
@ -892,7 +899,7 @@ UrlbarTestUtils.formHistory = {
* @returns {string}
* The form history name of the urlbar in the window.
*/
getFormHistoryName(window = BrowserWindowTracker.getTopWindow()) {
getFormHistoryName(window = lazy.BrowserWindowTracker.getTopWindow()) {
return window ? window.gURLBar.formHistoryName : "searchbar-history";
},
};
@ -958,7 +965,7 @@ class TestProvider extends UrlbarProvider {
addCallback(this, result);
} else {
await new Promise(resolve => {
setTimeout(() => {
lazy.setTimeout(() => {
addCallback(this, result);
resolve();
}, this._addTimeout);

Просмотреть файл

@ -10,14 +10,18 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
CONTEXTUAL_SERVICES_PING_TYPES:
"resource:///modules/PartnerLinkAttribution.jsm",
const {
CONTEXTUAL_SERVICES_PING_TYPES,
PartnerLinkAttribution,
} = ChromeUtils.import("resource:///modules/PartnerLinkAttribution.jsm");
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ExperimentAPI: "resource://nimbus/ExperimentAPI.jsm",
ExperimentFakes: "resource://testing-common/NimbusTestUtils.jsm",
ExperimentManager: "resource://nimbus/lib/ExperimentManager.jsm",
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
PartnerLinkAttribution: "resource:///modules/PartnerLinkAttribution.jsm",
sinon: "resource://testing-common/Sinon.jsm",
TelemetryTestUtils: "resource://testing-common/TelemetryTestUtils.jsm",
TestUtils: "resource://testing-common/TestUtils.jsm",
@ -28,7 +32,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "UrlbarTestUtils", () => {
XPCOMUtils.defineLazyGetter(lazy, "UrlbarTestUtils", () => {
const { UrlbarTestUtils: module } = ChromeUtils.import(
"resource://testing-common/UrlbarTestUtils.jsm"
);
@ -103,11 +107,11 @@ class QSTestUtils {
}
get BEST_MATCH_LEARN_MORE_URL() {
return UrlbarProviderQuickSuggest.bestMatchHelpUrl;
return lazy.UrlbarProviderQuickSuggest.bestMatchHelpUrl;
}
get SCALARS() {
return UrlbarProviderQuickSuggest.TELEMETRY_SCALARS;
return lazy.UrlbarProviderQuickSuggest.TELEMETRY_SCALARS;
}
get TELEMETRY_EVENT_CATEGORY() {
@ -181,21 +185,21 @@ class QSTestUtils {
this.info?.(
"ensureQuickSuggestInit awaiting UrlbarQuickSuggest.readyPromise"
);
await UrlbarQuickSuggest.readyPromise;
await lazy.UrlbarQuickSuggest.readyPromise;
this.info?.(
"ensureQuickSuggestInit done awaiting UrlbarQuickSuggest.readyPromise"
);
// Stub _queueSettingsSync() so any actual remote settings syncs that happen
// during the test are ignored.
let sandbox = sinon.createSandbox();
sandbox.stub(UrlbarQuickSuggest, "_queueSettingsSync");
let sandbox = lazy.sinon.createSandbox();
sandbox.stub(lazy.UrlbarQuickSuggest, "_queueSettingsSync");
let cleanup = () => sandbox.restore();
this.registerCleanupFunction?.(cleanup);
if (results) {
UrlbarQuickSuggest._resultsByKeyword.clear();
await UrlbarQuickSuggest._addResults(results);
lazy.UrlbarQuickSuggest._resultsByKeyword.clear();
await lazy.UrlbarQuickSuggest._addResults(results);
}
if (config) {
this.setConfig(config);
@ -217,14 +221,14 @@ class QSTestUtils {
*/
async initNimbusFeature(value = {}) {
this.info?.("initNimbusFeature awaiting ExperimentManager.onStartup");
await ExperimentManager.onStartup();
await lazy.ExperimentManager.onStartup();
this.info?.("initNimbusFeature awaiting ExperimentAPI.ready");
await ExperimentAPI.ready();
await lazy.ExperimentAPI.ready();
this.info?.("initNimbusFeature awaiting ExperimentFakes.enrollWithRollout");
let doCleanup = await ExperimentFakes.enrollWithRollout({
featureId: NimbusFeatures.urlbar.featureId,
let doCleanup = await lazy.ExperimentFakes.enrollWithRollout({
featureId: lazy.NimbusFeatures.urlbar.featureId,
value: { enabled: true, ...value },
});
@ -248,7 +252,7 @@ class QSTestUtils {
* @param {object} config
*/
setConfig(config) {
UrlbarQuickSuggest._setConfig(config);
lazy.UrlbarQuickSuggest._setConfig(config);
}
/**
@ -274,15 +278,15 @@ class QSTestUtils {
// If we try to set the scenario before a previous update has finished,
// `updateFirefoxSuggestScenario` will bail, so wait.
await this.waitForScenarioUpdated();
await UrlbarPrefs.updateFirefoxSuggestScenario({ scenario });
await lazy.UrlbarPrefs.updateFirefoxSuggestScenario({ scenario });
}
/**
* Waits for any prior scenario update to finish.
*/
async waitForScenarioUpdated() {
await TestUtils.waitForCondition(
() => !UrlbarPrefs.updatingFirefoxSuggestScenario,
await lazy.TestUtils.waitForCondition(
() => !lazy.UrlbarPrefs.updatingFirefoxSuggestScenario,
"Waiting for updatingFirefoxSuggestScenario to be false"
);
}
@ -320,7 +324,7 @@ class QSTestUtils {
);
if (index < 0) {
let resultCount = UrlbarTestUtils.getResultCount(window);
let resultCount = lazy.UrlbarTestUtils.getResultCount(window);
if (isBestMatch) {
index = 1;
this.Assert.greater(
@ -338,7 +342,10 @@ class QSTestUtils {
}
}
let details = await UrlbarTestUtils.getDetailsOfResultAt(window, index);
let details = await lazy.UrlbarTestUtils.getDetailsOfResultAt(
window,
index
);
let { result } = details;
this.info?.(
@ -350,7 +357,7 @@ class QSTestUtils {
"UrlbarProviderQuickSuggest",
"Result provider name is UrlbarProviderQuickSuggest"
);
this.Assert.equal(details.type, UrlbarUtils.RESULT_TYPE.URL);
this.Assert.equal(details.type, lazy.UrlbarUtils.RESULT_TYPE.URL);
this.Assert.equal(details.isSponsored, isSponsored, "Result isSponsored");
if (url) {
this.Assert.equal(details.url, url, "Result URL");
@ -385,13 +392,13 @@ class QSTestUtils {
if (!isBestMatch) {
this.Assert.equal(
!!blockButton,
UrlbarPrefs.get("quickSuggestBlockingEnabled"),
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled"),
"The block button is present iff quick suggest blocking is enabled"
);
} else {
this.Assert.equal(
!!blockButton,
UrlbarPrefs.get("bestMatchBlockingEnabled"),
lazy.UrlbarPrefs.get("bestMatchBlockingEnabled"),
"The block button is present iff best match blocking is enabled"
);
}
@ -407,7 +414,10 @@ class QSTestUtils {
* The index of the result.
*/
async assertIsNotQuickSuggest(window, index) {
let details = await UrlbarTestUtils.getDetailsOfResultAt(window, index);
let details = await lazy.UrlbarTestUtils.getDetailsOfResultAt(
window,
index
);
this.Assert.notEqual(
details.result.providerName,
"UrlbarProviderQuickSuggest",
@ -421,7 +431,7 @@ class QSTestUtils {
* @param {object} window
*/
async assertNoQuickSuggestResults(window) {
for (let i = 0; i < UrlbarTestUtils.getResultCount(window); i++) {
for (let i = 0; i < lazy.UrlbarTestUtils.getResultCount(window); i++) {
await this.assertIsNotQuickSuggest(window, i);
}
}
@ -435,10 +445,14 @@ class QSTestUtils {
* expect a scalar not to be incremented, don't include it.
*/
assertScalars(expectedIndexesByScalarName) {
let scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
let scalars = lazy.TelemetryTestUtils.getProcessScalars(
"parent",
true,
true
);
for (let scalarName of Object.values(this.SCALARS)) {
if (scalarName in expectedIndexesByScalarName) {
TelemetryTestUtils.assertKeyedScalar(
lazy.TelemetryTestUtils.assertKeyedScalar(
scalars,
scalarName,
expectedIndexesByScalarName[scalarName],
@ -468,7 +482,7 @@ class QSTestUtils {
* The options object to pass to `TelemetryTestUtils.assertEvents()`.
*/
assertEvents(expectedEvents, filterOverrides = {}, options = undefined) {
TelemetryTestUtils.assertEvents(
lazy.TelemetryTestUtils.assertEvents(
expectedEvents,
{
category: QuickSuggestTestUtils.TELEMETRY_EVENT_CATEGORY,
@ -492,7 +506,7 @@ class QSTestUtils {
* it otherwise.
*/
createTelemetryPingSpy() {
let sandbox = sinon.createSandbox();
let sandbox = lazy.sinon.createSandbox();
let spy = sandbox.spy(
PartnerLinkAttribution._pingCentre,
"sendStructuredIngestionPing"
@ -615,7 +629,10 @@ class QSTestUtils {
* }
*/
assertTimestampsReplaced(result, urls) {
let { TIMESTAMP_TEMPLATE, TIMESTAMP_LENGTH } = UrlbarProviderQuickSuggest;
let {
TIMESTAMP_TEMPLATE,
TIMESTAMP_LENGTH,
} = lazy.UrlbarProviderQuickSuggest;
// Parse the timestamp strings from each payload property and save them in
// `urls[key].timestamp`.
@ -687,7 +704,7 @@ class QSTestUtils {
*/
async enrollExperiment({ valueOverrides = {} }) {
this.info?.("Awaiting ExperimentAPI.ready");
await ExperimentAPI.ready();
await lazy.ExperimentAPI.ready();
// Wait for any prior scenario updates to finish. If updates are ongoing,
// UrlbarPrefs will ignore the Nimbus update when the experiment is
@ -699,15 +716,17 @@ class QSTestUtils {
// These notifications signal either that pref updates due to enrollment are
// done or that updates weren't necessary.
let updatePromise = Promise.race([
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
]);
let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
enabled: true,
featureId: "urlbar",
value: valueOverrides,
});
let doExperimentCleanup = await lazy.ExperimentFakes.enrollWithFeatureConfig(
{
enabled: true,
featureId: "urlbar",
value: valueOverrides,
}
);
// Wait for the pref updates triggered by the experiment enrollment.
this.info?.("Awaiting update after enrolling in experiment");
@ -717,8 +736,10 @@ class QSTestUtils {
// The same pref updates will be triggered by unenrollment, so wait for
// them again.
let unenrollUpdatePromise = Promise.race([
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
lazy.TestUtils.topicObserved(
QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC
),
]);
this.info?.("Awaiting experiment cleanup");
@ -738,8 +759,8 @@ class QSTestUtils {
await new Promise(resolve => Services.tm.idleDispatchToMainThread(resolve));
Services.telemetry.clearEvents();
NimbusFeatures.urlbar._didSendExposureEvent = false;
UrlbarQuickSuggest._recordedExposureEvent = false;
lazy.NimbusFeatures.urlbar._didSendExposureEvent = false;
lazy.UrlbarQuickSuggest._recordedExposureEvent = false;
}
/**
@ -753,7 +774,7 @@ class QSTestUtils {
*/
async assertExposureEvent(expectedRecorded) {
this.Assert.equal(
UrlbarQuickSuggest._recordedExposureEvent,
lazy.UrlbarQuickSuggest._recordedExposureEvent,
expectedRecorded,
"_recordedExposureEvent is correct"
);
@ -779,7 +800,7 @@ class QSTestUtils {
// so likewise queue the assert to idle instead of doing it immediately.
await new Promise(resolve => {
Services.tm.idleDispatchToMainThread(() => {
TelemetryTestUtils.assertEvents(expectedEvents, filter);
lazy.TelemetryTestUtils.assertEvents(expectedEvents, filter);
resolve();
});
});

Просмотреть файл

@ -240,17 +240,6 @@ newtab-pocket-pocket-firefox-family = { -pocket-brand-name } is part of the { -b
newtab-pocket-save-to-pocket = Save to { -pocket-brand-name }
newtab-pocket-saved-to-pocket = Saved to { -pocket-brand-name }
# This is a button shown at the bottom of the Pocket section that loads more stories when clicked.
newtab-pocket-load-more-stories-button = Load more stories
## Pocket Final Card Section.
## This is for the final card in the Pocket grid.
newtab-pocket-last-card-title = Youre all caught up!
newtab-pocket-last-card-desc = Check back later for more.
newtab-pocket-last-card-image =
.alt = Youre all caught up
## Error Fallback Content.
## This message and suggested action link are shown in each section of UI that fails to render.

Просмотреть файл

@ -517,7 +517,7 @@ const ColorwayCollections = [
id: "independent-voices",
expiry:
colorwayClosetEnabled && AppConstants.NIGHTLY_BUILD
? "2022-12-31"
? "2023-01-24"
: "1970-01-01",
l10nId: {
title: "colorway-collection-independent-voices",

Просмотреть файл

@ -14573,7 +14573,7 @@ bool Document::PopFullscreenElement(UpdateViewport aUpdateViewport) {
}
MOZ_ASSERT(removedElement->State().HasState(ElementState::FULLSCREEN));
removedElement->RemoveStates(ElementState::FULLSCREEN);
removedElement->RemoveStates(ElementState::FULLSCREEN | ElementState::MODAL);
NotifyFullScreenChangedForMediaElement(*removedElement);
// Reset iframe fullscreen flag.
if (auto* iframe = HTMLIFrameElement::FromNode(removedElement)) {
@ -14586,23 +14586,20 @@ bool Document::PopFullscreenElement(UpdateViewport aUpdateViewport) {
}
void Document::SetFullscreenElement(Element& aElement) {
aElement.AddStates(ElementState::FULLSCREEN);
ElementState statesToAdd = ElementState::FULLSCREEN;
if (StaticPrefs::dom_fullscreen_modal() && !IsInChromeDocShell()) {
// Don't make the document modal in chrome documents, since we don't want
// the browser UI like the context menu / etc to be inert.
statesToAdd |= ElementState::MODAL;
}
aElement.AddStates(statesToAdd);
TopLayerPush(aElement);
NotifyFullScreenChangedForMediaElement(aElement);
UpdateViewportScrollbarOverrideForFullscreen(this);
}
static ElementState TopLayerModalStates() {
ElementState modalStates = ElementState::MODAL_DIALOG;
if (StaticPrefs::dom_fullscreen_modal()) {
modalStates |= ElementState::FULLSCREEN;
}
return modalStates;
}
void Document::TopLayerPush(Element& aElement) {
const bool modal =
aElement.State().HasAtLeastOneOfStates(TopLayerModalStates());
const bool modal = aElement.State().HasState(ElementState::MODAL);
auto predictFunc = [&aElement](Element* element) {
return element == &aElement;
@ -14639,7 +14636,7 @@ void Document::TopLayerPush(Element& aElement) {
}
void Document::AddModalDialog(HTMLDialogElement& aDialogElement) {
aDialogElement.AddStates(ElementState::MODAL_DIALOG);
aDialogElement.AddStates(ElementState::MODAL);
TopLayerPush(aDialogElement);
}
@ -14649,7 +14646,7 @@ void Document::RemoveModalDialog(HTMLDialogElement& aDialogElement) {
};
DebugOnly<Element*> removedElement = TopLayerPop(predicate);
MOZ_ASSERT(removedElement == &aDialogElement);
aDialogElement.RemoveStates(ElementState::MODAL_DIALOG);
aDialogElement.RemoveStates(ElementState::MODAL);
}
Element* Document::TopLayerPop(FunctionRef<bool(Element*)> aPredicate) {
@ -14690,15 +14687,14 @@ Element* Document::TopLayerPop(FunctionRef<bool(Element*)> aPredicate) {
return nullptr;
}
const ElementState modalStates = TopLayerModalStates();
const bool modal = removedElement->State().HasAtLeastOneOfStates(modalStates);
const bool modal = removedElement->State().HasState(ElementState::MODAL);
if (modal) {
removedElement->RemoveStates(ElementState::TOPMOST_MODAL);
bool foundExistingModalElement = false;
for (const nsWeakPtr& weakPtr : Reversed(mTopLayer)) {
nsCOMPtr<Element> element(do_QueryReferent(weakPtr));
if (element && element->State().HasAtLeastOneOfStates(modalStates)) {
if (element && element->State().HasState(ElementState::MODAL)) {
element->AddStates(ElementState::TOPMOST_MODAL);
foundExistingModalElement = true;
break;

Просмотреть файл

@ -7875,7 +7875,7 @@ static bool AllocateShmem(mozilla::dom::ContentChild* aChild,
IShmemAllocator* allocator = aChild ? static_cast<IShmemAllocator*>(aChild)
: static_cast<IShmemAllocator*>(aParent);
return allocator->AllocShmem(aSize, SharedMemory::TYPE_BASIC, aShmem);
return allocator->AllocShmem(aSize, aShmem);
}
static Shmem ConvertToShmem(mozilla::dom::ContentChild* aChild,
@ -8166,7 +8166,7 @@ struct GetSurfaceDataShmem {
ReturnType Allocate(size_t aSize) {
Shmem shmem;
if (!mAllocator->AllocShmem(aSize, SharedMemory::TYPE_BASIC, &shmem)) {
if (!mAllocator->AllocShmem(aSize, &shmem)) {
return Nothing();
}

Просмотреть файл

@ -107,9 +107,9 @@ bitflags! {
const AUTOFILL = 1u64 << 40;
/// Non-standard & undocumented.
const AUTOFILL_PREVIEW = 1u64 << 41;
/// State that dialog element is modal, for centered alignment
/// <https://html.spec.whatwg.org/multipage/#centered-alignment>
const MODAL_DIALOG = 1u64 << 42;
/// State for modal elements:
/// <https://drafts.csswg.org/selectors-4/#modal-state>
const MODAL = 1u64 << 42;
/// <https://html.spec.whatwg.org/multipage/#inert-subtrees>
const INERT = 1u64 << 43;
/// State for the topmost modal element in top layer
@ -164,7 +164,7 @@ bitflags! {
Self::FULLSCREEN.bits |
Self::HOVER.bits |
Self::URLTARGET.bits |
Self::MODAL_DIALOG.bits |
Self::MODAL.bits |
Self::INERT.bits |
Self::TOPMOST_MODAL.bits |
Self::REVEALED.bits;

Просмотреть файл

@ -51,6 +51,9 @@ async function testFullscreenIsModal(modal) {
clickButton(/* expectEvent = */ !modal);
ok(document.fullscreenElement.matches(":fullscreen"), "Fullscreen element matches :fullscreen");
is(document.fullscreenElement.matches(":modal"), modal, "Fullscreen element matches :modal");
await document.exitFullscreen();
clickButton(/* expectEvent = */ true);
}

Просмотреть файл

@ -4310,10 +4310,8 @@ void ClientWebGLContext::TexImage(uint8_t funcDims, GLenum imageTarget,
MOZ_ASSERT(desc->sd);
const auto byteCount = pShmem->Size<uint8_t>();
const auto* const src = pShmem->get<uint8_t>();
const auto shmemType =
mozilla::ipc::SharedMemory::SharedMemoryType::TYPE_BASIC;
mozilla::ipc::Shmem shmemForResend;
if (!child->AllocShmem(byteCount, shmemType, &shmemForResend)) {
if (!child->AllocShmem(byteCount, &shmemForResend)) {
NS_WARNING("AllocShmem failed in TexImage");
return;
}

Просмотреть файл

@ -30,9 +30,7 @@ Maybe<Range<uint8_t>> WebGLChild::AllocPendingCmdBytes(const size_t size) {
capacity = size;
}
auto shmem = webgl::RaiiShmem::Alloc(
this, capacity,
mozilla::ipc::SharedMemory::SharedMemoryType::TYPE_BASIC);
auto shmem = webgl::RaiiShmem::Alloc(this, capacity);
if (!shmem) {
NS_WARNING("Failed to alloc shmem for AllocPendingCmdBytes.");
return {};

Просмотреть файл

@ -27,11 +27,10 @@ class RaiiShmem final {
public:
/// Returns zeroed data.
static RaiiShmem Alloc(
mozilla::ipc::IProtocol* const allocator, const size_t size,
const mozilla::ipc::SharedMemory::SharedMemoryType type) {
static RaiiShmem Alloc(mozilla::ipc::IProtocol* const allocator,
const size_t size) {
mozilla::ipc::Shmem shmem;
if (!allocator->AllocShmem(size, type, &shmem)) return {};
if (!allocator->AllocShmem(size, &shmem)) return {};
return {allocator, shmem};
}

Просмотреть файл

@ -127,9 +127,7 @@ IPCResult WebGLParent::GetFrontBufferSnapshot(
const auto& surfSize = *maybeSize;
const auto byteSize = 4 * surfSize.x * surfSize.y;
auto shmem = webgl::RaiiShmem::Alloc(
aProtocol, byteSize,
mozilla::ipc::SharedMemory::SharedMemoryType::TYPE_BASIC);
auto shmem = webgl::RaiiShmem::Alloc(aProtocol, byteSize);
if (!shmem) {
NS_WARNING("Failed to alloc shmem for RecvGetFrontBufferSnapshot.");
return IPC_FAIL(aProtocol, "Failed to allocate shmem for result");
@ -158,9 +156,7 @@ IPCResult WebGLParent::RecvGetBufferSubData(const GLenum target,
}
const auto allocSize = 1 + byteSize;
auto shmem = webgl::RaiiShmem::Alloc(
this, allocSize,
mozilla::ipc::SharedMemory::SharedMemoryType::TYPE_BASIC);
auto shmem = webgl::RaiiShmem::Alloc(this, allocSize);
if (!shmem) {
NS_WARNING("Failed to alloc shmem for RecvGetBufferSubData.");
return IPC_FAIL(this, "Failed to allocate shmem for result");
@ -188,9 +184,7 @@ IPCResult WebGLParent::RecvReadPixels(const webgl::ReadPixelsDesc& desc,
}
const auto allocSize = std::max<uint64_t>(1, byteSize);
auto shmem = webgl::RaiiShmem::Alloc(
this, allocSize,
mozilla::ipc::SharedMemory::SharedMemoryType::TYPE_BASIC);
auto shmem = webgl::RaiiShmem::Alloc(this, allocSize);
if (!shmem) {
NS_WARNING("Failed to alloc shmem for RecvReadPixels.");
return IPC_FAIL(this, "Failed to allocate shmem for result");

Просмотреть файл

@ -81,7 +81,7 @@ void HTMLDialogElement::Show() {
}
bool HTMLDialogElement::IsInTopLayer() const {
return State().HasState(ElementState::MODAL_DIALOG);
return State().HasState(ElementState::MODAL);
}
void HTMLDialogElement::AddToTopLayerIfNeeded() {

Просмотреть файл

@ -352,7 +352,7 @@ bool ChromiumCDMParent::InitCDMInputBuffer(gmp::CDMInputBuffer& aBuffer,
}
Shmem shmem;
if (!AllocShmem(aSample->Size(), Shmem::SharedMemory::TYPE_BASIC, &shmem)) {
if (!AllocShmem(aSample->Size(), &shmem)) {
return false;
}
memcpy(shmem.get<uint8_t>(), aSample->Data(), aSample->Size());
@ -391,7 +391,7 @@ bool ChromiumCDMParent::SendBufferToCDM(uint32_t aSizeInBytes) {
GMP_LOG_DEBUG("ChromiumCDMParent::SendBufferToCDM() size=%" PRIu32,
aSizeInBytes);
Shmem shmem;
if (!AllocShmem(aSizeInBytes, Shmem::SharedMemory::TYPE_BASIC, &shmem)) {
if (!AllocShmem(aSizeInBytes, &shmem)) {
return false;
}
if (!SendGiveBuffer(std::move(shmem))) {

Просмотреть файл

@ -18,9 +18,8 @@ namespace mozilla::gmp {
// Compressed (encoded) data goes from the Decoder parent to the child;
// pool there, and then return with Encoded() frames and goes into the parent
// pool.
bool GMPSharedMemManager::MgrAllocShmem(
GMPSharedMem::GMPMemoryClasses aClass, size_t aSize,
ipc::Shmem::SharedMemory::SharedMemoryType aType, ipc::Shmem* aMem) {
bool GMPSharedMemManager::MgrAllocShmem(GMPSharedMem::GMPMemoryClasses aClass,
size_t aSize, ipc::Shmem* aMem) {
mData->CheckThread();
// first look to see if we have a free buffer large enough
@ -36,7 +35,7 @@ bool GMPSharedMemManager::MgrAllocShmem(
// Didn't find a buffer free with enough space; allocate one
size_t pagesize = ipc::SharedMemory::SystemPageSize();
aSize = (aSize + (pagesize - 1)) & ~(pagesize - 1); // round up to page size
bool retval = Alloc(aSize, aType, aMem);
bool retval = Alloc(aSize, aMem);
if (retval) {
// The allocator (or NeedsShmem call) should never return less than we ask
// for...

Просмотреть файл

@ -52,9 +52,7 @@ class GMPSharedMemManager {
virtual ~GMPSharedMemManager() = default;
virtual bool MgrAllocShmem(GMPSharedMem::GMPMemoryClasses aClass,
size_t aSize,
ipc::Shmem::SharedMemory::SharedMemoryType aType,
ipc::Shmem* aMem);
size_t aSize, ipc::Shmem* aMem);
virtual bool MgrDeallocShmem(GMPSharedMem::GMPMemoryClasses aClass,
ipc::Shmem& aMem);
@ -64,9 +62,7 @@ class GMPSharedMemManager {
// These have to be implemented using the AllocShmem/etc provided by the
// IPDL-generated interfaces, so have the Parent/Child implement them.
virtual bool Alloc(size_t aSize,
ipc::Shmem::SharedMemory::SharedMemoryType aType,
ipc::Shmem* aMem) = 0;
virtual bool Alloc(size_t aSize, ipc::Shmem* aMem) = 0;
virtual void Dealloc(ipc::Shmem&& aMem) = 0;
private:

Просмотреть файл

@ -179,9 +179,7 @@ mozilla::ipc::IPCResult GMPVideoDecoderChild::RecvDecodingComplete() {
return IPC_OK();
}
bool GMPVideoDecoderChild::Alloc(size_t aSize,
Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) {
bool GMPVideoDecoderChild::Alloc(size_t aSize, Shmem* aMem) {
MOZ_ASSERT(mPlugin->GMPMessageLoop() == MessageLoop::current());
bool rv;

Просмотреть файл

@ -42,8 +42,7 @@ class GMPVideoDecoderChild : public PGMPVideoDecoderChild,
void Error(GMPErr aError) override;
// GMPSharedMemManager
bool Alloc(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) override;
bool Alloc(size_t aSize, Shmem* aMem) override;
void Dealloc(Shmem&& aMem) override;
private:

Просмотреть файл

@ -402,9 +402,8 @@ mozilla::ipc::IPCResult GMPVideoDecoderParent::RecvNeedShmem(
const uint32_t& aFrameBufferSize, Shmem* aMem) {
ipc::Shmem mem;
if (!mVideoHost.SharedMemMgr()->MgrAllocShmem(
GMPSharedMem::kGMPFrameData, aFrameBufferSize,
ipc::SharedMemory::TYPE_BASIC, &mem)) {
if (!mVideoHost.SharedMemMgr()->MgrAllocShmem(GMPSharedMem::kGMPFrameData,
aFrameBufferSize, &mem)) {
GMP_LOG_ERROR("%s: Failed to get a shared mem buffer for Child! size %u",
__FUNCTION__, aFrameBufferSize);
return IPC_FAIL(this, "Failed to get a shared mem buffer for Child!");

Просмотреть файл

@ -53,9 +53,8 @@ class GMPVideoDecoderParent final : public PGMPVideoDecoderParent,
const nsCString& GetDisplayName() const override;
// GMPSharedMemManager
bool Alloc(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) override {
return AllocShmem(aSize, aType, aMem);
bool Alloc(size_t aSize, Shmem* aMem) override {
return AllocShmem(aSize, aMem);
}
void Dealloc(Shmem&& aMem) override { DeallocShmem(aMem); }

Просмотреть файл

@ -100,9 +100,8 @@ GMPErr GMPVideoEncodedFrameImpl::CreateEmptyFrame(uint32_t aSize) {
DestroyBuffer();
} else if (aSize > AllocatedSize()) {
DestroyBuffer();
if (!mHost->SharedMemMgr()->MgrAllocShmem(
GMPSharedMem::kGMPEncodedData, aSize, ipc::SharedMemory::TYPE_BASIC,
&mBuffer) ||
if (!mHost->SharedMemMgr()->MgrAllocShmem(GMPSharedMem::kGMPEncodedData,
aSize, &mBuffer) ||
!Buffer()) {
return GMPAllocErr;
}
@ -176,9 +175,8 @@ void GMPVideoEncodedFrameImpl::SetAllocatedSize(uint32_t aNewSize) {
}
ipc::Shmem new_mem;
if (!mHost->SharedMemMgr()->MgrAllocShmem(
GMPSharedMem::kGMPEncodedData, aNewSize,
ipc::SharedMemory::TYPE_BASIC, &new_mem) ||
if (!mHost->SharedMemMgr()->MgrAllocShmem(GMPSharedMem::kGMPEncodedData,
aNewSize, &new_mem) ||
!new_mem.get<uint8_t>()) {
return;
}

Просмотреть файл

@ -172,9 +172,7 @@ mozilla::ipc::IPCResult GMPVideoEncoderChild::RecvEncodingComplete() {
return IPC_OK();
}
bool GMPVideoEncoderChild::Alloc(size_t aSize,
Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) {
bool GMPVideoEncoderChild::Alloc(size_t aSize, Shmem* aMem) {
MOZ_ASSERT(mPlugin->GMPMessageLoop() == MessageLoop::current());
bool rv;
@ -189,7 +187,7 @@ bool GMPVideoEncoderChild::Alloc(size_t aSize,
this, &GMPVideoEncoderChild::RecvEncodingComplete));
}
#else
rv = AllocShmem(aSize, aType, aMem);
rv = AllocShmem(aSize, aMem);
#endif
return rv;
}

Просмотреть файл

@ -38,8 +38,7 @@ class GMPVideoEncoderChild : public PGMPVideoEncoderChild,
void Error(GMPErr aError) override;
// GMPSharedMemManager
bool Alloc(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) override;
bool Alloc(size_t aSize, Shmem* aMem) override;
void Dealloc(Shmem&& aMem) override;
private:

Просмотреть файл

@ -279,9 +279,8 @@ mozilla::ipc::IPCResult GMPVideoEncoderParent::RecvNeedShmem(
// This test may be paranoia now that we don't shut down the VideoHost
// in ::Shutdown, but doesn't hurt
if (!mVideoHost.SharedMemMgr() ||
!mVideoHost.SharedMemMgr()->MgrAllocShmem(
GMPSharedMem::kGMPEncodedData, aEncodedBufferSize,
ipc::SharedMemory::TYPE_BASIC, &mem)) {
!mVideoHost.SharedMemMgr()->MgrAllocShmem(GMPSharedMem::kGMPEncodedData,
aEncodedBufferSize, &mem)) {
GMP_LOG_ERROR(
"%s::%s: Failed to get a shared mem buffer for Child! size %u",
__CLASS__, __FUNCTION__, aEncodedBufferSize);

Просмотреть файл

@ -51,9 +51,8 @@ class GMPVideoEncoderParent : public GMPVideoEncoderProxy,
uint32_t GetPluginId() const override { return mPluginId; }
// GMPSharedMemManager
bool Alloc(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
Shmem* aMem) override {
return AllocShmem(aSize, aType, aMem);
bool Alloc(size_t aSize, Shmem* aMem) override {
return AllocShmem(aSize, aMem);
}
void Dealloc(Shmem&& aMem) override { DeallocShmem(aMem); }

Просмотреть файл

@ -72,9 +72,8 @@ GMPErr GMPPlaneImpl::MaybeResize(int32_t aNewSize) {
}
ipc::Shmem new_mem;
if (!mHost->SharedMemMgr()->MgrAllocShmem(
GMPSharedMem::kGMPFrameData, aNewSize, ipc::SharedMemory::TYPE_BASIC,
&new_mem) ||
if (!mHost->SharedMemMgr()->MgrAllocShmem(GMPSharedMem::kGMPFrameData,
aNewSize, &new_mem) ||
!new_mem.get<uint8_t>()) {
return GMPAllocErr;
}

Просмотреть файл

@ -62,16 +62,11 @@ class RemoteDecoderManagerChild final
void DeallocateSurfaceDescriptor(
const SurfaceDescriptorGPUVideo& aSD) override;
bool AllocShmem(size_t aSize,
mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
mozilla::ipc::Shmem* aShmem) override {
return PRemoteDecoderManagerChild::AllocShmem(aSize, aShmType, aShmem);
bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) override {
return PRemoteDecoderManagerChild::AllocShmem(aSize, aShmem);
}
bool AllocUnsafeShmem(size_t aSize,
mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
mozilla::ipc::Shmem* aShmem) override {
return PRemoteDecoderManagerChild::AllocUnsafeShmem(aSize, aShmType,
aShmem);
bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) override {
return PRemoteDecoderManagerChild::AllocUnsafeShmem(aSize, aShmem);
}
// Can be called from any thread, dispatches the request to the IPDL thread

Просмотреть файл

@ -272,8 +272,7 @@ mozilla::ipc::IPCResult RemoteDecoderManagerParent::RecvReadback(
size_t length = ImageDataSerializer::ComputeRGBBufferSize(size, format);
Shmem buffer;
if (!length ||
!AllocShmem(length, Shmem::SharedMemory::TYPE_BASIC, &buffer)) {
if (!length || !AllocShmem(length, &buffer)) {
*aResult = null_t();
return IPC_OK();
}

Просмотреть файл

@ -162,11 +162,9 @@ class ShmemPool final {
bool AllocateShmem(T* aInstance, size_t aSize, ShmemBuffer& aRes,
AllocationPolicy aPolicy) {
return (aPolicy == AllocationPolicy::Default &&
aInstance->AllocShmem(aSize, ipc::SharedMemory::TYPE_BASIC,
&aRes.mShmem)) ||
aInstance->AllocShmem(aSize, &aRes.mShmem)) ||
(aPolicy == AllocationPolicy::Unsafe &&
aInstance->AllocUnsafeShmem(aSize, ipc::SharedMemory::TYPE_BASIC,
&aRes.mShmem));
aInstance->AllocUnsafeShmem(aSize, &aRes.mShmem));
}
const PoolType mPoolType;
Mutex mMutex MOZ_UNANNOTATED;

Просмотреть файл

@ -20,8 +20,9 @@
<p id="display"></p>
<div id="content">
</div>
<div id="div"></div>
<input id="input" type="text" />
<div id="div">
<input id="input" type="text" />
</div>
<pre id="test">
<script type="application/javascript">
/*

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше