Add post embeds (images and external links)

zio/stable
Paul Frazee 2022-12-14 15:35:15 -06:00
parent 345ec83f26
commit 4966b2152e
30 changed files with 936 additions and 242 deletions

View File

@ -222,6 +222,8 @@ PODS:
- glog - glog
- react-native-cameraroll (5.1.0): - react-native-cameraroll (5.1.0):
- React-Core - React-Core
- react-native-image-resizer (3.0.4):
- React-Core
- react-native-pager-view (6.0.2): - react-native-pager-view (6.0.2):
- React-Core - React-Core
- react-native-safe-area-context (4.4.1): - react-native-safe-area-context (4.4.1):
@ -299,6 +301,8 @@ PODS:
- React-jsi (= 0.68.2) - React-jsi (= 0.68.2)
- React-logger (= 0.68.2) - React-logger (= 0.68.2)
- React-perflogger (= 0.68.2) - React-perflogger (= 0.68.2)
- rn-fetch-blob (0.12.0):
- React-Core
- RNCAsyncStorage (1.17.10): - RNCAsyncStorage (1.17.10):
- React-Core - React-Core
- RNCClipboard (1.11.1): - RNCClipboard (1.11.1):
@ -374,6 +378,7 @@ DEPENDENCIES:
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`) - React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
- React-logger (from `../node_modules/react-native/ReactCommon/logger`) - React-logger (from `../node_modules/react-native/ReactCommon/logger`)
- "react-native-cameraroll (from `../node_modules/@react-native-camera-roll/camera-roll`)" - "react-native-cameraroll (from `../node_modules/@react-native-camera-roll/camera-roll`)"
- "react-native-image-resizer (from `../node_modules/@bam.tech/react-native-image-resizer`)"
- react-native-pager-view (from `../node_modules/react-native-pager-view`) - react-native-pager-view (from `../node_modules/react-native-pager-view`)
- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`) - react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)
- react-native-splash-screen (from `../node_modules/react-native-splash-screen`) - react-native-splash-screen (from `../node_modules/react-native-splash-screen`)
@ -390,6 +395,7 @@ DEPENDENCIES:
- React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`) - React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`)
- React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`) - React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`)
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`) - ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- rn-fetch-blob (from `../node_modules/rn-fetch-blob`)
- "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)" - "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)"
- "RNCClipboard (from `../node_modules/@react-native-clipboard/clipboard`)" - "RNCClipboard (from `../node_modules/@react-native-clipboard/clipboard`)"
- RNGestureHandler (from `../node_modules/react-native-gesture-handler`) - RNGestureHandler (from `../node_modules/react-native-gesture-handler`)
@ -446,6 +452,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon/logger" :path: "../node_modules/react-native/ReactCommon/logger"
react-native-cameraroll: react-native-cameraroll:
:path: "../node_modules/@react-native-camera-roll/camera-roll" :path: "../node_modules/@react-native-camera-roll/camera-roll"
react-native-image-resizer:
:path: "../node_modules/@bam.tech/react-native-image-resizer"
react-native-pager-view: react-native-pager-view:
:path: "../node_modules/react-native-pager-view" :path: "../node_modules/react-native-pager-view"
react-native-safe-area-context: react-native-safe-area-context:
@ -478,6 +486,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon/runtimeexecutor" :path: "../node_modules/react-native/ReactCommon/runtimeexecutor"
ReactCommon: ReactCommon:
:path: "../node_modules/react-native/ReactCommon" :path: "../node_modules/react-native/ReactCommon"
rn-fetch-blob:
:path: "../node_modules/rn-fetch-blob"
RNCAsyncStorage: RNCAsyncStorage:
:path: "../node_modules/@react-native-async-storage/async-storage" :path: "../node_modules/@react-native-async-storage/async-storage"
RNCClipboard: RNCClipboard:
@ -519,6 +529,7 @@ SPEC CHECKSUMS:
React-jsinspector: c5989c77cb89ae6a69561095a61cce56a44ae8e8 React-jsinspector: c5989c77cb89ae6a69561095a61cce56a44ae8e8
React-logger: a0833912d93b36b791b7a521672d8ee89107aff1 React-logger: a0833912d93b36b791b7a521672d8ee89107aff1
react-native-cameraroll: a40b082318eb1ecd0336a2f29d9f74b7f2c8cae8 react-native-cameraroll: a40b082318eb1ecd0336a2f29d9f74b7f2c8cae8
react-native-image-resizer: 794abf75ec13ed1f0dbb1f134e27504ea65e9e66
react-native-pager-view: 592421df0259bf7a7a4fe85b74c24f3f39905605 react-native-pager-view: 592421df0259bf7a7a4fe85b74c24f3f39905605
react-native-safe-area-context: 99b24a0c5acd0d5dcac2b1a7f18c49ea317be99a react-native-safe-area-context: 99b24a0c5acd0d5dcac2b1a7f18c49ea317be99a
react-native-splash-screen: 4312f786b13a81b5169ef346d76d33bc0c6dc457 react-native-splash-screen: 4312f786b13a81b5169ef346d76d33bc0c6dc457
@ -535,6 +546,7 @@ SPEC CHECKSUMS:
React-RCTVibration: 79040b92bfa9c3c2d2cb4f57e981164ec7ab9374 React-RCTVibration: 79040b92bfa9c3c2d2cb4f57e981164ec7ab9374
React-runtimeexecutor: b960b687d2dfef0d3761fbb187e01812ebab8b23 React-runtimeexecutor: b960b687d2dfef0d3761fbb187e01812ebab8b23
ReactCommon: 095366164a276d91ea704ce53cb03825c487a3f2 ReactCommon: 095366164a276d91ea704ce53cb03825c487a3f2
rn-fetch-blob: f065bb7ab7fb48dd002629f8bdcb0336602d3cba
RNCAsyncStorage: 0c357f3156fcb16c8589ede67cc036330b6698ca RNCAsyncStorage: 0c357f3156fcb16c8589ede67cc036330b6698ca
RNCClipboard: 2834e1c4af68697089cdd455ee4a4cdd198fa7dd RNCClipboard: 2834e1c4af68697089cdd455ee4a4cdd198fa7dd
RNGestureHandler: 28ad20bf02257791f7f137b31beef34b9549f54b RNGestureHandler: 28ad20bf02257791f7f137b31beef34b9549f54b

View File

@ -12,6 +12,7 @@
"lint": "eslint . --ext .js,.jsx,.ts,.tsx" "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
}, },
"dependencies": { "dependencies": {
"@bam.tech/react-native-image-resizer": "^3.0.4",
"@fortawesome/fontawesome-svg-core": "^6.1.1", "@fortawesome/fontawesome-svg-core": "^6.1.1",
"@fortawesome/free-regular-svg-icons": "^6.1.1", "@fortawesome/free-regular-svg-icons": "^6.1.1",
"@fortawesome/free-solid-svg-icons": "^6.1.1", "@fortawesome/free-solid-svg-icons": "^6.1.1",
@ -51,6 +52,7 @@
"react-native-url-polyfill": "^1.3.0", "react-native-url-polyfill": "^1.3.0",
"react-native-version-number": "^0.3.6", "react-native-version-number": "^0.3.6",
"react-native-web": "^0.17.7", "react-native-web": "^0.17.7",
"rn-fetch-blob": "^0.12.0",
"tlds": "^1.234.0" "tlds": "^1.234.0"
}, },
"devDependencies": { "devDependencies": {

View File

@ -1,3 +1,2 @@
export const LOGIN_INCLUDE_DEV_SERVERS = true export const LOGIN_INCLUDE_DEV_SERVERS = true
export const TABS_ENABLED = false export const TABS_ENABLED = false
export const IMAGES_ENABLED = false

View File

@ -0,0 +1,61 @@
import RNFetchBlob from 'rn-fetch-blob'
import ImageResizer from '@bam.tech/react-native-image-resizer'
interface DownloadAndResizeOpts {
uri: string
width: number
height: number
mode: 'contain' | 'cover' | 'stretch'
timeout: number
}
export async function downloadAndResize(opts: DownloadAndResizeOpts) {
let appendExt
try {
const urip = new URL(opts.uri)
const ext = urip.pathname.split('.').pop()
if (ext === 'jpg' || ext === 'jpeg') {
appendExt = 'jpeg'
} else if (ext === 'png') {
appendExt = 'png'
} else {
return
}
} catch (e: any) {
console.error('Invalid URI', opts.uri, e)
return
}
let downloadRes
try {
const downloadResPromise = RNFetchBlob.config({
fileCache: true,
appendExt,
}).fetch('GET', opts.uri)
const to1 = setTimeout(() => downloadResPromise.cancel(), opts.timeout)
downloadRes = await downloadResPromise
clearTimeout(to1)
let localUri = downloadRes.path()
if (!localUri.startsWith('file://')) {
localUri = `file://${localUri}`
}
const resizeRes = await ImageResizer.createResizedImage(
localUri,
opts.width,
opts.height,
'JPEG',
0.7,
undefined,
undefined,
undefined,
{mode: opts.mode},
)
return resizeRes
} finally {
if (downloadRes) {
downloadRes.flush()
}
}
}

