Skip to content

Commit

Permalink
Merge pull request #1 from TransforMap/master
Browse files Browse the repository at this point in the history
update my fork
  • Loading branch information
mrothauer authored Feb 26, 2017
2 parents 45183ce + 4e11403 commit f40a9ca
Show file tree
Hide file tree
Showing 5 changed files with 291 additions and 19 deletions.
15 changes: 11 additions & 4 deletions app/assets/index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ html(lang='en')
meta(charset="utf-8")
meta(name="viewport" content="initial-scale=1.0, user-scalable=no")
meta(name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi")
script(src='/vendor.js')
script(src='/app.js')
script(src='vendor.js')
script(src='app.js')
script require('initialize')
script(defer='defer' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js')
script(src='https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js')
script.
if(! Modernizr.promises) {
document.write('<script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></sc' + 'ript>')
document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.2/fetch.min.js"></sc' + 'ript>')
}
link(href='//fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css')
link(rel='stylesheet', href="/app.css")
link(rel='stylesheet', href="/vendor.css")
link(rel='stylesheet', href="app.css")
link(rel='stylesheet', href="vendor.css")
body
#forms
h1 TransforMap Editor
Expand Down
57 changes: 45 additions & 12 deletions app/lib/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const initMap = require('./map.js')
const getUrlVars = require('./getUrlVars.js')
const redFetch = require('./red_fetch.js')
const taxonomy = require('./taxonomy.js')
const translations = require('./translations.js')
window.translations = translations

var map
const endpoint = 'https://data.transformap.co/place/'
Expand Down Expand Up @@ -38,13 +40,21 @@ module.exports = function () {
return toiArray
}

var lang = 'en'
var startLang = translations.selectAllowedLang(translations.current_lang)
console.log("lang on start: " + startLang)
console.log(translations.supported_languages)
var typeOfInintiatives = []
var toiHashtable = {}

function fillTOIs (data) {
$('#_key_type_of_initiative').empty()

typeOfInintiatives = []
toiHashtable = {}

var toiSelect = document.getElementById('_key_type_of_initiative')
var dataArray = data.results.bindings
const current_lang = dataArray[0].itemLabel['xml:lang']
dataArray.forEach(function (entry) {
if (!entry.type_of_initiative_tag) {
return
Expand All @@ -53,7 +63,7 @@ module.exports = function () {
return
}
var label = {}
label[entry.itemLabel['xml:lang']] = entry.itemLabel.value
label[current_lang] = entry.itemLabel.value

var currentObject = {
item: entry.item.value,
Expand All @@ -72,7 +82,7 @@ module.exports = function () {
if (a.type_of_initiative_tag && a.type_of_initiative_tag.match(/^other_/)) return 1
if (b.type_of_initiative_tag && b.type_of_initiative_tag.match(/^other_/)) return -1

if (a.label[lang] < b.label[lang]) {
if (a.label[current_lang] < b.label[current_lang]) {
return -1
} else {
return 1
Expand All @@ -96,18 +106,13 @@ module.exports = function () {
})
}

var label = document.createTextNode(entry.label[lang]) // FIXME fallback langs
var label = document.createTextNode(entry.label[current_lang]) // FIXME fallback langs
newOption.appendChild(label)

toiSelect.appendChild(newOption)
})
}

// load taxonomy from server
redFetch([ taxonomy.getLangTaxURL(lang), 'https://raw.githubusercontent.com/TransforMap/transformap-viewer-translations/master/taxonomy-backup/susy/taxonomy.' + lang + '.json' ],
fillTOIs,
function (error) { console.error('none of the taxonomy data urls available') })

function addFreeTagsRow () {
var freetags = document.getElementById('freetags')

Expand Down Expand Up @@ -229,6 +234,34 @@ module.exports = function () {
map.addControl(map.my_drawControl)
}

//add languageswitcher
var menu = document.getElementById('menu')
$('#menu').append(
'<div id=languageSelector onClick="$(\'#languageSelector ul\').toggleClass(\'open\');">' +
'<span lang=en>Choose Language:</span>' +
'<ul></ul>' +
'</div>')

function initializeTranslatedTOIs(Q5data) {
translations.initializeLanguageSwitcher(Q5data)

var nowPossibleLang = translations.selectAllowedLang(translations.current_lang)
translations.current_lang = nowPossibleLang
fetchAndSetNewTranslation(nowPossibleLang)
}

function fetchAndSetNewTranslation(lang) {
redFetch([ taxonomy.getLangTaxURL(lang), 'https://raw.githubusercontent.com/TransforMap/transformap-viewer-translations/master/taxonomy-backup/susy/taxonomy.' + lang + '.json' ],
fillTOIs,
function (error) { console.error('none of the taxonomy data urls available') })
}
translations.fetchAndSetNewTranslation = fetchAndSetNewTranslation

redFetch( [ "https://base.transformap.co/wiki/Special:EntityData/Q5.json", "https://raw.githubusercontent.com/TransforMap/transformap-viewer/Q5-fallback.json" ],
initializeTranslatedTOIs,
function(error) { console.error("none of the lang init data urls available") } );


function createCORSRequest (method, url) {
// taken from https://www.html5rocks.com/en/tutorials/cors/
var xhr = new XMLHttpRequest()
Expand Down Expand Up @@ -373,7 +406,7 @@ module.exports = function () {
alert('nothing to delete')
return
}
if(!confirm('Do you really want to delete this POI? It will be only marked as deleted and can restored later if you save the current Browser URL.')) {
if(!confirm('Do you really want to delete this POI? It will be only marked as deleted and can be restored later if you save the current Browser URL.')) {
console.log('user aborted delete')
return
}
Expand Down Expand Up @@ -460,10 +493,10 @@ module.exports = function () {
}
document.getElementById('coordsearch').onclick = clickSearch

function stopRKey(evt) {
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null)
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null)
if ((evt.keyCode == 13) && (node.type == 'text')) {
if ((evt.keyCode == 13) && (node.type == 'text')) {
return false
}
}
Expand Down
4 changes: 2 additions & 2 deletions app/lib/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ function initMap () {

map = L.map('map', {
zoomControl: true,
center: center ? center : new L.LatLng(51.1657, 10.4515),
zoom: zoom ? zoom : 15,
center: center ? center : new L.LatLng(28.6, 9),
zoom: zoom ? zoom : 2,
layers: defaultlayer
})

Expand Down
191 changes: 191 additions & 0 deletions app/lib/translations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// mostly taken from https://github.com/TransforMap/transformap-viewer/blob/gh-pages/scripts/map.js

function getLangs () {
var language = window.navigator.languages ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage);

if(typeof language === 'string')
language = [ language ];

// we need to have the following languages:
// browserlang
// a short one (de instead of de-AT) if not present
// en as fallback if not present

for(var i = 0; i < language.length; i++) {
if(language[i].match(/-/)) {
var short_lang = language[i].match(/^([a-zA-Z]*)-/)[1];
if(language.indexOf(short_lang) == -1) {
language.push(short_lang);
continue;
}
}
}

if(language.indexOf("en") == -1)
language.push("en");

console.log(language);
return language;
}

function setFallbackLangs() {
fallback_langs = [];
if(current_lang != "en") {
for(var i=0; i < browser_languages.length; i++) {
var abbr = browser_languages[i];
if(current_lang != abbr)
fallback_langs.push(abbr);
}
}
console.log("new fallback langs: " + fallback_langs.join(",") + ".");
}

function resetLang() {
current_lang = "en";
for(var i=0; i < browser_languages.length; i++) {
var abbr = browser_languages[i];
if(abbr_langnames[abbr]) {
current_lang = abbr;
break;
}
}
switchToLang(current_lang);
}

/* get languages for UI from our Wikibase, and pick languages that are translated there */

var supported_languages = [],
langnames = [],
abbr_langnames = {},
langnames_abbr = {};
function initializeLanguageSwitcher(returned_data){
var lang;
for(lang in returned_data.entities.Q5.labels) { //Q5 is arbitrary. Choose one that gets translated for sure.
supported_languages.push(lang);
}
var langstr = supported_languages.join("|");

var langstr_query =
'SELECT ?lang ?langLabel ?abbr ' +
'WHERE' +
'{' +
'?lang wdt:P218 ?abbr;' +
'FILTER regex (?abbr, "^('+langstr+')$").' +
'SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }' +
'}';

langstr_query = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql?query=' +encodeURIComponent(langstr_query) + "&format=json";
$.getJSON(langstr_query, function (langstrings){

langstrings.results.bindings.forEach(function (item) {
abbr_langnames[item.abbr.value] = item.langLabel.value;
langnames_abbr[item.langLabel.value] = item.abbr.value;
langnames.push(item.langLabel.value);
});
langnames.sort();

resetLang();
setFallbackLangs();

langnames.forEach(function (item) {
var langcode = langnames_abbr[item];
var is_default = (langcode == current_lang) ? " class=default" : "";
console.log("adding lang '" + langcode + "' (" + item + ")");
$("#languageSelector ul").append("<li targetlang=" + langcode + is_default + " onClick='window.translations.switchToLang(\""+langcode+"\");'>"+item+"</li>");
});
});
}

function switchToLang(lang) {
$("#languageSelector li.default").removeClass("default");
$("#languageSelector li[targetlang="+lang+"]").addClass("default");
current_lang = lang;
window.translations.current_lang = lang;
window.translations.fetchAndSetNewTranslation(lang);
setFallbackLangs();
/*
//updateTranslatedTexts();
if(! dictionary[lang]) {
var dict_uri = "https://raw.githubusercontent.com/TransforMap/transformap-viewer-translations/master/json/"+lang+".json";
$.ajax({
url: dict_uri,
context: { lang: current_lang },
success: function(returned_data) {
var trans_jsonobj = JSON.parse(returned_data);
if(! dictionary[this.lang])
dictionary[this.lang] = {};
for (item in trans_jsonobj) {
var index = reverse_dic[item];
dictionary[this.lang][index] = trans_jsonobj[item];
}
console.log("successfully fetched " + this.lang);
//updateTranslatedTexts();
}
});
}
// As rebuilding the filters does not yet support advanced mode by default,
// we switch to simple mode, as language switching is a very rare case.
if(getFilterMode() == "advanced")
toggleAdvancedFilterMode();
resetFilter();
setFilterLang(lang);
*/
console.log("new lang:" +lang);
}

// if wishedLang is in supported, OK
// shorten wishedLang and see if in supported
// take fallback
function selectAllowedLang(wishedLang) {
console.log("selectAllowedLang(" + wishedLang + ") called")
if(wishedLang) {
if(supported_languages.indexOf(wishedLang) != -1) {
current_lang = wishedLang
return current_lang
}
console.log("not in supported, try shorten")
var matches = wishedLang.match(/^([a-zA-Z]*)-/)
if(matches && matches[1]) {
var short_lang = matches[1];
console.log("short: " + short_lang)
if(short_lang) {
if(supported_languages.indexOf(short_lang) != -1) {
current_lang = short_lang
console.log("current_lang set to " + short_lang)
return current_lang
}
}
}
}
setFallbackLangs()
if(fallback_langs[0]) {
if(supported_languages.indexOf(fallback_langs[0]) != -1) {
current_lang = fallback_langs[0]
return current_lang
}
}
current_lang = 'en'
return current_lang
}

var browser_languages = getLangs(),
current_lang = browser_languages[0],
fallback_langs = [];

module.exports = {
getLangs: getLangs,
initializeLanguageSwitcher: initializeLanguageSwitcher,
supported_languages: supported_languages,
browser_languages: browser_languages,
current_lang: current_lang,
switchToLang: switchToLang,
selectAllowedLang: selectAllowedLang
}
Loading

0 comments on commit f40a9ca

Please sign in to comment.