From 38e38f4644b23031fb8a36105667ab776e234296 Mon Sep 17 00:00:00 2001 From: Anthony Shull Date: Fri, 31 Jan 2025 14:53:54 -0600 Subject: [PATCH] Maintain locale information when visiting MyCharlie (#2348) --- assets/js/translate-analytics.js | 10 ++++++++++ lib/dotcom/content_rewriter.ex | 1 + lib/dotcom/content_rewriters/links.ex | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/assets/js/translate-analytics.js b/assets/js/translate-analytics.js index f4d7080bfc..e08d4beab5 100644 --- a/assets/js/translate-analytics.js +++ b/assets/js/translate-analytics.js @@ -14,6 +14,10 @@ export default () => { if (typeof MutationObserver === "function") { // Tell the observer to monitor for changes to HTML attributes const config = { attributes: true }; + + // Get the language of the page on load. + const oldLanguage = document.querySelector("html").getAttribute("lang"); + // Build the function to run when a change is observed const callback = mutationList => { // Loop through each observed change @@ -36,6 +40,12 @@ export default () => { event: "translate", language: newLanguage && newLanguage !== "en" ? newLanguage : "" }); + + // If the page loaded with one language and switched to another, we have to reload the page. + // This is so that page content can be rendered differently with the added cookie information. + if (newLanguage !== oldLanguage) { + window.location.reload(); + } } } } diff --git a/lib/dotcom/content_rewriter.ex b/lib/dotcom/content_rewriter.ex index 1bafe1810d..2752201046 100644 --- a/lib/dotcom/content_rewriter.ex +++ b/lib/dotcom/content_rewriter.ex @@ -94,6 +94,7 @@ defmodule Dotcom.ContentRewriter do element |> Links.add_target_to_redirect() |> Links.add_preview_params(conn) + |> Links.add_locale_params(conn) |> rewrite_children(conn, context) end diff --git a/lib/dotcom/content_rewriters/links.ex b/lib/dotcom/content_rewriters/links.ex index bc7068258e..481068fa03 100644 --- a/lib/dotcom/content_rewriters/links.ex +++ b/lib/dotcom/content_rewriters/links.ex @@ -40,4 +40,24 @@ defmodule Dotcom.ContentRewriters.Links do element end end + + @doc """ + If the user has used Google Translate on dotcom, we want to forward them to MyCharlie with the same language. + """ + def add_locale_params({"a", attrs, children} = element, %{cookies: %{"googtrans" => languages}}) do + attr_map = Enum.into(attrs, %{}) + href = Map.get(attr_map, "href", "") + locale = String.split(languages, "/") |> List.last() + + if String.match?(href, ~r/mycharlie.mbta.com/) do + updated_href = "#{href}?locale=#{locale}" + updated_attrs = attr_map |> Map.replace!("href", updated_href) |> Map.to_list() + + {"a", updated_attrs, children} + else + element + end + end + + def add_locale_params(element, _conn), do: element end