1import { ImageContentPositionObject, ImageContentPositionValue } from '../Image.types'; 2 3export function ensureValueIsWebUnits(value: string | number) { 4 const trimmedValue = String(value).trim(); 5 if (trimmedValue.endsWith('%')) { 6 return trimmedValue; 7 } 8 return `${trimmedValue}px`; 9} 10 11type KeysOfUnion<T> = T extends T ? keyof T : never; 12 13export const absoluteFilledPosition = { 14 width: '100%', 15 height: '100%', 16 position: 'absolute', 17 left: 0, 18 top: 0, 19} as const; 20 21export function getObjectPositionFromContentPositionObject( 22 contentPosition?: ImageContentPositionObject 23): string { 24 const resolvedPosition = { ...contentPosition } as Record< 25 KeysOfUnion<ImageContentPositionObject>, 26 ImageContentPositionValue 27 >; 28 if (!resolvedPosition) { 29 return '50% 50%'; 30 } 31 if (resolvedPosition.top == null && resolvedPosition.bottom == null) { 32 resolvedPosition.top = '50%'; 33 } 34 if (resolvedPosition.left == null && resolvedPosition.right == null) { 35 resolvedPosition.left = '50%'; 36 } 37 38 return ( 39 ['top', 'bottom', 'left', 'right'] 40 .map((key) => { 41 if (key in resolvedPosition) { 42 return `${key} ${ensureValueIsWebUnits(resolvedPosition[key])}`; 43 } 44 return ''; 45 }) 46 .join(' ') || '50% 50%' 47 ); 48} 49