Add overview of all themes if none are defined

This commit is contained in:
pietervdvn 2021-01-14 22:25:11 +01:00
parent 7a2b99a566
commit 092c12a449
12 changed files with 94 additions and 53 deletions

View file

@ -22,7 +22,8 @@ export default class AllTranslationAssets {
ready: new Translation( {"en":"Done!","ca":"Fet.","es":"Hecho.","nl":"Klaar!","fr":"Finis!","gl":"Feito!","de":"Erledigt!"} ), ready: new Translation( {"en":"Done!","ca":"Fet.","es":"Hecho.","nl":"Klaar!","fr":"Finis!","gl":"Feito!","de":"Erledigt!"} ),
retrying: new Translation( {"en":"Loading data failed. Trying again... ({count})","ca":"La càrrega de dades ha fallat.Tornant-ho a intentar... ({count})","es":"La carga de datos ha fallado.Volviéndolo a probar... ({count})","gl":"A carga dos datos fallou. Tentándoo de novo... ({count})","fr":"Le chargement a échoué. Essayer à nouveau... ({count})","de":"Laden von Daten fehlgeschlagen. Erneuter Versuch... ({count})"} ), retrying: new Translation( {"en":"Loading data failed. Trying again... ({count})","ca":"La càrrega de dades ha fallat.Tornant-ho a intentar... ({count})","es":"La carga de datos ha fallado.Volviéndolo a probar... ({count})","gl":"A carga dos datos fallou. Tentándoo de novo... ({count})","fr":"Le chargement a échoué. Essayer à nouveau... ({count})","de":"Laden von Daten fehlgeschlagen. Erneuter Versuch... ({count})"} ),
}, },
general: { loginWithOpenStreetMap: new Translation( {"en":"Login with OpenStreetMap","ca":"Entra a OpenStreetMap","es":"Entra en OpenStreetMap","nl":"Aanmelden met OpenStreetMap","fr":"Se connecter avec OpenStreeMap","gl":"Inicia a sesión no OpenStreetMap","de":"Anmeldung mit OpenStreetMap"} ), general: { index: new Translation( {"#":"This text is shown above the theme buttons when no theme is loaded","en":"<h3>Welcome to MapComplete</h3> MapComplete is an OpenStreetMap-viewer and editor, which shows you information about a specific theme.<br/><br/>Pick a theme below to get started.","nl":"<h3>Welkom bij MapComplete</h3> MapComplete is een OpenStreetMap applicatie waar informatie over een specifiek thema bekeken en aangepast kan worden.<br/><br/>Kies hieronder een thema om te beginnen."} ),
loginWithOpenStreetMap: new Translation( {"en":"Login with OpenStreetMap","ca":"Entra a OpenStreetMap","es":"Entra en OpenStreetMap","nl":"Aanmelden met OpenStreetMap","fr":"Se connecter avec OpenStreeMap","gl":"Inicia a sesión no OpenStreetMap","de":"Anmeldung mit OpenStreetMap"} ),
welcomeBack: new Translation( {"en":"You are logged in, welcome back!","ca":"Has entrat, benvingut.","es":"Has entrado, bienvenido.","nl":"Je bent aangemeld. Welkom terug!","fr":"Vous êtes connecté. Bienvenue!","gl":"Iniciaches a sesión, benvido.","de":"Sie sind eingeloggt, willkommen zurück!"} ), welcomeBack: new Translation( {"en":"You are logged in, welcome back!","ca":"Has entrat, benvingut.","es":"Has entrado, bienvenido.","nl":"Je bent aangemeld. Welkom terug!","fr":"Vous êtes connecté. Bienvenue!","gl":"Iniciaches a sesión, benvido.","de":"Sie sind eingeloggt, willkommen zurück!"} ),
loginToStart: new Translation( {"en":"Login to answer this question","ca":"Entra per contestar aquesta pregunta","es":"Entra para contestar esta pregunta","nl":"Meld je aan om deze vraag te beantwoorden","fr":"Connectez-vous pour répondre à cette question","gl":"Inicia a sesión para responder esta pregunta","de":"Anmelden, um diese Frage zu beantworten"} ), loginToStart: new Translation( {"en":"Login to answer this question","ca":"Entra per contestar aquesta pregunta","es":"Entra para contestar esta pregunta","nl":"Meld je aan om deze vraag te beantwoorden","fr":"Connectez-vous pour répondre à cette question","gl":"Inicia a sesión para responder esta pregunta","de":"Anmelden, um diese Frage zu beantworten"} ),
search: { search: new Translation( {"en":"Search a location","ca":"Cerca una ubicació","es":"Busca una ubicación","nl":"Zoek naar een locatie","fr":"Chercher un lieu","gl":"Procurar unha localización","de":"Einen Ort suchen"} ), search: { search: new Translation( {"en":"Search a location","ca":"Cerca una ubicació","es":"Busca una ubicación","nl":"Zoek naar een locatie","fr":"Chercher un lieu","gl":"Procurar unha localización","de":"Einen Ort suchen"} ),

View file

@ -2,7 +2,7 @@ import { Utils } from "../Utils";
export default class Constants { export default class Constants {
public static vNumber = "0.4.7"; public static vNumber = "0.4.8";
// The user journey states thresholds when a new feature gets unlocked // The user journey states thresholds when a new feature gets unlocked
public static userJourney = { public static userJourney = {

View file

@ -125,11 +125,11 @@ export default class State {
this.layoutToUse.setData(layoutToUse); this.layoutToUse.setData(layoutToUse);
const zoom = State.asFloat( const zoom = State.asFloat(
QueryParameters.GetQueryParameter("z", "" + layoutToUse.startZoom, "The initial/current zoom level") QueryParameters.GetQueryParameter("z", "" + layoutToUse?.startZoom, "The initial/current zoom level")
.syncWith(LocalStorageSource.Get("zoom"))); .syncWith(LocalStorageSource.Get("zoom")));
const lat = State.asFloat(QueryParameters.GetQueryParameter("lat", "" + layoutToUse.startLat, "The initial/current latitude") const lat = State.asFloat(QueryParameters.GetQueryParameter("lat", "" + layoutToUse?.startLat, "The initial/current latitude")
.syncWith(LocalStorageSource.Get("lat"))); .syncWith(LocalStorageSource.Get("lat")));
const lon = State.asFloat(QueryParameters.GetQueryParameter("lon", "" + layoutToUse.startLon, "The initial/current longitude of the app") const lon = State.asFloat(QueryParameters.GetQueryParameter("lon", "" + layoutToUse?.startLon, "The initial/current longitude of the app")
.syncWith(LocalStorageSource.Get("lon"))); .syncWith(LocalStorageSource.Get("lon")));
@ -192,7 +192,7 @@ export default class State {
testParam === "true", testParam === "true",
QueryParameters.GetQueryParameter("oauth_token", undefined, QueryParameters.GetQueryParameter("oauth_token", undefined,
"Used to complete the login"), "Used to complete the login"),
layoutToUse.id, layoutToUse?.id,
true true
); );

View file

@ -78,7 +78,6 @@ export default class FullWelcomePaneWithTabs extends UIElement {
]).SetClass("only-on-mobile") ]).SetClass("only-on-mobile")
.onClick(() => State.state.fullScreenMessage.setData(undefined)); .onClick(() => State.state.fullScreenMessage.setData(undefined));
tabbedPart.SetStyle("overflow-y: auto; max-height: calc( 100vh - 4em);display:block;")
this._component = new Combine([tabbedPart, backButton]).SetStyle("width:100%;"); this._component = new Combine([tabbedPart, backButton]).SetStyle("width:100%;");
} }

View file

@ -10,12 +10,17 @@ import {SubtleButton} from "../Base/SubtleButton";
import Translations from "../i18n/Translations"; import Translations from "../i18n/Translations";
import * as personal from "../../assets/themes/personalLayout/personalLayout.json" import * as personal from "../../assets/themes/personalLayout/personalLayout.json"
import Constants from "../../Models/Constants"; import Constants from "../../Models/Constants";
import LanguagePicker from "../LanguagePicker";
export default class MoreScreen extends UIElement { export default class MoreScreen extends UIElement {
private readonly _onMainScreen: boolean;
private _component: UIElement;
constructor() { constructor(onMainScreen: boolean = false) {
super(State.state.locationControl); super(State.state.locationControl);
this._onMainScreen = onMainScreen;
this.ListenTo(State.state.osmConnection.userDetails); this.ListenTo(State.state.osmConnection.userDetails);
this.ListenTo(State.state.installedThemes); this.ListenTo(State.state.installedThemes);
} }
@ -35,7 +40,7 @@ export default class MoreScreen extends UIElement {
return undefined; return undefined;
} }
} }
if (layout.id === State.state.layoutToUse.data.id) { if (layout.id === State.state.layoutToUse.data?.id) {
return undefined; return undefined;
} }
@ -115,12 +120,23 @@ export default class MoreScreen extends UIElement {
} }
} }
let intro : UIElement= tr.intro;
if(this._onMainScreen){
intro = new Combine([
LanguagePicker.CreateLanguagePicker(Translations.t.general.index.SupportedLanguages())
.SetStyle("position: absolute; right: 1.5em; top: 1.5em;"),
Translations.t.general.index.SetStyle("margin-top: 2em;display:block; margin-bottom: 1em;")
])
}
return new VerticalCombine([ this._component = new VerticalCombine([
tr.intro, intro,
new VerticalCombine(els), new VerticalCombine(els),
tr.streetcomplete tr.streetcomplete
]).Render(); ]);
return this._component.Render();
} }
} }

