Bug 1944627 - update sidebar button checked state for non-revamped sidebar cases...
[gecko.git] / browser / components / firefoxview / helpers.mjs
blobf1122c38e3e1ba27f19234206c7021808af6cf18
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 const lazy = {};
6 const loggersByName = new Map();
8 ChromeUtils.defineESModuleGetters(lazy, {
9   BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
10   Log: "resource://gre/modules/Log.sys.mjs",
11   PlacesUIUtils: "resource:///modules/PlacesUIUtils.sys.mjs",
12   PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
13 });
15 ChromeUtils.defineLazyGetter(lazy, "relativeTimeFormat", () => {
16   return new Services.intl.RelativeTimeFormat(undefined, { style: "narrow" });
17 });
19 // Cutoff of 1.5 minutes + 1 second to determine what text string to display
20 export const NOW_THRESHOLD_MS = 91000;
22 // Configure logging level via this pref
23 export const LOGGING_PREF = "browser.tabs.firefox-view.logLevel";
25 export const MAX_TABS_FOR_RECENT_BROWSING = 5;
27 export function formatURIForDisplay(uriString) {
28   return lazy.BrowserUtils.formatURIStringForDisplay(uriString);
31 export function convertTimestamp(
32   timestamp,
33   fluentStrings,
34   _nowThresholdMs = NOW_THRESHOLD_MS
35 ) {
36   if (!timestamp) {
37     // It's marginally better to show nothing instead of "53 years ago"
38     return "";
39   }
40   const elapsed = Date.now() - timestamp;
41   let formattedTime;
42   if (elapsed <= _nowThresholdMs) {
43     // Use a different string for very recent timestamps
44     formattedTime = fluentStrings.formatValueSync(
45       "firefoxview-just-now-timestamp"
46     );
47   } else {
48     formattedTime = lazy.relativeTimeFormat.formatBestUnit(new Date(timestamp));
49   }
50   return formattedTime;
53 export function createFaviconElement(image, targetURI = "") {
54   let favicon = document.createElement("div");
55   favicon.style.backgroundImage = `url('${getImageUrl(image, targetURI)}')`;
56   favicon.classList.add("favicon");
57   return favicon;
60 export function getImageUrl(icon, targetURI) {
61   return icon ? lazy.PlacesUIUtils.getImageURL(icon) : `page-icon:${targetURI}`;
64 /**
65  * This function doesn't just copy the link to the clipboard, it creates a
66  * URL object on the clipboard, so when it's pasted into an application that
67  * supports it, it displays the title as a link.
68  */
69 export function placeLinkOnClipboard(title, uri) {
70   let node = {
71     type: 0,
72     title,
73     uri,
74   };
76   // Copied from doCommand/placesCmd_copy in PlacesUIUtils.sys.mjs
78   // This is a little hacky, but there is a lot of code in Places that handles
79   // clipboard stuff, so it's easier to reuse.
81   // This order is _important_! It controls how this and other applications
82   // select data to be inserted based on type.
83   let contents = [
84     { type: lazy.PlacesUtils.TYPE_X_MOZ_URL, entries: [] },
85     { type: lazy.PlacesUtils.TYPE_HTML, entries: [] },
86     { type: lazy.PlacesUtils.TYPE_PLAINTEXT, entries: [] },
87   ];
89   contents.forEach(function (content) {
90     content.entries.push(lazy.PlacesUtils.wrapNode(node, content.type));
91   });
93   let xferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(
94     Ci.nsITransferable
95   );
96   xferable.init(null);
98   function addData(type, data) {
99     xferable.addDataFlavor(type);
100     xferable.setTransferData(type, lazy.PlacesUtils.toISupportsString(data));
101   }
103   contents.forEach(function (content) {
104     addData(content.type, content.entries.join(lazy.PlacesUtils.endl));
105   });
107   Services.clipboard.setData(xferable, null, Ci.nsIClipboard.kGlobalClipboard);
111  * Get or create a logger, whose log-level is controlled by a pref
113  * @param {string} loggerName - Creating named loggers helps differentiate log messages from different
114                                 components or features.
115  */
117 export function getLogger(loggerName) {
118   if (!loggersByName.has(loggerName)) {
119     let logger = lazy.Log.repository.getLogger(`FirefoxView.${loggerName}`);
120     logger.manageLevelFromPref(LOGGING_PREF);
121     logger.addAppender(
122       new lazy.Log.ConsoleAppender(new lazy.Log.BasicFormatter())
123     );
124     loggersByName.set(loggerName, logger);
125   }
126   return loggersByName.get(loggerName);
129 export function escapeHtmlEntities(text) {
130   return (text || "")
131     .replace(/&/g, "&amp;")
132     .replace(/</g, "&lt;")
133     .replace(/>/g, "&gt;")
134     .replace(/"/g, "&quot;")
135     .replace(/'/g, "&#39;");
138 export function navigateToLink(e, url = e.originalTarget.url) {
139   let currentWindow =
140     e.target.ownerGlobal.browsingContext.embedderWindowGlobal.browsingContext
141       .window;
142   if (currentWindow.openTrustedLinkIn) {
143     let where = lazy.BrowserUtils.whereToOpenLink(
144       e.detail.originalEvent,
145       false,
146       true
147     );
148     if (where == "current") {
149       where = "tab";
150     }
151     currentWindow.openTrustedLinkIn(url, where);
152   }