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

📦 externalized portal locales #21945

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
17 changes: 13 additions & 4 deletions apps/portal/src/App.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-check
import React from 'react';
import * as Sentry from '@sentry/react';
import TriggerButton from './components/TriggerButton';
Expand All @@ -15,7 +16,7 @@ import './App.css';
import {hasRecommendations, allowCompMemberUpgrade, createPopupNotification, hasAvailablePrices, getCurrencySymbol, getFirstpromoterId, getPriceIdFromPageQuery, getProductCadenceFromPrice, getProductFromId, getQueryPrice, getSiteDomain, isActiveOffer, isComplimentaryMember, isInviteOnly, isPaidMember, isRecentMember, isSentryEventAllowed, removePortalLinkFromUrl} from './utils/helpers';
import {handleDataAttributes} from './data-attributes';

import i18nLib from '@tryghost/i18n';
import {createAsyncInstance} from '@tryghost/i18n/browser.mjs';

const DEV_MODE_DATA = {
showPopup: true,
Expand Down Expand Up @@ -191,10 +192,18 @@ export default class App extends React.Component {
/** Initialize portal setup on load, fetch data and setup state*/
async initSetup() {
try {
// i18n should be initialized in only one location, so create the instance before performing any async operations
const baseLocale = (this.props.siteI18nEnabled && this.props.locale) || 'en';
const i18n = createAsyncInstance('portal', baseLocale, this.props.localeRoot);

// Fetch data from API, links, preview, dev sources
const {site, member, page, showPopup, popupNotification, lastPage, pageQuery, pageData} = await this.fetchData();
const i18nLanguage = this.props.siteI18nEnabled ? this.props.locale || site.locale || 'en' : 'en';
const i18n = i18nLib(i18nLanguage, 'portal');

const localeWithSite = this.props.siteI18nEnabled && !this.props.locale && site.locale;

if (localeWithSite && baseLocale !== localeWithSite) {
i18n.changeLanguage(localeWithSite);
}

const state = {
site,
Expand All @@ -209,7 +218,7 @@ export default class App extends React.Component {
dir: i18n.dir() || 'ltr',
action: 'init:success',
initStatus: 'success',
locale: i18nLanguage
locale: localeWithSite || baseLocale
};

this.handleSignupQuery({site, pageQuery, member});
Expand Down
14 changes: 5 additions & 9 deletions apps/portal/src/data-attributes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// @ts-check
/* eslint-disable no-console */
import {getCheckoutSessionDataFromPlanAttribute, getUrlHistory} from './utils/helpers';
import {HumanReadableError, chooseBestErrorMessage} from './utils/errors';
import i18nLib from '@tryghost/i18n';
import {getAsyncInstance} from '@tryghost/i18n/browser.mjs';

export function formSubmitHandler({event, form, errorEl, siteUrl, submitHandler},
t = (str) => {
Expand Down Expand Up @@ -94,10 +95,7 @@ export function formSubmitHandler({event, form, errorEl, siteUrl, submitHandler}
});
}

export function planClickHandler({event, el, errorEl, siteUrl, site, member, clickHandler}) {
const i18nLanguage = site.locale | 'en';
const i18n = i18nLib(i18nLanguage, 'portal');
const t = i18n.t;
export function planClickHandler({event, el, errorEl, siteUrl, site, member, clickHandler, t}) {
el.removeEventListener('click', clickHandler);
event.preventDefault();
let plan = el.dataset.membersPlan;
Expand Down Expand Up @@ -178,9 +176,7 @@ export function planClickHandler({event, el, errorEl, siteUrl, site, member, cli
}

export function handleDataAttributes({siteUrl, site, member}) {
const i18nLanguage = site.locale | 'en';
const i18n = i18nLib(i18nLanguage, 'portal');
const t = i18n.t;
const {t} = getAsyncInstance('portal');
if (!siteUrl) {
return;
}
Expand All @@ -196,7 +192,7 @@ export function handleDataAttributes({siteUrl, site, member}) {
Array.prototype.forEach.call(document.querySelectorAll('[data-members-plan]'), function (el) {
let errorEl = el.querySelector('[data-members-error]');
function clickHandler(event) {
planClickHandler({el, event, errorEl, member, site, siteUrl, clickHandler});
planClickHandler({el, event, errorEl, member, site, siteUrl, clickHandler, t});
}
el.addEventListener('click', clickHandler);
});
Expand Down
17 changes: 14 additions & 3 deletions apps/portal/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,18 @@ function getSiteData() {
const apiKey = scriptTag.dataset.key;
const apiUrl = scriptTag.dataset.api;
const locale = scriptTag.dataset.locale; // not providing a fallback here but will do it within the app.
return {siteUrl, apiKey, apiUrl, siteI18nEnabled, locale};
let localeRoot = scriptTag.dataset.localeRoot ?? './locales';

// CASE: The root is based on the current script, resolve it
if (localeRoot.startsWith('.')) {
const currentPath = import.meta.url.slice(0, import.meta.url.lastIndexOf('/'));
localeRoot = new URL(localeRoot, currentPath).href;
}

// Remove the trailing slash since it's not needed by our i18n implementation
localeRoot = localeRoot.replace(/\/$/, '');

return {siteUrl, apiKey, apiUrl, siteI18nEnabled, locale, localeRoot};
}
return {};
}
Expand All @@ -42,12 +53,12 @@ function setup() {

function init() {
// const customSiteUrl = getSiteUrl();
const {siteUrl: customSiteUrl, apiKey, apiUrl, siteI18nEnabled, locale} = getSiteData();
const {siteUrl: customSiteUrl, apiKey, apiUrl, siteI18nEnabled, locale, localeRoot} = getSiteData();
const siteUrl = customSiteUrl || window.location.origin;
setup({siteUrl});
ReactDOM.render(
<React.StrictMode>
<App siteUrl={siteUrl} customSiteUrl={customSiteUrl} apiKey={apiKey} apiUrl={apiUrl} siteI18nEnabled={siteI18nEnabled} locale={locale}/>
<App siteUrl={siteUrl} customSiteUrl={customSiteUrl} apiKey={apiKey} apiUrl={apiUrl} siteI18nEnabled={siteI18nEnabled} locale={locale} localeRoot={localeRoot} />
</React.StrictMode>,
document.getElementById(ROOT_DIV_ID)
);
Expand Down
11 changes: 3 additions & 8 deletions apps/portal/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import {defineConfig} from 'vitest/config';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import reactPlugin from '@vitejs/plugin-react';
import svgrPlugin from 'vite-plugin-svgr';
import {ghostI18nPlugin} from '@tryghost/i18n/plugin.js';

import pkg from './package.json';

import {SUPPORTED_LOCALES} from '@tryghost/i18n';

export default defineConfig((config) => {
const outputFileName = pkg.name[0] === '@' ? pkg.name.slice(pkg.name.indexOf('/') + 1) : pkg.name;

Expand All @@ -30,7 +29,8 @@ export default defineConfig((config) => {
plugins: [
cssInjectedByJsPlugin(),
reactPlugin(),
svgrPlugin()
svgrPlugin(),
ghostI18nPlugin('portal', 'opt-in'),
],
esbuild: {
loader: 'jsx',
Expand Down Expand Up @@ -69,11 +69,6 @@ export default defineConfig((config) => {
output: {
manualChunks: false
}
},
commonjsOptions: {
include: [/ghost/, /node_modules/],
dynamicRequireRoot: '../../',
dynamicRequireTargets: SUPPORTED_LOCALES.map(locale => `../../ghost/i18n/locales/${locale}/portal.json`)
}
},
test: {
Expand Down
2 changes: 1 addition & 1 deletion ghost/core/core/frontend/helpers/ghost_head.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function getMembersHelper(data, frontendKey, excludeList) {
attributes['accent-color'] = colorString;
}
const dataAttributes = getDataAttributes(attributes);
membersHelper += `<script defer src="${scriptUrl}" ${dataAttributes} crossorigin="anonymous"></script>`;
membersHelper += `<script type="module" defer src="${scriptUrl}" ${dataAttributes} crossorigin="anonymous"></script>`;
}
if (!excludeList.has('cta_styles')) {
membersHelper += (`<style id="gh-members-styles">${templateStyles}</style>`);
Expand Down
Loading
Loading