summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/lib/AboutPreferences.sys.mjs
blob: 08e0ca422a47d3e5ee0880f55f4baaeb505af73e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/* 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/. */

import {
  actionTypes as at,
  actionCreators as ac,
} from "resource://activity-stream/common/Actions.mjs";

const HTML_NS = "http://www.w3.org/1999/xhtml";
export const PREFERENCES_LOADED_EVENT = "home-pane-loaded";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
});

// These "section" objects are formatted in a way to be similar to the ones from
// SectionsManager to construct the preferences view.
const PREFS_BEFORE_SECTIONS = () => [
  {
    id: "search",
    pref: {
      feed: "showSearch",
      titleString: "home-prefs-search-header",
    },
    icon: "chrome://global/skin/icons/search-glass.svg",
  },
  {
    id: "topsites",
    pref: {
      feed: "feeds.topsites",
      titleString: "home-prefs-shortcuts-header",
      descString: "home-prefs-shortcuts-description",
      get nestedPrefs() {
        return Services.prefs.getBoolPref("browser.topsites.useRemoteSetting")
          ? [
              {
                name: "showSponsoredTopSites",
                titleString: "home-prefs-shortcuts-by-option-sponsored",
                eventSource: "SPONSORED_TOP_SITES",
              },
            ]
          : [];
      },
    },
    icon: "chrome://browser/skin/topsites.svg",
    maxRows: 4,
    rowsPref: "topSitesRows",
    eventSource: "TOP_SITES",
  },
];

export class AboutPreferences {
  init() {
    Services.obs.addObserver(this, PREFERENCES_LOADED_EVENT);
  }

  uninit() {
    Services.obs.removeObserver(this, PREFERENCES_LOADED_EVENT);
  }

  onAction(action) {
    switch (action.type) {
      case at.INIT:
        this.init();
        break;
      case at.UNINIT:
        this.uninit();
        break;
      case at.SETTINGS_OPEN:
        action._target.browser.ownerGlobal.openPreferences("paneHome");
        break;
      // This is used to open the web extension settings page for an extension
      case at.OPEN_WEBEXT_SETTINGS:
        action._target.browser.ownerGlobal.BrowserOpenAddonsMgr(
          `addons://detail/${encodeURIComponent(action.data)}`
        );
        break;
    }
  }

  handleDiscoverySettings(sections) {
    // Deep copy object to not modify original Sections state in store
    let sectionsCopy = JSON.parse(JSON.stringify(sections));
    sectionsCopy.forEach(obj => {
      if (obj.id === "topstories") {
        obj.rowsPref = "";
      }
    });
    return sectionsCopy;
  }

  setupUserEvent(element, eventSource) {
    element.addEventListener("command", e => {
      const { checked } = e.target;
      if (typeof checked === "boolean") {
        this.store.dispatch(
          ac.UserEvent({
            event: "PREF_CHANGED",
            source: eventSource,
            value: { status: checked, menu_source: "ABOUT_PREFERENCES" },
          })
        );
      }
    });
  }

  observe(window) {
    const discoveryStreamConfig = this.store.getState().DiscoveryStream.config;
    let sections = this.store.getState().Sections;

    if (discoveryStreamConfig.enabled) {
      sections = this.handleDiscoverySettings(sections);
    }

    const featureConfig = lazy.NimbusFeatures.newtab.getAllVariables() || {};

    this.renderPreferences(window, [
      ...PREFS_BEFORE_SECTIONS(featureConfig),
      ...sections,
    ]);
  }

