assetPathUtils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow strict
  9. */
  10. 'use strict';
  11. import type {PackagerAsset} from './AssetRegistry';
  12. const androidScaleSuffix = {
  13. '0.75': 'ldpi',
  14. '1': 'mdpi',
  15. '1.5': 'hdpi',
  16. '2': 'xhdpi',
  17. '3': 'xxhdpi',
  18. '4': 'xxxhdpi',
  19. };
  20. /**
  21. * FIXME: using number to represent discrete scale numbers is fragile in essence because of
  22. * floating point numbers imprecision.
  23. */
  24. function getAndroidAssetSuffix(scale: number): string {
  25. if (scale.toString() in androidScaleSuffix) {
  26. return androidScaleSuffix[scale.toString()];
  27. }
  28. throw new Error('no such scale ' + scale.toString());
  29. }
  30. // See https://developer.android.com/guide/topics/resources/drawable-resource.html
  31. const drawableFileTypes = new Set([
  32. 'gif',
  33. 'jpeg',
  34. 'jpg',
  35. 'png',
  36. 'svg',
  37. 'webp',
  38. 'xml',
  39. ]);
  40. function getAndroidResourceFolderName(
  41. asset: PackagerAsset,
  42. scale: number,
  43. ): string | $TEMPORARY$string<'raw'> {
  44. if (!drawableFileTypes.has(asset.type)) {
  45. return 'raw';
  46. }
  47. var suffix = getAndroidAssetSuffix(scale);
  48. if (!suffix) {
  49. throw new Error(
  50. "Don't know which android drawable suffix to use for scale: " +
  51. scale +
  52. '\nAsset: ' +
  53. JSON.stringify(asset, null, '\t') +
  54. '\nPossible scales are:' +
  55. JSON.stringify(androidScaleSuffix, null, '\t'),
  56. );
  57. }
  58. const androidFolder = 'drawable-' + suffix;
  59. return androidFolder;
  60. }
  61. function getAndroidResourceIdentifier(asset: PackagerAsset): string {
  62. var folderPath = getBasePath(asset);
  63. return (folderPath + '/' + asset.name)
  64. .toLowerCase()
  65. .replace(/\//g, '_') // Encode folder structure in file name
  66. .replace(/([^a-z0-9_])/g, '') // Remove illegal chars
  67. .replace(/^assets_/, ''); // Remove "assets_" prefix
  68. }
  69. function getBasePath(asset: PackagerAsset): string {
  70. var basePath = asset.httpServerLocation;
  71. if (basePath[0] === '/') {
  72. basePath = basePath.substr(1);
  73. }
  74. return basePath;
  75. }
  76. module.exports = {
  77. getAndroidAssetSuffix: getAndroidAssetSuffix,
  78. getAndroidResourceFolderName: getAndroidResourceFolderName,
  79. getAndroidResourceIdentifier: getAndroidResourceIdentifier,
  80. getBasePath: getBasePath,
  81. };