From 3d46f478174403a64bd194e8c60e11b07bbd5d2d Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Thu, 12 Sep 2024 11:41:19 +0200 Subject: [PATCH] Change embedded posts to use web UI (#31766) Co-authored-by: Claire --- app/helpers/accounts_helper.rb | 8 - app/helpers/media_component_helper.rb | 36 -- app/javascript/entrypoints/embed.tsx | 74 ++++ app/javascript/entrypoints/public.tsx | 37 -- app/javascript/hooks/useRenderSignal.ts | 32 ++ app/javascript/mastodon/actions/statuses.js | 6 +- app/javascript/mastodon/components/logo.tsx | 7 + .../mastodon/components/more_from_author.jsx | 6 +- .../features/standalone/status/index.tsx | 87 ++++ .../status/components/detailed_status.jsx | 322 --------------- .../status/components/detailed_status.tsx | 390 ++++++++++++++++++ .../containers/detailed_status_container.js | 140 ------- .../mastodon/features/status/index.jsx | 2 +- app/javascript/styles/application.scss | 1 - .../styles/mastodon/components.scss | 31 +- app/javascript/styles/mastodon/statuses.scss | 152 ------- app/serializers/oembed_serializer.rb | 20 +- app/views/layouts/embedded.html.haml | 2 +- app/views/statuses/_detailed_status.html.haml | 80 ---- app/views/statuses/_poll.html.haml | 36 -- app/views/statuses/_simple_status.html.haml | 70 ---- app/views/statuses/_status.html.haml | 2 - app/views/statuses/embed.html.haml | 3 +- config/locales/af.yml | 1 - config/locales/an.yml | 12 - config/locales/ar.yml | 20 - config/locales/ast.yml | 9 - config/locales/be.yml | 16 - config/locales/bg.yml | 12 - config/locales/bn.yml | 1 - config/locales/br.yml | 4 - config/locales/ca.yml | 12 - config/locales/ckb.yml | 12 - config/locales/co.yml | 12 - config/locales/cs.yml | 16 - config/locales/cy.yml | 20 - config/locales/da.yml | 12 - config/locales/de.yml | 12 - config/locales/el.yml | 12 - config/locales/en-GB.yml | 12 - config/locales/en.yml | 12 - config/locales/eo.yml | 12 - config/locales/es-AR.yml | 12 - config/locales/es-MX.yml | 12 - config/locales/es.yml | 12 - config/locales/et.yml | 12 - config/locales/eu.yml | 12 - config/locales/fa.yml | 12 - config/locales/fi.yml | 12 - config/locales/fo.yml | 12 - config/locales/fr-CA.yml | 12 - config/locales/fr.yml | 12 - config/locales/fy.yml | 12 - config/locales/ga.yml | 18 - config/locales/gd.yml | 16 - config/locales/gl.yml | 12 - config/locales/he.yml | 16 - config/locales/hi.yml | 1 - config/locales/hr.yml | 14 - config/locales/hu.yml | 12 - config/locales/hy.yml | 12 - config/locales/ia.yml | 12 - config/locales/id.yml | 10 - config/locales/ie.yml | 12 - config/locales/io.yml | 12 - config/locales/is.yml | 12 - config/locales/it.yml | 12 - config/locales/ja.yml | 10 - config/locales/ka.yml | 3 - config/locales/kab.yml | 12 - config/locales/kk.yml | 12 - config/locales/ko.yml | 10 - config/locales/ku.yml | 12 - config/locales/la.yml | 1 - config/locales/lad.yml | 12 - config/locales/lt.yml | 6 - config/locales/lv.yml | 14 - config/locales/ml.yml | 1 - config/locales/ms.yml | 10 - config/locales/my.yml | 10 - config/locales/nl.yml | 12 - config/locales/nn.yml | 12 - config/locales/no.yml | 12 - config/locales/oc.yml | 12 - config/locales/pa.yml | 1 - config/locales/pl.yml | 16 - config/locales/pt-BR.yml | 12 - config/locales/pt-PT.yml | 12 - config/locales/ro.yml | 14 - config/locales/ru.yml | 16 - config/locales/ry.yml | 1 - config/locales/sc.yml | 12 - config/locales/sco.yml | 12 - config/locales/si.yml | 12 - config/locales/sk.yml | 16 - config/locales/sl.yml | 16 - config/locales/sq.yml | 12 - config/locales/sr-Latn.yml | 14 - config/locales/sr.yml | 14 - config/locales/sv.yml | 12 - config/locales/ta.yml | 2 - config/locales/te.yml | 1 - config/locales/th.yml | 10 - config/locales/tr.yml | 12 - config/locales/tt.yml | 7 - config/locales/uk.yml | 16 - config/locales/uz.yml | 2 - config/locales/vi.yml | 10 - config/locales/zgh.yml | 1 - config/locales/zh-CN.yml | 10 - config/locales/zh-HK.yml | 10 - config/locales/zh-TW.yml | 10 - public/embed.js | 105 +++-- spec/controllers/statuses_controller_spec.rb | 1 - spec/helpers/media_component_helper_spec.rb | 22 - 115 files changed, 710 insertions(+), 1928 deletions(-) create mode 100644 app/javascript/entrypoints/embed.tsx create mode 100644 app/javascript/hooks/useRenderSignal.ts create mode 100644 app/javascript/mastodon/features/standalone/status/index.tsx delete mode 100644 app/javascript/mastodon/features/status/components/detailed_status.jsx create mode 100644 app/javascript/mastodon/features/status/components/detailed_status.tsx delete mode 100644 app/javascript/mastodon/features/status/containers/detailed_status_container.js delete mode 100644 app/javascript/styles/mastodon/statuses.scss delete mode 100644 app/views/statuses/_detailed_status.html.haml delete mode 100644 app/views/statuses/_poll.html.haml delete mode 100644 app/views/statuses/_simple_status.html.haml delete mode 100644 app/views/statuses/_status.html.haml diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb index 158a0815e12..d804566c935 100644 --- a/app/helpers/accounts_helper.rb +++ b/app/helpers/accounts_helper.rb @@ -19,14 +19,6 @@ module AccountsHelper end end - def account_action_button(account) - return if account.memorial? || account.moved? - - link_to ActivityPub::TagManager.instance.url_for(account), class: 'button logo-button', target: '_new' do - safe_join([logo_as_symbol, t('accounts.follow')]) - end - end - def account_formatted_stat(value) number_to_human(value, precision: 3, strip_insignificant_zeros: true) end diff --git a/app/helpers/media_component_helper.rb b/app/helpers/media_component_helper.rb index fa8f34fb4d3..60ccdd08359 100644 --- a/app/helpers/media_component_helper.rb +++ b/app/helpers/media_component_helper.rb @@ -57,26 +57,6 @@ module MediaComponentHelper end end - def render_card_component(status, **options) - component_params = { - sensitive: sensitive_viewer?(status, current_account), - card: serialize_status_card(status).as_json, - }.merge(**options) - - react_component :card, component_params - end - - def render_poll_component(status, **options) - component_params = { - disabled: true, - poll: serialize_status_poll(status).as_json, - }.merge(**options) - - react_component :poll, component_params do - render partial: 'statuses/poll', locals: { status: status, poll: status.preloadable_poll, autoplay: prefers_autoplay? } - end - end - private def serialize_media_attachment(attachment) @@ -86,22 +66,6 @@ module MediaComponentHelper ) end - def serialize_status_card(status) - ActiveModelSerializers::SerializableResource.new( - status.preview_card, - serializer: REST::PreviewCardSerializer - ) - end - - def serialize_status_poll(status) - ActiveModelSerializers::SerializableResource.new( - status.preloadable_poll, - serializer: REST::PollSerializer, - scope: current_user, - scope_name: :current_user - ) - end - def sensitive_viewer?(status, account) if !account.nil? && account.id == status.account_id status.sensitive diff --git a/app/javascript/entrypoints/embed.tsx b/app/javascript/entrypoints/embed.tsx new file mode 100644 index 00000000000..f8c824d287a --- /dev/null +++ b/app/javascript/entrypoints/embed.tsx @@ -0,0 +1,74 @@ +import './public-path'; +import { createRoot } from 'react-dom/client'; + +import { afterInitialRender } from 'mastodon/../hooks/useRenderSignal'; + +import { start } from '../mastodon/common'; +import { Status } from '../mastodon/features/standalone/status'; +import { loadPolyfills } from '../mastodon/polyfills'; +import ready from '../mastodon/ready'; + +start(); + +function loaded() { + const mountNode = document.getElementById('mastodon-status'); + + if (mountNode) { + const attr = mountNode.getAttribute('data-props'); + + if (!attr) return; + + const props = JSON.parse(attr) as { id: string; locale: string }; + const root = createRoot(mountNode); + + root.render(); + } +} + +function main() { + ready(loaded).catch((error: unknown) => { + console.error(error); + }); +} + +loadPolyfills() + .then(main) + .catch((error: unknown) => { + console.error(error); + }); + +interface SetHeightMessage { + type: 'setHeight'; + id: string; + height: number; +} + +function isSetHeightMessage(data: unknown): data is SetHeightMessage { + if ( + data && + typeof data === 'object' && + 'type' in data && + data.type === 'setHeight' + ) + return true; + else return false; +} + +window.addEventListener('message', (e) => { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typings are not correct, it can be null in very rare cases + if (!e.data || !isSetHeightMessage(e.data) || !window.parent) return; + + const data = e.data; + + // We use a timeout to allow for the React page to render before calculating the height + afterInitialRender(() => { + window.parent.postMessage( + { + type: 'setHeight', + id: data.id, + height: document.getElementsByTagName('html')[0]?.scrollHeight, + }, + '*', + ); + }); +}); diff --git a/app/javascript/entrypoints/public.tsx b/app/javascript/entrypoints/public.tsx index b06675c2ee2..d33e00d5da8 100644 --- a/app/javascript/entrypoints/public.tsx +++ b/app/javascript/entrypoints/public.tsx @@ -37,43 +37,6 @@ const messages = defineMessages({ }, }); -interface SetHeightMessage { - type: 'setHeight'; - id: string; - height: number; -} - -function isSetHeightMessage(data: unknown): data is SetHeightMessage { - if ( - data && - typeof data === 'object' && - 'type' in data && - data.type === 'setHeight' - ) - return true; - else return false; -} - -window.addEventListener('message', (e) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typings are not correct, it can be null in very rare cases - if (!e.data || !isSetHeightMessage(e.data) || !window.parent) return; - - const data = e.data; - - ready(() => { - window.parent.postMessage( - { - type: 'setHeight', - id: data.id, - height: document.getElementsByTagName('html')[0]?.scrollHeight, - }, - '*', - ); - }).catch((e: unknown) => { - console.error('Error in setHeightMessage postMessage', e); - }); -}); - function loaded() { const { messages: localeData } = getLocale(); diff --git a/app/javascript/hooks/useRenderSignal.ts b/app/javascript/hooks/useRenderSignal.ts new file mode 100644 index 00000000000..740df4a35a3 --- /dev/null +++ b/app/javascript/hooks/useRenderSignal.ts @@ -0,0 +1,32 @@ +// This hook allows a component to signal that it's done rendering in a way that +// can be used by e.g. our embed code to determine correct iframe height + +let renderSignalReceived = false; + +type Callback = () => void; + +let onInitialRender: Callback; + +export const afterInitialRender = (callback: Callback) => { + if (renderSignalReceived) { + callback(); + } else { + onInitialRender = callback; + } +}; + +export const useRenderSignal = () => { + return () => { + if (renderSignalReceived) { + return; + } + + renderSignalReceived = true; + + if (typeof onInitialRender !== 'undefined') { + window.requestAnimationFrame(() => { + onInitialRender(); + }); + } + }; +}; diff --git a/app/javascript/mastodon/actions/statuses.js b/app/javascript/mastodon/actions/statuses.js index 340cee8024b..1e4e545d8c9 100644 --- a/app/javascript/mastodon/actions/statuses.js +++ b/app/javascript/mastodon/actions/statuses.js @@ -49,11 +49,13 @@ export function fetchStatusRequest(id, skipLoading) { }; } -export function fetchStatus(id, forceFetch = false) { +export function fetchStatus(id, forceFetch = false, alsoFetchContext = true) { return (dispatch, getState) => { const skipLoading = !forceFetch && getState().getIn(['statuses', id], null) !== null; - dispatch(fetchContext(id)); + if (alsoFetchContext) { + dispatch(fetchContext(id)); + } if (skipLoading) { return; diff --git a/app/javascript/mastodon/components/logo.tsx b/app/javascript/mastodon/components/logo.tsx index b7f8bd66950..fe9680d0e3a 100644 --- a/app/javascript/mastodon/components/logo.tsx +++ b/app/javascript/mastodon/components/logo.tsx @@ -7,6 +7,13 @@ export const WordmarkLogo: React.FC = () => ( ); +export const IconLogo: React.FC = () => ( + + Mastodon + + +); + export const SymbolLogo: React.FC = () => ( Mastodon ); diff --git a/app/javascript/mastodon/components/more_from_author.jsx b/app/javascript/mastodon/components/more_from_author.jsx index c20e76ac459..719f4dda86f 100644 --- a/app/javascript/mastodon/components/more_from_author.jsx +++ b/app/javascript/mastodon/components/more_from_author.jsx @@ -2,14 +2,12 @@ import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; +import { IconLogo } from 'mastodon/components/logo'; import { AuthorLink } from 'mastodon/features/explore/components/author_link'; export const MoreFromAuthor = ({ accountId }) => (
- - - - + }} />
); diff --git a/app/javascript/mastodon/features/standalone/status/index.tsx b/app/javascript/mastodon/features/standalone/status/index.tsx new file mode 100644 index 00000000000..d5cb7e7f40b --- /dev/null +++ b/app/javascript/mastodon/features/standalone/status/index.tsx @@ -0,0 +1,87 @@ +/* eslint-disable @typescript-eslint/no-unsafe-return, + @typescript-eslint/no-explicit-any, + @typescript-eslint/no-unsafe-assignment */ + +import { useEffect, useCallback } from 'react'; + +import { Provider } from 'react-redux'; + +import { useRenderSignal } from 'mastodon/../hooks/useRenderSignal'; +import { fetchStatus, toggleStatusSpoilers } from 'mastodon/actions/statuses'; +import { hydrateStore } from 'mastodon/actions/store'; +import { Router } from 'mastodon/components/router'; +import { DetailedStatus } from 'mastodon/features/status/components/detailed_status'; +import initialState from 'mastodon/initial_state'; +import { IntlProvider } from 'mastodon/locales'; +import { makeGetStatus, makeGetPictureInPicture } from 'mastodon/selectors'; +import { store, useAppSelector, useAppDispatch } from 'mastodon/store'; + +const getStatus = makeGetStatus() as unknown as (arg0: any, arg1: any) => any; +const getPictureInPicture = makeGetPictureInPicture() as unknown as ( + arg0: any, + arg1: any, +) => any; + +const Embed: React.FC<{ id: string }> = ({ id }) => { + const status = useAppSelector((state) => getStatus(state, { id })); + const pictureInPicture = useAppSelector((state) => + getPictureInPicture(state, { id }), + ); + const domain = useAppSelector((state) => state.meta.get('domain')); + const dispatch = useAppDispatch(); + const dispatchRenderSignal = useRenderSignal(); + + useEffect(() => { + dispatch(fetchStatus(id, false, false)); + }, [dispatch, id]); + + const handleToggleHidden = useCallback(() => { + dispatch(toggleStatusSpoilers(id)); + }, [dispatch, id]); + + // This allows us to calculate the correct page height for embeds + if (status) { + dispatchRenderSignal(); + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + const permalink = status?.get('url') as string; + + return ( +
+ + + +
+ ); +}; + +export const Status: React.FC<{ id: string }> = ({ id }) => { + useEffect(() => { + if (initialState) { + store.dispatch(hydrateStore(initialState)); + } + }, []); + + return ( + + + + + + + + ); +}; diff --git a/app/javascript/mastodon/features/status/components/detailed_status.jsx b/app/javascript/mastodon/features/status/components/detailed_status.jsx deleted file mode 100644 index 8ee1ec9b9bd..00000000000 --- a/app/javascript/mastodon/features/status/components/detailed_status.jsx +++ /dev/null @@ -1,322 +0,0 @@ -import PropTypes from 'prop-types'; - -import { FormattedDate, FormattedMessage } from 'react-intl'; - -import classNames from 'classnames'; -import { Link, withRouter } from 'react-router-dom'; - -import ImmutablePropTypes from 'react-immutable-proptypes'; -import ImmutablePureComponent from 'react-immutable-pure-component'; - -import AlternateEmailIcon from '@/material-icons/400-24px/alternate_email.svg?react'; -import { AnimatedNumber } from 'mastodon/components/animated_number'; -import { ContentWarning } from 'mastodon/components/content_warning'; -import EditedTimestamp from 'mastodon/components/edited_timestamp'; -import { getHashtagBarForStatus } from 'mastodon/components/hashtag_bar'; -import { Icon } from 'mastodon/components/icon'; -import PictureInPicturePlaceholder from 'mastodon/components/picture_in_picture_placeholder'; -import { VisibilityIcon } from 'mastodon/components/visibility_icon'; -import { WithRouterPropTypes } from 'mastodon/utils/react_router'; - -import { Avatar } from '../../../components/avatar'; -import { DisplayName } from '../../../components/display_name'; -import MediaGallery from '../../../components/media_gallery'; -import StatusContent from '../../../components/status_content'; -import Audio from '../../audio'; -import scheduleIdleTask from '../../ui/util/schedule_idle_task'; -import Video from '../../video'; - -import Card from './card'; - -class DetailedStatus extends ImmutablePureComponent { - - static propTypes = { - status: ImmutablePropTypes.map, - onOpenMedia: PropTypes.func.isRequired, - onOpenVideo: PropTypes.func.isRequired, - onToggleHidden: PropTypes.func.isRequired, - onTranslate: PropTypes.func.isRequired, - measureHeight: PropTypes.bool, - onHeightChange: PropTypes.func, - domain: PropTypes.string.isRequired, - compact: PropTypes.bool, - showMedia: PropTypes.bool, - pictureInPicture: ImmutablePropTypes.contains({ - inUse: PropTypes.bool, - available: PropTypes.bool, - }), - onToggleMediaVisibility: PropTypes.func, - ...WithRouterPropTypes, - }; - - state = { - height: null, - }; - - handleAccountClick = (e) => { - if (e.button === 0 && !(e.ctrlKey || e.metaKey) && this.props.history) { - e.preventDefault(); - this.props.history.push(`/@${this.props.status.getIn(['account', 'acct'])}`); - } - - e.stopPropagation(); - }; - - handleOpenVideo = (options) => { - this.props.onOpenVideo(this.props.status.getIn(['media_attachments', 0]), options); - }; - - handleExpandedToggle = () => { - this.props.onToggleHidden(this.props.status); - }; - - _measureHeight (heightJustChanged) { - if (this.props.measureHeight && this.node) { - scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 })); - - if (this.props.onHeightChange && heightJustChanged) { - this.props.onHeightChange(); - } - } - } - - setRef = c => { - this.node = c; - this._measureHeight(); - }; - - componentDidUpdate (prevProps, prevState) { - this._measureHeight(prevState.height !== this.state.height); - } - - handleModalLink = e => { - e.preventDefault(); - - let href; - - if (e.target.nodeName !== 'A') { - href = e.target.parentNode.href; - } else { - href = e.target.href; - } - - window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes'); - }; - - handleTranslate = () => { - const { onTranslate, status } = this.props; - onTranslate(status); - }; - - _properStatus () { - const { status } = this.props; - - if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { - return status.get('reblog'); - } else { - return status; - } - } - - getAttachmentAspectRatio () { - const attachments = this._properStatus().get('media_attachments'); - - if (attachments.getIn([0, 'type']) === 'video') { - return `${attachments.getIn([0, 'meta', 'original', 'width'])} / ${attachments.getIn([0, 'meta', 'original', 'height'])}`; - } else if (attachments.getIn([0, 'type']) === 'audio') { - return '16 / 9'; - } else { - return (attachments.size === 1 && attachments.getIn([0, 'meta', 'small', 'aspect'])) ? attachments.getIn([0, 'meta', 'small', 'aspect']) : '3 / 2'; - } - } - - render () { - const status = this._properStatus(); - const outerStyle = { boxSizing: 'border-box' }; - const { compact, pictureInPicture } = this.props; - - if (!status) { - return null; - } - - let media = ''; - let applicationLink = ''; - let reblogLink = ''; - let favouriteLink = ''; - - if (this.props.measureHeight) { - outerStyle.height = `${this.state.height}px`; - } - - const language = status.getIn(['translation', 'language']) || status.get('language'); - - if (pictureInPicture.get('inUse')) { - media = ; - } else if (status.get('media_attachments').size > 0) { - if (status.getIn(['media_attachments', 0, 'type']) === 'audio') { - const attachment = status.getIn(['media_attachments', 0]); - const description = attachment.getIn(['translation', 'description']) || attachment.get('description'); - - media = ( - {status.getIn(['application', 'name'])}; - } - - const visibilityLink = <>·; - - if (['private', 'direct'].includes(status.get('visibility'))) { - reblogLink = ''; - } else if (this.props.history) { - reblogLink = ( - - - - - - - ); - } else { - reblogLink = ( - - - - - - - ); - } - - if (this.props.history) { - favouriteLink = ( - - - - - - - ); - } else { - favouriteLink = ( - - - - - - - ); - } - - const {statusContentProps, hashtagBar} = getHashtagBarForStatus(status); - const expanded = !status.get('hidden') || status.get('spoiler_text').length === 0; - - return ( -
-
- {status.get('visibility') === 'direct' && ( -
-
- -
- )} - -
- -
- - {status.get('spoiler_text').length > 0 && } - - {expanded && ( - <> - - - {media} - {hashtagBar} - - )} - -
-
- - - - - {visibilityLink} - - {applicationLink} -
- - {status.get('edited_at') &&
} - -
- {reblogLink} - {reblogLink && <>·} - {favouriteLink} -
-
-
-
- ); - } - -} - -export default withRouter(DetailedStatus); diff --git a/app/javascript/mastodon/features/status/components/detailed_status.tsx b/app/javascript/mastodon/features/status/components/detailed_status.tsx new file mode 100644 index 00000000000..fa843122fbc --- /dev/null +++ b/app/javascript/mastodon/features/status/components/detailed_status.tsx @@ -0,0 +1,390 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access, + @typescript-eslint/no-unsafe-call, + @typescript-eslint/no-explicit-any, + @typescript-eslint/no-unsafe-assignment */ + +import type { CSSProperties } from 'react'; +import { useState, useRef, useCallback } from 'react'; + +import { FormattedDate, FormattedMessage } from 'react-intl'; + +import classNames from 'classnames'; +import { Link } from 'react-router-dom'; + +import AlternateEmailIcon from '@/material-icons/400-24px/alternate_email.svg?react'; +import { AnimatedNumber } from 'mastodon/components/animated_number'; +import { ContentWarning } from 'mastodon/components/content_warning'; +import EditedTimestamp from 'mastodon/components/edited_timestamp'; +import type { StatusLike } from 'mastodon/components/hashtag_bar'; +import { getHashtagBarForStatus } from 'mastodon/components/hashtag_bar'; +import { Icon } from 'mastodon/components/icon'; +import { IconLogo } from 'mastodon/components/logo'; +import PictureInPicturePlaceholder from 'mastodon/components/picture_in_picture_placeholder'; +import { VisibilityIcon } from 'mastodon/components/visibility_icon'; + +import { Avatar } from '../../../components/avatar'; +import { DisplayName } from '../../../components/display_name'; +import MediaGallery from '../../../components/media_gallery'; +import StatusContent from '../../../components/status_content'; +import Audio from '../../audio'; +import scheduleIdleTask from '../../ui/util/schedule_idle_task'; +import Video from '../../video'; + +import Card from './card'; + +interface VideoModalOptions { + startTime: number; + autoPlay?: boolean; + defaultVolume: number; + componentIndex: number; +} + +export const DetailedStatus: React.FC<{ + status: any; + onOpenMedia?: (status: any, index: number, lang: string) => void; + onOpenVideo?: (status: any, lang: string, options: VideoModalOptions) => void; + onTranslate?: (status: any) => void; + measureHeight?: boolean; + onHeightChange?: () => void; + domain: string; + showMedia?: boolean; + withLogo?: boolean; + pictureInPicture: any; + onToggleHidden?: (status: any) => void; + onToggleMediaVisibility?: () => void; +}> = ({ + status, + onOpenMedia, + onOpenVideo, + onTranslate, + measureHeight, + onHeightChange, + domain, + showMedia, + withLogo, + pictureInPicture, + onToggleMediaVisibility, + onToggleHidden, +}) => { + const properStatus = status?.get('reblog') ?? status; + const [height, setHeight] = useState(0); + const nodeRef = useRef(); + + const handleOpenVideo = useCallback( + (options: VideoModalOptions) => { + const lang = (status.getIn(['translation', 'language']) || + status.get('language')) as string; + if (onOpenVideo) + onOpenVideo(status.getIn(['media_attachments', 0]), lang, options); + }, + [onOpenVideo, status], + ); + + const handleExpandedToggle = useCallback(() => { + if (onToggleHidden) onToggleHidden(status); + }, [onToggleHidden, status]); + + const _measureHeight = useCallback( + (heightJustChanged?: boolean) => { + if (measureHeight && nodeRef.current) { + scheduleIdleTask(() => { + if (nodeRef.current) + setHeight(Math.ceil(nodeRef.current.scrollHeight) + 1); + }); + + if (onHeightChange && heightJustChanged) { + onHeightChange(); + } + } + }, + [onHeightChange, measureHeight, setHeight], + ); + + const handleRef = useCallback( + (c: HTMLDivElement) => { + nodeRef.current = c; + _measureHeight(); + }, + [_measureHeight], + ); + + const handleTranslate = useCallback(() => { + if (onTranslate) onTranslate(status); + }, [onTranslate, status]); + + if (!properStatus) { + return null; + } + + let media; + let applicationLink; + let reblogLink; + let attachmentAspectRatio; + + if (properStatus.get('media_attachments').getIn([0, 'type']) === 'video') { + attachmentAspectRatio = `${properStatus.get('media_attachments').getIn([0, 'meta', 'original', 'width'])} / ${properStatus.get('media_attachments').getIn([0, 'meta', 'original', 'height'])}`; + } else if ( + properStatus.get('media_attachments').getIn([0, 'type']) === 'audio' + ) { + attachmentAspectRatio = '16 / 9'; + } else { + attachmentAspectRatio = + properStatus.get('media_attachments').size === 1 && + properStatus + .get('media_attachments') + .getIn([0, 'meta', 'small', 'aspect']) + ? properStatus + .get('media_attachments') + .getIn([0, 'meta', 'small', 'aspect']) + : '3 / 2'; + } + + const outerStyle = { boxSizing: 'border-box' } as CSSProperties; + + if (measureHeight) { + outerStyle.height = height; + } + + const language = + status.getIn(['translation', 'language']) || status.get('language'); + + if (pictureInPicture.get('inUse')) { + media = ; + } else if (status.get('media_attachments').size > 0) { + if (status.getIn(['media_attachments', 0, 'type']) === 'audio') { + const attachment = status.getIn(['media_attachments', 0]); + const description = + attachment.getIn(['translation', 'description']) || + attachment.get('description'); + + media = ( +