All files / lib/utils imagePreload.ts

5.35% Statements 9/168
0% Branches 0/84
0% Functions 0/56
6.04% Lines 9/149

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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255            1x                         1x                       1x                               1x                                                   1x                               1x                                                                                                                       1x                                                                                         1x                               1x                                                                                        
import { Game } from '@uniquegood/realworld-web-interface/lib/models/game';
import { Screen } from '@uniquegood/realworld-web-interface/lib/models/game/Screen';
import { Layer } from '@uniquegood/realworld-web-interface/lib/models/game/Layer';
import { Statement } from '@uniquegood/realworld-web-interface/lib/models/game/Statement';
import React from 'react';
 
const imagePreload = async (imageUrl: string) => {
  return new Promise<void>((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve();
    };
    img.onerror = () => {
      reject();
    };
    img.src = imageUrl;
  });
};
 
export const imageListPreload = async (imageUrlList: string[]) => {
  const imageSeperatedCount = 5;
  const imageSeperatedCountList = Array.from(
    { length: Math.ceil(imageUrlList.length / imageSeperatedCount) },
    (_, i) => i
  );
  for await (const i of imageSeperatedCountList) {
    const imageSeperatedList = imageUrlList.slice(i, i + imageSeperatedCount);
    await Promise.all(imageSeperatedList.map(imagePreload));
  }
};
 
export const getImageFromLayer = (layer: Layer) => {
  const imageList: string[] = [];
 
  if (layer.type === 'ar') {
    imageList.push(layer.guideImageUrl);
    imageList.push(layer.overlayImageUrl);
    imageList.push(layer.targetImageUrl);
  } else if (layer.type === 'photoFrame') {
    imageList.push(layer.frameImageUrl);
  }
 
  return imageList.reduce((acc, cur) => {
    if (cur) acc.push(cur);
    return acc;
  }, [] as string[]);
};
export const getImageListFromStatement = (game: Game, statement: Statement) => {
  const imageList: string[] = [];
 
  if (statement.type === 'if' || statement.type === 'consumeItem') {
    statement.trueStatementList.forEach((statement) => {
      imageList.push(...getImageListFromStatement(game, statement as Statement));
    });
    statement.falseStatementList.forEach((statement) => {
      imageList.push(...getImageListFromStatement(game, statement as Statement));
    });
  } else if (statement.type === 'itemModal') {
    if (statement.item?.type === 'itemReference') {
      const targetItemId = statement.item.id;
      const targetItem = game.itemList.find(({ id }) => id === targetItemId);
      if (targetItem?.mainImageUrl) imageList.push(targetItem.mainImageUrl);
    }
  } else if (statement.type === 'openLayer') {
    if (statement.layer?.type === 'layerReference') {
      const targetLayerId = statement.layer.id;
      const targetLayer = game.layerList.find(({ id }) => id === targetLayerId);
      if (targetLayer) imageList.push(...getImageFromLayer(targetLayer));
    }
  }
 
  return imageList;
};
export const getRelativeScreenListFromStatement = (statement: Statement) => {
  const relativeScreenList: string[] = [];
 
  if (statement.type === 'if' || statement.type === 'consumeItem') {
    statement.trueStatementList.forEach((statement) => {
      relativeScreenList.push(...getRelativeScreenListFromStatement(statement as Statement));
    });
    statement.falseStatementList.forEach((statement) => {
      relativeScreenList.push(...getRelativeScreenListFromStatement(statement as Statement));
    });
  } else if (statement.type === 'moveScreen') {
    if (statement.screen?.type === 'screenReference') relativeScreenList.push(statement.screen.id);
  }
 
  return relativeScreenList;
};
export const getImageListFromScreen = (game: Game, screen: Screen) => {
  const imageList: string[] = [];
 
  if (!screen) return imageList;
 
  if (screen.style.backgroundImageUrl) imageList.push(screen.style.backgroundImageUrl);
 
  if (screen.type === 'swipe') {
    screen.pageList.forEach((page) => {
      page.blockList.forEach((block) => {
        if (block.type === 'image') imageList.push(block.imageUrl);
        Object.values(block.actionMap).forEach((action) => {
          action.statementList.forEach((statement) => {
            imageList.push(...getImageListFromStatement(game, statement));
          });
        });
      });
    });
  } else if (screen.type === 'scroll') {
    screen.page.blockList.forEach((block) => {
      if (block.type === 'image') imageList.push(block.imageUrl);
      Object.values(block.actionMap).forEach((action) => {
        action.statementList.forEach((statement) => {
          imageList.push(...getImageListFromStatement(game, statement));
        });
      });
    });
  } else if (screen.type === 'visualNovel') {
    Object.values(screen.actionMap).forEach((action) => {
      action.statementList.forEach((statement) => {
        imageList.push(...getImageListFromStatement(game, statement));
      });
    });
    screen.speakerList.forEach((speaker) => {
      if (speaker.imageUrl) imageList.push(speaker.imageUrl);
    });
    screen.conversationList.forEach((conversation) => {
      if (conversation.mainImageUrl) imageList.push(conversation.mainImageUrl);
    });
  } else if (screen.type === 'gpsMap') {
    screen.gpsPointList.forEach((gpsPoint) => {
      imageList.push(gpsPoint.beforeImage);
      imageList.push(gpsPoint.afterImage);
      Object.values(gpsPoint.actionMap).forEach((action) => {
        action.statementList.forEach((statement) => {
          imageList.push(...getImageListFromStatement(game, statement));
        });
      });
    });
  } else if (screen.type === 'start') {
    if (screen.style.backgroundImageUrl) imageList.push(screen.style.backgroundImageUrl);
  } else if (screen.type === 'end') {
    if (screen.style.backgroundImageUrl) imageList.push(screen.style.backgroundImageUrl);
  }
 
  return imageList.reduce((acc, cur) => {
    if (cur && !acc.includes(cur)) acc.push(cur);
    return acc;
  }, [] as string[]);
};
export const getRelativeScreenListFromScreen = (screen: Screen) => {
  const relativeScreenList: string[] = [];
 
  if (screen.type === 'swipe') {
    screen.pageList.forEach((page) => {
      page.blockList.forEach((block) => {
        Object.values(block.actionMap).forEach((action) => {
          action.statementList.forEach((statement) => {
            relativeScreenList.push(...getRelativeScreenListFromStatement(statement));
          });
        });
      });
    });
  } else if (screen.type === 'scroll') {
    screen.page.blockList.forEach((block) => {
      Object.values(block.actionMap).forEach((action) => {
        action.statementList.forEach((statement) => {
          relativeScreenList.push(...getRelativeScreenListFromStatement(statement));
        });
      });
    });
  } else if (screen.type === 'visualNovel') {
    Object.values(screen.actionMap).forEach((action) => {
      action.statementList.forEach((statement) => {
        relativeScreenList.push(...getRelativeScreenListFromStatement(statement));
      });
    });
  } else if (screen.type === 'gpsMap') {
    screen.gpsPointList.forEach((gpsPoint) => {
      Object.values(gpsPoint.actionMap).forEach((action) => {
        action.statementList.forEach((statement) => {
          relativeScreenList.push(...getRelativeScreenListFromStatement(statement));
        });
      });
    });
  } else if (screen.type === 'start') {
    if (screen.nextScreenId) relativeScreenList.push(screen.nextScreenId);
  }
 
  return relativeScreenList.reduce((acc, cur) => {
    if (cur && !acc.includes(cur)) acc.push(cur);
    return acc;
  }, [] as string[]);
};
 