View File

@ -22,9 +22,13 @@ export interface LinkMeta {
url: string url: string
title?: string title?: string
description?: string description?: string
image?: string
} }
export async function getLinkMeta(url: string): Promise<LinkMeta> { export async function getLinkMeta(
url: string,
timeout = 5e3,
): Promise<LinkMeta> {
if (isBskyAppUrl(url)) { if (isBskyAppUrl(url)) {
// TODO this could be better // TODO this could be better
url = convertBskyAppUrlIfNeeded(url) url = convertBskyAppUrlIfNeeded(url)
@ -57,14 +61,20 @@ export async function getLinkMeta(url: string): Promise<LinkMeta> {
} }
try { try {
const httpRes = await fetch(url) const controller = new AbortController()
const to = setTimeout(() => controller.abort(), timeout || 5e3)
const httpRes = await fetch(url, {
headers: {accept: 'text/html'},
signal: controller.signal,
})
const httpResBody = await httpRes.text() const httpResBody = await httpRes.text()
clearTimeout(to)
const httpResMeta = extractHtmlMeta(httpResBody) const httpResMeta = extractHtmlMeta(httpResBody)
meta.title = httpResMeta.title ? he.decode(httpResMeta.title) : undefined meta.title = httpResMeta.title ? he.decode(httpResMeta.title) : undefined
meta.description = httpResMeta.description meta.description = httpResMeta.description
? he.decode(httpResMeta.description) ? he.decode(httpResMeta.description)
: undefined : undefined
// TODO meta.image = httpResMeta.image meta.image = httpResMeta.image
} catch (e) { } catch (e) {
// failed // failed
console.log(e) console.log(e)

View File

@ -5,12 +5,15 @@
// import {ReactNativeStore} from './auth' // import {ReactNativeStore} from './auth'
import {sessionClient as AtpApi} from '../../third-party/api' import {sessionClient as AtpApi} from '../../third-party/api'
import * as Profile from '../../third-party/api/src/client/types/app/bsky/actor/profile'
import * as Post from '../../third-party/api/src/client/types/app/bsky/feed/post'
import {AtUri} from '../../third-party/uri' import {AtUri} from '../../third-party/uri'
import {APP_BSKY_GRAPH} from '../../third-party/api' import {APP_BSKY_GRAPH} from '../../third-party/api'
import * as AppBskyEmbedImages from '../../third-party/api/src/client/types/app/bsky/embed/images'
import * as AppBskyEmbedExternal from '../../third-party/api/src/client/types/app/bsky/embed/External'
import {RootStoreModel} from '../models/root-store' import {RootStoreModel} from '../models/root-store'
import {extractEntities} from '../../lib/strings' import {extractEntities} from '../../lib/strings'
import {isNetworkError} from '../../lib/errors'
import {downloadAndResize} from '../../lib/download'
import {getLikelyType, LikelyType, getLinkMeta} from '../../lib/link-meta'
const TIMEOUT = 10e3 // 10s const TIMEOUT = 10e3 // 10s
@ -21,12 +24,112 @@ export function doPolyfill() {
export async function post( export async function post(
store: RootStoreModel, store: RootStoreModel,
text: string, text: string,
replyTo?: Post.ReplyRef, replyTo?: string,
images?: string[],
knownHandles?: Set<string>, knownHandles?: Set<string>,
onStateChange?: (state: string) => void,
) { ) {
let embed: AppBskyEmbedImages.Main | AppBskyEmbedExternal.Main | undefined
let reply let reply
onStateChange?.('Processing...')
const entities = extractEntities(text, knownHandles)
if (entities) {
for (const ent of entities) {
if (ent.type === 'mention') {
const prof = await store.profiles.getProfile(ent.value)
ent.value = prof.data.did
}
}
}
if (images?.length) {
embed = {
$type: 'app.bsky.embed.images',
images: [],
} as AppBskyEmbedImages.Main
let i = 1
for (const image of images) {
onStateChange?.(`Uploading image #${i++}...`)
const res = await store.api.com.atproto.blob.upload(
image, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts
{encoding: 'image/jpeg'},
)
embed.images.push({
image: {
cid: res.data.cid,
mimeType: 'image/jpeg',
},
alt: '', // TODO supply alt text
})
}
}
if (!embed && entities) {
const link = entities.find(
ent =>
ent.type === 'link' &&
getLikelyType(ent.value || '') === LikelyType.HTML,
)
if (link) {
try {
onStateChange?.(`Fetching link metadata...`)
let thumb
const linkMeta = await getLinkMeta(link.value)
if (linkMeta.image) {
onStateChange?.(`Downloading link thumbnail...`)
const thumbLocal = await downloadAndResize({
uri: linkMeta.image,
width: 250,
height: 250,
mode: 'contain',
timeout: 15e3,
}).catch(() => undefined)
if (thumbLocal) {
onStateChange?.(`Uploading link thumbnail...`)
let encoding
if (thumbLocal.uri.endsWith('.png')) {
encoding = 'image/png'
} else if (
thumbLocal.uri.endsWith('.jpeg') ||
thumbLocal.uri.endsWith('.jpg')
) {
encoding = 'image/jpeg'
} else {
console.error(
'Unexpected image format for thumbnail, skipping',
thumbLocal.uri,
)
}
if (encoding) {
const thumbUploadRes = await store.api.com.atproto.blob.upload(
thumbLocal.uri, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts
{encoding},
)
thumb = {
cid: thumbUploadRes.data.cid,
mimeType: encoding,
}
}
}
}
embed = {
$type: 'app.bsky.embed.external',
external: {
uri: link.value,
title: linkMeta.title || linkMeta.url,
description: linkMeta.description || '',
thumb,
},
} as AppBskyEmbedExternal.Main
} catch (e: any) {
console.error('Failed to fetch link meta', link.value, e)
}
}
}
if (replyTo) { if (replyTo) {
const replyToUrip = new AtUri(replyTo.uri) const replyToUrip = new AtUri(replyTo)
const parentPost = await store.api.app.bsky.feed.post.get({ const parentPost = await store.api.app.bsky.feed.post.get({
user: replyToUrip.host, user: replyToUrip.host,
rkey: replyToUrip.rkey, rkey: replyToUrip.rkey,
@ -42,24 +145,29 @@ export async function post(
} }
} }
} }
const entities = extractEntities(text, knownHandles)
if (entities) { try {
for (const ent of entities) { onStateChange?.(`Posting...`)
if (ent.type === 'mention') {
const prof = await store.profiles.getProfile(ent.value)
ent.value = prof.data.did
}
}
}
return await store.api.app.bsky.feed.post.create( return await store.api.app.bsky.feed.post.create(
{did: store.me.did || ''}, {did: store.me.did || ''},
{ {
text, text,
reply, reply,
embed,
entities, entities,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
}, },
) )
} catch (e: any) {
console.error(`Failed to create post: ${e.toString()}`)
if (isNetworkError(e)) {
throw new Error(
'Post failed to upload. Please check your Internet connection and try again.',
)
} else {
throw e
}
}
} }
export async function repost(store: RootStoreModel, uri: string, cid: string) { export async function repost(store: RootStoreModel, uri: string, cid: string) {

View File

@ -49,6 +49,7 @@ export class FeedItemModel implements GetTimeline.FeedItem {
repostedBy?: ActorRef.WithInfo repostedBy?: ActorRef.WithInfo
trendedBy?: ActorRef.WithInfo trendedBy?: ActorRef.WithInfo
record: Record<string, unknown> = {} record: Record<string, unknown> = {}
embed?: GetTimeline.FeedItem['embed']
replyCount: number = 0 replyCount: number = 0
repostCount: number = 0 repostCount: number = 0
upvoteCount: number = 0 upvoteCount: number = 0
@ -78,6 +79,7 @@ export class FeedItemModel implements GetTimeline.FeedItem {
this.repostedBy = v.repostedBy this.repostedBy = v.repostedBy
this.trendedBy = v.trendedBy this.trendedBy = v.trendedBy
this.record = v.record this.record = v.record
this.embed = v.embed
this.replyCount = v.replyCount this.replyCount = v.replyCount
this.repostCount = v.repostCount this.repostCount = v.repostCount
this.upvoteCount = v.upvoteCount this.upvoteCount = v.upvoteCount

View File

@ -1,6 +1,5 @@
import {makeAutoObservable, runInAction} from 'mobx' import {makeAutoObservable, runInAction} from 'mobx'
import {AppBskyFeedGetPostThread as GetPostThread} from '../../third-party/api' import {AppBskyFeedGetPostThread as GetPostThread} from '../../third-party/api'
import * as Embed from '../../third-party/api/src/client/types/app/bsky/feed/embed'
import * as ActorRef from '../../third-party/api/src/client/types/app/bsky/actor/ref' import * as ActorRef from '../../third-party/api/src/client/types/app/bsky/actor/ref'
import {AtUri} from '../../third-party/uri' import {AtUri} from '../../third-party/uri'
import _omit from 'lodash.omit' import _omit from 'lodash.omit'
@ -60,7 +59,7 @@ export class PostThreadViewPostModel implements GetPostThread.Post {
declaration: {cid: '', actorType: ''}, declaration: {cid: '', actorType: ''},
} }
record: Record<string, unknown> = {} record: Record<string, unknown> = {}
embed?: Embed.Main = undefined embed?: GetPostThread.Post['embed'] = undefined
parent?: PostThreadViewPostModel parent?: PostThreadViewPostModel
replyCount: number = 0 replyCount: number = 0
replies?: PostThreadViewPostModel[] replies?: PostThreadViewPostModel[]

View File

@ -58,6 +58,13 @@ export class ProfileImageLightbox {
} }
} }
export class ImageLightbox {
name = 'image'
constructor(public uri: string) {
makeAutoObservable(this)
}
}
export interface ComposerOptsPostRef { export interface ComposerOptsPostRef {
uri: string uri: string
cid: string cid: string
@ -84,7 +91,7 @@ export class ShellUiModel {
| ServerInputModal | ServerInputModal
| undefined | undefined
isLightboxActive = false isLightboxActive = false
activeLightbox: ProfileImageLightbox | undefined activeLightbox: ProfileImageLightbox | ImageLightbox | undefined
isComposerActive = false isComposerActive = false
composerOpts: ComposerOpts | undefined composerOpts: ComposerOpts | undefined
@ -116,7 +123,7 @@ export class ShellUiModel {
this.activeModal = undefined this.activeModal = undefined
} }
openLightbox(lightbox: ProfileImageLightbox) { openLightbox(lightbox: ProfileImageLightbox | ImageLightbox) {
this.isLightboxActive = true this.isLightboxActive = true
this.activeLightbox = lightbox this.activeLightbox = lightbox
} }

View File

@ -38,7 +38,8 @@ __export(src_exports, {
AppBskyActorSearch: () => search_exports, AppBskyActorSearch: () => search_exports,
AppBskyActorSearchTypeahead: () => searchTypeahead_exports, AppBskyActorSearchTypeahead: () => searchTypeahead_exports,
AppBskyActorUpdateProfile: () => updateProfile_exports, AppBskyActorUpdateProfile: () => updateProfile_exports,
AppBskyFeedEmbed: () => embed_exports, AppBskyEmbedExternal: () => external_exports,
AppBskyEmbedImages: () => images_exports,
AppBskyFeedGetAuthorFeed: () => getAuthorFeed_exports, AppBskyFeedGetAuthorFeed: () => getAuthorFeed_exports,
AppBskyFeedGetPostThread: () => getPostThread_exports, AppBskyFeedGetPostThread: () => getPostThread_exports,
AppBskyFeedGetRepostedBy: () => getRepostedBy_exports, AppBskyFeedGetRepostedBy: () => getRepostedBy_exports,
@ -99,6 +100,7 @@ __export(src_exports, {
ComNS: () => ComNS, ComNS: () => ComNS,
ConfirmationRecord: () => ConfirmationRecord, ConfirmationRecord: () => ConfirmationRecord,
DeclarationRecord: () => DeclarationRecord, DeclarationRecord: () => DeclarationRecord,
EmbedNS: () => EmbedNS,
FeedNS: () => FeedNS, FeedNS: () => FeedNS,
FollowRecord: () => FollowRecord, FollowRecord: () => FollowRecord,
GraphNS: () => GraphNS, GraphNS: () => GraphNS,
@ -5621,69 +5623,25 @@ var schemaDict = {
} }
} }
}, },
AppBskyFeedEmbed: { AppBskyEmbedExternal: {
lexicon: 1, lexicon: 1,
id: "app.bsky.feed.embed", id: "app.bsky.embed.external",
description: "Content embedded in other content, such as an image or link embedded in a post.", description: "An representation of some externally linked content, embedded in another form of content",
defs: { defs: {
main: { main: {
type: "object", type: "object",
description: "A list embeds in a post or document.", required: ["external"],
required: ["media"],
properties: { properties: {
items: { external: {
type: "array",
items: {
type: "union",
refs: [
"lex:app.bsky.feed.embed#media",
"lex:app.bsky.feed.embed#record",
"lex:app.bsky.feed.embed#external"
]
}
}
}
},
media: {
type: "object",
required: ["original"],
properties: {
alt: {
type: "string"
},
thumb: {
type: "image"
},
original: {
type: "blob"
}
}
},
record: {
type: "object",
required: ["type", "author", "record"],
properties: {
type: {
type: "string",
const: "record"
},
author: {
type: "ref", type: "ref",
ref: "lex:app.bsky.actor.ref#withInfo" ref: "lex:app.bsky.embed.external#external"
},
record: {
type: "unknown"
} }
} }
}, },
external: { external: {
type: "object", type: "object",
required: ["type", "uri", "title", "description", "imageUri"], required: ["uri", "title", "description"],
properties: { properties: {
type: {
type: "string",
const: "external"
},
uri: { uri: {
type: "string" type: "string"
}, },
@ -5693,7 +5651,105 @@ var schemaDict = {
description: { description: {
type: "string" type: "string"
}, },
imageUri: { thumb: {
type: "image",
accept: ["image/*"],
maxWidth: 250,
maxHeight: 250,
maxSize: 1e5
}
}
},
presented: {
type: "object",
required: ["external"],
properties: {
external: {
type: "ref",
ref: "lex:app.bsky.embed.external#presentedExternal"
}
}
},
presentedExternal: {
type: "object",
required: ["uri", "title", "description"],
properties: {
uri: {
type: "string"
},
title: {
type: "string"
},
description: {
type: "string"
},
thumb: {
type: "string"
}
}
}
}
},
AppBskyEmbedImages: {
lexicon: 1,
id: "app.bsky.embed.images",
description: "A set of images embedded in some other form of content",
defs: {
main: {
type: "object",
required: ["images"],
properties: {
images: {
type: "array",
items: {
type: "ref",
ref: "lex:app.bsky.embed.images#image"
},
maxLength: 4
}
}
},
image: {
type: "object",
required: ["image", "alt"],
properties: {
image: {
type: "image",
accept: ["image/*"],
maxWidth: 500,
maxHeight: 500,
maxSize: 3e5
},
alt: {
type: "string"
}
}
},
presented: {
type: "object",
required: ["images"],
properties: {
images: {
type: "array",
items: {
type: "ref",
ref: "lex:app.bsky.embed.images#presentedImage"
},
maxLength: 4
}
}
},
presentedImage: {
type: "object",
required: ["thumb", "fullsize", "alt"],
properties: {
thumb: {
type: "string"
},
fullsize: {
type: "string"
},
alt: {
type: "string" type: "string"
} }
} }
@ -5781,8 +5837,11 @@ var schemaDict = {
type: "unknown" type: "unknown"
}, },
embed: { embed: {
type: "ref", type: "union",
ref: "lex:app.bsky.feed.embed" refs: [
"lex:app.bsky.embed.images#presented",
"lex:app.bsky.embed.external#presented"
]
}, },
replyCount: { replyCount: {
type: "integer" type: "integer"
@ -5889,8 +5948,11 @@ var schemaDict = {
type: "unknown" type: "unknown"
}, },
embed: { embed: {
type: "ref", type: "union",
ref: "lex:app.bsky.feed.embed" refs: [
"lex:app.bsky.embed.images#presented",
"lex:app.bsky.embed.external#presented"
]
}, },
parent: { parent: {
type: "union", type: "union",
@ -6123,8 +6185,11 @@ var schemaDict = {
type: "unknown" type: "unknown"
}, },
embed: { embed: {
type: "ref", type: "union",
ref: "lex:app.bsky.feed.embed" refs: [
"lex:app.bsky.embed.images#presented",
"lex:app.bsky.embed.external#presented"
]
}, },
replyCount: { replyCount: {
type: "integer" type: "integer"
@ -6268,6 +6333,13 @@ var schemaDict = {
type: "ref", type: "ref",
ref: "lex:app.bsky.feed.post#replyRef" ref: "lex:app.bsky.feed.post#replyRef"
}, },
embed: {
type: "union",
refs: [
"lex:app.bsky.embed.images",
"lex:app.bsky.embed.external"
]
},
createdAt: { createdAt: {
type: "datetime" type: "datetime"
} }
@ -7748,8 +7820,11 @@ var profile_exports = {};
// src/client/types/app/bsky/actor/ref.ts // src/client/types/app/bsky/actor/ref.ts
var ref_exports = {}; var ref_exports = {};
// src/client/types/app/bsky/feed/embed.ts // src/client/types/app/bsky/embed/external.ts
var embed_exports = {}; var external_exports = {};
// src/client/types/app/bsky/embed/images.ts
var images_exports = {};
// src/client/types/app/bsky/feed/post.ts // src/client/types/app/bsky/feed/post.ts
var post_exports = {}; var post_exports = {};
@ -8015,6 +8090,7 @@ var BskyNS = class {
constructor(service) { constructor(service) {
this._service = service; this._service = service;
this.actor = new ActorNS(service); this.actor = new ActorNS(service);
this.embed = new EmbedNS(service);
this.feed = new FeedNS(service); this.feed = new FeedNS(service);
this.graph = new GraphNS(service); this.graph = new GraphNS(service);
this.notification = new NotificationNS(service); this.notification = new NotificationNS(service);
@ -8094,6 +8170,11 @@ var ProfileRecord = class {
); );
} }
}; };
var EmbedNS = class {
constructor(service) {
this._service = service;
}
};
var FeedNS = class { var FeedNS = class {
constructor(service) { constructor(service) {
this._service = service; this._service = service;
@ -8626,7 +8707,8 @@ var SessionManager = class extends import_events.default {
AppBskyActorSearch, AppBskyActorSearch,
AppBskyActorSearchTypeahead, AppBskyActorSearchTypeahead,
AppBskyActorUpdateProfile, AppBskyActorUpdateProfile,
AppBskyFeedEmbed, AppBskyEmbedExternal,
AppBskyEmbedImages,
AppBskyFeedGetAuthorFeed, AppBskyFeedGetAuthorFeed,
AppBskyFeedGetPostThread, AppBskyFeedGetPostThread,
AppBskyFeedGetRepostedBy, AppBskyFeedGetRepostedBy,
@ -8687,6 +8769,7 @@ var SessionManager = class extends import_events.default {
ComNS, ComNS,
ConfirmationRecord, ConfirmationRecord,
DeclarationRecord, DeclarationRecord,
EmbedNS,
FeedNS, FeedNS,
FollowRecord, FollowRecord,
GraphNS, GraphNS,

File diff suppressed because one or more lines are too long

View File

@ -83,7 +83,8 @@ export * as AppBskyActorRef from './types/app/bsky/actor/ref';
export * as AppBskyActorSearch from './types/app/bsky/actor/search'; export * as AppBskyActorSearch from './types/app/bsky/actor/search';
export * as AppBskyActorSearchTypeahead from './types/app/bsky/actor/searchTypeahead'; export * as AppBskyActorSearchTypeahead from './types/app/bsky/actor/searchTypeahead';
export * as AppBskyActorUpdateProfile from './types/app/bsky/actor/updateProfile'; export * as AppBskyActorUpdateProfile from './types/app/bsky/actor/updateProfile';
export * as AppBskyFeedEmbed from './types/app/bsky/feed/embed'; export * as AppBskyEmbedExternal from './types/app/bsky/embed/external';
export * as AppBskyEmbedImages from './types/app/bsky/embed/images';
export * as AppBskyFeedGetAuthorFeed from './types/app/bsky/feed/getAuthorFeed'; export * as AppBskyFeedGetAuthorFeed from './types/app/bsky/feed/getAuthorFeed';
export * as AppBskyFeedGetPostThread from './types/app/bsky/feed/getPostThread'; export * as AppBskyFeedGetPostThread from './types/app/bsky/feed/getPostThread';
export * as AppBskyFeedGetRepostedBy from './types/app/bsky/feed/getRepostedBy'; export * as AppBskyFeedGetRepostedBy from './types/app/bsky/feed/getRepostedBy';
@ -209,6 +210,7 @@ export declare class AppNS {
export declare class BskyNS { export declare class BskyNS {
_service: ServiceClient; _service: ServiceClient;
actor: ActorNS; actor: ActorNS;
embed: EmbedNS;
feed: FeedNS; feed: FeedNS;
graph: GraphNS; graph: GraphNS;
notification: NotificationNS; notification: NotificationNS;
@ -247,6 +249,10 @@ export declare class ProfileRecord {
}>; }>;
delete(params: Omit<ComAtprotoRepoDeleteRecord.InputSchema, 'collection'>, headers?: Record<string, string>): Promise<void>; delete(params: Omit<ComAtprotoRepoDeleteRecord.InputSchema, 'collection'>, headers?: Record<string, string>): Promise<void>;
} }
export declare class EmbedNS {
_service: ServiceClient;
constructor(service: ServiceClient);
}
export declare class FeedNS { export declare class FeedNS {
_service: ServiceClient; _service: ServiceClient;
post: PostRecord; post: PostRecord;

View File

@ -1371,65 +1371,25 @@ export declare const schemaDict: {
}; };
}; };
}; };
AppBskyFeedEmbed: { AppBskyEmbedExternal: {
lexicon: number; lexicon: number;
id: string; id: string;
description: string; description: string;
defs: { defs: {
main: { main: {
type: string; type: string;
description: string;
required: string[]; required: string[];
properties: { properties: {
items: { external: {
type: string;
items: {
type: string;
refs: string[];
};
};
};
};
media: {
type: string;
required: string[];
properties: {
alt: {
type: string;
};
thumb: {
type: string;
};
original: {
type: string;
};
};
};
record: {
type: string;
required: string[];
properties: {
type: {
type: string;
const: string;
};
author: {
type: string; type: string;
ref: string; ref: string;
}; };
record: {
type: string;
};
}; };
}; };
external: { external: {
type: string; type: string;
required: string[]; required: string[];
properties: { properties: {
type: {
type: string;
const: string;
};
uri: { uri: {
type: string; type: string;
}; };
@ -1439,7 +1399,105 @@ export declare const schemaDict: {
description: { description: {
type: string; type: string;
}; };
imageUri: { thumb: {
type: string;
accept: string[];
maxWidth: number;
maxHeight: number;
maxSize: number;
};
};
};
presented: {
type: string;
required: string[];
properties: {
external: {
type: string;
ref: string;
};
};
};
presentedExternal: {
type: string;
required: string[];
properties: {
uri: {
type: string;
};
title: {
type: string;
};
description: {
type: string;
};
thumb: {
type: string;
};
};
};
};
};
AppBskyEmbedImages: {
lexicon: number;
id: string;
description: string;
defs: {
main: {
type: string;
required: string[];
properties: {
images: {
type: string;
items: {
type: string;
ref: string;
};
maxLength: number;
};
};
};
image: {
type: string;
required: string[];
properties: {
image: {
type: string;
accept: string[];
maxWidth: number;
maxHeight: number;
maxSize: number;
};
alt: {
type: string;
};
};
};
presented: {
type: string;
required: string[];
properties: {
images: {
type: string;
items: {
type: string;
ref: string;
};
maxLength: number;
};
};
};
presentedImage: {
type: string;
required: string[];
properties: {
thumb: {
type: string;
};
fullsize: {
type: string;
};
alt: {
type: string; type: string;
}; };
}; };
@ -1518,7 +1576,7 @@ export declare const schemaDict: {
}; };
embed: { embed: {
type: string; type: string;
ref: string; refs: string[];
}; };
replyCount: { replyCount: {
type: string; type: string;
@ -1611,7 +1669,7 @@ export declare const schemaDict: {
}; };
embed: { embed: {
type: string; type: string;
ref: string; refs: string[];
}; };
parent: { parent: {
type: string; type: string;
@ -1829,7 +1887,7 @@ export declare const schemaDict: {
}; };
embed: { embed: {
type: string; type: string;
ref: string; refs: string[];
}; };
replyCount: { replyCount: {
type: string; type: string;
@ -1973,6 +2031,10 @@ export declare const schemaDict: {
type: string; type: string;
ref: string; ref: string;
}; };
embed: {
type: string;
refs: string[];
};
createdAt: { createdAt: {
type: string; type: string;
}; };
@ -2869,7 +2931,8 @@ export declare const ids: {
AppBskyActorSearch: string; AppBskyActorSearch: string;
AppBskyActorSearchTypeahead: string; AppBskyActorSearchTypeahead: string;
AppBskyActorUpdateProfile: string; AppBskyActorUpdateProfile: string;
AppBskyFeedEmbed: string; AppBskyEmbedExternal: string;
AppBskyEmbedImages: string;
AppBskyFeedGetAuthorFeed: string; AppBskyFeedGetAuthorFeed: string;
AppBskyFeedGetPostThread: string; AppBskyFeedGetPostThread: string;
AppBskyFeedGetRepostedBy: string; AppBskyFeedGetRepostedBy: string;

View File

@ -0,0 +1,26 @@
export interface Main {
external: External;
[k: string]: unknown;
}
export interface External {
uri: string;
title: string;
description: string;
thumb?: {
cid: string;
mimeType: string;
[k: string]: unknown;
};
[k: string]: unknown;
}
export interface Presented {
external: PresentedExternal;
[k: string]: unknown;
}
export interface PresentedExternal {
uri: string;
title: string;
description: string;
thumb?: string;
[k: string]: unknown;
}

View File

@ -0,0 +1,23 @@
export interface Main {
images: Image[];
[k: string]: unknown;
}
export interface Image {
image: {
cid: string;
mimeType: string;
[k: string]: unknown;
};
alt: string;
[k: string]: unknown;
}
export interface Presented {
images: PresentedImage[];
[k: string]: unknown;
}
export interface PresentedImage {
thumb: string;
fullsize: string;
alt: string;
[k: string]: unknown;
}

View File

@ -1,6 +1,7 @@
import { Headers } from '@atproto/xrpc'; import { Headers } from '@atproto/xrpc';
import * as AppBskyActorRef from '../actor/ref'; import * as AppBskyActorRef from '../actor/ref';
import * as AppBskyFeedEmbed from './embed'; import * as AppBskyEmbedImages from '../embed/images';
import * as AppBskyEmbedExternal from '../embed/external';
export interface QueryParams { export interface QueryParams {
author: string; author: string;
limit?: number; limit?: number;
@ -28,7 +29,10 @@ export interface FeedItem {
trendedBy?: AppBskyActorRef.WithInfo; trendedBy?: AppBskyActorRef.WithInfo;
repostedBy?: AppBskyActorRef.WithInfo; repostedBy?: AppBskyActorRef.WithInfo;
record: {}; record: {};
embed?: AppBskyFeedEmbed.Main; embed?: AppBskyEmbedImages.Presented | AppBskyEmbedExternal.Presented | {
$type: string;
[k: string]: unknown;
};
replyCount: number; replyCount: number;
repostCount: number; repostCount: number;
upvoteCount: number; upvoteCount: number;

View File

@ -1,6 +1,7 @@
import { Headers, XRPCError } from '@atproto/xrpc'; import { Headers, XRPCError } from '@atproto/xrpc';
import * as AppBskyActorRef from '../actor/ref'; import * as AppBskyActorRef from '../actor/ref';
import * as AppBskyFeedEmbed from './embed'; import * as AppBskyEmbedImages from '../embed/images';
import * as AppBskyEmbedExternal from '../embed/external';
export interface QueryParams { export interface QueryParams {
uri: string; uri: string;
depth?: number; depth?: number;
@ -30,7 +31,10 @@ export interface Post {
cid: string; cid: string;
author: AppBskyActorRef.WithInfo; author: AppBskyActorRef.WithInfo;
record: {}; record: {};
embed?: AppBskyFeedEmbed.Main; embed?: AppBskyEmbedImages.Presented | AppBskyEmbedExternal.Presented | {
$type: string;
[k: string]: unknown;
};
parent?: Post | NotFoundPost | { parent?: Post | NotFoundPost | {
$type: string; $type: string;
[k: string]: unknown; [k: string]: unknown;

View File

@ -1,6 +1,7 @@
import { Headers } from '@atproto/xrpc'; import { Headers } from '@atproto/xrpc';
import * as AppBskyActorRef from '../actor/ref'; import * as AppBskyActorRef from '../actor/ref';
import * as AppBskyFeedEmbed from './embed'; import * as AppBskyEmbedImages from '../embed/images';
import * as AppBskyEmbedExternal from '../embed/external';
export interface QueryParams { export interface QueryParams {
algorithm?: string; algorithm?: string;
limit?: number; limit?: number;
@ -28,7 +29,10 @@ export interface FeedItem {
trendedBy?: AppBskyActorRef.WithInfo; trendedBy?: AppBskyActorRef.WithInfo;
repostedBy?: AppBskyActorRef.WithInfo; repostedBy?: AppBskyActorRef.WithInfo;
record: {}; record: {};
embed?: AppBskyFeedEmbed.Main; embed?: AppBskyEmbedImages.Presented | AppBskyEmbedExternal.Presented | {
$type: string;
[k: string]: unknown;
};
replyCount: number; replyCount: number;
repostCount: number; repostCount: number;
upvoteCount: number; upvoteCount: number;

View File

@ -1,8 +1,14 @@
import * as AppBskyEmbedImages from '../embed/images';
import * as AppBskyEmbedExternal from '../embed/external';
import * as ComAtprotoRepoStrongRef from '../../../com/atproto/repo/strongRef'; import * as ComAtprotoRepoStrongRef from '../../../com/atproto/repo/strongRef';
export interface Record { export interface Record {
text: string; text: string;
entities?: Entity[]; entities?: Entity[];
reply?: ReplyRef; reply?: ReplyRef;
embed?: AppBskyEmbedImages.Main | AppBskyEmbedExternal.Main | {
$type: string;
[k: string]: unknown;
};
createdAt: string; createdAt: string;
[k: string]: unknown; [k: string]: unknown;
} }

File diff suppressed because one or more lines are too long

View File

@ -29,7 +29,6 @@ import {detectLinkables} from '../../../lib/strings'
import {UserLocalPhotosModel} from '../../../state/models/user-local-photos' import {UserLocalPhotosModel} from '../../../state/models/user-local-photos'
import {PhotoCarouselPicker} from './PhotoCarouselPicker' import {PhotoCarouselPicker} from './PhotoCarouselPicker'
import {SelectedPhoto} from './SelectedPhoto' import {SelectedPhoto} from './SelectedPhoto'
import {IMAGES_ENABLED} from '../../../build-flags'
const MAX_TEXT_LENGTH = 256 const MAX_TEXT_LENGTH = 256
const DANGER_TEXT_LENGTH = MAX_TEXT_LENGTH const DANGER_TEXT_LENGTH = MAX_TEXT_LENGTH
@ -46,6 +45,7 @@ export const ComposePost = observer(function ComposePost({
const store = useStores() const store = useStores()
const textInput = useRef<TextInput>(null) const textInput = useRef<TextInput>(null)
const [isProcessing, setIsProcessing] = useState(false) const [isProcessing, setIsProcessing] = useState(false)
const [processingState, setProcessingState] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [text, setText] = useState('') const [text, setText] = useState('')
const [selectedPhotos, setSelectedPhotos] = useState<string[]>([]) const [selectedPhotos, setSelectedPhotos] = useState<string[]>([])
@ -81,6 +81,10 @@ export const ComposePost = observer(function ComposePost({
} }
}, []) }, [])
const onSelectPhotos = (photos: string[]) => {
setSelectedPhotos(photos)
}
const onChangeText = (newText: string) => { const onChangeText = (newText: string) => {
setText(newText) setText(newText)
@ -109,15 +113,16 @@ export const ComposePost = observer(function ComposePost({
} }
setIsProcessing(true) setIsProcessing(true)
try { try {
const replyRef = replyTo await apilib.post(
? {uri: replyTo.uri, cid: replyTo.cid} store,
: undefined text,
await apilib.post(store, text, replyRef, autocompleteView.knownHandles) replyTo?.uri,
} catch (e: any) { selectedPhotos,
console.error(`Failed to create post: ${e.toString()}`) autocompleteView.knownHandles,
setError( setProcessingState,
'Post failed to upload. Please check your Internet connection and try again.',
) )
} catch (e: any) {
setError(e.message)
setIsProcessing(false) setIsProcessing(false)
return return
} }
@ -189,6 +194,11 @@ export const ComposePost = observer(function ComposePost({
</View> </View>
)} )}
</View> </View>
{isProcessing ? (
<View style={styles.processingLine}>
<Text>{processingState}</Text>
</View>
) : undefined}
{error !== '' && ( {error !== '' && (
<View style={styles.errorLine}> <View style={styles.errorLine}>
<View style={styles.errorIcon}> <View style={styles.errorIcon}>
@ -198,7 +208,7 @@ export const ComposePost = observer(function ComposePost({
size={10} size={10}
/> />
</View> </View>
<Text style={s.red4}>{error}</Text> <Text style={[s.red4, s.flex1]}>{error}</Text>
</View> </View>
)} )}
{replyTo ? ( {replyTo ? (
@ -240,15 +250,12 @@ export const ComposePost = observer(function ComposePost({
</View> </View>
<SelectedPhoto <SelectedPhoto
selectedPhotos={selectedPhotos} selectedPhotos={selectedPhotos}
setSelectedPhotos={setSelectedPhotos} onSelectPhotos={onSelectPhotos}
/> />
{IMAGES_ENABLED && {localPhotos.photos != null && selectedPhotos.length < 4 && (
localPhotos.photos != null &&
text === '' &&
selectedPhotos.length === 0 && (
<PhotoCarouselPicker <PhotoCarouselPicker
selectedPhotos={selectedPhotos} selectedPhotos={selectedPhotos}
setSelectedPhotos={setSelectedPhotos} onSelectPhotos={onSelectPhotos}
localPhotos={localPhotos} localPhotos={localPhotos}
/> />
)} )}
@ -322,6 +329,13 @@ const styles = StyleSheet.create({
paddingHorizontal: 20, paddingHorizontal: 20,
paddingVertical: 6, paddingVertical: 6,
}, },
processingLine: {
backgroundColor: colors.gray1,
borderRadius: 6,
paddingHorizontal: 8,
paddingVertical: 6,
marginBottom: 6,
},
errorLine: { errorLine: {
flexDirection: 'row', flexDirection: 'row',
backgroundColor: colors.red1, backgroundColor: colors.red1,

View File

@ -8,48 +8,54 @@ import {
openCropper, openCropper,
} from 'react-native-image-crop-picker' } from 'react-native-image-crop-picker'
const IMAGE_PARAMS = {
width: 500,
height: 500,
freeStyleCropEnabled: true,
forceJpg: true, // ios only
compressImageQuality: 0.7,
}
export const PhotoCarouselPicker = ({ export const PhotoCarouselPicker = ({
selectedPhotos, selectedPhotos,
setSelectedPhotos, onSelectPhotos,
localPhotos, localPhotos,
}: { }: {
selectedPhotos: string[] selectedPhotos: string[]
setSelectedPhotos: React.Dispatch<React.SetStateAction<string[]>> onSelectPhotos: (v: string[]) => void
localPhotos: any localPhotos: any
}) => { }) => {
const handleOpenCamera = useCallback(() => { const handleOpenCamera = useCallback(() => {
openCamera({ openCamera({
mediaType: 'photo', mediaType: 'photo',
cropping: true, cropping: true,
width: 1000, ...IMAGE_PARAMS,
height: 1000,
}).then( }).then(
item => { item => {
setSelectedPhotos([item.path, ...selectedPhotos]) onSelectPhotos([item.path, ...selectedPhotos])
}, },
_err => { _err => {
// ignore // ignore
}, },
) )
}, [selectedPhotos, setSelectedPhotos]) }, [selectedPhotos, onSelectPhotos])
const handleSelectPhoto = useCallback( const handleSelectPhoto = useCallback(
async (uri: string) => { async (uri: string) => {
const img = await openCropper({ const img = await openCropper({
mediaType: 'photo', mediaType: 'photo',
path: uri, path: uri,
width: 1000, ...IMAGE_PARAMS,
height: 1000,
}) })
setSelectedPhotos([img.path, ...selectedPhotos]) onSelectPhotos([img.path, ...selectedPhotos])
}, },
[selectedPhotos, setSelectedPhotos], [selectedPhotos, onSelectPhotos],
) )
const handleOpenGallery = useCallback(() => { const handleOpenGallery = useCallback(() => {
openPicker({ openPicker({
multiple: true, multiple: true,
maxFiles: 4, maxFiles: 4 - selectedPhotos.length,
mediaType: 'photo', mediaType: 'photo',
}).then(async items => { }).then(async items => {
const result = [] const result = []
@ -58,14 +64,13 @@ export const PhotoCarouselPicker = ({
const img = await openCropper({ const img = await openCropper({
mediaType: 'photo', mediaType: 'photo',
path: image.path, path: image.path,
width: 1000, ...IMAGE_PARAMS,
height: 1000,
}) })
result.push(img.path) result.push(img.path)
} }
setSelectedPhotos([...result, ...selectedPhotos]) onSelectPhotos([...result, ...selectedPhotos])
}) })
}, [selectedPhotos, setSelectedPhotos]) }, [selectedPhotos, onSelectPhotos])
return ( return (
<ScrollView <ScrollView

View File

@ -5,10 +5,10 @@ import {colors} from '../../lib/styles'
export const SelectedPhoto = ({ export const SelectedPhoto = ({
selectedPhotos, selectedPhotos,
setSelectedPhotos, onSelectPhotos,
}: { }: {
selectedPhotos: string[] selectedPhotos: string[]
setSelectedPhotos: React.Dispatch<React.SetStateAction<string[]>> onSelectPhotos: (v: string[]) => void
}) => { }) => {
const imageStyle = const imageStyle =
selectedPhotos.length === 1 selectedPhotos.length === 1
@ -19,11 +19,9 @@ export const SelectedPhoto = ({
const handleRemovePhoto = useCallback( const handleRemovePhoto = useCallback(
item => { item => {
setSelectedPhotos( onSelectPhotos(selectedPhotos.filter(filterItem => filterItem !== item))
selectedPhotos.filter(filterItem => filterItem !== item),
)
}, },
[selectedPhotos, setSelectedPhotos], [selectedPhotos, onSelectPhotos],
) )
return selectedPhotos.length !== 0 ? ( return selectedPhotos.length !== 0 ? (
@ -57,8 +55,10 @@ const styles = StyleSheet.create({
marginTop: 16, marginTop: 16,
}, },
image: { image: {
resizeMode: 'contain',
borderRadius: 8, borderRadius: 8,
margin: 2, margin: 2,
backgroundColor: colors.gray1,
}, },
image250: { image250: {
width: 250, width: 250,

View File

@ -0,0 +1,25 @@
import React from 'react'
import {Image, StyleSheet, useWindowDimensions, View} from 'react-native'
export function Component({uri}: {uri: string}) {
const winDim = useWindowDimensions()
const top = winDim.height / 2 - (winDim.width - 40) / 2 - 100
console.log(uri)
return (
<View style={[styles.container, {top}]}>
<Image style={styles.image} source={{uri}} />
</View>
)
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
left: 0,
},
image: {
resizeMode: 'contain',
width: '100%',
aspectRatio: 1,
},
})

View File

@ -7,6 +7,7 @@ import {useStores} from '../../../state'
import * as models from '../../../state/models/shell-ui' import * as models from '../../../state/models/shell-ui'
import * as ProfileImageLightbox from './ProfileImage' import * as ProfileImageLightbox from './ProfileImage'
import * as ImageLightbox from './Image'
export const Lightbox = observer(function Lightbox() { export const Lightbox = observer(function Lightbox() {
const store = useStores() const store = useStores()
@ -26,6 +27,12 @@ export const Lightbox = observer(function Lightbox() {
{...(store.shell.activeLightbox as models.ProfileImageLightbox)} {...(store.shell.activeLightbox as models.ProfileImageLightbox)}
/> />
) )
} else if (store.shell.activeLightbox?.name === 'image') {
element = (
<ImageLightbox.Component
{...(store.shell.activeLightbox as models.ImageLightbox)}
/>
)
} else { } else {
return <View /> return <View />
} }

View File

@ -167,7 +167,7 @@ export const PostThreadItem = observer(function PostThreadItem({
style={[styles.postText, styles.postTextLarge]} style={[styles.postText, styles.postTextLarge]}
/> />
</View> </View>
<PostEmbeds entities={record.entities} style={s.mb10} /> <PostEmbeds embed={item.embed} style={s.mb10} />
{item._isHighlightedPost && hasEngagement ? ( {item._isHighlightedPost && hasEngagement ? (
<View style={styles.expandedInfo}> <View style={styles.expandedInfo}>
{item.repostCount ? ( {item.repostCount ? (
@ -277,7 +277,7 @@ export const PostThreadItem = observer(function PostThreadItem({
style={[styles.postText]} style={[styles.postText]}
/> />
</View> </View>
<PostEmbeds entities={record.entities} style={{marginBottom: 10}} /> <PostEmbeds embed={item.embed} style={{marginBottom: 10}} />
<PostCtrls <PostCtrls
replyCount={item.replyCount} replyCount={item.replyCount}
repostCount={item.repostCount} repostCount={item.repostCount}

View File

@ -198,7 +198,7 @@ export const FeedItem = observer(function FeedItem({
style={styles.postText} style={styles.postText}
/> />
</View> </View>
<PostEmbeds entities={record.entities} style={{marginBottom: 10}} /> <PostEmbeds embed={item.embed} style={{marginBottom: 10}} />
<PostCtrls <PostCtrls
replyCount={item.replyCount} replyCount={item.replyCount}
repostCount={item.repostCount} repostCount={item.repostCount}

View File

@ -1,88 +1,170 @@
import React, {useEffect, useState} from 'react' import React, {useEffect, useState} from 'react'
import { import {
ActivityIndicator, ActivityIndicator,
Image,
ImageStyle,
StyleSheet, StyleSheet,
StyleProp, StyleProp,
Text, Text,
TouchableWithoutFeedback,
View, View,
ViewStyle, ViewStyle,
} from 'react-native' } from 'react-native'
import {Entity} from '../../../third-party/api/src/client/types/app/bsky/feed/post' import {
Record as PostRecord,
Entity,
} from '../../../third-party/api/src/client/types/app/bsky/feed/post'
import * as AppBskyEmbedImages from '../../../third-party/api/src/client/types/app/bsky/embed/images'
import * as AppBskyEmbedExternal from '../../../third-party/api/src/client/types/app/bsky/embed/external'
import {Link} from '../util/Link' import {Link} from '../util/Link'
import {LinkMeta, getLikelyType, LikelyType} from '../../../lib/link-meta' import {LinkMeta, getLikelyType, LikelyType} from '../../../lib/link-meta'
import {colors} from '../../lib/styles' import {colors} from '../../lib/styles'
import {useStores} from '../../../state' import {AutoSizedImage} from './images/AutoSizedImage'
type Embed =
| AppBskyEmbedImages.Presented
| AppBskyEmbedExternal.Presented
| {$type: string; [k: string]: unknown}
export function PostEmbeds({ export function PostEmbeds({
entities, embed,
style, style,
}: { }: {
entities?: Entity[] embed?: Embed
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
}) { }) {
const store = useStores() if (embed?.$type === 'app.bsky.embed.images#presented') {
const [linkMeta, setLinkMeta] = useState<LinkMeta | undefined>(undefined) const imgEmbed = embed as AppBskyEmbedImages.Presented
const link = entities?.find( if (imgEmbed.images.length > 0) {
ent => const Thumb = ({i, style}: {i: number; style: StyleProp<ImageStyle>}) => (
ent.type === 'link' && getLikelyType(ent.value || '') === LikelyType.HTML, <AutoSizedImage
style={style}
uri={imgEmbed.images[i].thumb}
fullSizeUri={imgEmbed.images[i].fullsize}
/>
) )
if (imgEmbed.images.length === 4) {
useEffect(() => {
let aborted = false
store.linkMetas.getLinkMeta(link?.value || '').then(linkMeta => {
if (!aborted) {
setLinkMeta(linkMeta)
}
})
return () => {
aborted = true
}
}, [link])
if (!link) {
return <View />
}
return ( return (
<Link style={[styles.outer, style]} href={link.value}> <View style={styles.imagesContainer}>
{linkMeta ? ( <View style={styles.imagePair}>
<> <Thumb i={0} style={styles.imagePairItem} />
<Text numberOfLines={1} style={styles.title}> <View style={styles.imagesWidthSpacer} />
{linkMeta.title || linkMeta.url} <Thumb i={1} style={styles.imagePairItem} />
</View>
<View style={styles.imagesHeightSpacer} />
<View style={styles.imagePair}>
<Thumb i={2} style={styles.imagePairItem} />
<View style={styles.imagesWidthSpacer} />
<Thumb i={3} style={styles.imagePairItem} />
</View>
</View>
)
} else if (imgEmbed.images.length === 3) {
return (
<View style={styles.imagesContainer}>
<View style={styles.imageWide}>
<Thumb i={0} style={styles.imageWideItem} />
</View>
<View style={styles.imagesHeightSpacer} />
<View style={styles.imagePair}>
<Thumb i={1} style={styles.imagePairItem} />
<View style={styles.imagesWidthSpacer} />
<Thumb i={2} style={styles.imagePairItem} />
</View>
</View>
)
} else if (imgEmbed.images.length === 2) {
return (
<View style={styles.imagesContainer}>
<View style={styles.imagePair}>
<Thumb i={0} style={styles.imagePairItem} />
<View style={styles.imagesWidthSpacer} />
<Thumb i={1} style={styles.imagePairItem} />
</View>
</View>
)
} else {
return (
<View style={styles.imagesContainer}>
<View style={styles.imageBig}>
<Thumb i={0} style={styles.imageBigItem} />
</View>
</View>
)
}
}
}
if (embed?.$type === 'app.bsky.embed.external#presented') {
const externalEmbed = embed as AppBskyEmbedExternal.Presented
const link = externalEmbed.external
return (
<Link style={[styles.extOuter, style]} href={link.uri}>
{link.thumb ? (
<AutoSizedImage style={style} uri={link.thumb} />
) : undefined}
<Text numberOfLines={1} style={styles.extTitle}>
{link.title || link.uri}
</Text> </Text>
<Text numberOfLines={1} style={styles.url}> <Text numberOfLines={1} style={styles.extUrl}>
{linkMeta.url} {link.uri}
</Text> </Text>
{linkMeta.description ? ( {link.description ? (
<Text numberOfLines={2} style={styles.description}> <Text numberOfLines={2} style={styles.extDescription}>
{linkMeta.description} {link.description}
</Text> </Text>
) : undefined} ) : undefined}
</>
) : (
<ActivityIndicator />
)}
</Link> </Link>
) )
}
return <View />
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
outer: { imagesContainer: {
marginBottom: 20,
},
imagesWidthSpacer: {
width: 5,
},
imagesHeightSpacer: {
height: 5,
},
imagePair: {
flexDirection: 'row',
},
imagePairItem: {
resizeMode: 'contain',
flex: 1,
borderRadius: 4,
},
imageWide: {},
imageWideItem: {
resizeMode: 'contain',
borderRadius: 4,
},
imageBig: {},
imageBigItem: {
borderRadius: 4,
},
extOuter: {
borderWidth: 1, borderWidth: 1,
borderColor: colors.gray2, borderColor: colors.gray2,
borderRadius: 8, borderRadius: 8,
padding: 10, padding: 10,
}, },
title: { extImage: {
// TODO
},
extTitle: {
fontSize: 16, fontSize: 16,
fontWeight: 'bold', fontWeight: 'bold',
}, },
description: { extDescription: {
marginTop: 4, marginTop: 4,
fontSize: 15, fontSize: 15,
}, },
url: { extUrl: {
color: colors.gray4, color: colors.gray4,
}, },
}) })

View File

@ -0,0 +1,112 @@
import React, {useState, useEffect, useMemo} from 'react'
import {
Image,
ImageStyle,
LayoutChangeEvent,
StyleProp,
StyleSheet,
Text,
TouchableWithoutFeedback,
View,
} from 'react-native'
import {ImageLightbox} from '../../../../state/models/shell-ui'
import {useStores} from '../../../../state'
import {colors} from '../../../lib/styles'
const MAX_HEIGHT = 300
interface Dim {
width: number
height: number
}
export function AutoSizedImage({
uri,
fullSizeUri,
style,
}: {
uri: string
fullSizeUri?: string
style: StyleProp<ImageStyle>
}) {
const store = useStores()
const [error, setError] = useState<string | undefined>()
const [imgInfo, setImgInfo] = useState<Dim | undefined>()
const [containerInfo, setContainerInfo] = useState<Dim | undefined>()
const calculatedStyle = useMemo(() => {
if (imgInfo && containerInfo) {
// imgInfo.height / imgInfo.width = x / containerInfo.width
// x = imgInfo.height / imgInfo.width * containerInfo.width
return {
height: Math.min(
MAX_HEIGHT,
(imgInfo.height / imgInfo.width) * containerInfo.width,
),
}
}
return undefined
}, [imgInfo, containerInfo])
useEffect(() => {
Image.getSize(
uri,
(width: number, height: number) => {
setImgInfo({width, height})
},
(error: any) => {
setError(String(error))
},
)
}, [uri])
const onLayout = (evt: LayoutChangeEvent) => {
setContainerInfo({
width: evt.nativeEvent.layout.width,
height: evt.nativeEvent.layout.height,
})
}
const onPressImage = () => {
if (fullSizeUri) {
store.shell.openLightbox(new ImageLightbox(fullSizeUri))
}
}
return (
<View style={style}>
<TouchableWithoutFeedback onPress={onPressImage}>
{error ? (
<View style={[styles.container, styles.errorContainer]}>
<Text style={styles.error}>{error}</Text>
</View>
) : calculatedStyle ? (
<View style={styles.container}>
<Image style={calculatedStyle} source={{uri}} />
</View>
) : (
<View style={[style, styles.placeholder]} onLayout={onLayout} />
)}
</TouchableWithoutFeedback>
</View>
)
}
const styles = StyleSheet.create({
placeholder: {
width: '100%',
aspectRatio: 1,
backgroundColor: colors.gray1,
},
errorContainer: {
backgroundColor: colors.red1,
paddingHorizontal: 8,
paddingVertical: 4,
},
container: {
borderRadius: 8,
overflow: 'hidden',
},
error: {
color: colors.red5,
},
})

View File

@ -1135,6 +1135,11 @@
"@babel/helper-validator-identifier" "^7.18.6" "@babel/helper-validator-identifier" "^7.18.6"
to-fast-properties "^2.0.0" to-fast-properties "^2.0.0"
"@bam.tech/react-native-image-resizer@^3.0.4":
version "3.0.4"
resolved "https://registry.yarnpkg.com/@bam.tech/react-native-image-resizer/-/react-native-image-resizer-3.0.4.tgz#3e127818e88df89e5c51a07e2556bf6ef872df26"
integrity sha512-p2Ecs469bntk4Ke4CEYyEoVBKBT+8JyaXXPz4Fm55s9G+jEg99p1V9MHkza2k7OAq1iUF8oAtZ/wZ9zKn6b43Q==
"@bcoe/v8-coverage@^0.2.3": "@bcoe/v8-coverage@^0.2.3":
version "0.2.3" version "0.2.3"
resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39"
@ -3609,6 +3614,11 @@ balanced-match@^1.0.0:
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
base-64@0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/base-64/-/base-64-0.1.0.tgz#780a99c84e7d600260361511c4877613bf24f6bb"
integrity sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==
base64-js@^1.1.2, base64-js@^1.3.1, base64-js@^1.5.1: base64-js@^1.1.2, base64-js@^1.3.1, base64-js@^1.5.1:
version "1.5.1" version "1.5.1"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"
@ -6079,6 +6089,18 @@ glob-to-regexp@^0.4.1:
resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e"
integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==
glob@7.0.6:
version "7.0.6"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.0.6.tgz#211bafaf49e525b8cd93260d14ab136152b3f57a"
integrity sha512-f8c0rE8JiCxpa52kWPAOa3ZaYEnzofDzCQLCn3Vdk0Z5OVLq3BsRFJI4S4ykpeVW6QMGBUkMeUpoEgWnMTnw5Q==
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.0.2"
once "^1.3.0"
path-is-absolute "^1.0.0"
glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6: glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6:
version "7.2.3" version "7.2.3"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b"
@ -10769,6 +10791,14 @@ rimraf@~2.6.2:
dependencies: dependencies:
glob "^7.1.3" glob "^7.1.3"
rn-fetch-blob@^0.12.0:
version "0.12.0"
resolved "https://registry.yarnpkg.com/rn-fetch-blob/-/rn-fetch-blob-0.12.0.tgz#ec610d2f9b3f1065556b58ab9c106eeb256f3cba"
integrity sha512-+QnR7AsJ14zqpVVUbzbtAjq0iI8c9tCg49tIoKO2ezjzRunN7YL6zFSFSWZm6d+mE/l9r+OeDM3jmb2tBb2WbA==
dependencies:
base-64 "0.1.0"
glob "7.0.6"
rollup-plugin-terser@^7.0.0: rollup-plugin-terser@^7.0.0:
version "7.0.2" version "7.0.2"
resolved "https://registry.yarnpkg.com/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz#e8fbba4869981b2dc35ae7e8a502d5c6c04d324d" resolved "https://registry.yarnpkg.com/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz#e8fbba4869981b2dc35ae7e8a502d5c6c04d324d"