All files / src/lib/project loadFontData.ts

27.27% Statements 15/55
0% Branches 0/18
0% Functions 0/7
27.27% Lines 15/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 1181x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x     1x                                                                                                                                                             1x                                           1x 1x  
import { glob } from "lib/helpers/glob";
import { promisify } from "util";
import { v4 as uuid } from "uuid";
import { readJson } from "fs-extra";
import { stat } from "fs";
import pngSize from "lib/helpers/pngSize";
 
import parseAssetPath from "shared/lib/assets/parseAssetPath";
import { toValidSymbol } from "shared/lib/helpers/symbols";
import { FontResource, FontResourceAsset } from "shared/lib/resources/types";
import { getAssetResource } from "./assets";
const statAsync = promisify(stat);
 
const loadFontData =
  (projectRoot: string) =>
  async (filename: string): Promise<FontResourceAsset | null> => {
    const { file, plugin } = parseAssetPath(filename, projectRoot, "fonts");
    const resource = await getAssetResource(FontResource, filename);
    try {
      const size = await pngSize(filename);
      const fileStat = await statAsync(filename, { bigint: true });
      const inode = fileStat.ino.toString();
 
      const metadataFilename = filename.replace(/\.png$/i, ".json");
      let mapping: Record<string, number> = {};
      let tableMapping: Record<string, number> = {};
      let name: string = file.replace(/.png/i, "");
      try {
        const metadataFile = await readJson(metadataFilename);
        if (typeof metadataFile === "object") {
          if (
            metadataFile.mapping &&
            typeof metadataFile.mapping === "object"
          ) {
            mapping = metadataFile.mapping;
          }
          if (metadataFile.table && typeof metadataFile.table === "object") {
            tableMapping = metadataFile.table;
          }
          if (metadataFile.name) {
            name = metadataFile.name;
          }
        }
      } catch {}
 
      let table = (Array.from(Array(256)) as number[]).fill(-1);
 
      if (Object.keys(tableMapping).length) {
        //get highest mapped char
        const mappingKeys = Object.keys(tableMapping)
          .map((mappingKey) => {
            return mappingKey.charCodeAt(0);
          })
          .filter((charcode) => {
            return charcode < 256;
          });
        const maxValue = Math.max(...mappingKeys) + 1;
        //adjust the table size to fit tableMapping
        if (table.length < maxValue) {
          table = table.concat(
            (Array.from(Array(maxValue - table.length)) as number[]).fill(-1),
          );
        }
        //modify the table with the tableMapping
        Object.entries(tableMapping).forEach(([key, value]) => {
          const tableIndex = key.charCodeAt(0); //get ascii value of mapped char
          if (tableIndex < 256) {
            table[tableIndex] = value; //assign mapped value to table
          }
        });
      }
 
      return {
        _resourceType: "font",
        id: uuid(),
        plugin,
        name,
        symbol: toValidSymbol(`font_${name}`),
        _v: Date.now(),
        ...resource,
        width: size.width,
        height: size.height,
        mapping,
        table,
        filename: file,
        inode,
      };
    } catch (e) {
      console.error(e);
      return null;
    }
  };
 
const loadAllFontData = async (
  projectRoot: string,
): Promise<FontResourceAsset[]> => {
  const imagePaths = await glob("assets/fonts/**/@(*.png|*.PNG)", {
    cwd: projectRoot,
    absolute: true,
  });
  const pluginPaths = await glob("plugins/*/**/fonts/**/@(*.png|*.PNG)", {
    cwd: projectRoot,
    absolute: true,
  });
  const imageData = (
    await Promise.all(
      ([] as Promise<FontResourceAsset | null>[]).concat(
        imagePaths.map(loadFontData(projectRoot)),
        pluginPaths.map(loadFontData(projectRoot)),
      ),
    )
  ).filter((i) => i);
  return imageData as FontResourceAsset[];
};
 
export default loadAllFontData;
export { loadFontData };