export const getImageListFromScreenWithRelative = (game: Game, screenId: string) => {
  const currentScreen = game.screenMap[screenId];
 
  // 현재 스크린의 이미지 정보를 선언 시점부터 주입
  const imageList = getImageListFromScreen(game, currentScreen);
  const relativeScreenList = getRelativeScreenListFromScreen(currentScreen);
  relativeScreenList.forEach((relativeScreenId) => {
    imageList.push(...getImageListFromScreen(game, game.screenMap[relativeScreenId]));
  });
 
  return imageList.reduce((acc, cur) => {
    if (cur && !acc.includes(cur)) acc.push(cur);
    return acc;
  }, [] as string[]);
};
 
export const useImagePreload = (imageUrlList: string[]) => {
  const [completeCount, setCompleteCount] = React.useState(0);
 
  const imagePreloadFn = async (imageUrl: string) => {
    try {
      await imagePreload(imageUrl);
    } catch (e) {
      console.error(e);
    } finally {
      setCompleteCount((prev) => prev + 1);
    }
  };
 
  React.useEffect(() => {
    setCompleteCount(0);
 
    (async () => {
      const imageSeperatedCount = 5;
      const imageSeperatedCountList = Array.from(
        { length: Math.ceil(imageUrlList.length / imageSeperatedCount) },
        (_, i) => i
      );
      for await (const i of imageSeperatedCountList) {
        if (i === imageSeperatedCountList.length - 1) {
          await Promise.all(imageUrlList.slice(i * imageSeperatedCount).map(imagePreloadFn));
        } else {
          const imageSeperatedList = imageUrlList.slice(
            i * imageSeperatedCount,
            i * imageSeperatedCount + imageSeperatedCount
          );
          await Promise.all(imageSeperatedList.map(imagePreloadFn));
        }
      }
    })();
  }, [imageUrlList]);
 
  return React.useMemo(
    () => ({
      completeCount,
      totalCount: imageUrlList.length
    }),
    [completeCount, imageUrlList.length]
  );
};