common.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import * as zstd from "zstddec";
  2. import { KeyEvent, controlKeyFromJSON, ControlKey } from "./message";
  3. import { KEY_MAP, LANGS } from "./gen_js_from_hbb";
  4. let decompressor: zstd.ZSTDDecoder;
  5. export async function initZstd() {
  6. const tmp = new zstd.ZSTDDecoder();
  7. await tmp.init();
  8. console.log("zstd ready");
  9. decompressor = tmp;
  10. }
  11. export async function decompress(compressedArray: Uint8Array) {
  12. const MAX = 1024 * 1024 * 64;
  13. const MIN = 1024 * 1024;
  14. let n = 30 * compressedArray.length;
  15. if (n > MAX) {
  16. n = MAX;
  17. }
  18. if (n < MIN) {
  19. n = MIN;
  20. }
  21. try {
  22. if (!decompressor) {
  23. await initZstd();
  24. }
  25. return decompressor.decode(compressedArray, n);
  26. } catch (e) {
  27. console.error("decompress failed: " + e);
  28. return undefined;
  29. }
  30. }
  31. const LANG = getLang();
  32. export function translate(locale: string, text: string): string {
  33. const lang = LANG || locale.substring(locale.length - 2).toLowerCase();
  34. let en = LANGS.en as any;
  35. let dict = (LANGS as any)[lang];
  36. if (!dict) dict = en;
  37. let res = dict[text];
  38. if (!res && lang != "en") res = en[text];
  39. return res || text;
  40. }
  41. const zCode = "z".charCodeAt(0);
  42. const aCode = "a".charCodeAt(0);
  43. export function mapKey(name: string, isDesktop: Boolean) {
  44. const tmp = KEY_MAP[name] || name;
  45. if (tmp.length == 1) {
  46. const chr = tmp.charCodeAt(0);
  47. if (!isDesktop && (chr > zCode || chr < aCode))
  48. return KeyEvent.fromPartial({ unicode: chr });
  49. else return KeyEvent.fromPartial({ chr });
  50. }
  51. const control_key = controlKeyFromJSON(tmp);
  52. if (control_key == ControlKey.UNRECOGNIZED) {
  53. console.error("Unknown control key " + tmp);
  54. }
  55. return KeyEvent.fromPartial({ control_key });
  56. }
  57. export async function sleep(ms: number) {
  58. await new Promise((r) => setTimeout(r, ms));
  59. }
  60. function getLang(): string {
  61. try {
  62. const queryString = window.location.search;
  63. const urlParams = new URLSearchParams(queryString);
  64. return urlParams.get("lang") || "";
  65. } catch (e) {
  66. return "";
  67. }
  68. }