Shared/Localizations: Add translatable Units formatting (#5063)
This commit is contained in:
@@ -33,6 +33,7 @@ namespace Content.Shared.Localizations
|
||||
loc.AddFunction(culture, "PRESSURE", FormatPressure);
|
||||
loc.AddFunction(culture, "POWERWATTS", FormatPowerWatts);
|
||||
loc.AddFunction(culture, "POWERJOULES", FormatPowerJoules);
|
||||
loc.AddFunction(culture, "UNITS", FormatUnits);
|
||||
loc.AddFunction(culture, "TOSTRING", args => FormatToString(culture, args));
|
||||
loc.AddFunction(culture, "LOC", FormatLoc);
|
||||
}
|
||||
@@ -85,5 +86,45 @@ namespace Content.Shared.Localizations
|
||||
{
|
||||
return FormatUnitsGeneric(args, "zzzz-fmt-power-joules");
|
||||
}
|
||||
|
||||
private static ILocValue FormatUnits(LocArgs args)
|
||||
{
|
||||
if (!Units.Types.TryGetValue(((LocValueString) args.Args[0]).Value, out var ut))
|
||||
throw new ArgumentException($"Unknown unit type {((LocValueString) args.Args[0]).Value}");
|
||||
|
||||
var fmtstr = ((LocValueString) args.Args[1]).Value;
|
||||
|
||||
double max = Double.NegativeInfinity;
|
||||
var iargs = new double[args.Args.Count - 1];
|
||||
for (var i = 2; i < args.Args.Count; i++)
|
||||
{
|
||||
var n = ((LocValueNumber) args.Args[i]).Value;
|
||||
if (n > max)
|
||||
max = n;
|
||||
|
||||
iargs[i - 2] = n;
|
||||
}
|
||||
|
||||
if (!ut!.TryGetUnit(max, out var mu))
|
||||
throw new ArgumentException("Unit out of range for type");
|
||||
|
||||
var fargs = new object[iargs.Length];
|
||||
|
||||
for (var i = 0; i < iargs.Length; i++)
|
||||
fargs[i] = iargs[i] * mu.Factor;
|
||||
|
||||
fargs[^1] = Loc.GetString($"units-{mu.Unit.ToLower()}");
|
||||
|
||||
// Before anyone complains about "{"+"${...}", at least it's better than MS's approach...
|
||||
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#escaping-braces
|
||||
//
|
||||
// Note that the closing brace isn't replaced so that format specifiers can be applied.
|
||||
var res = String.Format(
|
||||
fmtstr.Replace("{UNIT", "{" + $"{fargs.Length - 1}"),
|
||||
fargs
|
||||
);
|
||||
|
||||
return new LocValueString(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user