Ảnh và cache
Ảnh responsive (srcset)
Phần tiêu đề “Ảnh responsive (srcset)”Carousel đo vùng media, nhân với mật độ điểm ảnh của thiết bị và chọn ảnh vừa đủ nét mà không tải thừa. Có hai cách khai báo các kích thước.
Danh sách biến thể, dạng srcset của React Native (width là w-descriptor):
getImage={(p) => [ { uri: `${p.base}-640.jpg`, width: 640, height: 480 }, { uri: `${p.base}-1280.jpg`, width: 1280, height: 960 }, { uri: `${p.base}-2560.jpg`, width: 2560, height: 1920 },]}Biến thể nhỏ nhất mà vẫn đủ rộng sẽ được chọn; nếu có height, cover và contain tính cả tỉ lệ khung hình. Biến thể đã có trong cache được ưu tiên nếu không lớn quá 2 lần mức cần.
URL dựng theo kích thước, cho các CDN ảnh (imgix, Cloudinary, Unsplash, resizer kiểu Next.js). Tham số thứ ba là kích thước cần, tính bằng pixel vật lý, làm tròn lên một trong vài bậc (WIDTH_STEPS: 320, 480, 640, 750, 828, 1080, 1200, 1440, 1920, 2560, …) để CDN và cache chỉ thấy vài URL cho mỗi ảnh, thay vì mỗi thiết bị một URL:
getImage={(p, i, target) => ({ uri: `https://images.unsplash.com/photo-${p.id}?w=${target.width}&h=${target.height}&fit=crop`,})}target gồm width, height, pixelRatio, layoutWidth, layoutHeight (dp) và fit.
Không cần sizes: HTML cần nó vì trình duyệt chọn ảnh trước khi layout, còn carousel chọn sau khi layout.
Xoay màn hình và đổi kích thước. Khi vùng ảnh lớn lên (dọc sang ngang, chia đôi màn hình, đổi cỡ cửa sổ trên web), biến thể nét hơn được tải ở nền trong khi ảnh hiện tại vẫn hiển thị, rồi crossfade trong 220 ms sau khi decode xong. Khi vùng ảnh nhỏ đi, ảnh nét đang hiện được giữ nguyên và không tải gì thêm, giống trình duyệt. Không bao giờ có khung hình trống. Với hiệu ứng liquid, ảnh theo kích thước mới chậm một khung hình sau khi layout đổi (lần render đọc kích thước đó): nếu đo canvas trên UI thread thay vào đó thì mỗi khung hình đều phải đo một lần, suốt thời gian carousel còn mount.
Ảnh từ mạng và cache
Phần tiêu đề “Ảnh từ mạng và cache”Ảnh từ mạng ({ uri: 'https://…' }) đi qua một cache trên đĩa, bật sẵn mặc định. Mỗi ảnh được lưu kèm thời điểm tải và thời điểm hết hạn.
// Hằng số ở cấp module (hoặc useMemo): carousel memo tuỳ chọn theo identity.const CACHE = { strategy: 'stale-while-revalidate', // mặc định maxAge: 6 * 60 * 60 * 1000, // 6 giờ khi server không gửi Cache-Control} as const;
<MorphCarousel imageCache={CACHE} getImage={(p) => ({ uri: p.imageUrl })} … />| Chiến lược | Đã cache, còn hạn | Đã cache, hết hạn | Chưa cache |
|---|---|---|---|
stale-while-revalidate (mặc định) |
Hiện ngay, không gửi request | Hiện ngay, kiểm tra lại ở nền, thay ảnh nếu server có bản mới. Quá maxStale thì chờ mạng |
Tải về |
cache-first |
Hiện ngay, không gửi request | Chờ mạng; bản cũ là phương án dự phòng khi mất mạng | Tải về |
network-first |
Kiểm tra lại trước khi hiện; bản đã cache là dự phòng khi mất mạng | Như cột bên | Tải về |
Thời hạn của ảnh:
- Nếu server gửi
Cache-Control: max-age(hoặcExpires), dùng thời hạn đó.no-cachenghĩa là “luôn kiểm tra lại”,no-storenghĩa là “không ghi xuống đĩa”. ĐặtrespectHttpHeaders: falseđể luôn dùngmaxAge. - Nếu không, dùng
maxAge(mặc định 24 giờ).
Khi kiểm tra lại, cache gửi If-None-Match / If-Modified-Since. Nếu ảnh không đổi, server trả 304 và không có dữ liệu ảnh nào được truyền. Nếu ảnh đã đổi, file mới mang tên mới nên view ảnh tải lại, và file cũ bị xoá. Ảnh đang nằm trên màn hình cũng được kiểm tra lại khi hết hạn, không chỉ lúc mount.
Tuỳ chọn của imageCache:
| Tuỳ chọn | Mặc định | Mô tả |
|---|---|---|
strategy |
'stale-while-revalidate' |
Xem bảng trên |
maxAge |
24 giờ | Thời hạn (ms) khi server không gửi |
maxStale |
7 ngày | stale-while-revalidate còn được hiện ảnh cũ bao lâu sau khi hết hạn, trong lúc chờ ảnh mới |
respectHttpHeaders |
true |
Dùng Cache-Control / Expires và tuân theo no-store |
headers |
Header cho request, ví dụ Authorization |
|
getCacheKey(url) |
URL | Cho URL ký (signed URL) có query đổi mỗi lần: (url) => url.split('?')[0] |
Truyền imageCache={false} để tải thẳng từ mạng.
Thứ tự tải và tải trước
Phần tiêu đề “Thứ tự tải và tải trước”Mọi lượt tải đi qua một hàng đợi, giới hạn số request song song (mặc định 4), với ba mức ưu tiên:
| Mức ưu tiên | Dùng cho |
|---|---|
high |
Ảnh của trang đang xem |
normal |
Các trang kế bên (cách một trang) |
low |
Các trang xa hơn trong cửa sổ render, prefetch, revalidate ở nền |
Khi người dùng vuốt, ảnh của trang mới được đẩy lên đầu hàng đợi, nên vuốt nhanh không phải chờ ảnh của các trang đã đi qua.
Ngoài cửa sổ render (windowSize), carousel tải trước ảnh của prefetch trang nữa mỗi bên (mặc định 1) mà không render, chọn đúng biến thể mà trang đó sẽ chọn khi mount. prefetch={0} để tắt.
Để tải ảnh trước khi carousel tồn tại (màn hình tiếp theo, một item trong danh sách sắp hiện ra), dùng hook hoặc hàm:
import { imageTargetFor, usePrefetchImages, imageCache } from 'expo-morph-carousel';
// Ở màn hình trước: dựng đúng các URL mà carousel sẽ yêu cầuconst target = imageTargetFor({ width: screenWidth - 32, height: 240 }, PixelRatio.get(), 'cover');const { loaded, total, failed, done } = usePrefetchImages( products.map((p) => cdnUrl(p.image, target.width)), { priority: 'low' }, // mặc định; `enabled: false` để chờ);
// Hoặc gọi trực tiếp, ví dụ sau khi API danh sách trả vềawait imageCache.prefetch(urls, cacheOptions, 'low');imageTargetFor chính là hàm carousel dùng để tạo target cho getImage, nên URL tải trước trùng với URL carousel sẽ yêu cầu.
Giới hạn
Phần tiêu đề “Giới hạn”| Cấu hình | Mặc định | |
|---|---|---|
maxSize |
100 MB | Dung lượng trên đĩa. File ít dùng nhất bị xoá trước |
maxEntries |
500 | Số file trên đĩa |
maxConcurrent |
4 | Số lượt tải song song; phần còn lại chờ theo thứ tự ưu tiên |
decodedImages |
24 | Số ảnh đã decode giữ trong bộ nhớ cho hiệu ứng liquid. Mỗi ảnh tốn rộng × cao × 4 byte (ảnh 1080×810 ≈ 3,5 MB), nên 24 ảnh như vậy ≈ 84 MB. Hạ xuống nếu dùng ảnh lớn trên máy ít RAM |
decodedBytes |
96 MB | Ngân sách bộ nhớ cho các ảnh đã decode đó; ảnh lâu không dùng nhất bị bỏ trước khi chạm một trong hai giới hạn |
imageCache.configure({ maxSize: 50 * 1024 * 1024, maxEntries: 300, maxConcurrent: 6, decodedImages: 12 });imageCache.getConfig(); // giá trị hiện tạiconfigure có hiệu lực ngay; hạ maxSize hoặc maxEntries sẽ xoá bớt ngay. Nên gọi một lần lúc khởi động (ví dụ trong root layout).
Xem và xoá cache
Phần tiêu đề “Xem và xoá cache”imageCache.getEntry(url); // { fetchedAt, expiresAt, etag, size, … }imageCache.stats(); // { hits, misses, revalidations, notModified, updates, errors, entries, size, active, queued }const stats = useImageCacheStats(); // như trên, cập nhật trực tiếp, cho bảng debugawait imageCache.remove(url);await imageCache.clear(); // ví dụ khi đăng xuấtFile được lưu trong <thư mục cache>/expo-morph-carousel/ trên iOS và Android (hệ điều hành có thể xoá khi thiếu dung lượng) và trong Cache Storage trên web. Ảnh đã decode cũng được giữ trong bộ nhớ (24 ảnh gần nhất), nên vuốt qua lại không phải decode lại.
Để thử, app ví dụ có một server ảnh local gửi ETag và Cache-Control, và có thể đổi ảnh:
npm run image-server --workspace example # http://localhost:8090, max-age 30 giâyadb reverse tcp:8090 tcp:8090 # Android emulatorMở “Remote images” trong app ví dụ. Bảng thông tin hiện thời điểm tải ảnh hiện tại, ảnh còn hạn bao lâu, và các bộ đếm của cache; nút “Swap images on server” đổi nội dung mà mọi URL trả về.
Mã nguồn của demo
Phần tiêu đề “Mã nguồn của demo”import Constants from 'expo-constants';import { imageCache, MorphCarousel, type CacheStrategy, type ImageCacheOptions, type MorphCarouselRef, useImageCacheStats, WIDTH_STEPS,} from 'expo-morph-carousel';import { useEffect, useMemo, useRef, useState } from 'react';import { PixelRatio, Platform, Pressable, ScrollView, StyleSheet, Switch, Text, useWindowDimensions, View,} from 'react-native';
import { heightFor, photos, REMOTE_MEDIA_HEIGHT, REMOTE_SIDE_MARGIN, unsplashUrl } from '../data/products';import { column } from '../data/layout';
/** * Remote images through the carousel's disk cache. * * "Local server" talks to example/scripts/image-server.mjs, which sends ETag * and Cache-Control headers and can swap its images, so every cache path can * be watched: a fresh hit (no request), a 304 revalidation after expiry, and a * new image replacing a stale one after "Swap images on server". */
type Source = 'local' | 'unsplash';
/** Host of the computer running Metro, which also runs the image server. */function serverHost() { if (Platform.OS === 'web') return typeof location === 'undefined' ? 'localhost' : location.hostname; const hostUri = Constants.expoConfig?.hostUri ?? 'localhost:8081'; return hostUri.split(':')[0];}const SERVER = `http://${serverHost()}:8090`;
const localItems = [0, 1, 2, 3, 4].map((n) => ({ id: `local-${n}`, title: `Image ${n + 1}`, uri: `${SERVER}/img/${n}.png`, color: ['#6a4fd8', '#f0a020', '#20a890', '#3478f6', '#eb405a'][n],}));
type Item = { id: string; title: string; uri: string; color: string; unsplash?: string };
const STRATEGIES: CacheStrategy[] = ['stale-while-revalidate', 'cache-first', 'network-first'];const AGES: { label: string; ms: number }[] = [ { label: '10 s', ms: 10_000 }, { label: '1 min', ms: 60_000 }, { label: '1 day', ms: 86_400_000 },];
export default function RemoteScreen() { const [source, setSource] = useState<Source>('local'); const [strategy, setStrategy] = useState<CacheStrategy>('stale-while-revalidate'); const [maxAge, setMaxAge] = useState(AGES[0].ms); const [serverHeaders, setServerHeaders] = useState(true); const [enabled, setEnabled] = useState(true); const [tapImage, setTapImage] = useState(true); const [keepCorners, setKeepCorners] = useState(true); const [index, setIndex] = useState(0); const [note, setNote] = useState(''); const carousel = useRef<MorphCarouselRef>(null);
const items: Item[] = source === 'local' ? localItems : photos.map((p) => ({ id: p.id, title: p.title, uri: p.uri, color: p.color, unsplash: p.id })); const screen = useWindowDimensions();
// Stable options object: the carousel memoizes on identity. const cache = useMemo<ImageCacheOptions | false>( () => (enabled ? { strategy, maxAge, respectHttpHeaders: serverHeaders } : false), [enabled, strategy, maxAge, serverHeaders], );
const stats = useImageCacheStats(); const config = imageCache.getConfig(); const now = useNow(); const current = items[index]; // Unsplash items exist in several sizes (one URL per target width); show // every cached variant, newest first, to see the upgrade after a rotation. const variants = current?.unsplash ? WIDTH_STEPS.map((w) => ({ w, e: imageCache.getEntry(unsplashUrl(current.unsplash!, w, heightFor(w))) })) .filter((v) => v.e) .sort((a, b) => b.e!.fetchedAt - a.e!.fetchedAt) : []; const entry = current?.unsplash ? variants[0]?.e : current ? imageCache.getEntry(current.uri) : undefined;
const call = async (path: string) => { try { const res = await fetch(`${SERVER}${path}`); setNote((await res.text()).trim()); } catch { setNote(`Server not reachable at ${SERVER}. Run: npm run image-server --workspace example`); } };
return ( <ScrollView contentInsetAdjustmentBehavior="automatic" contentContainerStyle={[styles.screen, column]}> <MorphCarousel key={source} ref={carousel} testID="remote-carousel" data={items} keyExtractor={(p) => p.id} // Unsplash: ask the CDN for exactly the size the media area needs // (target is in physical pixels, rounded to a few widths). getImage={(p, _i, t) => ({ uri: p.unsplash ? unsplashUrl(p.unsplash, t.width, heightFor(t.width)) : p.uri, })} getPlaceholderColor={(p) => p.color} getAccessibilityLabel={(p) => p.title} accessibilityLabel="Remote images" imageCache={cache} mediaFit={source === 'local' ? 'contain' : 'cover'} mediaPadding={source === 'local' ? 24 : 0} mediaHeight={REMOTE_MEDIA_HEIGHT} // Photos: keep the rectangle sharp while the content melts (no rounded, // eaten-in corners). Shapes on a transparent background melt whole. liquid={ source === 'local' ? { preserveShape: keepCorners } : { blur: 36, threshold: 0.35, preserveShape: keepCorners } } // Tap the image: left 30% back, the rest forward. Taps on the text // below do nothing. tapToNavigate={tapImage ? { area: 'media' } : false} loop onIndexChange={setIndex} style={styles.card} renderItem={({ item }) => ( <View style={styles.page}> <Text style={styles.title}>{item.title}</Text> <Text style={styles.meta} numberOfLines={1}> {item.uri.replace(/^https?:\/\//, '')} </Text> </View> )} />
<View style={styles.panel}> <Text style={styles.panelTitle}>Current image</Text> <Text style={styles.mono}> {entry ? `fetched ${ago(now - entry.fetchedAt)} ago · ${ entry.expiresAt > now ? `fresh for ${ago(entry.expiresAt - now)}` : `stale ${ago(now - entry.expiresAt)}` }${entry.etag ? ` · ETag ${entry.etag}` : ''}` : enabled ? 'not cached yet' : 'cache off'} {variants.length > 0 && `\nvariants: ${variants.map((v) => `${v.w}w`).join(', ')} (newest first)`} </Text> <Text style={styles.panelTitle}>Screen</Text> <Text style={styles.mono}> {Math.round(screen.width)}×{Math.round(screen.height)} dp @{PixelRatio.get()}x ·{' '} {screen.width > screen.height ? 'landscape' : 'portrait'} </Text> <Text style={styles.panelTitle}>Cache</Text> <Text style={styles.mono}> {imageCache.isAvailable() ? '' : 'no store on this platform · '} {stats.entries} files · {(stats.size / 1024).toFixed(0)} KB{'\n'} hits {stats.hits} · downloads {stats.misses} · revalidations {stats.revalidations} {'\n'}304 {stats.notModified} · updated {stats.updates} · errors {stats.errors} {'\n'}downloading {stats.active} · queued {stats.queued} {'\n'}limits {Math.round(config.maxSize / 1048576)} MB · {config.maxEntries} files ·{' '} {config.maxConcurrent} parallel · {config.decodedImages} decoded ·{' '} {Math.round(config.decodedBytes / 1048576)} MB </Text> </View>
<Section label="Source"> <Chips values={['local', 'unsplash'] as Source[]} labels={{ local: 'Local server', unsplash: 'Unsplash' }} value={source} onChange={setSource} /> </Section> <Section label="Strategy"> <Chips values={STRATEGIES} value={strategy} onChange={setStrategy} /> </Section> <Section label={serverHeaders ? 'maxAge (used when the server sends no Cache-Control)' : 'maxAge'}> <Chips values={AGES.map((a) => a.ms)} labels={Object.fromEntries(AGES.map((a) => [a.ms, a.label]))} value={maxAge} onChange={setMaxAge} /> </Section>
<View style={styles.toggles}> <Toggle label="Tap the image to change page" value={tapImage} onChange={setTapImage} /> <Toggle label="Keep image corners while morphing" value={keepCorners} onChange={setKeepCorners} /> <Toggle label="Cache enabled" value={enabled} onChange={setEnabled} /> <Toggle label="Use server Cache-Control / ETag" value={serverHeaders} onChange={setServerHeaders} /> </View>
<View style={styles.buttons}> <Button label="Prefetch all" onPress={() => void imageCache.prefetch( items.map((i) => i.uri), cache || undefined, ) } /> <Button label="Clear cache" onPress={() => void imageCache.clear()} /> {source === 'local' && ( <> <Button label="Swap images on server" onPress={() => void call('/swap')} /> <Button label="Server max-age 10 s" onPress={() => void call('/config?maxAge=10')} /> <Button label="Server max-age 1 h" onPress={() => void call('/config?maxAge=3600')} /> </> )} </View> {!!note && <Text style={styles.note}>{note}</Text>} {source === 'local' && ( <Text style={styles.note}> Server: {SERVER}. Start it with `npm run image-server --workspace example`; on an Android emulator also run `adb reverse tcp:8090 tcp:8090`. </Text> )} {source === 'unsplash' && ( <Text style={styles.note}> Photos from Unsplash (unsplash.com, Unsplash License). The CDN sends Cache-Control max-age of one year: with the “Use server Cache-Control” switch on, the cache keeps them that long; turn it off to use maxAge. </Text> )} </ScrollView> );}
function useNow() { const [now, setNow] = useState(() => Date.now()); useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []); return now;}
function ago(ms: number) { const s = Math.round(ms / 1000); if (s < 90) return `${s} s`; if (s < 5400) return `${Math.round(s / 60)} min`; return `${Math.round(s / 3600)} h`;}
function Section({ label, children }: { label: string; children: React.ReactNode }) { return ( <View style={styles.section}> <Text style={styles.label}>{label}</Text> {children} </View> );}
function Chips<V extends string | number>({ values, labels, value, onChange,}: { values: V[]; labels?: Record<string, string>; value: V; onChange: (v: V) => void;}) { return ( <View style={styles.chips}> {values.map((v) => ( <Pressable key={String(v)} onPress={() => onChange(v)} style={[styles.chip, v === value && styles.chipOn]} > <Text style={[styles.chipText, v === value && styles.chipTextOn]}> {labels?.[String(v)] ?? String(v)} </Text> </Pressable> ))} </View> );}
function Toggle({ label, value, onChange,}: { label: string; value: boolean; onChange: (v: boolean) => void;}) { return ( <View style={styles.toggle}> <Text style={styles.toggleText}>{label}</Text> <Switch value={value} onValueChange={onChange} accessibilityLabel={label} /> </View> );}
function Button({ label, onPress }: { label: string; onPress: () => void }) { return ( <Pressable style={styles.button} onPress={onPress} accessibilityRole="button"> <Text style={styles.buttonText}>{label}</Text> </Pressable> );}
const styles = StyleSheet.create({ screen: { padding: REMOTE_SIDE_MARGIN, gap: 12 }, card: { height: 380, borderRadius: 24, backgroundColor: '#fff' }, page: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 6, paddingHorizontal: 16 }, title: { fontSize: 22, fontWeight: '700', color: '#1c1c1e' }, meta: { fontSize: 12, color: '#6e6e73' }, panel: { borderRadius: 16, backgroundColor: '#1c1c1e', padding: 14, gap: 4 }, panelTitle: { fontSize: 12, fontWeight: '600', color: '#8e8e93', textTransform: 'uppercase' }, mono: { fontSize: 13, color: '#f2f2f7', fontFamily: Platform.select({ ios: 'Menlo', default: 'monospace' }), }, section: { gap: 6 }, label: { fontSize: 13, color: '#6e6e73' }, chips: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, chip: { paddingHorizontal: 12, paddingVertical: 8, borderRadius: 999, backgroundColor: '#fff' }, chipOn: { backgroundColor: '#5b4bd6' }, chipText: { fontSize: 14, color: '#1c1c1e' }, chipTextOn: { color: '#fff', fontWeight: '600' }, toggles: { borderRadius: 16, backgroundColor: '#fff', paddingHorizontal: 14 }, toggle: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 8 }, toggleText: { fontSize: 15, color: '#1c1c1e', flexShrink: 1 }, buttons: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, button: { paddingHorizontal: 14, paddingVertical: 10, borderRadius: 12, backgroundColor: '#e5e5ea' }, buttonText: { fontSize: 14, fontWeight: '600', color: '#1c1c1e' }, note: { fontSize: 12, color: '#6e6e73' },});import type { ImageSourcePropType } from 'react-native';
export type Product = { id: string; title: string; description: string; image: ImageSourcePropType; /** Shown as a blob while the image loads, and used for accents. */ color: string;};
export const products: Product[] = [ { id: 'orb', title: 'Meet Orb', description: 'A glossy sphere with a soft highlight. Swipe to watch it melt into the next shape.', image: require('../assets/shapes/orb.png'), color: '#6a4fd8', }, { id: 'tile', title: 'Explore Tile', description: 'A rounded square with a warm gradient, the kind of shape app icons are made of.', image: require('../assets/shapes/tile.png'), color: '#f0a020', }, { id: 'ring', title: 'Discover Ring', description: 'A torus with a hole in the middle. The liquid effect fills it in, then opens it again.', image: require('../assets/shapes/ring.png'), color: '#20a890', }, { id: 'pill', title: 'Experience Pill', description: 'A tall capsule. Tall and wide shapes stretch the blob in between.', image: require('../assets/shapes/pill.png'), color: '#3478f6', }, { id: 'heart', title: 'Love Heart', description: 'Two circles and a point. Watch the point grow out of the blob.', image: require('../assets/shapes/heart.png'), color: '#eb405a', },];
/** * Devices for the product showcase: original drawings (example/scripts/ * make-devices.mjs), cropped to their outline. Dark bodies and glowing * screens of different colors make the liquid morph easy to follow. */export const devices: Product[] = [ { id: 'watch', title: 'Meet Orbit Watch', description: 'A rounded case on a woven band. Swipe and it melts into the next device.', image: require('../assets/devices/watch.png'), color: '#6a4fd8', }, { id: 'phone', title: 'Nova Phone', description: 'Edge-to-edge glass with an ocean wallpaper, tall and narrow.', image: require('../assets/devices/phone.png'), color: '#0b7fc4', }, { id: 'laptop', title: 'Explore Slate Laptop', description: 'A wide screen on a thin base: the blob stretches from tall to wide.', image: require('../assets/devices/laptop.png'), color: '#c2368f', }, { id: 'mini', title: 'Cube Mini', description: 'A small silver box with no screen at all, seen from above.', image: require('../assets/devices/mini.png'), color: '#8f959d', }, { id: 'desktop', title: 'Vista Desktop', description: 'A large display with a sunset on a round foot.', image: require('../assets/devices/desktop.png'), color: '#e0566b', },];
/** * Product photos for the showcase, cut out of their studio background and * cropped to the product. Tall and wide products alternate, so the liquid * blob visibly stretches from one outline to the next. */export const showcase: Product[] = [ { id: 'watch-plum', title: 'Watch Series 12', description: 'A plum sport band and an always-on display. Swipe and it melts into the next product.', image: require('../assets/showcase/watch-plum.png'), color: '#5c1f33', }, { id: 'macbook', title: 'MacBook Pro 14', description: 'From a tall watch to a wide laptop: the blob stretches sideways on the way.', image: require('../assets/showcase/macbook.png'), color: '#2c2c30', }, { id: 'iphone-red', title: 'iPhone 18 Pro', description: 'Tall and narrow again, in a deep red finish with a three-camera plateau.', image: require('../assets/showcase/iphone-red.png'), color: '#6e2334', }, { id: 'mini-front', title: 'Mac mini', description: 'The widest of all: a low silver box, seen from the front.', image: require('../assets/showcase/mini-front.png'), color: '#6b7076', }, { id: 'iphone-white', title: 'iPhone 18 Pro, white', description: 'The back and the side: two outlines the liquid has to join.', image: require('../assets/showcase/iphone-white.png'), color: '#7d7a76', }, { id: 'iphone-duo', title: 'iPhone Duo', description: 'A phone that unfolds into a small laptop, half open.', image: require('../assets/showcase/iphone-duo.png'), color: '#1f2b45', }, { id: 'watch-starlight', title: 'Watch Series 12, starlight', description: 'A light band and a vivid purple face, back to a tall outline.', image: require('../assets/showcase/watch-starlight.png'), color: '#6a3fc8', }, { id: 'mini-top', title: 'Mac mini, from above', description: 'A rounded square to finish: the blob settles into an even shape.', image: require('../assets/showcase/mini-top.png'), color: '#5e6369', },];
/** Media height of the remote screen's carousel; the home screen prefetches for it. */export const REMOTE_MEDIA_HEIGHT = 240;/** Horizontal padding of the remote screen around the carousel. */export const REMOTE_SIDE_MARGIN = 16;
/** Photos are requested at 4:3; the carousel covers its area and crops the rest. */export const heightFor = (width: number) => Math.round((width * 3) / 4);
/** * An Unsplash image URL at a given size. Unsplash serves through imgix, which * resizes on the fly: `w` and `h` in pixels, `fit=crop` fills the box. */export function unsplashUrl(id: string, width: number, height: number) { return `https://images.unsplash.com/photo-${id}?w=${width}&h=${height}&fit=crop&q=80&fm=jpg`;}
/** * Remote photos for the image-loading demo, from Unsplash (free to use under * the Unsplash License, https://unsplash.com/license). `uri` is a fixed 800 px * variant; the remote screen builds the URL per size with `unsplashUrl`. * * Unsplash answers with `Cache-Control: max-age=31536000` (one year), so with * `respectHttpHeaders` on, the cache keeps these for a year. */export const photos = [ { id: '1506905925346-21bda4d32df4', title: 'Sea of clouds', color: '#5b6478' }, { id: '1501785888041-af3ef285b470', title: 'Alpine lake', color: '#2fa7a0' }, { id: '1470071459604-3b5ec3a7fe05', title: 'Misty valley', color: '#6e7a5a' }, { id: '1441974231531-c6227db76b6e', title: 'Forest path', color: '#3e4a2c' }, { id: '1507525428034-b723cf961d3e', title: 'Beach at sunset', color: '#7fc4c8' }, { id: '1500530855697-b586d89ba3ee', title: 'Desert road', color: '#a0553c' }, { id: '1433086966358-54859d0ed716', title: 'Waterfall', color: '#3f6b3a' },].map((p) => ({ ...p, uri: unsplashUrl(p.id, 800, 600),}));Xem trên GitHub: app/remote.tsxXem trên GitHub: data/products.ts