ext-modular/localization.js

103 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-07-02 16:04:00 +00:00
"use strict";
const cl = global.botanLoader;
const Dragonfly = global.Dragonfly;
const ProxyLocale = function( name, _locale, _parent )
{
var _thisProxy = new Proxy( _locale, {
get: ( target, prop ) => {
switch( prop )
{
case Symbol.toPrimitive:
return () => _locale( global.lang || "en-US" );
2016-07-03 11:51:57 +00:00
case "name":
return _parent ? `${_parent.name}.${name}` : name;
2016-07-02 16:04:00 +00:00
case "inspect":
return _parent
2016-07-03 11:51:57 +00:00
? () => `LocaleString[ Locale${_parent.name}.${name} ]`
: () => `LocaleString`
2016-07-02 16:04:00 +00:00
;
}
if( target[ prop ] == undefined )
{
target[ prop ] = ProxyLocale(
prop
, function( lang, stack )
{
if( !stack )
{
2016-07-03 11:51:57 +00:00
stack = stack || [ prop, name ];
2016-07-02 16:04:00 +00:00
}
else
{
2016-07-03 11:51:57 +00:00
stack[1] = name + "." + stack[1];
2016-07-02 16:04:00 +00:00
}
return _locale( lang, stack );
}
, _thisProxy );
}
return Reflect.get( target, prop );
}
} );
return _thisProxy;
};
const rLocale = function( lang, stack )
{
2016-07-03 11:51:57 +00:00
var Zone = "LocaleSX." + lang + stack[1];
2016-07-02 16:04:00 +00:00
try
{
var zoneFile = cl.load( Zone );
var translated = zoneFile[ stack[0] ];
if( translated == undefined )
{
throw new Error( `Translation does not exists: ${Zone}[ ${stack[0]} ]` );
}
return translated;
}
catch( e )
{
Dragonfly.Warning( e );
}
2016-07-03 11:51:57 +00:00
return Zone + "." + stack[1];
2016-07-02 16:04:00 +00:00
};
2016-07-03 09:41:59 +00:00
String.prototype.L = function( ...args )
{
var i = 0;
var j = -1;
var str = "";
var a = 0;
while( ~( j = this.indexOf( "%s", i ) ) )
{
i = j + 2;
// %% => % literal
if( this[ j - 1 ] == "%" ) continue;
str += this.substring( i, j ) + args[ a ++ ];
}
if( str == "" ) return this.replace( "%%", "%" );
else str += this.substring( i, this.length );
return str;
};
2016-07-02 16:04:00 +00:00
module.exports = ProxyLocale( "", rLocale );