From ab405edfb63c589204fed7d54748f2d1e8108d18 Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Thu, 18 Oct 2018 13:48:05 +0200 Subject: [PATCH] luci-base: cbi.js: add client side translation infrastructure Implement the string hash algorithm used by LuCI's translation system in JavaScript and provide a `_()` translation wrapper function to lookup messages in the global string table. Once client side translation loading is activated in a later commit, JavaScript code can use the same string translation mechanism as server side Lua code, e.g. `_("Static Routes")` would yield "Statische Routen" when the German translation is loaded. Signed-off-by: Jo-Philipp Wich --- .../htdocs/luci-static/resources/cbi.js | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/modules/luci-base/htdocs/luci-static/resources/cbi.js b/modules/luci-base/htdocs/luci-static/resources/cbi.js index c27cc8264e..a0c0d355f5 100644 --- a/modules/luci-base/htdocs/luci-static/resources/cbi.js +++ b/modules/luci-base/htdocs/luci-static/resources/cbi.js @@ -15,6 +15,57 @@ var cbi_d = []; var cbi_t = []; var cbi_strings = { path: {}, label: {} }; +function sfh(s) { + if (s === null || s.length === 0) + return null; + + var hash = (s.length >>> 0), + len = (s.length >>> 2), + off = 0, tmp; + + while (len--) { + hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0; + tmp = ((((s.charCodeAt(off + 3) << 8) + s.charCodeAt(off + 2)) << 11) ^ hash) >>> 0; + hash = ((hash << 16) ^ tmp) >>> 0; + hash += hash >>> 11; + off += 4; + } + + switch ((s.length & 3) >>> 0) { + case 3: + hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0; + hash = (hash ^ (hash << 16)) >>> 0; + hash = (hash ^ (s.charCodeAt(off + 2) << 18)) >>> 0; + hash += hash >> 11; + break; + + case 2: + hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0; + hash = (hash ^ (hash << 11)) >>> 0; + hash += hash >>> 17; + break; + + case 1: + hash += s.charCodeAt(off); + hash = (hash ^ (hash << 10)) >>> 0; + hash += hash >>> 1; + break; + } + + hash = (hash ^ (hash << 3)) >>> 0; + hash += hash >>> 5; + hash = (hash ^ (hash << 4)) >>> 0; + hash += hash >>> 17; + hash = (hash ^ (hash << 25)) >>> 0; + hash += hash >>> 6; + + return (0x100000000 + hash).toString(16).substr(1); +} + +function _(s) { + return (window.TR && TR[sfh(s)]) || s; +} + function Int(x) { return (/^-?\d+$/.test(x) ? +x : NaN); } -- 2.30.2