summaryrefslogtreecommitdiff
path: root/packages/prosody-ui/src/fonts/FontChanger.tsx
blob: 9ae9c840a90b3fb557a72dcc67a710cf2c776bfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import React, { useEffect, useState, type ReactNode } from "react";
import fontIcon from "../assets/icons/font.svg";
import { getScriptPredictor, type ISO_15924_CODE } from "@sortug/langlib";
import ThaiFontLoader from "./Thai";
import HanFontLoader from "./Hani";
import LatnFontLoader from "./Latn";
import JpanFontLoader from "./Jpan";

function findFontCount(lang: ISO_15924_CODE): number {
  if (lang === "Thai") return 7;
  if (lang === "Jpan") return 6;
  // TODO get more latin fonts
  if (lang === "Latn") return 1;
  if ((lang as any) === "IPA") return 6;
  if (lang.startsWith("Han")) return 23;
  return 0;
}

function FontChanger({
  text,
  script,
  children,
}: {
  text: string;
  script?: ISO_15924_CODE;
  lang?: string;
  children: ReactNode;
}) {
  const [script2, setScript] = useState<ISO_15924_CODE | null>(script || null);
  useEffect(() => {
    if (script) return;
    const predictor = getScriptPredictor();
    const res = predictor(text);
    console.log("script predicted", res);
    const rescript: ISO_15924_CODE | null = res[0];
    if (!rescript) {
      console.error("script undetected", text);
      return;
    }
    setScript(rescript);
    setFontCount(findFontCount(rescript));
  }, [text]);

  const [fontIdx, setFont] = useState(0);
  const [fontCount, setFontCount] = useState(0);
  function changeFont() {
    if (fontIdx === fontCount) setFont(0);
    else setFont((prev) => prev + 1);
  }
  if (!script2)
    return <div className="error">Couldn't detect script of {text}</div>;
  return (
    <div className={`font-changer font-${script}-${fontIdx}`}>
      <img className="font-icon cp" onClick={changeFont} src={fontIcon} />
      {script2 === "Thai" ? (
        <ThaiFontLoader>{children}</ThaiFontLoader>
      ) : script2.startsWith("Han") ? (
        <HanFontLoader>{children}</HanFontLoader>
      ) : script2 === "Jpan" ? (
        <JpanFontLoader>{children}</JpanFontLoader>
      ) : script2 === "Latn" ? (
        <LatnFontLoader>{children}</LatnFontLoader>
      ) : null}
    </div>
  );
}

export default FontChanger;