View file

@ -42,7 +42,7 @@ export default class SharePanel extends UIElement {
"Copy the json configuration from the 'save-tab', paste it between the 'nowiki'-tags in the Wiki", "Copy the json configuration from the 'save-tab', paste it between the 'nowiki'-tags in the Wiki",
"Click 'save' to save the wiki page", "Click 'save' to save the wiki page",
"Share the link with the url parameter <span class='literal-code'>userlayout=wiki:YOURWIKIPAGE</span>, e.g. " + "Share the link with the url parameter <span class='literal-code'>userlayout=wiki:YOURWIKIPAGE</span>, e.g. " +
`<a href='./index.html?userlayout=${proposedNameEnc}' target='_blank'>https://${window.location.host}?userlayout=${proposedNameEnc}</a>` `<a href='./custom?userlayout=${proposedNameEnc}' target='_blank'>https://${window.location.host}?userlayout=${proposedNameEnc}</a>`
].map(li => `<li>${li}</li>`), ].map(li => `<li>${li}</li>`),
"</ol>", "</ol>",

View file

@ -11,7 +11,7 @@ export class Translation extends UIElement {
constructor(translations: object, context?: string) { constructor(translations: object, context?: string) {
super(Locale.language) super(Locale.language)
if(translations === undefined){ if (translations === undefined) {
throw `Translation without content (${context})` throw `Translation without content (${context})`
} }
let count = 0; let count = 0;
@ -19,11 +19,40 @@ export class Translation extends UIElement {
count++; count++;
} }
this.translations = translations; this.translations = translations;
if(count === 0){ if (count === 0) {
throw `No translations given in the object (${context})` throw `No translations given in the object (${context})`
} }
} }
get txt(): string {
if (this.translations["*"]) {
return this.translations["*"];
}
const txt = this.translations[Translation.forcedLanguage ?? Locale.language.data];
if (txt !== undefined) {
return txt;
}
const en = this.translations["en"];
if (en !== undefined) {
return en;
}
for (const i in this.translations) {
return this.translations[i]; // Return a random language
}
console.error("Missing language ", Locale.language.data, "for", this.translations)
return "";
}
public SupportedLanguages(): string[] {
const langs = []
for (const translationsKey in this.translations) {
if(translationsKey === "#"){
continue;
}
langs.push(translationsKey)
}
return langs;
}
public Subs(text: any): Translation { public Subs(text: any): Translation {
const newTranslations = {}; const newTranslations = {};
@ -57,27 +86,6 @@ export class Translation extends UIElement {
} }
get txt(): string {
if (this.translations["*"]) {
return this.translations["*"];
}
const txt = this.translations[Translation.forcedLanguage ?? Locale.language.data];
if (txt !== undefined) {
return txt;
}
const en = this.translations["en"];
if (en !== undefined) {
return en;
}
for (const i in this.translations) {
return this.translations[i]; // Return a random language
}
console.error("Missing language ", Locale.language.data, "for", this.translations)
return "";
}
InnerRender(): string { InnerRender(): string {
return this.txt return this.txt
} }

View file

@ -24,10 +24,10 @@
"maintainer": "MapComplete", "maintainer": "MapComplete",
"icon": "./assets/themes/cyclofix/logo.svg", "icon": "./assets/themes/cyclofix/logo.svg",
"version": "0", "version": "0",
"startLat": 50.8465573, "startLat": 0,
"defaultBackgroundId": "CartoDB.Voyager", "defaultBackgroundId": "CartoDB.Voyager",
"startLon": 4.3516970, "startLon": 0,
"startZoom": 16, "startZoom": 1,
"widenFactor": 0.05, "widenFactor": 0.05,
"socialImage": "./assets/themes/cyclofix/logo.svg", "socialImage": "./assets/themes/cyclofix/logo.svg",
"layers": [ "layers": [

View file

@ -162,6 +162,13 @@
} }
}, },
"general": { "general": {
"index": {
"#": "This text is shown above the theme buttons when no theme is loaded",
"en": "<h3>Welcome to MapComplete</h3> MapComplete is an OpenStreetMap-viewer and editor, which shows you information about a specific theme.<br/><br/>Pick a theme below to get started.",
"nl": "<h3>Welkom bij MapComplete</h3> MapComplete is een OpenStreetMap applicatie waar informatie over een specifiek thema bekeken en aangepast kan worden.<br/><br/>Kies hieronder een thema om te beginnen."
},
"loginWithOpenStreetMap": { "loginWithOpenStreetMap": {
"en": "Login with OpenStreetMap", "en": "Login with OpenStreetMap",
"ca": "Entra a OpenStreetMap", "ca": "Entra a OpenStreetMap",

View file

@ -19,7 +19,9 @@
<link rel="stylesheet" href="vendor/MarkerCluster.css"/> <link rel="stylesheet" href="vendor/MarkerCluster.css"/>
<link rel="stylesheet" href="vendor/MarkerCluster.Default.css"/> <link rel="stylesheet" href="vendor/MarkerCluster.Default.css"/>
<!-- $$$CUSTOM-CSS --> <!-- $$$CUSTOM-CSS -->
<!-- $$$MANIFEST -->
<link rel="manifest" href="./manifest.manifest"> <link rel="manifest" href="./manifest.manifest">
<link rel="icon" href="assets/svg/add.svg" sizes="any" type="image/svg+xml"> <link rel="icon" href="assets/svg/add.svg" sizes="any" type="image/svg+xml">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
@ -35,7 +37,7 @@
</head> </head>
<body> <body>
<div style="position: absolute; left: 1em; bottom: 1em; width:35vh; height:35vh;" <div style="position: fixed; left: 1em; bottom: 1em; width:35vh; height:35vh;"
id="decoration-desktop"> id="decoration-desktop">
<!-- A nice decoration while loading or on errors --> <!-- A nice decoration while loading or on errors -->
<!-- DECORATION 0 START --> <!-- DECORATION 0 START -->
@ -63,7 +65,6 @@
</div> </div>
<div id="centermessage">Loading MapComplete, hang on...</div> <div id="centermessage">Loading MapComplete, hang on...</div>
<div id="top-right"></div>
<span id="geolocate-button"></span> <span id="geolocate-button"></span>
<div id="leafletDiv"></div> <div id="leafletDiv"></div>

View file

@ -6,8 +6,10 @@ import {UIEventSource} from "./Logic/UIEventSource";
import * as $ from "jquery"; import * as $ from "jquery";
import LayoutConfig from "./Customizations/JSON/LayoutConfig"; import LayoutConfig from "./Customizations/JSON/LayoutConfig";
import {Utils} from "./Utils"; import {Utils} from "./Utils";
import MoreScreen from "./UI/BigComponents/MoreScreen";
import State from "./State";
let defaultLayout = "bookcases" let defaultLayout = ""
// --------------------- Special actions based on the parameters ----------------- // --------------------- Special actions based on the parameters -----------------
// @ts-ignore // @ts-ignore
if (location.href.startsWith("http://buurtnatuur.be")) { if (location.href.startsWith("http://buurtnatuur.be")) {
@ -21,7 +23,7 @@ if (location.href.indexOf("buurtnatuur.be") >= 0) {
} }
const customCssQP = QueryParameters.GetQueryParameter("custom-css", "", "If specified, the custom css from the given link will be loaded additionaly"); const customCssQP = QueryParameters.GetQueryParameter("custom-css", "", "If specified, the custom css from the given link will be loaded additionaly");
if(customCssQP.data !== undefined && customCssQP.data !== ""){ if (customCssQP.data !== undefined && customCssQP.data !== "") {
Utils.LoadCustomCss(customCssQP.data); Utils.LoadCustomCss(customCssQP.data);
} }
@ -42,17 +44,16 @@ if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
// ----------------- SELECT THE RIGHT QUESTSET ----------------- // ----------------- SELECT THE RIGHT QUESTSET -----------------
const path = window.location.pathname.split("/").slice(-1)[0]; const path = window.location.pathname.split("/").slice(-1)[0];
if (path !== "index.html" && path !== "") { if (path !== "index.html" && path !== "") {
defaultLayout = path; defaultLayout = path;
if(path.endsWith(".html")){ if (path.endsWith(".html")) {
defaultLayout = path.substr(0, path.length - 5); defaultLayout = path.substr(0, path.length - 5);
} }
console.log("Using layout", defaultLayout); console.log("Using layout", defaultLayout);
} }
defaultLayout = QueryParameters.GetQueryParameter("layout", defaultLayout,"The layout to load into MapComplete").data; defaultLayout = QueryParameters.GetQueryParameter("layout", defaultLayout, "The layout to load into MapComplete").data;
let layoutToUse: LayoutConfig = AllKnownLayouts.allSets[defaultLayout.toLowerCase()] ?? AllKnownLayouts["all"]; let layoutToUse: LayoutConfig = AllKnownLayouts.allSets[defaultLayout.toLowerCase()];
const userLayoutParam = QueryParameters.GetQueryParameter("userlayout", "false"); const userLayoutParam = QueryParameters.GetQueryParameter("userlayout", "false");
@ -73,10 +74,10 @@ if (layoutFromBase64.startsWith("wiki:")) {
// Hacky McHackFace has been working here. This'll probably break in the future // Hacky McHackFace has been working here. This'll probably break in the future
const startTrigger = "<div class=\"mw-parser-output\">"; const startTrigger = "<div class=\"mw-parser-output\">";
const start = data.indexOf(startTrigger); const start = data.indexOf(startTrigger);
data = data.substr(start, data = data.substr(start,
data.indexOf("<div class=\"printfooter\">") - start) data.indexOf("<div class=\"printfooter\">") - start)
data = data.substr(0, data.lastIndexOf("</p>")) data = data.substr(0, data.lastIndexOf("</p>"))
data = data.substr( data.indexOf("<p>") + 3) data = data.substr(data.indexOf("<p>") + 3)
console.log(data) console.log(data)
try { try {
const parsed = JSON.parse(data); const parsed = JSON.parse(data);
@ -100,8 +101,16 @@ if (layoutFromBase64.startsWith("wiki:")) {
} else if (layoutFromBase64 !== "false") { } else if (layoutFromBase64 !== "false") {
layoutToUse = InitUiElements.LoadLayoutFromHash(userLayoutParam); layoutToUse = InitUiElements.LoadLayoutFromHash(userLayoutParam);
InitUiElements.InitAll(layoutToUse, layoutFromBase64, testing, defaultLayout, location.hash.substr(1)); InitUiElements.InitAll(layoutToUse, layoutFromBase64, testing, defaultLayout, location.hash.substr(1));
} else { } else if (layoutToUse !== undefined) {
// This is the default case: a builtin theme
InitUiElements.InitAll(layoutToUse, layoutFromBase64, testing, defaultLayout); InitUiElements.InitAll(layoutToUse, layoutFromBase64, testing, defaultLayout);
} else {
State.state = new State(undefined);
document.getElementById("messagesboxmobile").remove();
new MoreScreen(true)
.SetStyle("background: var(--background-color); display: block; margin-left: 5vw; margin-right: 5vw; pointer-events: all;")
.AttachTo("topleft-tools");
} }
window.addEventListener('contextmenu', function (e) { // Not compatible with IE < 9 window.addEventListener('contextmenu', function (e) { // Not compatible with IE < 9
e.preventDefault(); e.preventDefault();

View file

@ -227,7 +227,7 @@ function createLandingPage(layout: LayoutConfig) {
} }
let output = template let output = template
.replace(`./manifest.manifest`, `./${enc(layout.id)}.webmanifest`) .replace("./manifest.manifest",`${enc(layout.id)}.webmanifest`)
.replace("<!-- $$$OG-META -->", og) .replace("<!-- $$$OG-META -->", og)
.replace(/<title>.+?<\/title>/, `<title>${ogTitle}</title>`) .replace(/<title>.+?<\/title>/, `<title>${ogTitle}</title>`)
.replace("Loading MapComplete, hang on...", `Loading MapComplete theme <i>${ogTitle}</i>...`) .replace("Loading MapComplete, hang on...", `Loading MapComplete theme <i>${ogTitle}</i>...`)
@ -251,7 +251,7 @@ if (! existsSync(generatedDir)) {
mkdirSync(generatedDir) mkdirSync(generatedDir)
} }
const blacklist = ["", "test", ".", "..", "manifest", "index", "land", "preferences", "account", "openstreetmap"] const blacklist = ["", "test", ".", "..", "manifest", "index", "land", "preferences", "account", "openstreetmap","custom"]
const all = AllKnownLayouts.allSets; const all = AllKnownLayouts.allSets;
let wikiPage = "{|class=\"wikitable sortable\"\n" + let wikiPage = "{|class=\"wikitable sortable\"\n" +
@ -278,12 +278,12 @@ for (const layoutName in all) {
const manifestLocation = encodeURIComponent(layout.id.toLowerCase()) + ".webmanifest"; const manifestLocation = encodeURIComponent(layout.id.toLowerCase()) + ".webmanifest";
writeFile(manifestLocation, manif, err); writeFile(manifestLocation, manif, err);
// Create a landing page for the given theme
const landing = createLandingPage(layout); const landing = createLandingPage(layout);
writeFile(enc(layout.id) + ".html", landing, err) writeFile(enc(layout.id) + ".html", landing, err)
wikiPage += "\n"+generateWikiEntry(layout); wikiPage += "\n"+generateWikiEntry(layout);
} }
wikiPage += "\n|}" wikiPage += "\n|}"
writeFile(generatedDir + "/wikiIndex", wikiPage, (err) => { writeFile(generatedDir + "/wikiIndex", wikiPage, (err) => {