  /**
   * Render preferences to an about:preferences content window with the provided
   * preferences structure.
   */
  renderPreferences({ document, Preferences, gHomePane }, prefStructure) {
    // Helper to create a new element and append it
    const createAppend = (tag, parent, options) =>
      parent.appendChild(document.createXULElement(tag, options));

    // Helper to get fluentIDs sometimes encase in an object
    const getString = message =>
      typeof message !== "object" ? message : message.id;

    // Helper to link a UI element to a preference for updating
    const linkPref = (element, name, type) => {
      const fullPref = `browser.newtabpage.activity-stream.${name}`;
      element.setAttribute("preference", fullPref);
      Preferences.add({ id: fullPref, type });

      // Prevent changing the UI if the preference can't be changed
      element.disabled = Preferences.get(fullPref).locked;
    };

    // Insert a new group immediately after the homepage one
    const homeGroup = document.getElementById("homepageGroup");
    const contentsGroup = homeGroup.insertAdjacentElement(
      "afterend",
      homeGroup.cloneNode()
    );
    contentsGroup.id = "homeContentsGroup";
    contentsGroup.setAttribute("data-subcategory", "contents");
    const homeHeader = createAppend("label", contentsGroup).appendChild(
      document.createElementNS(HTML_NS, "h2")
    );
    document.l10n.setAttributes(homeHeader, "home-prefs-content-header2");

    const homeDescription = createAppend("description", contentsGroup);
    homeDescription.classList.add("description-deemphasized");

    document.l10n.setAttributes(
      homeDescription,
      "home-prefs-content-description2"
    );

    // Add preferences for each section
    prefStructure.forEach(sectionData => {
      const {
        id,
        pref: prefData,
        icon = "webextension",
        maxRows,
        rowsPref,
        shouldHidePref,
        eventSource,
      } = sectionData;
      const {
        feed: name,
        titleString = {},
        descString,
        nestedPrefs = [],
      } = prefData || {};

      // Don't show any sections that we don't want to expose in preferences UI
      if (shouldHidePref) {
        return;
      }

      // Use full icon spec for certain protocols or fall back to packaged icon
      const iconUrl = !icon.search(/^(chrome|moz-extension|resource):/)
        ? icon
        : `chrome://activity-stream/content/data/content/assets/glyph-${icon}-16.svg`;

      // Add the main preference for turning on/off a section
      const sectionVbox = createAppend("vbox", contentsGroup);
      sectionVbox.setAttribute("data-subcategory", id);
      const checkbox = createAppend("checkbox", sectionVbox);
      checkbox.classList.add("section-checkbox");
      checkbox.setAttribute("src", iconUrl);
      // Setup a user event if we have an event source for this pref.
      if (eventSource) {
        this.setupUserEvent(checkbox, eventSource);
      }
      document.l10n.setAttributes(
        checkbox,
        getString(titleString),
        titleString.values
      );

      linkPref(checkbox, name, "bool");

      // Specially add a link for stories
      if (id === "topstories") {
        const sponsoredHbox = createAppend("hbox", sectionVbox);
        sponsoredHbox.setAttribute("align", "center");
        sponsoredHbox.appendChild(checkbox);
        checkbox.classList.add("tail-with-learn-more");

        const link = createAppend("label", sponsoredHbox, { is: "text-link" });
        link.classList.add("learn-sponsored");
        link.setAttribute("href", sectionData.pref.learnMore.link.href);
        document.l10n.setAttributes(link, sectionData.pref.learnMore.link.id);
      }

      // Add more details for the section (e.g., description, more prefs)
      const detailVbox = createAppend("vbox", sectionVbox);
      detailVbox.classList.add("indent");
      if (descString) {
        const description = createAppend("description", detailVbox);
        description.classList.add("indent", "text-deemphasized");
        document.l10n.setAttributes(
          description,
          getString(descString),
          descString.values
        );

        // Add a rows dropdown if we have a pref to control and a maximum
        if (rowsPref && maxRows) {
          const detailHbox = createAppend("hbox", detailVbox);
          detailHbox.setAttribute("align", "center");
          description.setAttribute("flex", 1);
          detailHbox.appendChild(description);

          // Add box so the search tooltip is positioned correctly
          const tooltipBox = createAppend("hbox", detailHbox);

          // Add appropriate number of localized entries to the dropdown
          const menulist = createAppend("menulist", tooltipBox);
          menulist.setAttribute("crop", "none");
          const menupopup = createAppend("menupopup", menulist);
          for (let num = 1; num <= maxRows; num++) {
            const item = createAppend("menuitem", menupopup);
            document.l10n.setAttributes(
              item,
              "home-prefs-sections-rows-option",
              { num }
            );
            item.setAttribute("value", num);
          }
          linkPref(menulist, rowsPref, "int");
        }
      }

      const subChecks = [];
      const fullName = `browser.newtabpage.activity-stream.${sectionData.pref.feed}`;
      const pref = Preferences.get(fullName);

      // Add a checkbox pref for any nested preferences
      nestedPrefs.forEach(nested => {
        const subcheck = createAppend("checkbox", detailVbox);
        // Setup a user event if we have an event source for this pref.
        if (nested.eventSource) {
          this.setupUserEvent(subcheck, nested.eventSource);
        }
        subcheck.classList.add("indent");
        document.l10n.setAttributes(subcheck, nested.titleString);
        linkPref(subcheck, nested.name, "bool");
        subChecks.push(subcheck);
        subcheck.disabled = !pref._value;
        subcheck.hidden = nested.hidden;
      });

      // Disable any nested checkboxes if the parent pref is not enabled.
      pref.on("change", () => {
        subChecks.forEach(subcheck => {
          subcheck.disabled = !pref._value;
        });
      });
    });

    // Update the visibility of the Restore Defaults btn based on checked prefs
    gHomePane.toggleRestoreDefaultsBtn();
  }
}