diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb index 158a0815e..d804566c9 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 fa8f34fb4..60ccdd083 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 000000000..f8c824d28 --- /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 b06675c2e..d33e00d5d 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 000000000..740df4a35 --- /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 340cee802..1e4e545d8 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 b7f8bd669..fe9680d0e 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 c20e76ac4..719f4dda8 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 000000000..d5cb7e7f4 --- /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 8ee1ec9b9..000000000 --- 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 000000000..fa843122f --- /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 = ( +