Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clients(psi): expose hasLocale in bundle types #14325

Merged
merged 2 commits into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion build/build-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,17 @@ export function swapLocale(lhr, requestedLocale) {
function registerLocaleData(locale, lhlMessages) {
// Stub function only included for types
}
export const format = {registerLocaleData};

/**
* Returns whether the requestedLocale is registered and available for use
* @param {LH.Locale} requestedLocale
* @return {boolean}
*/
function hasLocale(requestedLocale) {
// Stub function only included for types
return false;
}
export const format = {registerLocaleData, hasLocale};
`;

const bundle = await rollup({
Expand Down
2 changes: 1 addition & 1 deletion report/test-assets/faux-psi-template.html
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
</head>
<body >
<noscript>PSI requires JavaScript. Please enable.</noscript>
<button type=button id="translate">→ Español</button>
<button type=button id="translate">rotate locale</button>
<div class="page">
<button type=button id="reanalyze">Reanalyze</button>
<div class="tabset">
Expand Down
146 changes: 80 additions & 66 deletions report/test-assets/faux-psi.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,91 +13,105 @@ const lighthouseRenderer = window['report'];

const wait = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms));


(async function __initPsiReports__() {
renderLHReport();

document.querySelector('button#reanalyze')?.addEventListener('click', () => {
renderLHReport();
__initPsiReports__();
});

document.querySelector('button#translate')?.addEventListener('click', async () => {
await swapLhrLocale('es');
renderLHReport();
const hash = location.hash.slice(1);
const someLocales = ['es', 'ja', 'ru', 'ar', 'en-US'];
// Just rotate to the next one
const nextLocale = someLocales[(someLocales.indexOf(hash) + 1) % someLocales.length];
location.hash = `#${nextLocale}`;
location.reload();
});
})();

async function renderLHReport() {
// @ts-expect-error
const mobileLHR = window.__LIGHTHOUSE_JSON__;
const desktopLHR = JSON.parse(JSON.stringify(mobileLHR));
const hash = location.hash.slice(1);
if (hash) {
// @ts-expect-error Can't do string to LH.Locale
await swapLhrLocale(hash);
}

const lhrs = {
'mobile': mobileLHR,
'desktop': desktopLHR,
};
// We deliberately want the non-blocking await behavior w/ forEach
['mobile', 'desktop'].forEach(async id => {
const container = document.querySelector(`section#${id} .reportContainer`);
if (!container) throw new Error('Unexpected DOM. Bailing.');
container.textContent = 'Analyzing…';
await wait(id === 'desktop' ? 3000 : 500);

for (const [tabId, lhr] of Object.entries(lhrs)) {
await distinguishLHR(lhr, tabId);
// @ts-expect-error
const lhr = JSON.parse(JSON.stringify(window.__LIGHTHOUSE_JSON__));
await distinguishLHR(lhr, id);

const container = document.querySelector(`section#${tabId} .reportContainer`);
if (!container) throw new Error('Unexpected DOM. Bailing.');
renderLHReport(lhr, container);
});
})();

try {
container.textContent = 'Analyzing…';
await wait(500);
for (const el of container.childNodes) el.remove();

const reportRootEl = lighthouseRenderer.renderReport(lhr, {
omitTopbar: true,
disableFireworks: true,
disableDarkMode: true,
});
// TODO: display warnings if appropriate.
for (const el of reportRootEl.querySelectorAll('.lh-warnings--toplevel')) {
el.setAttribute('hidden', 'true');
}

// Move env block
const metaItemsEl = reportRootEl.querySelector('.lh-meta__items');
if (metaItemsEl) {
reportRootEl.querySelector('.lh-metrics-container')?.parentNode?.insertBefore(
metaItemsEl,
reportRootEl.querySelector('.lh-buttons')
);
reportRootEl.querySelector('.lh-metrics-container')?.closest('.lh-category')?.classList
.add('lh--hoisted-meta');
}

container.append(reportRootEl);

// Override some LH styles. (To find .lh-vars we must descend from reportRootEl's parent)
for (const el of container.querySelectorAll('article.lh-vars')) {
// Ensure these css var names are not stale.
el.style.setProperty('--report-content-max-width', '100%');
el.style.setProperty('--edge-gap-padding', '0');
}
for (const el of reportRootEl.querySelectorAll('footer.lh-footer')) {
el.style.display = 'none';
}
} catch (e) {
console.error(e);
container.textContent = 'Error: LHR failed to render.';
/**
* @param {any} lhr
* @param {Element} container
*/
async function renderLHReport(lhr, container) {
try {
for (const el of container.childNodes) el.remove();

const reportRootEl = lighthouseRenderer.renderReport(lhr, {
omitTopbar: true,
disableFireworks: true,
disableDarkMode: true,
});
// TODO: display warnings if appropriate.
for (const el of reportRootEl.querySelectorAll('.lh-warnings--toplevel')) {
el.setAttribute('hidden', 'true');
}

// Move env block
const metaItemsEl = reportRootEl.querySelector('.lh-meta__items');
if (metaItemsEl) {
reportRootEl.querySelector('.lh-metrics-container')?.parentNode?.insertBefore(
metaItemsEl,
reportRootEl.querySelector('.lh-buttons')
);
reportRootEl.querySelector('.lh-metrics-container')?.closest('.lh-category')?.classList
.add('lh--hoisted-meta');
}

container.append(reportRootEl);

// Override some LH styles. (To find .lh-vars we must descend from reportRootEl's parent)
for (const el of container.querySelectorAll('article.lh-vars')) {
// Ensure these css var names are not stale.
el.style.setProperty('--report-content-max-width', '100%');
el.style.setProperty('--edge-gap-padding', '0');
}
for (const el of reportRootEl.querySelectorAll('footer.lh-footer')) {
el.style.display = 'none';
}
} catch (e) {
console.error(e);
container.textContent = 'Error: LHR failed to render.';
}
}

/**
* @param {LH.Locale} locale
*/
async function swapLhrLocale(locale) {
const response = await fetch(`https://www.gstatic.com/pagespeed/insights/ui/locales/${locale}.json`);
/** @type {import('../../shared/localization/locales').LhlMessages} */
const lhlMessages = await response.json();
console.log(lhlMessages);
if (!lhlMessages) throw new Error(`could not fetch data for locale: ${locale}`);

lighthouseRenderer.format.registerLocaleData(locale, lhlMessages);
// @ts-expect-error LHR global
const lhrLocale = window.__LIGHTHOUSE_JSON__['configSettings']['locale'];

// Only fetch and swapLocale if necessary.
if (lhrLocale === locale) return;

if (!lighthouseRenderer.format.hasLocale(locale)) {
// Requires running a server in LH root and viewing localhost:XXXX/dist/sample-reports/⌣.psi.english/index.html
const response = await fetch(`/shared/localization/locales/${locale}.json`);
/** @type {import('../../shared/localization/locales').LhlMessages} */
const lhlMessages = await response.json();
if (!lhlMessages) throw new Error(`could not fetch data for locale: ${locale}`);
lighthouseRenderer.format.registerLocaleData(locale, lhlMessages);
}
// @ts-expect-error LHR global
window.__LIGHTHOUSE_JSON__ = lighthouseRenderer.swapLocale(window.__LIGHTHOUSE_JSON__, locale)
.lhr;
Expand Down
2 changes: 1 addition & 1 deletion shared/localization/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ function _getLocaleMessages(locale) {
}

/**
* Returns whether the `requestedLocale` can be used.
* Returns whether the `requestedLocale` is registered and available for use
* @param {LH.Locale} requestedLocale
* @return {boolean}
*/
Expand Down