No more need to add '.clone()' for compiled translations, removed a bunch of 'clones'

This commit is contained in:
Pieter Vander Vennet 2021-10-25 21:50:38 +02:00
parent feb684d9e5
commit 9dc8404c43
8 changed files with 56 additions and 61 deletions

View file

@ -40,20 +40,16 @@ export default class FilterView extends VariableUiElement {
const iconUnselected = new Combine([Svg.checkbox_empty]).SetStyle( const iconUnselected = new Combine([Svg.checkbox_empty]).SetStyle(
iconStyle iconStyle
); );
const name: Translation = config.config.name.Clone(); const name: Translation = config.config.name;
const styledNameChecked = name const styledNameChecked = name.Clone().SetStyle("font-size:large;padding-left:1.25rem");
.Clone()
.SetStyle("font-size:large;padding-left:1.25rem");
const styledNameUnChecked = name const styledNameUnChecked = name.Clone().SetStyle("font-size:large;padding-left:1.25rem");
.Clone()
.SetStyle("font-size:large;padding-left:1.25rem");
const zoomStatus = const zoomStatus =
new Toggle( new Toggle(
undefined, undefined,
Translations.t.general.layerSelection.zoomInToSeeThisLayer.Clone() Translations.t.general.layerSelection.zoomInToSeeThisLayer
.SetClass("alert") .SetClass("alert")
.SetStyle("display: block ruby;width:min-content;"), .SetStyle("display: block ruby;width:min-content;"),
State.state.locationControl.map(location => location.zoom >= config.config.minzoom) State.state.locationControl.map(location => location.zoom >= config.config.minzoom)
@ -97,20 +93,16 @@ export default class FilterView extends VariableUiElement {
const name: Translation = Translations.WT( const name: Translation = Translations.WT(
filteredLayer.layerDef.name filteredLayer.layerDef.name
)?.Clone(); );
const styledNameChecked = name const styledNameChecked = name.Clone().SetStyle("font-size:large;padding-left:1.25rem");
.Clone()
.SetStyle("font-size:large;padding-left:1.25rem");
const styledNameUnChecked = name const styledNameUnChecked = name.Clone().SetStyle("font-size:large;padding-left:1.25rem");
.Clone()
.SetStyle("font-size:large;padding-left:1.25rem");
const zoomStatus = const zoomStatus =
new Toggle( new Toggle(
undefined, undefined,
Translations.t.general.layerSelection.zoomInToSeeThisLayer.Clone() Translations.t.general.layerSelection.zoomInToSeeThisLayer
.SetClass("alert") .SetClass("alert")
.SetStyle("display: block ruby;width:min-content;"), .SetStyle("display: block ruby;width:min-content;"),
State.state.locationControl.map(location => location.zoom >= filteredLayer.layerDef.minzoom) State.state.locationControl.map(location => location.zoom >= filteredLayer.layerDef.minzoom)

View file

@ -50,7 +50,7 @@ export default class FullWelcomePaneWithTabs extends ScrollableFullScreen {
{header: `<img src='${state.layoutToUse.icon}'>`, content: welcome}, {header: `<img src='${state.layoutToUse.icon}'>`, content: welcome},
{ {
header: Svg.osm_logo_img, header: Svg.osm_logo_img,
content: Translations.t.general.openStreetMapIntro.Clone().SetClass("link-underline") content: Translations.t.general.openStreetMapIntro.SetClass("link-underline")
}, },
] ]
@ -64,7 +64,7 @@ export default class FullWelcomePaneWithTabs extends ScrollableFullScreen {
header: Svg.add_img, header: Svg.add_img,
content: content:
new Combine([ new Combine([
Translations.t.general.morescreen.intro.Clone(), Translations.t.general.morescreen.intro,
new MoreScreen(state) new MoreScreen(state)
]).SetClass("flex flex-col") ]).SetClass("flex flex-col")
}); });
@ -86,7 +86,7 @@ export default class FullWelcomePaneWithTabs extends ScrollableFullScreen {
tabsWithAboutMc.push({ tabsWithAboutMc.push({
header: Svg.help, header: Svg.help,
content: new Combine([Translations.t.general.aboutMapcomplete.Clone() content: new Combine([Translations.t.general.aboutMapcomplete
.Subs({"osmcha_link": Utils.OsmChaLinkFor(7)}), "<br/>Version " + Constants.vNumber]) .Subs({"osmcha_link": Utils.OsmChaLinkFor(7)}), "<br/>Version " + Constants.vNumber])
.SetClass("link-underline") .SetClass("link-underline")
} }

View file

@ -6,8 +6,6 @@ import {SubtleButton} from "../Base/SubtleButton";
import Translations from "../i18n/Translations"; import Translations from "../i18n/Translations";
import * as personal from "../../assets/themes/personal/personal.json" import * as personal from "../../assets/themes/personal/personal.json"
import Constants from "../../Models/Constants"; import Constants from "../../Models/Constants";
import LanguagePicker from "../LanguagePicker";
import IndexText from "./IndexText";
import BaseUIElement from "../BaseUIElement"; import BaseUIElement from "../BaseUIElement";
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig"; import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig";
import {UIEventSource} from "../../Logic/UIEventSource"; import {UIEventSource} from "../../Logic/UIEventSource";
@ -201,14 +199,13 @@ export default class MoreScreen extends Combine {
}) ?? new UIEventSource<string>(`${linkPrefix}${linkSuffix}`) }) ?? new UIEventSource<string>(`${linkPrefix}${linkSuffix}`)
let description = Translations.WT(layout.shortDescription).Clone();
return new SubtleButton(layout.icon, return new SubtleButton(layout.icon,
new Combine([ new Combine([
`<dt class='text-lg leading-6 font-medium text-gray-900 group-hover:text-blue-800'>`, `<dt class='text-lg leading-6 font-medium text-gray-900 group-hover:text-blue-800'>`,
Translations.WT(layout.title).Clone(), Translations.WT(layout.title),
`</dt>`, `</dt>`,
`<dd class='mt-1 text-base text-gray-500 group-hover:text-blue-900 overflow-ellipsis'>`, `<dd class='mt-1 text-base text-gray-500 group-hover:text-blue-900 overflow-ellipsis'>`,
description.Clone().SetClass("subtle") ?? "", Translations.WT(layout.shortDescription)?.SetClass("subtle") ?? "",
`</dd>`, `</dd>`,
]), {url: linkText, newTab: false}); ]), {url: linkText, newTab: false});
} }

