2.1.0 β€’ Published 4 months ago

@iceyleagons/klarity v2.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

πŸ—ΊοΈ Klarity (JS)

GitHub release (with filter) GitHub issues GitHub GitHub Repo stars

Klarity is a lightweight internalization library for the Kotlin programming language, with support for JavaScript thanks to Kotlin Multiplatform. It makes it super easy to create multi-lingual projects.

What it provides:

  • Script language to skyrocket the capabilities of translators
  • Simple yet powerful customization
  • Multiple built-in source support (properties, json)
  • Middlewares (for ex.: to add coloring in Minecraft server plugins)
  • Automatic file generation from default values
  • Basically no dependencies (except for some built-in file format supports)

So internalization becomes as simple and powerful as:

const { Klarity, sources } = require("@iceyleagons/klarity");

// To ensure scripting working properly, please enable it.
Klarity.configure({ scriptingEnabled:  true });

// Registering source
const source = new sources.JsonSource({
	key: "You have {IF(EQ(amount, '1'), IF(SW(item, 'a', 'e', 'i', 'o', 'u'), 'an', 'a'), amount)} {item}{IF(GT(amount, '1'), 's', '')}"
});
Klarity.registerSource("en", source);

console.log(Klarity.translate("key", "<default value>", { amount:  4, item:  "apple" }));
// Output:
// Amount = 2, Item = apple --> You have 2 apples
// Amount = 1, Item = apple --> You have an apple
// Amount = 1, Item = pear --y You have a pear

πŸ’» Basic usage

To use Klarity, you will first have to install it via your package manager of choice. I recommend PNPM.

pnpm install @iceyleagons/klarity

After that's done, you will need to register one or more TranslationSources, if no source is present Klarity will use the text in the default value parameter.

Klarity.registerSource("en", enSource);
Klarity.registerSource("hu", huSource);

If that's done, you're ready to go, just use

let translation = Klarity.translate("key", "<default value>");

// Or with parameters
let translation = Klarity.translate("path.to.translation2", "Value is: {param}", { param:  "it works" })

Please note, that parameters can only be lowercase, but can include numbers!

However Klarity provides much more configuration to fine tune it to your use case!

Klarity.configure({
	defaultLanguage:  "en",
	scriptingEnabled:  true,
	globals: {
		suffix:  " SUFFIX",
		prefix:  "[PREFIX] ",
		globalParameters:  new Map(),
	}
});

There are even more, take a look in Customizing for them :)

πŸ“œ Understanding the script

If you have ever used Excel's formulas, this script will feel very similar.

In essence everything inside {} will be parsed by the parser (although you can escape it with \ ). Anything inside ' ' will become a string (you cannot use "!) Anything outside of ' ' will be considered as a parameter passed from the underlying code implementation.

To empower translators we've included many useful functions, but these are not limited, as Klarity provides an API to register your own functions.

FunctionsTypeReturnDescription
FALSE()ConstantsBoolBoolean false
TRUE()ConstantsBoolBoolean true
AND(bool...)LogicBoolIf all of the values inside the AND function are true, the function will return true.
IF(condition, pass, else)LogicString or IntIf statement, the first argument is the condition, second will get executed if the condition returns true, otherwise the 3rd argument will get executed.
NOT(bool)LogicBoolInverts the boolean value inside the function.
OR(bool...)LogicBoolIf any of the values are true, the function will return true, false otherwise.
GTEQ(int, int)CheckBoolChecks whether the first argument is greater than, or equal to the second one. Returns true/false accordingly.
GT(int, int)CheckBoolChecks whether the first argument is greater than the second one. Returns true/false accordingly.
LTEQ(int, int)CheckBoolChecks whether the first argument is less than, or equal to the second one. Returns true/false accordingly.
LT(int, int)CheckBoolChecks whether the first argument is less than the second one. Returns true/false accordingly.
EW(string, string...)CheckBoolChecks whether the first argument ends with any of the following arguments. Returns true/false accordingly.
SW(string, string...)CheckBoolChecks whether the first argument starts with any of the following arguments. Returns true/false accordingly.
EQ(any, any)CheckBoolChecks whether the two parameters equal. Returns true if they are equal, false otherwise.
NE(any, any)CheckBoolChecks whether the two parameters are not equal. Returns true if they are not equal, false otherwise.
ISEMPTY(string)CheckBoolReturns true if the given string argument is empty (contains no characters)
MATCH(string, string)CheckBoolChecks whether the second argument matches the regular expression provided in the first argument. Returns true if they match
ADD(int, int)ArithmeticIntAdds the two integers together.
SUB(int, int)ArithmeticIntSubtracts the second integer from the first one.
MUL(int, int)ArithmeticIntMultiplies the two integers.
DIV(int, int)ArithmeticIntDivides the first integer with the second one.
MOD(int, int)ArithmeticIntModulus operation. Calculates the remainder of truncating division of the first integer by the second one
CONCAT(any...)UtilityStringConcatenates the arguments together.
JOIN(string, any...)UtilityStringCreates a string from all the elements separated using separator (first argument).
RANDOM(any...)UtilityString, Int or BoolPicks a random argument and returns it.

πŸ–ŒοΈ Customizing

Currently - due to time limits - other than the KDoc I will not supply a documentation for customization. However, feel free to look at the built in features as an example.

You can customize Klarity in two different ways:

  • Adding custom translation sources
  • Adding new script functions
  • Add middlewares

πŸ—‚οΈ Translation Sources

Translation sources are responsible for retrieving the strings from whatever source, and to write default values (if supported).

To add a custom translation source, just implement the TranslationSource interface and register it via

Klarity.registerSource("lang-code", source);

πŸ“‘ Middlewares

Middlewares are codes that can modify the output of Klarity.translate() after the script has been parsed. This could be useful to add custom parsing, for example adding color code support in Minecraft plugins. Additionally it can do filtering and verification as well.

Please note, that whatever the middleware outputs will become the output of Klarity.translate(). There can also be multiple middlewares, they are called in the order of registration. Every middleware will get the output of the previous one as an input.

To create a middleware, implement the KlarityMiddleware interface and register it via

Klarity.registerMiddleware({
    modify: (text) => {
	    return "Hello world"; // Now every output will be hello world
    },
});

πŸ”€ Script functions

Although the Kotlin version of Klarity supports registering custom script functions, the JS version does not have an option to do that just yet.

βž• Contribution

If you have a great idea for the project, feel free to contribute in the way outlined in CONTRIBUTING.md

βš–οΈ License

Klarity is licensed under the terms of MIT License. See the actual license here

❀️ Projects using Klarity

If you want to see your project here, feel free to open an pull request.

  • Be the first one!
2.1.0

4 months ago

2.0.2

4 months ago

2.0.1

4 months ago

2.0.0

4 months ago

1.1.0

10 months ago