diff --git a/libs/pxt-common/pxt-core.d.ts b/libs/pxt-common/pxt-core.d.ts index 00cdce5f3202..d97ec35eb22c 100644 --- a/libs/pxt-common/pxt-core.d.ts +++ b/libs/pxt-common/pxt-core.d.ts @@ -15,6 +15,7 @@ interface Array { //% help=arrays/push //% shim=Array_::push weight=50 //% blockId="array_push" block="%list| add value %value| to end" blockNamespace="arrays" + //% list.fieldOptions.localizeVariable=true //% list.label="list to change" item.label="value to add" //% group="Modify" push(item: T): void; @@ -710,4 +711,4 @@ declare namespace control { //% shim=_control::_onCodeStop export function _onCodeStop(arg: any): void; -} \ No newline at end of file +} diff --git a/localtypings/pxtarget.d.ts b/localtypings/pxtarget.d.ts index 911c2d6f66fd..3ab513fa9cbf 100644 --- a/localtypings/pxtarget.d.ts +++ b/localtypings/pxtarget.d.ts @@ -925,6 +925,7 @@ declare namespace ts.pxtc { blockCombineSetHelp?: string; blockCombineChangeHelp?: string; blockSetVariable?: string; // show block with variable assigment in toolbox. Set equal to a name to control the var name + blockSetVariableLocalizable?: boolean; // extract blockSetVariable as display-only localization; the stored variable name is unchanged fixedInstances?: boolean; fixedInstance?: boolean; expose?: boolean; // expose to VM despite being in pxt:: namespace diff --git a/pxtblocks/fields/field_kind.ts b/pxtblocks/fields/field_kind.ts index 6256eed21ac0..7593339c4b83 100644 --- a/pxtblocks/fields/field_kind.ts +++ b/pxtblocks/fields/field_kind.ts @@ -128,11 +128,12 @@ function createMenuGenerator(opts: pxtc.KindInfo): Blockly.MenuGeneratorFunction if (sourceBlock?.workspace && !sourceBlock.isInFlyout) { const options = sourceBlock.workspace.getVariableMap().getVariablesOfType(kindType(opts.name)); options.forEach(model => { - res.push([model.getName(), model.getName()]); + const name = model.getName(); + res.push([getInitialMemberDisplayName(opts, name), name]); }); } else { // Can't create variables from within the flyout, so we just have to fake it - opts.initialMembers.forEach((e) => res.push([e, e]) ); + opts.initialMembers.forEach((e) => res.push([getInitialMemberDisplayName(opts, e), e]) ); } @@ -145,6 +146,13 @@ function createMenuGenerator(opts: pxtc.KindInfo): Blockly.MenuGeneratorFunction } } +function getInitialMemberDisplayName(opts: pxtc.KindInfo, name: string) { + const displayNames = opts.initialMemberDisplayNames; + return displayNames && Object.prototype.hasOwnProperty.call(displayNames, name) + ? displayNames[name] + : name; +} + type PromptFunction = (ws: Blockly.Workspace, opts: U, message: string, cb: (newValue: string) => void) => void; function promptForName(ws: Blockly.Workspace, opts: U, message: string, cb: (newValue: string) => void, promptFn: PromptFunction) { @@ -231,4 +239,4 @@ function createVariableForKind(ws: Blockly.Workspace, opts: pxtc.KindInfo, newNa function kindType(name: string) { return "KIND_" + name; -} \ No newline at end of file +} diff --git a/pxtblocks/loader.ts b/pxtblocks/loader.ts index 94cdcda3c203..e5b5bbdcd05e 100644 --- a/pxtblocks/loader.ts +++ b/pxtblocks/loader.ts @@ -27,7 +27,7 @@ import { COLOR_PICKER_BLOCK_TYPE } from "./plugins/colorpicker"; import { setDraggableShadowBlocks, setDuplicateOnDrag, setDuplicateOnDragStrategy } from "./plugins/duplicateOnDrag"; import { initCopyPaste } from "./copyPaste"; export { initCopyPaste } from "./copyPaste"; -import { FieldVariable } from "./plugins/newVariableField/fieldVariable"; +import { FieldVariable, setVariableFieldLocalizeFunction } from "./plugins/newVariableField/fieldVariable"; import { ArgumentReporterBlock, FieldArgumentReporter, setArgumentReporterLocalizeFunction } from "./plugins/functions"; import { getArgumentReporterParent } from "./plugins/functions/utils"; import { isFunctionDefinition } from "./compiler/util"; @@ -111,6 +111,13 @@ export function blockSymbol(type: string): pxtc.SymbolInfo { export function injectBlocks(blockInfo: pxtc.BlocksInfo): pxtc.SymbolInfo[] { cachedBlockInfo = blockInfo; + setVariableFieldLocalizeFunction((field, variable) => { + const info = getVariableFieldLocalizationInfo(field, variable, blockInfo); + if (!info) return undefined; + const localized = pxtc.getBlockTranslationsCacheKey(info.localizationKey); + return localized ? localized + info.suffix : undefined; + }); + setDraggableShadowBlocks([ COLOR_PICKER_BLOCK_TYPE, ...blockInfo.blocks.filter(fn => fn.attributes.duplicateShadowOnDrag).map(fn => fn.attributes.blockId) @@ -138,6 +145,63 @@ export function injectBlocks(blockInfo: pxtc.BlocksInfo): pxtc.SymbolInfo[] { }); } +export interface VariableFieldLocalizationInfo { + localizationKey: string; + suffix: string; +} + +export function getVariableFieldLocalizationInfo( + field: FieldVariable, + variable: Blockly.IVariableModel, + blockInfo: pxtc.BlocksInfo +): VariableFieldLocalizationInfo { + const sourceBlock = field.getSourceBlock(); + if (!sourceBlock || !blockInfo) return undefined; + + const rawName = variable.getName(); + let defaultName: string; + let allowNumericSuffix = false; + + if (sourceBlock.type === "variables_set") { + const valueBlock = sourceBlock.getInputTargetBlock("VALUE"); + const fn = valueBlock && blockInfo.blocksById[valueBlock.type]; + if (fn?.attributes.blockSetVariableLocalizable) { + defaultName = pxt.blocks.blockSetVariableName(fn); + allowNumericSuffix = true; + } + } + else if (sourceBlock.type === "variables_get") { + const parent = sourceBlock.getParent(); + const fn = parent && blockInfo.blocksById[parent.type]; + if (fn) { + const input = parent.inputList.filter(i => i.connection?.targetBlock() === sourceBlock)[0]; + if (input) { + const comp = pxt.blocks.compileInfo(fn); + const params = comp.thisParameter ? [comp.thisParameter, ...comp.parameters] : comp.parameters; + const param = params.filter(p => p.definitionName === input.name)[0]; + if (param && pxt.blocks.isVariableNameLocalizable(param)) { + defaultName = pxt.blocks.variableDefaultName(param.defaultValue, param.shadowBlockId); + allowNumericSuffix = !!defaultName; + } + } + } + } + + if (!defaultName) return undefined; + if (rawName === defaultName) { + return { localizationKey: pxt.blocks.variableNameLocalizationKey(defaultName), suffix: "" }; + } + + if (allowNumericSuffix && rawName.indexOf(defaultName) === 0) { + const suffix = rawName.slice(defaultName.length); + if (/^(?:[2-9]|[1-9][0-9]+)$/.test(suffix)) { + return { localizationKey: pxt.blocks.variableNameLocalizationKey(defaultName), suffix }; + } + } + + return undefined; +} + function injectBlockDefinition(info: pxtc.BlocksInfo, fn: pxtc.SymbolInfo, comp: pxt.blocks.BlockCompileInfo, blockXml: HTMLElement): boolean { let id = fn.attributes.blockId; diff --git a/pxtblocks/plugins/newVariableField/fieldVariable.ts b/pxtblocks/plugins/newVariableField/fieldVariable.ts index 89d3f5226cbe..3866f1071fcb 100644 --- a/pxtblocks/plugins/newVariableField/fieldVariable.ts +++ b/pxtblocks/plugins/newVariableField/fieldVariable.ts @@ -1,5 +1,7 @@ import * as Blockly from "blockly"; +let localizeFunction: ((field: FieldVariable, variable: Blockly.IVariableModel) => string) | undefined; + /** * This is the same as the Blockly variable field but with the addition * of a "New Variable" option in the dropdown @@ -10,6 +12,15 @@ export class FieldVariable extends Blockly.FieldVariable { static dropdownCreate(this: FieldVariable): Blockly.MenuOption[] { const options = Blockly.FieldVariable.dropdownCreate.call(this) as Blockly.MenuOption[]; + for (const option of options) { + if (option === Blockly.FieldDropdown.SEPARATOR) continue; + const variable = this.sourceBlock_?.workspace.getVariableMap().getVariableById(option[1]); + if (variable && localizeFunction) { + const localized = localizeFunction(this, variable); + if (localized) option[0] = localized; + } + } + const insertIndex = options.findIndex(e => e[1] === "RENAME_VARIABLE_ID"); options.splice( @@ -34,6 +45,43 @@ export class FieldVariable extends Blockly.FieldVariable { this.menuGenerator_ = FieldVariable.dropdownCreate; } + override init(): void { + super.init(); + this.sourceBlock_?.workspace.addChangeListener(this.onWorkspaceChange); + } + + protected override getDisplayText_(): string { + const variable = this.getVariable(); + if (variable && localizeFunction) { + const localized = localizeFunction(this, variable); + if (localized) return localized; + } + + return super.getDisplayText_(); + } + + override getAriaValue(): string { + const variable = this.getVariable(); + if (variable && localizeFunction) { + const localized = localizeFunction(this, variable); + if (localized) return localized; + } + + return super.getAriaValue(); + } + + private onWorkspaceChange = (event: Blockly.Events.Abstract) => { + if (event.type !== Blockly.Events.BLOCK_MOVE) return; + + const sourceBlock = this.getSourceBlock(); + const moved = event as Blockly.Events.BlockMove; + if (sourceBlock && (moved.blockId === sourceBlock.id + || moved.oldParentId === sourceBlock.id + || moved.newParentId === sourceBlock.id)) { + this.forceRerender(); + } + }; + protected override onItemSelected_(menu: Blockly.Menu, menuItem: Blockly.MenuItem) { if (this.sourceBlock_ && !this.sourceBlock_.isDeadOrDying()) { const id = menuItem.getValue(); @@ -142,6 +190,7 @@ export class FieldVariable extends Blockly.FieldVariable { } override dispose() { + this.sourceBlock_?.workspace.removeChangeListener(this.onWorkspaceChange); super.dispose(); if (this.svgRootBinding) { Blockly.browserEvents.unbind(this.svgRootBinding); @@ -190,3 +239,7 @@ export class FieldVariable extends Blockly.FieldVariable { // Override the default variable field Blockly.fieldRegistry.unregister("field_variable"); Blockly.fieldRegistry.register("field_variable", FieldVariable); + +export function setVariableFieldLocalizeFunction(func: ((field: FieldVariable, variable: Blockly.IVariableModel) => string) | undefined) { + localizeFunction = func; +} diff --git a/pxtcompiler/emitter/service.ts b/pxtcompiler/emitter/service.ts index 11905bd7f476..95bf36d20c02 100644 --- a/pxtcompiler/emitter/service.ts +++ b/pxtcompiler/emitter/service.ts @@ -355,10 +355,18 @@ namespace ts.pxtc { locStrings[param.labelLocalizationKey] = param.label; } - const defaultString = pxt.blocks.parameterDefaultToLocalizationString(param.defaultValue, param.type); - const defaultLocalizationKey = pxt.blocks.parameterDefaultLocalizationKey(si.qName, param.actualName); - if (defaultLocalizationKey && defaultString !== undefined) { - locStrings[defaultLocalizationKey] = defaultString; + const variableName = pxt.blocks.variableDefaultName(param.defaultValue, param.shadowBlockId); + if (variableName) { + if (pxt.blocks.isVariableNameLocalizable(param)) { + locStrings[pxt.blocks.variableNameLocalizationKey(variableName)] = variableName; + } + } + else { + const defaultString = pxt.blocks.parameterDefaultToLocalizationString(param.defaultValue, param.type); + const defaultLocalizationKey = pxt.blocks.parameterDefaultLocalizationKey(si.qName, param.actualName); + if (defaultLocalizationKey && defaultString !== undefined) { + locStrings[defaultLocalizationKey] = defaultString; + } } } if (comp.handlerArgs?.length) { @@ -368,6 +376,11 @@ namespace ts.pxtc { } } + const blockSetVariableName = pxt.blocks.blockSetVariableName(si); + if (blockSetVariableName && si.attributes.blockSetVariableLocalizable) { + locStrings[pxt.blocks.variableNameLocalizationKey(blockSetVariableName)] = blockSetVariableName; + } + if (si.attributes.ariaLabel) { locStrings[`${si.qName}|ariaLabel`] = si.attributes.ariaLabel; } diff --git a/pxtlib/blocks.ts b/pxtlib/blocks.ts index 56d86b3d658d..69706bf5f7f7 100644 --- a/pxtlib/blocks.ts +++ b/pxtlib/blocks.ts @@ -95,6 +95,55 @@ namespace pxt.blocks { return qName ? `${qName}|param|${actualName}|defl` : undefined; } + export function variableNameLocalizationKey(name: string) { + return name ? `{id:var}${name}` : undefined; + } + + export function variableDefaultName(defaultValue: string, shadowBlockId: string) { + if (!defaultValue || shadowBlockId !== "variables_get") return undefined; + + if (defaultValue.charAt(0) === "\"") { + try { + const parsed = JSON.parse(defaultValue); + return typeof parsed === "string" ? parsed : undefined; + } + catch (e) { + return undefined; + } + } + + return defaultValue; + } + + export function blockSetVariableName(fn: pxtc.SymbolInfo) { + if (fn.attributes.blockSetVariable === undefined || !fn.retType) return undefined; + + const rawName = fn.attributes.blockSetVariable; + return !rawName || isReservedWord(rawName) ? fn.retType.toLowerCase() : rawName; + } + + export function isVariableNameLocalizable(param: BlockParameter) { + const value = param.fieldOptions?.localizeVariable; + return value === "true"; + } + + export function defaultVariableNames(fn: pxtc.SymbolInfo) { + const result: string[] = []; + const blockSetName = blockSetVariableName(fn); + if (blockSetName && fn.attributes.blockSetVariableLocalizable) result.push(blockSetName); + + if (fn.attributes.block) { + const comp = compileInfo(fn); + const params = comp.thisParameter ? [comp.thisParameter, ...comp.parameters] : comp.parameters; + for (const param of params) { + const name = variableDefaultName(param.defaultValue, param.shadowBlockId); + if (name && isVariableNameLocalizable(param) && result.indexOf(name) < 0) result.push(name); + } + } + + return result; + } + export function parameterDefaultToLocalizationString(defaultValue: string, type?: string) { if (!defaultValue) return undefined; if (type === "string" && defaultValue.charAt(0) !== "\"") return defaultValue; diff --git a/pxtlib/service.ts b/pxtlib/service.ts index 64e2c21605f4..d72cacee3b84 100644 --- a/pxtlib/service.ts +++ b/pxtlib/service.ts @@ -56,6 +56,7 @@ namespace ts.pxtc { blockId: string; promptHint: string; initialMembers: string[]; + initialMemberDisplayNames?: pxt.Map; } export interface CompletionEntry { @@ -536,10 +537,12 @@ namespace ts.pxtc { } const initialMembers: string[] = []; + const initialMemberDisplayNames: pxt.Map = {}; if (info.byQName[kindNamespace]) { for (const api of pxtc.Util.values(info.byQName)) { if (api.namespace === kindNamespace && api.attributes.isKind) { initialMembers.push(api.name); + initialMemberDisplayNames[api.name] = api.attributes.block || api.name; } } } @@ -550,6 +553,7 @@ namespace ts.pxtc { name: kindNamespace, memberName: s.attributes.kindMemberName || kindNamespace, initialMembers: initialMembers, + initialMemberDisplayNames, promptHint: s.attributes.enumPromptHint || Util.lf("Create a new kind..."), createFunctionName: s.attributes.kindCreateFunction || "create" }; @@ -700,6 +704,16 @@ namespace ts.pxtc { Util.jsonMergeFrom(loc, apiLocalizationStrings); packageLocalizationStrings = loc; + const variableNames: pxt.Map = {}; + Util.values(apis.byQName).forEach(fn => { + pxt.blocks.defaultVariableNames(fn).forEach(name => variableNames[name] = true); + }); + Object.keys(variableNames).forEach(name => { + const key = pxt.blocks.variableNameLocalizationKey(name); + if (loc[key]) setBlockTranslationCacheKey(key, loc[key]); + else clearBlockTranslationCacheKey(key); + }); + const toLocalize = Util.values(apis.byQName).filter(fn => fn.attributes._translatedLanguageCode !== lang); await Util.promiseMapAll(toLocalize, async fn => { const altLocSrc = fn.attributes.useLoc || fn.attributes.blockAliasFor; @@ -764,18 +778,20 @@ namespace ts.pxtc { } } - const defaultString = pxt.blocks.parameterDefaultToLocalizationString(param.defaultValue, param.type); - const defaultLocalizationKey = pxt.blocks.parameterDefaultLocalizationKey(fn.qName, param.actualName); - if (defaultLocalizationKey && defaultString !== undefined) { - const locSuff = defaultLocalizationKey.slice(fn.qName.length); - const paramDefault = lookupLoc(locSuff, langLower + locSuff); - if (paramDefault !== undefined) { - if (!fn.attributes._untranslatedParamDefl) { - fn.attributes._untranslatedParamDefl = U.clone(fn.attributes.paramDefl || {}); + if (!pxt.blocks.variableDefaultName(param.defaultValue, param.shadowBlockId)) { + const defaultString = pxt.blocks.parameterDefaultToLocalizationString(param.defaultValue, param.type); + const defaultLocalizationKey = pxt.blocks.parameterDefaultLocalizationKey(fn.qName, param.actualName); + if (defaultLocalizationKey && defaultString !== undefined) { + const locSuff = defaultLocalizationKey.slice(fn.qName.length); + const paramDefault = lookupLoc(locSuff, langLower + locSuff); + if (paramDefault !== undefined) { + if (!fn.attributes._untranslatedParamDefl) { + fn.attributes._untranslatedParamDefl = U.clone(fn.attributes.paramDefl || {}); + } + if (!fn.attributes.paramDefl) fn.attributes.paramDefl = {}; + fn.attributes.paramDefl[param.actualName] = pxt.blocks.localizationStringToParameterDefault(paramDefault); + syncParameterDefaults(fn); } - if (!fn.attributes.paramDefl) fn.attributes.paramDefl = {}; - fn.attributes.paramDefl[param.actualName] = pxt.blocks.localizationStringToParameterDefault(paramDefault); - syncParameterDefaults(fn); } } } diff --git a/tests/blocklycompiler-test/baselines/sprite_kind.ts b/tests/blocklycompiler-test/baselines/sprite_kind.ts index d9999fbabc2a..78b6581077c3 100644 --- a/tests/blocklycompiler-test/baselines/sprite_kind.ts +++ b/tests/blocklycompiler-test/baselines/sprite_kind.ts @@ -2,4 +2,4 @@ namespace SpriteKind { export const Rocket = SpriteKind.create() export const Whatever = SpriteKind.create() } -let x = SpriteKind.Rocket + SpriteKind.Player + SpriteKind.Whatever \ No newline at end of file +let x = SpriteKind.Rocket + SpriteKind.Player + (SpriteKind.Projectile + SpriteKind.Food + (SpriteKind.Enemy + SpriteKind.Whatever)) diff --git a/tests/blocklycompiler-test/cases/sprite_kind.blocks b/tests/blocklycompiler-test/cases/sprite_kind.blocks index 91349b153ebd..c47211d4afed 100644 --- a/tests/blocklycompiler-test/cases/sprite_kind.blocks +++ b/tests/blocklycompiler-test/cases/sprite_kind.blocks @@ -31,8 +31,36 @@ 0 - -Whatever + +ADD + +0 + +ADD + +0 +Projectile + + +0 +Food + + + + +0 + +ADD + +0 +Enemy + + +0 +Whatever + + + @@ -40,4 +68,4 @@ - \ No newline at end of file + diff --git a/tests/blocklycompiler-test/commentparsing.spec.ts b/tests/blocklycompiler-test/commentparsing.spec.ts index 7d997a5d3251..8de1c3b87b4a 100644 --- a/tests/blocklycompiler-test/commentparsing.spec.ts +++ b/tests/blocklycompiler-test/commentparsing.spec.ts @@ -540,6 +540,63 @@ describe("comment attribute parser", () => { chai.expect(strings["display.showNumber|param|value|defl"]).to.equal(undefined); }); + it("should extract display-only default variable names", () => { + const blockSet = testSymbolInfo("sprites.create", "create sprite", [], ` + //% blockSetVariable="projectile" + //% blockSetVariableLocalizable + `); + blockSet.retType = "Sprite"; + const unquoted = testSymbolInfo("sprites.follow", "follow $other=variables_get", [testParameter("other", "Sprite")], ` + //% other.defl=otherSprite + //% other.fieldOptions.localizeVariable=true + `); + const quotedOne = testSymbolInfo("images.draw", "draw in $picture=variables_get", [testParameter("picture", "Image")], ` + //% picture.defl="picture" + //% picture.fieldOptions.localizeVariable=true + `); + const quotedTwo = testSymbolInfo("images.fill", "fill $picture=variables_get", [testParameter("picture", "Image")], ` + //% picture.defl="picture" + //% picture.fieldOptions.localizeVariable=true + `); + + const docs = pxtc.genDocs("test", testApisInfo([blockSet, unquoted, quotedOne, quotedTwo]), { locs: true }); + const strings = JSON.parse(docs["test-strings.json"]); + chai.expect(strings["{id:var}projectile"]).to.equal("projectile"); + chai.expect(strings["{id:var}otherSprite"]).to.equal("otherSprite"); + chai.expect(strings["{id:var}picture"]).to.equal("picture"); + chai.expect(strings["images.draw|param|picture|defl"]).to.equal(undefined); + chai.expect(Object.keys(strings).filter(key => key === "{id:var}picture")).to.have.length(1); + + const notOptedIn = testSymbolInfo("light.createStrip", "create strip", [], ` + //% blockSetVariable="strip" + `); + notOptedIn.retType = "Strip"; + const unscoped = JSON.parse(pxtc.genDocs("test", testApisInfo([notOptedIn]), { locs: true })["test-strings.json"]); + chai.expect(unscoped["{id:var}strip"]).to.equal(undefined); + }); + + it("should cache variable display translations without translating raw parameter defaults", async () => { + const symbol = testSymbolInfo("images.draw", "draw in $picture=variables_get", [testParameter("picture", "Image")], ` + //% picture.defl="picture" + //% picture.fieldOptions.localizeVariable=true + `); + pxt.Util.setUserLanguage("da"); + try { + await pxtc.localizeApisAsync(testApisInfo([symbol]), { + localizationStringsAsync: () => Promise.resolve({ + "{id:var}picture": "billede" + }) + } as unknown as pxt.MainPackage); + + chai.expect(pxtc.getBlockTranslationsCacheKey("{id:var}picture")).to.equal("billede"); + chai.expect(symbol.attributes.paramDefl["picture"]).to.equal("picture"); + chai.expect(symbol.parameters[0].default).to.equal("picture"); + } + finally { + pxt.Util.setUserLanguage("en"); + } + }); + it("should apply localized parameter default strings", async () => { const explicitDefault = testSymbolInfo("game.setGameOverMessage", "use message $message", [testParameter("message", "string")], ` //% message.defl="GAME OVER!" @@ -683,4 +740,4 @@ function parseDef(def: string, ...expected: (string | pxtc.BlockPart)[]) { else { chai.expect(res).to.equal(undefined, "Expected `" + def + "` to error"); } -} \ No newline at end of file +} diff --git a/tests/blocklycompiler-test/localizedFields.spec.ts b/tests/blocklycompiler-test/localizedFields.spec.ts new file mode 100644 index 000000000000..5ca23ba32d7d --- /dev/null +++ b/tests/blocklycompiler-test/localizedFields.spec.ts @@ -0,0 +1,217 @@ +/// + +import * as Blockly from "blockly"; +import * as pxtblockly from "../../pxtblocks"; + +describe("localized identifier display fields", () => { + afterEach(() => pxtblockly.setVariableFieldLocalizeFunction(undefined)); + + it("localizes a default variable display without changing its model, id, XML, or dropdown value", () => { + const workspace = new Blockly.Workspace(); + const variable = workspace.getVariableMap().createVariable("myTile", "", "variable-id"); + Blockly.Blocks["localized_variable_test"] = { init() { } }; + const block = workspace.newBlock("localized_variable_test"); + const field = new pxtblockly.FieldVariable("myTile"); + block.appendDummyInput().appendField(field, "VAR"); + field.initModel(); + field.setValue(variable.getId()); + + chai.expect((field as any).getDisplayText_()).to.equal("myTile"); + chai.expect(field.getAriaValue()).to.equal("Variable 'myTile'"); + + pxtblockly.setVariableFieldLocalizeFunction((_field, model) => + model.getName() === "myTile" ? "minFlise" : undefined); + + chai.expect((field as any).getDisplayText_()).to.equal("minFlise"); + chai.expect(field.getAriaValue()).to.equal("minFlise"); + chai.expect(field.getText()).to.equal("myTile"); + chai.expect(field.getValue()).to.equal("variable-id"); + + const xmlField = document.createElement("field"); + field.toXml(xmlField); + chai.expect(xmlField.textContent).to.equal("myTile"); + chai.expect(xmlField.getAttribute("id")).to.equal("variable-id"); + + const serialized = Blockly.Xml.workspaceToDom(workspace); + chai.expect(Blockly.Xml.domToText(serialized)).to.contain(">myTile"); + chai.expect(Blockly.Xml.domToText(serialized)).not.to.contain("minFlise"); + const restoredWorkspace = new Blockly.Workspace(); + Blockly.Xml.domToWorkspace(serialized, restoredWorkspace); + const restoredVariable = restoredWorkspace.getVariableMap().getVariableById("variable-id"); + chai.expect(restoredVariable.getName()).to.equal("myTile"); + restoredWorkspace.dispose(); + + const option = field.getOptions(false).filter(option => + option !== Blockly.FieldDropdown.SEPARATOR && option[1] === "variable-id")[0] as Blockly.MenuOption; + chai.expect(option[0]).to.equal("minFlise"); + chai.expect(option[1]).to.equal("variable-id"); + + let rerenders = 0; + (field as any).forceRerender = () => rerenders++; + (field as any).onWorkspaceChange({ + type: Blockly.Events.BLOCK_MOVE, + blockId: "moved-block", + oldParentId: block.id, + newParentId: undefined + } as Blockly.Events.BlockMove); + chai.expect(rerenders).to.equal(1); + + workspace.getVariableMap().renameVariable(variable, "renamedTile"); + field.refreshVariableName(); + chai.expect(field.getText()).to.equal("renamedTile"); + chai.expect((field as any).getDisplayText_()).to.equal("renamedTile"); + workspace.dispose(); + }); + + it("only identifies names in generated/default API contexts", () => { + const factory = testSymbol("sprites.create", "create sprite", "Sprite", ` + //% blockSetVariable="myTile" + //% blockSetVariableLocalizable + `); + const blockInfo = testBlocksInfo([factory]); + const variable = { getName: () => "myTile" } as Blockly.IVariableModel; + + const generatedSet = { + type: "variables_set", + getInputTargetBlock: () => ({ type: factory.attributes.blockId }) + } as unknown as Blockly.Block; + const generatedField = { getSourceBlock: () => generatedSet } as pxtblockly.FieldVariable; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(generatedField, variable, blockInfo)).to.deep.equal({ + localizationKey: "{id:var}myTile", + suffix: "" + }); + + const generatedSecond = { getName: () => "myTile2" } as Blockly.IVariableModel; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(generatedField, generatedSecond, blockInfo)).to.deep.equal({ + localizationKey: "{id:var}myTile", + suffix: "2" + }); + + const generatedTenth = { getName: () => "myTile10" } as Blockly.IVariableModel; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(generatedField, generatedTenth, blockInfo)).to.deep.equal({ + localizationKey: "{id:var}myTile", + suffix: "10" + }); + + const unlocalizedFactory = testSymbol("sprites.createUnlocalized", "create sprite", "Sprite", ` + //% blockSetVariable="myTile" + `); + const unlocalizedBlockInfo = testBlocksInfo([unlocalizedFactory]); + const unlocalizedSet = { + type: "variables_set", + getInputTargetBlock: () => ({ type: unlocalizedFactory.attributes.blockId }) + } as unknown as Blockly.Block; + const unlocalizedField = { getSourceBlock: () => unlocalizedSet } as pxtblockly.FieldVariable; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(unlocalizedField, variable, unlocalizedBlockInfo)).to.equal(undefined); + + const userGet = { + type: "variables_get", + getParent: (): any => null + } as unknown as Blockly.Block; + const userField = { getSourceBlock: () => userGet } as pxtblockly.FieldVariable; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(userField, variable, blockInfo)).to.equal(undefined); + + const nested = testSymbol("sprites.overlaps", "overlaps $other=variables_get", "boolean", ` + //% other.defl=otherSprite + //% other.fieldOptions.localizeVariable=true + `); + nested.parameters = [{ name: "other", description: "", type: "Sprite", properties: [], default: "otherSprite" }]; + const nestedBlockInfo = testBlocksInfo([nested]); + const sourceGet = { type: "variables_get" } as Blockly.Block; + const parent = { + type: nested.attributes.blockId, + inputList: [{ name: "other", connection: { targetBlock: () => sourceGet } }] + } as unknown as Blockly.Block; + (sourceGet as any).getParent = () => parent; + const nestedField = { getSourceBlock: () => sourceGet } as pxtblockly.FieldVariable; + const nestedVariable = { getName: () => "otherSprite" } as Blockly.IVariableModel; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(nestedField, nestedVariable, nestedBlockInfo)).to.deep.equal({ + localizationKey: "{id:var}otherSprite", + suffix: "" + }); + + const nestedSecond = { getName: () => "otherSprite2" } as Blockly.IVariableModel; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(nestedField, nestedSecond, nestedBlockInfo)).to.deep.equal({ + localizationKey: "{id:var}otherSprite", + suffix: "2" + }); + + const unlocalizedNested = testSymbol("sprites.overlapsUnlocalized", "overlaps $other=variables_get", "boolean", ` + //% other.defl=otherSprite + `); + unlocalizedNested.parameters = [{ name: "other", description: "", type: "Sprite", properties: [], default: "otherSprite" }]; + const unlocalizedNestedInfo = testBlocksInfo([unlocalizedNested]); + const unlocalizedParent = { + type: unlocalizedNested.attributes.blockId, + inputList: [{ name: "other", connection: { targetBlock: () => sourceGet } }] + } as unknown as Blockly.Block; + (sourceGet as any).getParent = () => unlocalizedParent; + chai.expect(pxtblockly.getVariableFieldLocalizationInfo(nestedField, nestedVariable, unlocalizedNestedInfo)).to.equal(undefined); + }); + + it("uses localized SpriteKind labels with raw stored values and leaves custom kinds unchanged", () => { + const opts: pxtc.KindInfo = { + name: "SpriteKind", + memberName: "kind", + createFunctionName: "create", + blockId: "spritekind", + promptHint: "", + initialMembers: ["Player", "Projectile", "Food", "Enemy"], + initialMemberDisplayNames: { + Player: "Spiller", + Projectile: "Projektil", + Food: "Mad", + Enemy: "Fjende" + } + }; + const workspace = new Blockly.Workspace(); + workspace.getVariableMap().createVariable("CustomKind", "KIND_SpriteKind", "custom-kind-id"); + workspace.getVariableMap().createVariable("toString", "KIND_SpriteKind", "prototype-kind-id"); + Blockly.Blocks["spritekind_field_test"] = { init() { } }; + const block = workspace.newBlock("spritekind_field_test"); + const field = new pxtblockly.FieldKind(opts); + block.appendDummyInput().appendField(field, "MEMBER"); + + const options = field.getOptions(false).filter(option => option !== Blockly.FieldDropdown.SEPARATOR) as Blockly.MenuOption[]; + for (const [display, raw] of [["Spiller", "Player"], ["Projektil", "Projectile"], ["Mad", "Food"], ["Fjende", "Enemy"]]) { + chai.expect(options.some(option => option[0] === display && option[1] === raw)).to.equal(true); + field.setValue(raw); + chai.expect(field.getValue()).to.equal(raw); + const xmlField = document.createElement("field"); + field.toXml(xmlField); + chai.expect(xmlField.textContent).to.equal(raw); + } + chai.expect(options.some(option => option[0] === "CustomKind" && option[1] === "CustomKind")).to.equal(true); + chai.expect(options.some(option => option[0] === "toString" && option[1] === "toString")).to.equal(true); + workspace.dispose(); + }); +}); + +function testSymbol(qName: string, block: string, retType: string, attributes = ""): pxtc.SymbolInfo { + const qNameParts = qName.split("."); + const attrs = pxtc.parseCommentString(` + //% block="${block}" + //% blockId="${qName.replace(/\./g, "_")}" + ${attributes} + `); + return { + attributes: attrs, + name: qNameParts[qNameParts.length - 1], + namespace: qNameParts.slice(0, -1).join("."), + fileName: "test.ts", + kind: pxtc.SymbolKind.Function, + parameters: [], + retType, + qName + } as pxtc.SymbolInfo; +} + +function testBlocksInfo(symbols: pxtc.SymbolInfo[]): pxtc.BlocksInfo { + const byQName: pxt.Map = {}; + const blocksById: pxt.Map = {}; + symbols.forEach(symbol => { + byQName[symbol.qName] = symbol; + blocksById[symbol.attributes.blockId] = symbol; + }); + return { apis: { byQName, jres: {} }, blocks: symbols, blocksById, enumsByName: {}, kindsByName: {} } as pxtc.BlocksInfo; +} diff --git a/tests/blocklycompiler-test/test-library/spritekind.ts b/tests/blocklycompiler-test/test-library/spritekind.ts index 91b38135f046..39ce978f031c 100644 --- a/tests/blocklycompiler-test/test-library/spritekind.ts +++ b/tests/blocklycompiler-test/test-library/spritekind.ts @@ -18,16 +18,16 @@ namespace SpriteKind { return nextKind++; } - //% isKind + //% isKind block="Player" blockIdentity="sprites._spriteType" export const Player = create(); - //% isKind + //% isKind block="Projectile" blockIdentity="sprites._spriteType" export const Projectile = create(); - //% isKind + //% isKind block="Food" blockIdentity="sprites._spriteType" export const Food = create(); - //% isKind + //% isKind block="Enemy" blockIdentity="sprites._spriteType" export const Enemy = create(); } @@ -156,4 +156,4 @@ namespace images { export function __positionPicker(index: number) { return index; } -} \ No newline at end of file +} diff --git a/tests/blocklycompiler-test/test.spec.ts b/tests/blocklycompiler-test/test.spec.ts index d6e3e3854002..89070202c677 100644 --- a/tests/blocklycompiler-test/test.spec.ts +++ b/tests/blocklycompiler-test/test.spec.ts @@ -14,6 +14,7 @@ import "./workspaceResize.spec"; import "./blockInjection.spec"; import "./tutorialToolbox.spec"; import "./gridpicker.spec"; +import "./localizedFields.spec"; const WEB_PREFIX = "http://localhost:9876"; @@ -1291,4 +1292,4 @@ describe("blockly compiler", function () { blockTestAsync("inheritance").then(done, done); }); }) -}); \ No newline at end of file +}); diff --git a/tests/pydecompile-test/pydecompilerunner.ts b/tests/pydecompile-test/pydecompilerunner.ts index 478664e99f7a..3959606061df 100644 --- a/tests/pydecompile-test/pydecompilerunner.ts +++ b/tests/pydecompile-test/pydecompilerunner.ts @@ -33,6 +33,36 @@ pxt.setAppTarget(util.testAppTarget); // TODO: deduplicate this code with decompilerrunner.ts describe("pydecompiler", () => { + it("preserves identifiers behind localized block display labels through a Python round trip", async () => { + const rawTypescript = ` +let myTile = 0 +let kinds = [ + SpriteKind.Player, + SpriteKind.Projectile, + SpriteKind.Food, + SpriteKind.Enemy +] +`; + const python = await util.ts2pyAsync(rawTypescript, testBlocksDir, false, "localized display identity"); + + chai.expect(python).to.contain("myTile = 0"); + for (const kind of ["player", "projectile", "food", "enemy"]) { + chai.expect(python).to.contain(`SpriteKind.${kind}`); + } + for (const localized of ["min_flise", "spiller", "projektil", "mad", "fjende"]) { + chai.expect(python.toLowerCase()).not.to.contain(localized.toLowerCase()); + } + + const roundTrip = await util.py2tsAsync(python, testBlocksDir, false, false, "localized display identity"); + chai.expect(roundTrip.ts).to.contain("myTile"); + for (const kind of ["Player", "Projectile", "Food", "Enemy"]) { + chai.expect(roundTrip.ts).to.contain(`SpriteKind.${kind}`); + } + for (const localized of ["minFlise", "Spiller", "Projektil", "Mad", "Fjende"]) { + chai.expect(roundTrip.ts).not.to.contain(localized); + } + }); + let decompilerBaselineFiles = util.getFilesByExt(decompilerBaselines, ".py") decompilerBaselineFiles = decompilerBaselineFiles.filter(f => f.indexOf(".local.py") === -1); @@ -108,4 +138,4 @@ function pydecompileTestCoreAsync(tsFilename: string, baselineFile: string) { }) .then(() => resolve(), reject); }); -} \ No newline at end of file +}