Skip to content
Open
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
1 change: 1 addition & 0 deletions cli/crowdin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export async function buildAllTranslationsAsync(fetchFileTranslationAsync: (file
await buildTranslationFilesAsync(["target-strings.json"], "target-strings.json");
await buildTranslationFilesAsync(["strings.json"], "strings.json", true);
await buildTranslationFilesAsync(["skillmap-strings.json"], "skillmap-strings.json", true);
await buildTranslationFilesAsync(["tutorialtool-strings.json"], "tutorialtool-strings.json", true);
await buildTranslationFilesAsync(["webstrings.json"], "webstrings.json", true);

const files: string[] = [];
Expand Down
18 changes: 17 additions & 1 deletion docs/static/tutorial-tool/tutorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ function loadIframe(selected) {
for (var _a = 0, _b = target.endpoints; _a < _b.length; _a++) {
var endpoint = _b[_a];
if (!selected || selected === target.name + "-" + endpoint.name) {
iframe.setAttribute("src", endpoint.url);
iframe.setAttribute("src", withLocale(endpoint.url));
selectedEndpoint = target.name + "-" + endpoint.name;
selectedId = target.id;
selectedTarget = target;
Expand All @@ -310,3 +310,19 @@ function loadIframe(selected) {
// Load first target
loadIframe(null);
}
// The legacy tool does not load the PXT localization runtime, so mirror only
// explicit language requests when it embeds an editor. The editor keeps its
// own saved-language and target-default fallback otherwise.
function withLocale(endpoint) {
var url = new URL(endpoint, window.location.href);
if (url.searchParams.has("lang") || url.searchParams.has("forcelang"))
return url.toString();
var hostUrl = new URL(window.location.href);
var hostParams = hostUrl.searchParams;
var hashParams = new URLSearchParams(hostUrl.hash.slice(1));
var forcedLanguage = hostParams.get("forcelang") || hashParams.get("forcelang");
var requestedLanguage = forcedLanguage || hostParams.get("lang") || hashParams.get("lang");
if (requestedLanguage)
url.searchParams.set(forcedLanguage ? "forcelang" : "lang", requestedLanguage);
return url.toString();
}
21 changes: 19 additions & 2 deletions docs/static/tutorial-tool/tutorial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ function loadIframe(selected: string) {
for (const target of targets) {
for (const endpoint of target.endpoints) {
if (!selected || selected === `${target.name}-${endpoint.name}`) {
iframe.setAttribute("src", endpoint.url);
iframe.setAttribute("src", withLocale(endpoint.url));
Comment thread
ChrisesDK marked this conversation as resolved.
Resolved
selectedEndpoint = `${target.name}-${endpoint.name}`;
selectedId = target.id;
selectedTarget = target;
Expand All @@ -343,4 +343,21 @@ function loadIframe(selected: string) {

// Load first target
loadIframe(null);
}
}

// The legacy tool does not load the PXT localization runtime, so mirror its
// language selection inputs when it embeds an editor.
function withLocale(endpoint: string): string {
const url = new URL(endpoint, window.location.href);
if (url.searchParams.has("lang") || url.searchParams.has("forcelang")) return url.toString();

const hostUrl = new URL(window.location.href);
const hostParams = hostUrl.searchParams;
const hashParams = new URLSearchParams(hostUrl.hash.slice(1));
const forcedLanguage = hostParams.get("forcelang") || hashParams.get("forcelang");
const requestedLanguage = forcedLanguage || hostParams.get("lang") || hashParams.get("lang");
if (requestedLanguage) {
url.searchParams.set(forcedLanguage ? "forcelang" : "lang", requestedLanguage);
}
return url.toString();
}
10 changes: 10 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,13 @@ const teacherTool = createWebappTasks("teachertool");
*********************************************************/

const tutorialTool = createWebappTasks("tutorialtool");
const buildTutorialToolTests = () => compileTsProject("tutorialtool/tests", "built/tests", true);
const runTutorialToolTests = () => exec(`${getMochaExecutable()} built/tests/tests/iframeUrl.spec.js built/tests/tests/legacyIframeUrl.spec.js built/tests/tests/localizationExtraction.spec.js --reporter dot`, true);
const testTutorialTool = gulp.series(
() => updateWebappStrings("tutorialtool"),
buildTutorialToolTests,
runTutorialToolTests
);

/********************************************************
Webapp build wrappers
Expand Down Expand Up @@ -816,6 +823,7 @@ const testAll = gulp.series(
testlanguageservice,
karma,
testSkillmap,
testTutorialTool,
testpxteditor,
testprojecttools,
testcli
Expand Down Expand Up @@ -927,7 +935,9 @@ exports.pxtrunner = gulp.series(
exports.pxtweb = pxtweb;
exports.pxtlib = pxtlib;
exports.skillmapTest = testSkillmap;
exports.tutorialtoolTest = testTutorialTool;
exports.updatestrings = updatestrings;
exports.tutorialtoolstrings = () => updateWebappStrings("tutorialtool");
exports.lint = lint
exports.testdecompiler = testdecompiler;
exports.testlang = testlang;
Expand Down
19 changes: 17 additions & 2 deletions pxtlib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1197,6 +1197,7 @@ namespace ts.pxtc.Util {
baseUrl: string;
code: string;
force?: boolean;
translationKind?: TranslationsKind;
}

export function updateLocalizationAsync(opts: LocalizationUpdateOptions): Promise<void> {
Expand All @@ -1218,14 +1219,20 @@ namespace ts.pxtc.Util {

const liveUpdateStrings = pxt.Util.liveLocalizationEnabled()
return downloadTranslationsAsync(targetId, baseUrl, code, liveUpdateStrings,
ts.pxtc.Util.TranslationsKind.Editor)
opts.translationKind || ts.pxtc.Util.TranslationsKind.Editor)
Comment thread
ChrisesDK marked this conversation as resolved.
Resolved
.then((translations) => {
if (translations) {
setUserLanguage(code);
pxt.analytics?.addDefaultProperties({ lang: code }); //set the new language in analytics.
setLocalizedStrings(translations);
}

// Tutorial Tool has no API surface, so avoid delaying its startup
// with an unused API catalog request.
if (opts.translationKind === ts.pxtc.Util.TranslationsKind.TutorialTool) {
return Promise.resolve();
}

// Download api translations
return ts.pxtc.Util.downloadTranslationsAsync(
targetId, baseUrl, code, liveUpdateStrings,
Expand All @@ -1243,7 +1250,8 @@ namespace ts.pxtc.Util {
Editor,
Sim,
Apis,
SkillMap
SkillMap,
TutorialTool
}

export function downloadTranslationsAsync(targetId: string, baseUrl: string, code: string, live: boolean, translationKind?: TranslationsKind): Promise<pxt.Map<string>> {
Expand Down Expand Up @@ -1278,6 +1286,13 @@ namespace ts.pxtc.Util {
{ staticName: "skillmap-strings.json", path: "/skillmap-strings.json" },
];
break;
case TranslationsKind.TutorialTool:
stringFiles = [
{ staticName: "strings.json", path: "strings.json" },
{ staticName: "target-strings.json", path: targetId + "/target-strings.json" },
{ staticName: "tutorialtool-strings.json", path: "/tutorialtool-strings.json" },
];
break;
}
let translations: pxt.Map<string>;
function mergeTranslations(tr: pxt.Map<string>) {
Expand Down
27 changes: 27 additions & 0 deletions tests/pxt-editor-test/editorrunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,33 @@ describe("simulator themes", () => {
]);
});

it("loads shared, target, and Tutorial Tool translations", async () => {
const requestedUrls: string[] = [];
const originalHttpGetJsonAsync = pxt.Util.httpGetJsonAsync;
pxt.Util.httpGetJsonAsync = <T>(url: string) => {
requestedUrls.push(url);
return Promise.resolve({} as T);
};

try {
await pxt.Util.downloadTranslationsAsync(
"arcade",
"https://example.com/",
"de",
false,
ts.pxtc.Util.TranslationsKind.TutorialTool
);
} finally {
pxt.Util.httpGetJsonAsync = originalHttpGetJsonAsync;
}

chai.expect(requestedUrls).to.include.members([
"https://example.com/locales/de/strings.json",
"https://example.com/locales/de/target-strings.json",
"https://example.com/locales/de/tutorialtool-strings.json",
]);
});

it("initializes an empty cloud-synced simulator theme map", () => {
chai.expect(pxt.auth.DEFAULT_USER_PREFERENCES().simulatorThemes).deep.equals({});
});
Expand Down
8 changes: 5 additions & 3 deletions tutorialtool/src/components/MakeCodeFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as React from "react";
import css from "./styling/MakeCodeFrame.module.scss";
import { setEditorRef } from "../services/makecodeEditorService";
import { getEditorUrl } from "../utils";
import { createTutorialToolEditorUrl } from "../utils/iframeUrl";
import { getLocaleParameter, getRequestedLocale } from "../utils/localization";

export interface MakeCodeFrameProps {
}
Expand All @@ -16,8 +18,7 @@ export const MakeCodeFrame = (props: MakeCodeFrameProps) => {
if (editorUrl.charAt(editorUrl.length - 1) === "/" && !pxt.BrowserUtils.isLocalHost()) {
url = editorUrl.substr(0, editorUrl.length - 1);
}
url += `?controller=1&teachertool=1&ws=mem&nocookiebanner=1`;
return url;
return createTutorialToolEditorUrl(url, window.location.href, getRequestedLocale() || pxt.Util.userLanguage(), getLocaleParameter());
}

const handleIframeRef = React.useCallback((ref: HTMLIFrameElement) => {
Expand All @@ -30,6 +31,7 @@ export const MakeCodeFrame = (props: MakeCodeFrameProps) => {
<iframe
className={css["makecode-frame"]}
src={createIFrameUrl()} ref={handleIframeRef}
title={lf("MakeCode editor")}
/>
);
}
}
24 changes: 15 additions & 9 deletions tutorialtool/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import "./global.scss";
import { App } from "./App";
import { AppStateProvider } from "./state/appStateContext";
import { Ticks } from "./constants";
import { initializeLocalizationAsync, localizeDocumentMetadata } from "./utils/localization";

function enableAnalytics() {
pxt.analytics.enable(pxt.Util.userLanguage());
Expand Down Expand Up @@ -45,14 +46,19 @@ window.addEventListener("DOMContentLoaded", () => {

pxt.Cloud.apiRoot = "https://www.makecode.com/api/";

enableAnalytics();
initializeLocalizationAsync()
.catch(e => pxt.log(`Unable to load Tutorial Tool localization: ${e}`))
.then(() => {
localizeDocumentMetadata();
enableAnalytics();

ReactDOM.render(
<React.StrictMode>
<AppStateProvider>
<App />
</AppStateProvider>
</React.StrictMode>,
document.getElementById("root")
);
ReactDOM.render(
<React.StrictMode>
<AppStateProvider>
<App />
</AppStateProvider>
</React.StrictMode>,
document.getElementById("root")
);
});
});
66 changes: 66 additions & 0 deletions tutorialtool/src/utils/iframeUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
export type LocaleParameter = "lang" | "forcelang";

export interface LocaleRequest {
language?: string;
parameter?: LocaleParameter;
live: boolean;
}

export function getLocaleRequest(url: string): LocaleRequest {
const parsed = new URL(url, "https://makecode.com");
return getLocaleRequestFromParams(parsed.searchParams)
|| getLocaleRequestFromParams(new URLSearchParams(parsed.hash.slice(1)))
|| { live: false };
}

function getLocaleRequestFromParams(params: URLSearchParams): LocaleRequest | undefined {
for (const [parameter, live] of [["liveforcelang", true], ["forcelang", false], ["livelang", true], ["lang", false]] as const) {
const language = params.get(parameter);
if (language) {
return {
language,
parameter: parameter.endsWith("forcelang") ? "forcelang" : "lang",
live
};
}
}

return undefined;
}

export function addLocaleToUrl(
editorUrl: string,
hostUrl: string,
resolvedLanguage?: string,
requestedParameter?: LocaleParameter
): string {
const url = new URL(editorUrl, hostUrl);
if (url.searchParams.has("forcelang") || url.searchParams.has("lang")) {
return url.toString();
}

const requested = getLocaleRequest(hostUrl);
if (requested.language) {
url.searchParams.set(requested.parameter!, requested.language);
} else if (resolvedLanguage && (requestedParameter || !/^en(?:-us)?$/i.test(resolvedLanguage))) {
url.searchParams.set(requestedParameter || "lang", resolvedLanguage);
}
return url.toString();
}

export function createTutorialToolEditorUrl(
editorUrl: string,
hostUrl: string,
resolvedLanguage?: string,
requestedParameter?: LocaleParameter
): string {
const url = new URL(editorUrl, hostUrl);

// These values are required by the Tutorial Tool and match the base behavior.
url.searchParams.set("controller", "1");
url.searchParams.set("teachertool", "1");
url.searchParams.set("ws", "mem");
url.searchParams.set("nocookiebanner", "1");

return addLocaleToUrl(url.toString(), hostUrl, resolvedLanguage, requestedParameter);
}
74 changes: 74 additions & 0 deletions tutorialtool/src/utils/localization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { getLocaleRequest, LocaleParameter } from "./iframeUrl";

let localeParameter: LocaleParameter | undefined;
let requestedLocale: string | undefined;

export function getLocaleParameter() {
return localeParameter;
}

export function getRequestedLocale() {
return requestedLocale;
}

/** Initialize localization using the same selection semantics as the editor. */
export async function initializeLocalizationAsync(): Promise<void> {
const href = window.location.href;
const theme = pxt.appTarget.appTheme;
const request = getLocaleRequest(href);
const translationMode = /[&?]translate=1/.test(href) && !pxt.BrowserUtils.isIE();

let language: string;
let force = false;
if (translationMode) {
language = ts.pxtc.Util.TRANSLATION_LOCALE;
force = true;
localeParameter = "forcelang";
requestedLocale = language;
pxt.Util.enableLiveLocalizationUpdates();
} else {
const hashMatch = /(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(window.location.hash);
if (hashMatch) pxt.BrowserUtils.changeHash(window.location.hash.replace(hashMatch[0], ""));

language = request.language
|| pxt.BrowserUtils.getCookieLang()
|| theme.defaultLocale
|| (navigator as any).userLanguage
|| navigator.language;
force = request.parameter === "forcelang";
localeParameter = request.parameter;
requestedLocale = request.language;

const staticLanguage = /staticlang=1/i.test(href);
const defaultLocale = theme.defaultLocale;
const languageLowerCase = language?.toLocaleLowerCase();
const localDevServe = pxt.BrowserUtils.isLocalHostDev()
&& (!languageLowerCase || (defaultLocale
? defaultLocale.toLocaleLowerCase() === languageLowerCase
: languageLowerCase === "en" || languageLowerCase === "en-us"));
const serveLocal = pxt.BrowserUtils.isPxtElectron() || localDevServe;
const updatesDisabled = staticLanguage || serveLocal || theme.disableLiveTranslations;

if (!updatesDisabled || request.live) {
pxt.Util.enableLiveLocalizationUpdates();
}
}

await pxt.Util.updateLocalizationAsync({
targetId: pxt.appTarget.id,
baseUrl: pxt.webConfig.commitCdnUrl,
code: language,
force,
translationKind: ts.pxtc.Util.TranslationsKind.TutorialTool
});

if (pxt.Util.isLocaleEnabled(language)) {
pxt.BrowserUtils.setCookieLang(language);
}
}

export function localizeDocumentMetadata() {
document.documentElement.lang = pxt.Util.userLanguage();
document.title = pxt.Util.lf("MakeCode Tutorial Tool");
document.querySelector('meta[name="description"]')?.setAttribute("content", pxt.Util.lf("MakeCode Tutorial Tool. Build markdown tutorials for MakeCode editors"));
}
Loading