summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/content-src/aboutwelcome/components/MRColorways.jsx
blob: 6a69f3483a788725b3b284938c88185263a6cb63 (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
/* 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 React, { useState, useEffect } from "react";
import { Localized } from "./MSLocalized";

export const ColorwayDescription = props => {
  const { colorway } = props;
  if (!colorway) {
    return null;
  }
  const { label, description } = colorway;
  return (
    <Localized text={description}>
      <div
        className="colorway-text"
        data-l10n-args={JSON.stringify({
          colorwayName: label,
        })}
      />
    </Localized>
  );
};

// Return colorway as "default" for default theme variations Automatic, Light, Dark,
// Alpenglow theme and legacy colorways which is not supported in Colorway picker.
// For themes other then default, theme names exist in
// format colorway-variationId inside LIGHT_WEIGHT_THEMES in AboutWelcomeParent
export function computeColorWay(themeName, systemVariations) {
  return !themeName ||
    themeName === "alpenglow" ||
    systemVariations.includes(themeName)
    ? "default"
    : themeName.split("-")[0];
}

// Set variationIndex based off activetheme value e.g. 'light', 'expressionist-soft'
export function computeVariationIndex(
  themeName,
  systemVariations,
  variations,
  defaultVariationIndex
) {
  // Check if themeName is in systemVariations, if yes choose variationIndex by themeName
  let index = systemVariations.findIndex(theme => theme === themeName);
  if (index >= 0) {
    return index;
  }

  // If themeName is one of the colorways, select variation index from colorways
  let variation = themeName?.split("-")[1];
  index = variations.findIndex(element => element === variation);
  if (index >= 0) {
    return index;
  }
  return defaultVariationIndex;
}

export function Colorways(props) {
  let {
    colorways,
    darkVariation,
    defaultVariationIndex,
    systemVariations,
    variations,
  } = props.content.tiles;
  let hasReverted = false;

  // Active theme id from JSON e.g. "expressionist"
  const activeId = computeColorWay(props.activeTheme, systemVariations);
  const [colorwayId, setState] = useState(activeId);
  const [variationIndex, setVariationIndex] = useState(defaultVariationIndex);

  function revertToDefaultTheme() {
    if (hasReverted) return;

    // Spoofing an event with current target value of "navigate_away"
    // helps the handleAction method to read the colorways theme as "revert"
    // which causes the initial theme to be activated.
    // The "navigate_away" action is set in content in the colorways screen JSON config.
    // Any value in the JSON for theme will work, provided it is not `<event>`.
    const event = {
      currentTarget: {
        value: "navigate_away",
      },
    };
    props.handleAction(event);
    hasReverted = true;
  }

  // Revert to default theme if the user navigates away from the page or spotlight modal
  // before clicking on the primary button to officially set theme.
  useEffect(() => {
    addEventListener("beforeunload", revertToDefaultTheme);
    addEventListener("pagehide", revertToDefaultTheme);

    return () => {
      removeEventListener("beforeunload", revertToDefaultTheme);
      removeEventListener("pagehide", revertToDefaultTheme);
    };
  });
  // Update state any time activeTheme changes.
  useEffect(() => {
    setState(computeColorWay(props.activeTheme, systemVariations));
    setVariationIndex(
      computeVariationIndex(
        props.activeTheme,
        systemVariations,
        variations,
        defaultVariationIndex
      )
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.activeTheme]);

  //select a random colorway
  useEffect(() => {
    //We don't want the default theme to be selected
    const randomIndex = Math.floor(Math.random() * (colorways.length - 1)) + 1;
    const randomColorwayId = colorways[randomIndex].id;

    // Change the variation to be the dark variation if configured and dark.
    // Additional colorway changes will remain dark while system is unchanged.
    if (
      darkVariation !== undefined &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
    ) {
      variations[variationIndex] = variations[darkVariation];
    }
    const value = `${randomColorwayId}-${variations[variationIndex]}`;
    props.handleAction({ currentTarget: { value } });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="tiles-theme-container">
      <div>
        <fieldset className="tiles-theme-section">
          <Localized text={props.content.subtitle}>
            <legend className="sr-only" />
          </Localized>
          {colorways.map(({ id, label, tooltip }) => (
            <Localized
              key={id + label}
              text={typeof tooltip === "object" ? tooltip : {}}
            >
              <label
                className="theme"
                title={label}
                data-l10n-args={JSON.stringify({
                  colorwayName: label,
                })}
              >
                <Localized text={typeof tooltip === "object" ? tooltip : {}}>
                  <span
                    className="sr-only colorway label"
                    id={`${id}-label`}
                    data-l10n-args={JSON.stringify({
                      colorwayName: tooltip,
                    })}
                  />
                </Localized>
                <Localized text={typeof label === "object" ? label : {}}>
                  <input
                    type="radio"
                    data-colorway={id}
                    name="theme"
                    value={
                      id === "default"
                        ? systemVariations[variationIndex]
                        : `${id}-${variations[variationIndex]}`
                    }
                    checked={colorwayId === id}
                    className="sr-only input"
                    onClick={props.handleAction}
                    data-l10n-args={JSON.stringify({
                      colorwayName: label,
                    })}
                    aria-labelledby={`${id}-label`}
                  />
                </Localized>
                <div
                  className={`icon colorway ${
                    colorwayId === id ? "selected" : ""
                  } ${id}`}
                />
              </label>
            </Localized>
          ))}
        </fieldset>
      </div>
      <ColorwayDescription
        colorway={colorways.find(colorway => colorway.id === activeId)}
      />
    </div>
  );
}