From 6e02c5690c8d861f99b74b0caa035962e351b92f Mon Sep 17 00:00:00 2001 From: Nicolas Gallagher Date: Thu, 31 Aug 2017 12:28:48 -0700 Subject: [PATCH] [add] support for AssetRegistry Applies changes from @fmoo to help with Metro packager support. Also fixed a Flow exposed by this change. --- src/components/Image/index.js | 24 +++++++++++++++++--- src/modules/AssetRegistry/index.js | 35 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 src/modules/AssetRegistry/index.js diff --git a/src/components/Image/index.js b/src/components/Image/index.js index 5cbdad6a..02f39e30 100644 --- a/src/components/Image/index.js +++ b/src/components/Image/index.js @@ -13,6 +13,7 @@ import applyNativeMethods from '../../modules/applyNativeMethods'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import createDOMElement from '../../modules/createDOMElement'; +import { getAssetByID } from '../../modules/AssetRegistry'; import ImageLoader from '../../modules/ImageLoader'; import ImageResizeMode from './ImageResizeMode'; import ImageStylePropTypes from './ImageStylePropTypes'; @@ -34,6 +35,7 @@ const STATUS_PENDING = 'PENDING'; const STATUS_IDLE = 'IDLE'; const ImageSourcePropType = oneOfType([ + number, shape({ height: number, uri: string.isRequired, @@ -47,7 +49,10 @@ const getImageState = (uri, shouldDisplaySource) => { }; const resolveAssetDimensions = source => { - if (typeof source === 'object') { + if (typeof source === 'number') { + const { height, width } = getAssetByID(source); + return { height, width }; + } else if (typeof source === 'object') { const { height, width } = source; return { height, width }; } @@ -55,14 +60,27 @@ const resolveAssetDimensions = source => { const svgDataUriPattern = /^data:image\/svg\+xml;/; const resolveAssetSource = source => { - const uri = typeof source === 'object' ? source.uri : source || ''; + let uri; + if (typeof source === 'number') { + // get the URI from the packager + const asset = getAssetByID(source); + const scale = asset.scales[0]; + const scaleSuffix = scale !== 1 ? `@${scale}x` : ''; + uri = asset ? `${asset.httpServerLocation}/${asset.name}${scaleSuffix}.${asset.type}` : ''; + } else if (source && source.uri) { + uri = source.uri; + } else { + uri = source || ''; + } + // SVG data may contain characters (e.g., #, ") that need to be escaped if (svgDataUriPattern.test(uri)) { const parts = uri.split(', + hash: string, + name: string, + type: string +}; + +const assets: Array = []; + +export function registerAsset(asset: PackagerAsset): number { + // `push` returns new array length, so the first asset will + // get id 1 (not 0) to make the value truthy + return assets.push(asset); +} + +export function getAssetByID(assetId: number): PackagerAsset { + return assets[assetId - 1]; +}