View file

@ -73,7 +73,7 @@ export default class FeatureInfoBox extends ScrollableFullScreen {
editElements.push(questionBox); editElements.push(questionBox);
} }
if(layerConfig.allowMove) { if (layerConfig.allowMove) {
editElements.push( editElements.push(
new VariableUiElement(tags.map(tags => tags.id).map(id => { new VariableUiElement(tags.map(tags => tags.id).map(id => {
const feature = State.state.allElements.ContainingFeatures.get(id) const feature = State.state.allElements.ContainingFeatures.get(id)
@ -149,8 +149,8 @@ export default class FeatureInfoBox extends ScrollableFullScreen {
)) ))
renderings.push(editors) renderings.push(editors)
return new Combine(renderings).SetClass("block")
return new Combine(renderings).SetClass("block")
} }
/** /**

View file

@ -46,7 +46,7 @@ export default class MoveWizard extends Toggle {
const t = Translations.t.move const t = Translations.t.move
const loginButton = new Toggle( const loginButton = new Toggle(
t.loginToMove.Clone().SetClass("btn").onClick(() => state.osmConnection.AttemptLogin()), t.loginToMove.SetClass("btn").onClick(() => state.osmConnection.AttemptLogin()),
undefined, undefined,
state.featureSwitchUserbadge state.featureSwitchUserbadge
) )
@ -54,8 +54,8 @@ export default class MoveWizard extends Toggle {
const reasons: MoveReason[] = [] const reasons: MoveReason[] = []
if (options.enableRelocation) { if (options.enableRelocation) {
reasons.push({ reasons.push({
text: t.reasons.reasonRelocation.Clone(), text: t.reasons.reasonRelocation,
invitingText: t.inviteToMove.reasonRelocation.Clone(), invitingText: t.inviteToMove.reasonRelocation,
icon: Svg.relocation_svg(), icon: Svg.relocation_svg(),
changesetCommentValue: "relocated", changesetCommentValue: "relocated",
lockBounds: false, lockBounds: false,
@ -66,7 +66,7 @@ export default class MoveWizard extends Toggle {
} }
if(options.enableImproveAccuracy){ if(options.enableImproveAccuracy){
reasons.push({ reasons.push({
text: t.reasons.reasonInaccurate.Clone(), text: t.reasons.reasonInaccurate,
invitingText: t.inviteToMove.reasonInaccurate, invitingText: t.inviteToMove.reasonInaccurate,
icon: Svg.crosshair_svg(), icon: Svg.crosshair_svg(),
changesetCommentValue: "improve_accuracy", changesetCommentValue: "improve_accuracy",
@ -85,14 +85,14 @@ export default class MoveWizard extends Toggle {
moveReason.setData(reason) moveReason.setData(reason)
moveButton = new SubtleButton( moveButton = new SubtleButton(
reason.icon.SetStyle("height: 1.5rem; width: auto;"), reason.icon.SetStyle("height: 1.5rem; width: auto;"),
Translations.WT(reason.invitingText).Clone() Translations.WT(reason.invitingText)
).onClick(() => { ).onClick(() => {
currentStep.setData("pick_location") currentStep.setData("pick_location")
}) })
}else{ }else{
moveButton = new SubtleButton( moveButton = new SubtleButton(
Svg.move_ui().SetStyle("height: 1.5rem; width: auto"), Svg.move_ui().SetStyle("height: 1.5rem; width: auto"),
t.inviteToMove.generic.Clone() t.inviteToMove.generic
).onClick(() => { ).onClick(() => {
currentStep.setData("reason") currentStep.setData("reason")
}) })
@ -101,7 +101,7 @@ export default class MoveWizard extends Toggle {
const moveAgainButton = new SubtleButton( const moveAgainButton = new SubtleButton(
Svg.move_ui(), Svg.move_ui(),
t.inviteToMoveAgain.Clone() t.inviteToMoveAgain
).onClick(() => { ).onClick(() => {
currentStep.setData("reason") currentStep.setData("reason")
}) })
@ -159,7 +159,7 @@ export default class MoveWizard extends Toggle {
state.allElements.getEventSourceById(id).ping() state.allElements.getEventSourceById(id).ping()
currentStep.setData("moved") currentStep.setData("moved")
}) })
const zoomInFurhter = t.zoomInFurther.Clone().SetClass("alert block m-6") const zoomInFurhter = t.zoomInFurther.SetClass("alert block m-6")
return new Combine([ return new Combine([
locationInput, locationInput,
new Toggle(confirmMove, zoomInFurhter, locationInput.GetValue().map(l => l.zoom >= 19)) new Toggle(confirmMove, zoomInFurhter, locationInput.GetValue().map(l => l.zoom >= 19))
@ -174,11 +174,11 @@ export default class MoveWizard extends Toggle {
case "start": case "start":
return moveButton; return moveButton;
case "reason": case "reason":
return new Combine([t.whyMove.Clone().SetClass("text-lg font-bold"), selectReason, cancelButton]).SetClass(dialogClasses); return new Combine([t.whyMove.SetClass("text-lg font-bold"), selectReason, cancelButton]).SetClass(dialogClasses);
case "pick_location": case "pick_location":
return new Combine([t.moveTitle.Clone().SetClass("text-lg font-bold"), new VariableUiElement(locationInput), cancelButton]).SetClass(dialogClasses) return new Combine([t.moveTitle.SetClass("text-lg font-bold"), new VariableUiElement(locationInput), cancelButton]).SetClass(dialogClasses)
case "moved": case "moved":
return new Combine([t.pointIsMoved.Clone().SetClass("thanks"), moveAgainButton]).SetClass("flex flex-col"); return new Combine([t.pointIsMoved.SetClass("thanks"), moveAgainButton]).SetClass("flex flex-col");
} }
@ -195,20 +195,20 @@ export default class MoveWizard extends Toggle {
const moveDisallowedReason = new UIEventSource<BaseUIElement>(undefined) const moveDisallowedReason = new UIEventSource<BaseUIElement>(undefined)
if (id.startsWith("way")) { if (id.startsWith("way")) {
moveDisallowedReason.setData(t.isWay.Clone()) moveDisallowedReason.setData(t.isWay)
} else if (id.startsWith("relation")) { } else if (id.startsWith("relation")) {
moveDisallowedReason.setData(t.isRelation.Clone()) moveDisallowedReason.setData(t.isRelation)
} else { } else {
OsmObject.DownloadReferencingWays(id).then(referencing => { OsmObject.DownloadReferencingWays(id).then(referencing => {
if (referencing.length > 0) { if (referencing.length > 0) {
console.log("Got a referencing way, move not allowed") console.log("Got a referencing way, move not allowed")
moveDisallowedReason.setData(t.partOfAWay.Clone()) moveDisallowedReason.setData(t.partOfAWay)
} }
}) })
OsmObject.DownloadReferencingRelations(id).then(partOf => { OsmObject.DownloadReferencingRelations(id).then(partOf => {
if(partOf.length > 0){ if(partOf.length > 0){
moveDisallowedReason.setData(t.partOfRelation.Clone()) moveDisallowedReason.setData(t.partOfRelation)
} }
}) })
} }
@ -216,7 +216,7 @@ export default class MoveWizard extends Toggle {
moveFlow, moveFlow,
new Combine([ new Combine([
Svg.move_not_allowed_svg().SetStyle("height: 2rem").SetClass("m-2"), Svg.move_not_allowed_svg().SetStyle("height: 2rem").SetClass("m-2"),
new Combine([t.cannotBeMoved.Clone(), new Combine([t.cannotBeMoved,
new VariableUiElement(moveDisallowedReason).SetClass("subtle") new VariableUiElement(moveDisallowedReason).SetClass("subtle")
]).SetClass("flex flex-col") ]).SetClass("flex flex-col")
]).SetClass("flex m-2 p-2 rounded-lg bg-gray-200"), ]).SetClass("flex m-2 p-2 rounded-lg bg-gray-200"),

View file

@ -27,6 +27,7 @@ import ChangeTagAction from "../../Logic/Osm/Actions/ChangeTagAction";
import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"; import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig";
import {Unit} from "../../Models/Unit"; import {Unit} from "../../Models/Unit";
import VariableInputElement from "../Input/VariableInputElement"; import VariableInputElement from "../Input/VariableInputElement";
import Toggle from "../Input/Toggle";
/** /**
* Shows the question element. * Shows the question element.
@ -76,7 +77,7 @@ export default class TagRenderingQuestion extends Combine {
const inputElement: InputElement<TagsFilter> = const inputElement: InputElement<TagsFilter> =
new VariableInputElement(applicableMappingsSrc.map(applicableMappings => new VariableInputElement(applicableMappingsSrc.map(applicableMappings =>
TagRenderingQuestion.GenerateInputElement(configuration, applicableMappings, applicableUnit, tags) TagRenderingQuestion.GenerateInputElement(configuration, applicableMappings, applicableUnit, tags)
)) ))
@ -105,8 +106,11 @@ export default class TagRenderingQuestion extends Combine {
.onClick(save) .onClick(save)
} }
const saveButton = options.saveButtonConstr(inputElement.GetValue()) const saveButton = new Combine([
options.saveButtonConstr(inputElement.GetValue()),
new Toggle(Translations.t.general.testing, undefined, State.state.featureSwitchIsTesting).SetClass("alert")
])
let bottomTags: BaseUIElement; let bottomTags: BaseUIElement;
if (options.bottomText !== undefined) { if (options.bottomText !== undefined) {
bottomTags = options.bottomText(inputElement.GetValue()) bottomTags = options.bottomText(inputElement.GetValue())
@ -119,7 +123,7 @@ export default class TagRenderingQuestion extends Combine {
return ""; return "";
} }
if (tagsFilter === undefined) { if (tagsFilter === undefined) {
return Translations.t.general.noTagsSelected.Clone().SetClass("subtle"); return Translations.t.general.noTagsSelected.SetClass("subtle");
} }
if (csCount < Constants.userJourney.tagsVisibleAndWikiLinked) { if (csCount < Constants.userJourney.tagsVisibleAndWikiLinked) {
const tagsStr = tagsFilter.asHumanString(false, true, tags.data); const tagsStr = tagsFilter.asHumanString(false, true, tags.data);
@ -136,6 +140,8 @@ export default class TagRenderingQuestion extends Combine {
options.cancelButton, options.cancelButton,
saveButton, saveButton,
bottomTags]) bottomTags])
this.SetClass("question disable-links") this.SetClass("question disable-links")
} }
@ -190,7 +196,7 @@ export default class TagRenderingQuestion extends Combine {
applicableMappings.map((mapping, i) => { applicableMappings.map((mapping, i) => {
return { return {
value: new And([mapping.if, ...allIfNotsExcept(i)]), value: new And([mapping.if, ...allIfNotsExcept(i)]),
shown: Translations.WT(mapping.then).Clone() shown: Translations.WT(mapping.then)
} }
}) })
) )
@ -204,7 +210,7 @@ export default class TagRenderingQuestion extends Combine {
if (inputEls.length == 0) { if (inputEls.length == 0) {
if(ff === undefined){ if (ff === undefined) {
throw "Error: could not generate a question: freeform and all mappings are undefined" throw "Error: could not generate a question: freeform and all mappings are undefined"
} }
return ff; return ff;

View file

@ -6,7 +6,6 @@ import BaseUIElement from "../BaseUIElement";
export default class Translations { export default class Translations {
static t = AllTranslationAssets.t; static t = AllTranslationAssets.t;
private static wtcache = {}
constructor() { constructor() {
throw "Translations is static. If you want to intitialize a new translation, use the singular form" throw "Translations is static. If you want to intitialize a new translation, use the singular form"
@ -45,15 +44,10 @@ export default class Translations {
return undefined; return undefined;
} }
if (typeof (s) === "string") { if (typeof (s) === "string") {
if (Translations.wtcache[s]) { return new Translation({en: s});
return Translations.wtcache[s];
}
const tr = new Translation({en: s});
Translations.wtcache[s] = tr;
return tr;
} }
if (s instanceof Translation) { if (s instanceof Translation) {
return s; return s.Clone() /* MUST CLONE HERE! */;
} }
console.error("Trying to Translation.WT, but got ", s) console.error("Trying to Translation.WT, but got ", s)
throw "??? Not a valid translation" throw "??? Not a valid translation"

View file

@ -33,7 +33,7 @@ class TranslationPart {
} }
const v = translations[translationsKey] const v = translations[translationsKey]
if (typeof (v) != "string") { if (typeof (v) != "string") {
console.error("Non-string object in translation while trying to add more translations to '", translationsKey ,"': ", v) console.error("Non-string object in translation while trying to add more translations to '", translationsKey, "': ", v)
throw "Error in an object depicting a translation: a non-string object was found. (" + context + ")\n You probably put some other section accidentally in the translation" throw "Error in an object depicting a translation: a non-string object was found. (" + context + ")\n You probably put some other section accidentally in the translation"
} }
this.contents.set(translationsKey, v) this.contents.set(translationsKey, v)
@ -166,7 +166,13 @@ function transformTranslation(obj: any, depth = 1) {
if (key.match("^[a-zA-Z0-9_]*$") === null) { if (key.match("^[a-zA-Z0-9_]*$") === null) {
throw "Invalid character in key: " + key throw "Invalid character in key: " + key
} }
values += (Utils.Times((_) => " ", depth)) + key + ": " + transformTranslation(obj[key], depth + 1) + ",\n" const value = obj[key]
if (isTranslation(value)) {
values += (Utils.Times((_) => " ", depth)) + "get " + key + "() { return new Translation(" + JSON.stringify(value) + ") }" + ",\n"
} else {
values += (Utils.Times((_) => " ", depth)) + key + ": " + transformTranslation(value, depth + 1) + ",\n"
}
} }
return `{${values}}`; return `{${values}}`;
@ -300,9 +306,9 @@ function MergeTranslation(source: any, target: any, language: string, context: s
} }
if (typeof sourceV === "object") { if (typeof sourceV === "object") {
if (targetV === undefined) { if (targetV === undefined) {
try{ try {
target[language] = sourceV; target[language] = sourceV;
}catch(e){ } catch (e) {
throw `At context${context}: Could not add a translation in language ${language} due to ${e}` throw `At context${context}: Could not add a translation in language ${language} due to ${e}`
} }
} else { } else {