cx-libtranslate.debug.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. var cx_libtranslate = (() => {
  2. var __getOwnPropNames = Object.getOwnPropertyNames;
  3. var __commonJS = (cb, mod) => function __require() {
  4. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  5. };
  6. // source/translation.js
  7. var require_translation = __commonJS({
  8. "source/translation.js"(exports) {
  9. var translation = class {
  10. /**
  11. * @var {string}
  12. * This is translated content.
  13. */
  14. #content;
  15. /**
  16. * @var {bool}
  17. * This is true, when content is translated from dict, and false
  18. * when could not being found.
  19. */
  20. #translated;
  21. /**
  22. * This create new translation. Translation store content of the
  23. * translation, make avairable to format translated phrase and also
  24. * store that translation was found in the phrasebook.
  25. *
  26. * @param {string} content - Content of the translation.
  27. * @param {bool} translated - True when translation could be found.
  28. */
  29. constructor(content, translated = true) {
  30. if (typeof content !== "string") {
  31. throw new TypeError("Translated content must be string.");
  32. }
  33. if (typeof translated !== "boolean") {
  34. throw new TypeError("Result of translation must be boolean.");
  35. }
  36. this.#content = content;
  37. this.#translated = translated;
  38. Object.freeze(this);
  39. }
  40. /**
  41. * This convert transiation to string.
  42. *
  43. * @returns {string} - Content of the translation.
  44. */
  45. toString() {
  46. return this.#content;
  47. }
  48. /**
  49. * @returns {string} - Content of the translation.
  50. */
  51. get text() {
  52. return this.#content;
  53. }
  54. /**
  55. * @returns {bool} - True when translation was found, false when not.
  56. */
  57. get valid() {
  58. return this.translated;
  59. }
  60. /**
  61. * This would format ready translation, with numbers, dats, and
  62. * other content, which could not being statically places into
  63. * translation. To use it, place name of content object key into
  64. * "#{}" in translation.
  65. *
  66. * @example ```
  67. * Translation: "I have more than #{how_many} apples!"
  68. * Object: { how_many: 10 }
  69. * Result: "I have more than 10 apples!"
  70. * ```
  71. *
  72. * @param {string} content
  73. * @returns {string}
  74. */
  75. format(content) {
  76. if (typeof content !== "object") {
  77. throw new TypeError("Content to format from must be object.");
  78. }
  79. if (!this.#translated) {
  80. return this.#content;
  81. }
  82. return this.#parse_format(content);
  83. }
  84. /**
  85. * This infill prepared translation with data from content
  86. * object.
  87. *
  88. * @see format
  89. *
  90. * @param {object} content - Content to load data from.
  91. * @returns {string} - Formater translation.
  92. */
  93. #parse_format(content) {
  94. let parts = this.#content.split("#{");
  95. let result = parts[0];
  96. for (let count = 1; count < parts.length; ++count) {
  97. const part = parts[count];
  98. const splited = part.split("}");
  99. if (splited.length === 1) {
  100. return result + splited[0];
  101. }
  102. const name = splited.splice(0, 1)[0].trim();
  103. const rest = splited.join("}");
  104. if (!(name in content)) {
  105. DEBUG: throw new RangeError(
  106. 'Could not find "' + name + '".'
  107. );
  108. result += rest;
  109. continue;
  110. }
  111. result += content[name] + rest;
  112. }
  113. return result;
  114. }
  115. };
  116. exports.translation = translation;
  117. }
  118. });
  119. // source/phrasebook.js
  120. var require_phrasebook = __commonJS({
  121. "source/phrasebook.js"(exports) {
  122. var translation = require_translation().translation;
  123. var phrasebook = class _phrasebook {
  124. /**
  125. * @var {Map}
  126. * This store phrases in flat notation.
  127. */
  128. #phrases;
  129. /**
  130. * @var {?object}
  131. * This store object for nested object notation.
  132. */
  133. #objects;
  134. /**
  135. * This create new phrasebook from phrases map, and optional object
  136. * for phrases in object notation.
  137. *
  138. * @param {Map} phrases - This contain phrases in flat notation.
  139. * @param {?object} objects - This contain phrases in object notation.
  140. */
  141. constructor(phrases, objects = null) {
  142. if (!(phrases instanceof Map)) {
  143. throw new TypeError("Phrases must an map.");
  144. }
  145. if (objects !== null && typeof objects !== "object") {
  146. throw new TypeError("Objects must be null or object.");
  147. }
  148. this.#phrases = phrases;
  149. this.#objects = objects;
  150. }
  151. /**
  152. * This translate given phrase. When phrase is in the nested object
  153. * notation, then try to find phrase in objects. When not, try to find
  154. * phrase in the flat phrases. When could not find phrase, then return
  155. * not translated phrase. Content always is returned as translation
  156. * object, which could be also formated wich numbers, dates and
  157. * much more.
  158. *
  159. * @param {string} phrase - Phrase to translate.
  160. * @returns {translation} - Translated phrase.
  161. */
  162. translate(phrase) {
  163. if (typeof phrase !== "string") {
  164. throw new TypeError("Phrase to translate must be an string.");
  165. }
  166. if (this.#is_nested(phrase)) {
  167. return this.#translate_nested(phrase);
  168. }
  169. return this.#translate_flat(phrase);
  170. }
  171. /**
  172. * This translate given phrase. When phrase is in the nested object
  173. * notation, then try to find phrase in objects. When not, try to find
  174. * phrase in the flat phrases. When could not find phrase, then return
  175. * not translated phrase. Content always is returned as translation
  176. * object, which could be also formated wich numbers, dates and
  177. * much more.
  178. *
  179. * @param {string} phrase - Phrase to translate.
  180. * @returns {translation} - Translated phrase.
  181. */
  182. get(phrase) {
  183. return this.translate(phrase);
  184. }
  185. /**
  186. * Check that phrase is nested or not.
  187. *
  188. * @param {string} phrase - Phrase to check that is nested
  189. * @returns {bool} - True when nested, false when not
  190. */
  191. #is_nested(phrase) {
  192. return phrase.indexOf(".") !== -1;
  193. }
  194. /**
  195. * This translate object notated phrase.
  196. *
  197. * @param {string} phrase - Phrase to translate.
  198. * @returns {translation} - Translated phrase.
  199. */
  200. #translate_nested(phrase) {
  201. if (this.#objects === null) {
  202. return this.#translate_flat(phrase);
  203. }
  204. const parts = phrase.trim().split(".");
  205. let current = this.#objects;
  206. for (const count in parts) {
  207. const part = parts[count];
  208. if (!(part in current)) {
  209. return new translation(phrase, false);
  210. }
  211. current = current[part];
  212. }
  213. if (typeof current !== "string") {
  214. return new translation(phrase, false);
  215. }
  216. return new translation(current, true);
  217. }
  218. /**
  219. * This set phrasebook as default. That mean, it would add own translate
  220. * function to global scope, and create _({string}) function in the global
  221. * scope. It is useable to minify code with translations. It is not
  222. * avairable in the NodeJS, only in the browser.
  223. *
  224. * @returns {phrasebook} - Object itself to chain loading.
  225. */
  226. set_as_default() {
  227. const translate = (content) => {
  228. return this.translate(content);
  229. };
  230. window._ = translate;
  231. window.translate = translate;
  232. }
  233. /**
  234. * This translate flat phrase.
  235. *
  236. * @param {string} phrase - Phrase to translate.
  237. * @returns {translation} - Translated phrase.
  238. */
  239. #translate_flat(phrase) {
  240. const prepared = _phrasebook.prepare(phrase);
  241. const found = this.#phrases.has(prepared);
  242. const translated = found ? this.#phrases.get(prepared) : phrase;
  243. return new translation(translated, found);
  244. }
  245. /**
  246. * This prepars phrase, that mean replece all spaces with "_", trim
  247. * and also replace all big letters with lowwer.
  248. *
  249. * @param {string} content - Phrase to preapre.
  250. * @return {string} - Prepared phrase.
  251. */
  252. static prepare(content) {
  253. if (typeof content !== "string") {
  254. throw new TypeError("Content to prepare must be an string.");
  255. }
  256. return content.trim().replaceAll(" ", "_").replaceAll(".", "_").toLowerCase();
  257. }
  258. };
  259. exports.phrasebook = phrasebook;
  260. }
  261. });
  262. // source/loader.js
  263. var require_loader = __commonJS({
  264. "source/loader.js"(exports) {
  265. var phrasebook = require_phrasebook().phrasebook;
  266. var loader = class {
  267. /**
  268. * @var {string}
  269. * This is location of the phrasebook on the server.
  270. */
  271. #path;
  272. /**
  273. * @var {bool}
  274. * This is true, when must load local file, or false when fetch.
  275. */
  276. #local;
  277. /**
  278. * This create new loader of the phrasebook.
  279. *
  280. * @param {string} path - Location of the phrasebook to fetch.
  281. * @param {bool} local - False when must fetch from remote.
  282. */
  283. constructor(path, local = false) {
  284. if (typeof path !== "string") {
  285. throw new TypeError("Path of the file must be string.");
  286. }
  287. if (typeof local !== "boolean") {
  288. throw new TypeError("Local must be bool variable.");
  289. }
  290. this.#path = path;
  291. this.#local = local;
  292. }
  293. /**
  294. * This load file from path given in the constructor, parse and return it.
  295. *
  296. * @returns {phrasebook} - New phrasebook with content from JSON file.
  297. */
  298. async #load_remote() {
  299. const request = await fetch(this.#path);
  300. const response = await request.json();
  301. return this.#parse(response);
  302. }
  303. /**
  304. * This load file from path given in the constructor, parse and return it.
  305. *
  306. * @returns {phrasebook} - New phrasebook with content from JSON file.
  307. */
  308. async #load_local() {
  309. let fs = null;
  310. if (fs === null) {
  311. throw new Error("Could not use ndoe:fs in browser.");
  312. }
  313. const content = await fs.readFile(this.#path, { encoding: "utf8" });
  314. const response = JSON.parse(content);
  315. return this.#parse(response);
  316. }
  317. /**
  318. * This load file from path given in the constructor, parse and return it.
  319. *
  320. * @returns {phrasebook} - New phrasebook with content from JSON file.
  321. */
  322. load() {
  323. if (this.#local) {
  324. return this.#load_local();
  325. }
  326. return this.#load_remote();
  327. }
  328. /**
  329. * This parse phrasebook. When phrasebook contain "phrases" or "objects"
  330. * keys, and also "objects" is not string, then parse it as nested file,
  331. * in the other way parse it as flat.
  332. *
  333. * @param {object} content - Fetched object with translations.
  334. * @returns {phrasebook} - Loaded phrasebook.
  335. */
  336. #parse(content) {
  337. const has_objects = "objects" in content && typeof content["objects"] === "object";
  338. const has_phrases = "phrases" in content && typeof content["phrases"] === "object";
  339. const is_nested = has_objects || has_phrases;
  340. if (is_nested) {
  341. const phrases = has_phrases ? content["phrases"] : {};
  342. const objects = has_objects ? content["objects"] : {};
  343. return new phrasebook(
  344. this.#parse_phrases(phrases),
  345. objects
  346. );
  347. }
  348. return new phrasebook(this.#parse_phrases(content));
  349. }
  350. /**
  351. * This parse flat phrases object to map.
  352. *
  353. * @param {object} content - Flat phrases object to pase.
  354. * @returns {Map} - Phrases parsed as Map.
  355. */
  356. #parse_phrases(content) {
  357. const phrases = /* @__PURE__ */ new Map();
  358. Object.keys(content).forEach((phrase) => {
  359. const name = phrasebook.prepare(phrase);
  360. const translation = content[phrase];
  361. phrases.set(name, translation);
  362. });
  363. return phrases;
  364. }
  365. };
  366. exports.loader = loader;
  367. }
  368. });
  369. // source/languages.js
  370. var require_languages = __commonJS({
  371. "source/languages.js"(exports) {
  372. var loader = require_loader().loader;
  373. var phrasebook = require_phrasebook().phrasebook;
  374. var languages = class {
  375. /**
  376. * @var {string}
  377. * This represents path to directory where phrasebooks had been stored.
  378. */
  379. #path;
  380. /**
  381. * @var {Map}
  382. * This store languages and its files on server.
  383. */
  384. #libs;
  385. /**
  386. * @var {bool}
  387. * This store that directory is in the local file system, or remote
  388. * server. When true, resources would be loaded by node:fs. When
  389. * false, resources would be fetched.
  390. */
  391. #local;
  392. /**
  393. * This create new languages library. Next, languages could be added to
  394. * the library by command, or by loading index file.
  395. *
  396. * @throws {TypeError} - When parameters is not in correct format.
  397. *
  398. * @param {string} path - Path to phrasebooks on the server or filesystem.
  399. * @param {bool} local - True when phrasebooks dirs would be loaded by
  400. * node:fs module. False when would be fetch.
  401. */
  402. constructor(path, local = false) {
  403. if (typeof path !== "string") {
  404. throw new TypeError("Path to the phrasebooks must be string.");
  405. }
  406. if (typeof local !== "boolean") {
  407. throw new TypeError("Local must be bool variable.");
  408. }
  409. this.#local = local;
  410. this.#path = path;
  411. this.#libs = /* @__PURE__ */ new Map();
  412. }
  413. /**
  414. * This add new language to the library by name. Name must be in form
  415. * like POSIX locale, like en_US, or pl_PL. That mean first two letter
  416. * mest be ISO 639-1 and second two letters mst be in ISO 3166-1 alpha-2
  417. * 2 letter country code format.
  418. *
  419. * @see https://www.loc.gov/standards/iso639-2/php/code_list.php
  420. * @see https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
  421. * @see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
  422. * @see https://en.wikipedia.org/wiki/Locale_(computer_software)
  423. *
  424. * @throws {TypeError} - When tpes of the parameters is not correct.
  425. *
  426. * @param {string} name - Name of the language, like "en_US".
  427. * @param {string} file - Name of the file in the directory.
  428. * @return {languages} - Instnace of this class to chain.
  429. */
  430. add(name, file) {
  431. if (typeof name !== "string") {
  432. throw new TypeError("Name of the language must be sting.");
  433. }
  434. if (typeof file !== "string") {
  435. throw new TypeError("File on in the directory must be string.");
  436. }
  437. if (this.#libs.has(name)) {
  438. console.error('Language "' + name + '" already loaded.');
  439. console.error("It could not being loaded twice.");
  440. return this;
  441. }
  442. if (!this.#valid_locale(name)) {
  443. console.error('Language name "' + name + '" invalid formated.');
  444. console.error("It could not being loaded.");
  445. return this;
  446. }
  447. this.#libs.set(name, file);
  448. return this;
  449. }
  450. /**
  451. * This load all phrasebook given in the index file. Index must be
  452. * JSON file, which contain one object. That object properties must be
  453. * languages names in the notation like in add function. Valus of that
  454. * properties musts being strings which contains names of the phrasebook
  455. * files in the path directory.
  456. *
  457. * @example ``` { "pl_PL": "polish.json", "en_US": "english.json" } ```
  458. *
  459. * @see add
  460. *
  461. * @param {string} index - Index file in the phrasebook directory.
  462. * @return {languages} - New languages instance with loaded index.
  463. */
  464. async load(index) {
  465. if (typeof index !== "string") {
  466. throw new TypeError("Name of index file is not string.");
  467. }
  468. const response = await this.#load_index(index);
  469. this.#libs.clear();
  470. Object.keys(response).forEach((name) => {
  471. if (typeof name !== "string") {
  472. console.error("Name of the language must be string.");
  473. console.error("Check languages index.");
  474. console.error("Skipping it.");
  475. return;
  476. }
  477. if (typeof response[name] !== "string") {
  478. console.error("Name of phrasebook file must be string.");
  479. console.error("Check languages index.");
  480. console.error("Skipping it.");
  481. return;
  482. }
  483. this.add(name, response[name]);
  484. });
  485. return this;
  486. }
  487. /**
  488. * This load index object. That check, and when content must be loaded
  489. * from local filesystem, it use node:fs, or when it must be fetched from
  490. * remote, then use fetch API.
  491. *
  492. * @param {string} index - Name of the index file in library.
  493. * @returns {object} - Loaded index file content.
  494. */
  495. async #load_index(index) {
  496. const path = this.#full_path(index);
  497. if (this.#local) {
  498. let fs = null;
  499. if (fs === null) {
  500. throw new Error("Could not use ndoe:fs in browser.");
  501. }
  502. return JSON.parse(
  503. await fs.readFile(path, { encoding: "utf-8" })
  504. );
  505. }
  506. const request = await fetch(path);
  507. return await request.json();
  508. }
  509. /**
  510. * This check that language exists in languages library.
  511. *
  512. * @param {string} name - Name of the language to check.
  513. * @return {bool} - True when language exists, false when not
  514. */
  515. has(name) {
  516. return this.#libs.has(name);
  517. }
  518. /**
  519. * This return all avairable languages.
  520. *
  521. * @return {Array} - List of all avairable languages.
  522. */
  523. get avairable() {
  524. const alls = new Array();
  525. this.#libs.keys().forEach((name) => {
  526. alls.push(name);
  527. });
  528. return alls;
  529. }
  530. /**
  531. * @returns {string} - Default
  532. */
  533. get default() {
  534. const avairable = this.avairable;
  535. if (avairable.length === 0) {
  536. throw new Error("Languages list is empty. Can not load default.");
  537. }
  538. return avairable[0];
  539. }
  540. /**
  541. * This load phrasebook with give name.
  542. *
  543. * @throws {TypeError} - Param type is not correct.
  544. * @throws {RangeError} - Language not exists in libs.
  545. *
  546. * @param {string} name - Name of the language to load.
  547. * @returns {phrasebook} - Phrasebook loaded from the file.
  548. */
  549. select(name) {
  550. if (typeof name !== "string") {
  551. throw new TypeError("Name of the language must be string.");
  552. }
  553. if (!this.has(name)) {
  554. DEBUG: throw new RangeError(
  555. 'Not found language "' + name + '".'
  556. );
  557. return new phrasebook(/* @__PURE__ */ new Map());
  558. }
  559. const file = this.#libs.get(name);
  560. const path = this.#full_path(file);
  561. return new loader(path, this.#local).load();
  562. }
  563. /**
  564. * This return full path to the file.
  565. *
  566. * @param {string} name - Name of the file to get its path
  567. * @return {string} - Full path of the file
  568. */
  569. #full_path(name) {
  570. let glue = "/";
  571. if (this.#path[this.#path.length - 1] === glue) {
  572. glue = "";
  573. }
  574. return this.#path + glue + name;
  575. }
  576. /**
  577. * This check that format is valid POSIX like locale.
  578. *
  579. * @param {string} name - Name to check format of.
  580. * @return {bool} - True when format is valid, false when not.
  581. */
  582. #valid_locale(name) {
  583. const splited = name.split("_");
  584. if (splited.length !== 2) {
  585. return false;
  586. }
  587. const first = splited[0];
  588. const second = splited[1];
  589. if (first.toLowerCase() !== first || first.length !== 2) {
  590. return false;
  591. }
  592. if (second.toUpperCase() !== second || second.length !== 2) {
  593. return false;
  594. }
  595. return true;
  596. }
  597. };
  598. exports.languages = languages;
  599. }
  600. });
  601. // source/selector.js
  602. var require_selector = __commonJS({
  603. "source/selector.js"(exports) {
  604. var languages = require_languages().languages;
  605. var selector = class {
  606. /**
  607. * @var {languages}
  608. * This store languages container.
  609. */
  610. #languages;
  611. /**
  612. * @var {?HTMLElement}
  613. * This store selector HTML container, or null when not created.
  614. */
  615. #container;
  616. /**
  617. * @var {HTMLElement}
  618. * This store languages HTML selector object.
  619. */
  620. #selector;
  621. /**
  622. * @var {Array}
  623. * This is array of callbacks which must being called after change.
  624. */
  625. #callbacks;
  626. /**
  627. * This create new selector object, from languages container.
  628. *
  629. * @param {languages} languages - Languages container to work on.
  630. */
  631. constructor(languages2) {
  632. this.#container = null;
  633. this.#languages = languages2;
  634. this.#callbacks = new Array();
  635. this.#selector = this.#create_selector();
  636. }
  637. /**
  638. * This check that selector is currently inserted anywhere.
  639. *
  640. * @returns {bool} - True when selector is inserted anywhere.
  641. */
  642. get is_inserted() {
  643. return this.#container !== null;
  644. }
  645. /**
  646. * This inserts selector into given HTML element, or directly into
  647. * document body, when any element is not specified. It returns
  648. * itselt, to call more functions inline.
  649. *
  650. * @param {?HTMLElement} where - Place to insert selector, or null.
  651. * @returns {selector} - This object to chain loading.
  652. */
  653. insert(where = null) {
  654. if (this.is_inserted) {
  655. return this;
  656. }
  657. if (where === null) {
  658. where = document.querySelector("body");
  659. }
  660. this.#container = this.#create_container();
  661. where.appendChild(this.#container);
  662. return this;
  663. }
  664. /**
  665. * This run all functions which was registered as onChange callback.
  666. */
  667. #on_change() {
  668. this.#callbacks.forEach((count) => {
  669. count(this.current);
  670. });
  671. }
  672. /**
  673. * This function remove selector from HTML element, if it is already
  674. * inserted anywhere.
  675. *
  676. * @returns {selector} - This object to chain loading.
  677. */
  678. remove() {
  679. if (!this.is_inserted) {
  680. return this;
  681. }
  682. this.#container.remove();
  683. this.#container = null;
  684. return this;
  685. }
  686. /**
  687. * This create new container with selector inside.
  688. *
  689. * @returns {HTMLElement} - New container with selector.
  690. */
  691. #create_container() {
  692. const container = document.createElement("div");
  693. container.classList.add(this.class_name);
  694. container.appendChild(this.#selector);
  695. return container;
  696. }
  697. /**
  698. * This add new callback to selector. All callbacks would be called
  699. * after language change. Callback would get one parameter, which is
  700. * name of the location.
  701. *
  702. * @param {CallableFunction} callback - Function to call on change.
  703. * @returns
  704. */
  705. add_listener(callback) {
  706. this.#callbacks.push(callback);
  707. return this;
  708. }
  709. /**
  710. * This return HTML class name of selector container.
  711. *
  712. * @returns {string} - HTML class name of selector container.
  713. */
  714. get class_name() {
  715. return "cx-libtranslate-language-selector";
  716. }
  717. /**
  718. * This create HTML option element from language name.
  719. *
  720. * @param {string} location - Name of single language.
  721. * @returns {HTMLElement} - New option element.
  722. */
  723. #create_option(location) {
  724. const name = location.split("_").pop();
  725. const option = document.createElement("option");
  726. option.innerText = name;
  727. option.value = location;
  728. return option;
  729. }
  730. /**
  731. * This return current selected language name.
  732. *
  733. * @returns {string} - Current selected language.
  734. */
  735. get current() {
  736. return this.#selector.value;
  737. }
  738. /**
  739. * This set current selected language for the selector.
  740. *
  741. * @param {string} name - Name of the language to set.
  742. * @returns {selector} - This to chain loading.
  743. */
  744. set_selection(name) {
  745. if (!this.#languages.has(name)) {
  746. DEBUG: throw new Error(
  747. 'Selector has not "' + name + '" language in the container.'
  748. );
  749. }
  750. this.#selector.value = name;
  751. return this;
  752. }
  753. /**
  754. * This reload languages list in the selector. It could be used
  755. * after change in the languages container.
  756. *
  757. * @returns {selector} - Itself to chain loading.
  758. */
  759. reload() {
  760. while (this.#selector.lastChild) {
  761. this.#selector.lastChild.remove();
  762. }
  763. this.#languages.avairable.forEach((count) => {
  764. this.#selector.appendChild(this.#create_option(count));
  765. });
  766. return this;
  767. }
  768. /**
  769. * This create new HTML selector object, witch all languages
  770. * from container inserted as options.
  771. *
  772. * @returns {HTMLElement} - New selector object.
  773. */
  774. #create_selector() {
  775. const selector2 = document.createElement("select");
  776. selector2.addEventListener("change", () => {
  777. this.#on_change();
  778. });
  779. this.#languages.avairable.forEach((count) => {
  780. selector2.appendChild(this.#create_option(count));
  781. });
  782. return selector2;
  783. }
  784. };
  785. exports.selector = selector;
  786. }
  787. });
  788. // source/autotranslate.js
  789. var require_autotranslate = __commonJS({
  790. "source/autotranslate.js"(exports) {
  791. var { phrasebook } = require_phrasebook();
  792. var autotranslate = class _autotranslate {
  793. /**
  794. * @var {?phrasebook}
  795. * This store phrasebook to get translates from, or store null, to get
  796. * translate content from global translate function.
  797. */
  798. #phrasebook;
  799. /**
  800. * @var {?MutationObserver}
  801. * This store observer object, when it is connecter and waiting for
  802. * changaes, or store null, when observer currently not working.
  803. */
  804. #observer;
  805. /**
  806. * This create new autotranslator. It require phrasebook, to loads
  807. * translations for phrases from. When null had been given, the it
  808. * use global translate function.
  809. *
  810. * @throws {Error} - When trying to use it in the NodeJS.
  811. *
  812. * @param {?phrasebook} phrasebook
  813. */
  814. constructor(phrasebook2 = null) {
  815. this.#observer = null;
  816. this.#phrasebook = phrasebook2;
  817. }
  818. /**
  819. * It return class name for elements, which would be translated by
  820. * autotranslator.
  821. *
  822. * @returns {string} - Class name for autotranslating elements.
  823. */
  824. static get_class_name() {
  825. return "translate";
  826. }
  827. /**
  828. * This return selector for choose elements which must be autotranslated.
  829. *
  830. * @returns {string} - Selector of the elements to translate.
  831. */
  832. get #class_selector() {
  833. return "." + _autotranslate.get_class_name();
  834. }
  835. /**
  836. * This return name of attribute which store phrase to translate.
  837. *
  838. * @returns {string} - Name of attribute which store phrase.
  839. */
  840. static get_attribute_name() {
  841. return "phrase";
  842. }
  843. /**
  844. * This check that autotranslator is connected and waiting to changes.
  845. *
  846. * @returns {bool} - True when observer is connected, fakse when not.
  847. */
  848. get is_connected() {
  849. return this.#observer !== null;
  850. }
  851. /**
  852. * This search elements which could be translated in the element given
  853. * in the parameter. When null given, then it search elements in the
  854. * all document.
  855. *
  856. * @param {?HTMLElement} where - Item to load items from or null.
  857. * @returns {Array} - Array of elements to translate.
  858. */
  859. #get_all_items(where = null) {
  860. if (where === null) {
  861. where = document;
  862. }
  863. return Array.from(
  864. where.querySelectorAll(this.#class_selector)
  865. );
  866. }
  867. /**
  868. * It translate given phrase, baseed on loaded phrasebook, or when not
  869. * loaded any, then use global translate function. When it also not
  870. * exists, then throws error in debug mode, or return not translated
  871. * phrase on production.
  872. *
  873. * @throws {Error} - When any option to translate not exists.
  874. *
  875. * @param {string} content - Phrase to translate.
  876. * @returns {string} - Translated content.
  877. */
  878. #translate(content) {
  879. if (this.#phrasebook !== null) {
  880. return this.#phrasebook.translate(content);
  881. }
  882. if (_ === void 0) {
  883. DEBUG: throw new Error("All translate options are unavairable.");
  884. return content;
  885. }
  886. return _(content);
  887. }
  888. /**
  889. * This add mutable observer to the body. It wait for DOM modifications,
  890. * and when any new node had been adder, or any phrase attribute had
  891. * been changed, then it trying to translate it.
  892. *
  893. * @returns {autotranslate} - This object to chain load.
  894. */
  895. connect() {
  896. if (this.is_connected) {
  897. return this;
  898. }
  899. const body = document.querySelector("body");
  900. const callback = (targets) => {
  901. this.#process(targets);
  902. };
  903. const options = {
  904. childList: true,
  905. attributes: true,
  906. characterData: false,
  907. subtree: true,
  908. attributeFilter: [_autotranslate.get_attribute_name()],
  909. attributeOldValue: false,
  910. characterDataOldValue: false
  911. };
  912. this.#observer = new MutationObserver(callback);
  913. this.#observer.observe(body, options);
  914. return this;
  915. }
  916. /**
  917. * This prcoess all given in the array mutable records.
  918. *
  919. * @param {Array} targets - Array with mutable records.
  920. */
  921. #process(targets) {
  922. targets.forEach((count) => {
  923. if (count.type === "attributes") {
  924. this.#update_single(count.target);
  925. return;
  926. }
  927. this.#get_all_items(count.target).forEach((count2) => {
  928. this.#update_single(count2);
  929. });
  930. });
  931. }
  932. /**
  933. * This disconnect observer, and remove it.
  934. *
  935. * @returns {autotranslate} - This object to chain loading.
  936. */
  937. disconnect() {
  938. if (!this.is_connected) {
  939. return this;
  940. }
  941. this.#observer.disconnect();
  942. this.#observer = null;
  943. return this;
  944. }
  945. /**
  946. * This update single element, based on phrase attribute. When element
  947. * is standard HTMLElement, then it place translated content into
  948. * innerText, but when element is input, like HTMLInputElement or
  949. * HTMLTextAreaElement, then it place result into placeholder. When
  950. * input is button, or submit, then it put content into value.
  951. *
  952. * @param {HTMLElement} target - Element to translate
  953. */
  954. #update_single(target) {
  955. const attrobute_name = _autotranslate.get_attribute_name();
  956. const phrase = target.getAttribute(attrobute_name);
  957. const result = this.#translate(phrase);
  958. if (target instanceof HTMLInputElement) {
  959. if (target.type === "button" || target.type === "submit") {
  960. target.value = result;
  961. return;
  962. }
  963. target.placeholder = result;
  964. return;
  965. }
  966. if (target instanceof HTMLTextAreaElement) {
  967. target.placeholder = result;
  968. return;
  969. }
  970. target.innerText = result;
  971. }
  972. /**
  973. * This update translation of all elements in the document. It is useable
  974. * when new autotranslator is created.
  975. *
  976. * @returns {autotranslate} - Instance of object to chain loading.
  977. */
  978. update() {
  979. this.#get_all_items().forEach((count) => {
  980. this.#update_single(count);
  981. });
  982. return this;
  983. }
  984. };
  985. exports.autotranslate = autotranslate;
  986. }
  987. });
  988. // source/preferences.js
  989. var require_preferences = __commonJS({
  990. "source/preferences.js"(exports) {
  991. var languages = require_languages().languages;
  992. var phrasebook = require_phrasebook().phrasebook;
  993. var selector = require_selector().selector;
  994. var autotranslate = require_autotranslate().autotranslate;
  995. var preferences = class {
  996. /**
  997. * @var {languages}
  998. * This store loaded languages object.
  999. */
  1000. #languages;
  1001. /**
  1002. * @var {?selector}
  1003. * This store selector for preferences.
  1004. */
  1005. #selector;
  1006. /**
  1007. * @var {?autotranslate}
  1008. * This store autotranslator, or null.
  1009. */
  1010. #autotranslate;
  1011. /**
  1012. * This create new language preferences manager from loaded languages
  1013. * object.
  1014. *
  1015. * @throws {Error} - When trying to use it in NodeJS.
  1016. *
  1017. * @param {languages} target - loaded languages object.
  1018. */
  1019. constructor(target) {
  1020. this.#selector = null;
  1021. this.#autotranslate = null;
  1022. this.#languages = target;
  1023. }
  1024. /**
  1025. * This return name of language key in localStorage.
  1026. *
  1027. * @returns {string} - Name of key in localStorage.
  1028. */
  1029. get #setting_name() {
  1030. return "cx_libtranslate_lang";
  1031. }
  1032. /**
  1033. * This return current saved language name, or null if any language
  1034. * is not selected yet.
  1035. *
  1036. * @returns {?string} - Saved language or null.
  1037. */
  1038. get #state() {
  1039. return localStorage.getItem(this.#setting_name);
  1040. }
  1041. /**
  1042. * This return selector, which could being used in the ui.
  1043. *
  1044. * @returns {selector} - New UI selector of the languages.
  1045. */
  1046. get selector() {
  1047. if (this.#selector !== null) {
  1048. return this.#selector;
  1049. }
  1050. this.#selector = new selector(this.#languages).set_selection(this.current).add_listener((target) => {
  1051. this.update(target);
  1052. }).add_listener(async (target) => {
  1053. if (this.#autotranslate === null) {
  1054. return;
  1055. }
  1056. this.#reload_autotranslate();
  1057. });
  1058. return this.#selector;
  1059. }
  1060. async #reload_autotranslate() {
  1061. const connected = this.#autotranslate.is_connected;
  1062. if (connected) {
  1063. this.#autotranslate.disconnect();
  1064. }
  1065. this.#autotranslate = null;
  1066. const created = await this.get_autotranslate();
  1067. if (connected) {
  1068. created.connect();
  1069. }
  1070. }
  1071. /**
  1072. * This load phrasebook for selected language, create autotranslate
  1073. * for it, and returns it. Autotranslate is cached in this object.
  1074. *
  1075. * @returns {autotranslate} - Autotranslate for phrasebook.
  1076. */
  1077. async get_autotranslate() {
  1078. if (this.#autotranslate !== null) {
  1079. return this.#autotranslate;
  1080. }
  1081. const phrasebook2 = await this.load_choosen_phrasebook();
  1082. this.#autotranslate = new autotranslate(phrasebook2);
  1083. this.#autotranslate.update();
  1084. return this.#autotranslate;
  1085. }
  1086. /**
  1087. * This save new selected language name to localStorage, or remove it
  1088. * from there if null given.
  1089. *
  1090. * @param {?string} content - Name of selected language or null.
  1091. */
  1092. set #state(content) {
  1093. if (content === null) {
  1094. localStorage.removeItem(this.#setting_name);
  1095. return;
  1096. }
  1097. localStorage.setItem(this.#setting_name, content);
  1098. }
  1099. /**
  1100. * This return current language from localStorage. When any language is
  1101. * not loaded yet, then return default language. It also check that value
  1102. * value from localStorage, and if it not avairable in languages storage,
  1103. * then also return default language.
  1104. *
  1105. * @return {string} - Name of the current language.
  1106. */
  1107. get current() {
  1108. const saved = this.#state;
  1109. if (saved === null) {
  1110. return this.#languages.default;
  1111. }
  1112. if (this.#languages.has(saved)) {
  1113. return saved;
  1114. }
  1115. return this.#languages.default;
  1116. }
  1117. /**
  1118. * This load phrasebook for current selected language.
  1119. *
  1120. * @returns {phrasebook} - Phrasebook for current language.
  1121. */
  1122. async load_choosen_phrasebook() {
  1123. return await this.#languages.select(this.current);
  1124. }
  1125. /**
  1126. * This return loaded languages container.
  1127. *
  1128. * @returns {languages} - Languages container.
  1129. */
  1130. get languages() {
  1131. return this.#languages;
  1132. }
  1133. /**
  1134. * This set new language for user. It also check that language exists
  1135. * in the language container. When not exists, throws error.
  1136. *
  1137. * @throws {Error} - When language not exists in container.
  1138. *
  1139. * @param {string} name - New language to select.
  1140. * @returns {preferences} - This object to chain.
  1141. */
  1142. update(name) {
  1143. DEBUG: if (!this.#languages.has(name)) {
  1144. let error = 'Can not set language "' + name + '" ';
  1145. error += "because not exists in languages container.";
  1146. throw new Error(error);
  1147. }
  1148. this.#state = name;
  1149. return this;
  1150. }
  1151. };
  1152. exports.preferences = preferences;
  1153. }
  1154. });
  1155. // source/core.js
  1156. var require_core = __commonJS({
  1157. "source/core.js"(exports, module) {
  1158. if (typeof module !== "undefined" && module.exports) {
  1159. module.exports.phrasebook = require_phrasebook().phrasebook;
  1160. module.exports.loader = require_loader().loader;
  1161. module.exports.languages = require_languages().languages;
  1162. module.exports.loader = require_loader().loader;
  1163. module.exports.preferences = require_preferences().preferences;
  1164. module.exports.selector = require_selector().selector;
  1165. module.exports.autotranslate = require_autotranslate().autotranslate;
  1166. } else {
  1167. window.cx_libtranslate = {
  1168. phrasebook: require_phrasebook().phrasebook,
  1169. loader: require_loader().loader,
  1170. languages: require_languages().languages,
  1171. translation: require_translation().translation,
  1172. preferences: require_preferences().preferences,
  1173. selector: require_selector().selector,
  1174. autotranslate: require_autotranslate().autotranslate
  1175. };
  1176. }
  1177. }
  1178. });
  1179. return require_core();
  1180. })();
  1181. //# sourceMappingURL=cx-libtranslate.debug.js.map