1
0
Fork 0
forked from gitea/nas

Merge remote-tracking branch 'parent/main' into upstream-20250403

This commit is contained in:
KMY 2025-04-03 08:36:36 +09:00
commit 32f5604499
265 changed files with 6227 additions and 3383 deletions

View file

@ -1,6 +1,6 @@
import { useCallback, useState } from 'react';
import { useEffect, useState } from 'react';
import { TransitionMotion, spring } from 'react-motion';
import { animated, useSpring, config } from '@react-spring/web';
import { reduceMotion } from '../initial_state';
@ -11,53 +11,49 @@ interface Props {
}
export const AnimatedNumber: React.FC<Props> = ({ value }) => {
const [previousValue, setPreviousValue] = useState(value);
const [direction, setDirection] = useState<1 | -1>(1);
const direction = value > previousValue ? -1 : 1;
if (previousValue !== value) {
setPreviousValue(value);
setDirection(value > previousValue ? 1 : -1);
}
const willEnter = useCallback(() => ({ y: -1 * direction }), [direction]);
const willLeave = useCallback(
() => ({ y: spring(1 * direction, { damping: 35, stiffness: 400 }) }),
[direction],
const [styles, api] = useSpring(
() => ({
from: { transform: `translateY(${100 * direction}%)` },
to: { transform: 'translateY(0%)' },
onRest() {
setPreviousValue(value);
},
config: { ...config.gentle, duration: 200 },
immediate: true, // This ensures that the animation is not played when the component is first rendered
}),
[value, previousValue],
);
// When the value changes, start the animation
useEffect(() => {
if (value !== previousValue) {
void api.start({ reset: true });
}
}, [api, previousValue, value]);
if (reduceMotion) {
return <ShortNumber value={value} />;
}
const styles = [
{
key: `${value}`,
data: value,
style: { y: spring(0, { damping: 35, stiffness: 400 }) },
},
];
return (
<TransitionMotion
styles={styles}
willEnter={willEnter}
willLeave={willLeave}
>
{(items) => (
<span className='animated-number'>
{items.map(({ key, data, style }) => (
<span
key={key}
style={{
position:
direction * (style.y ?? 0) > 0 ? 'absolute' : 'static',
transform: `translateY(${(style.y ?? 0) * 100}%)`,
}}
>
<ShortNumber value={data as number} />
</span>
))}
</span>
<span className='animated-number'>
<animated.span style={styles}>
<ShortNumber value={value} />
</animated.span>
{value !== previousValue && (
<animated.span
style={{
...styles,
position: 'absolute',
top: `${-100 * direction}%`, // Adds extra space on top of translateY
}}
role='presentation'
>
<ShortNumber value={previousValue} />
</animated.span>
)}
</TransitionMotion>
</span>
);
};

View file

@ -1,29 +1,36 @@
import PropTypes from 'prop-types';
import { useState, useCallback } from 'react';
import { defineMessages } from 'react-intl';
import classNames from 'classnames';
import { useDispatch } from 'react-redux';
import ContentCopyIcon from '@/material-icons/400-24px/content_copy.svg?react';
import { showAlert } from 'mastodon/actions/alerts';
import { IconButton } from 'mastodon/components/icon_button';
import { useAppDispatch } from 'mastodon/store';
const messages = defineMessages({
copied: { id: 'copy_icon_button.copied', defaultMessage: 'Copied to clipboard' },
copied: {
id: 'copy_icon_button.copied',
defaultMessage: 'Copied to clipboard',
},
});
export const CopyIconButton = ({ title, value, className }) => {
export const CopyIconButton: React.FC<{
title: string;
value: string;
className: string;
}> = ({ title, value, className }) => {
const [copied, setCopied] = useState(false);
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const handleClick = useCallback(() => {
navigator.clipboard.writeText(value);
void navigator.clipboard.writeText(value);
setCopied(true);
dispatch(showAlert({ message: messages.copied }));
setTimeout(() => setCopied(false), 700);
setTimeout(() => {
setCopied(false);
}, 700);
}, [setCopied, value, dispatch]);
return (
@ -31,13 +38,8 @@ export const CopyIconButton = ({ title, value, className }) => {
className={classNames(className, copied ? 'copied' : 'copyable')}
title={title}
onClick={handleClick}
icon=''
iconComponent={ContentCopyIcon}
/>
);
};
CopyIconButton.propTypes = {
title: PropTypes.string,
value: PropTypes.string,
className: PropTypes.string,
};

View file

@ -1,4 +1,4 @@
import React from 'react';
import type React from 'react';
import { FormattedMessage } from 'react-intl';

View file

@ -1,24 +1,15 @@
import { useCallback } from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { FormattedMessage } from 'react-intl';
import LockOpenIcon from '@/material-icons/400-24px/lock_open.svg?react';
import { unblockDomain } from 'mastodon/actions/domain_blocks';
import { useAppDispatch } from 'mastodon/store';
import { IconButton } from './icon_button';
const messages = defineMessages({
unblockDomain: {
id: 'account.unblock_domain',
defaultMessage: 'Unblock domain {domain}',
},
});
import { Button } from './button';
export const Domain: React.FC<{
domain: string;
}> = ({ domain }) => {
const intl = useIntl();
const dispatch = useAppDispatch();
const handleDomainUnblock = useCallback(() => {
@ -27,20 +18,17 @@ export const Domain: React.FC<{
return (
<div className='domain'>
<div className='domain__wrapper'>
<span className='domain__domain-name'>
<strong>{domain}</strong>
</span>
<div className='domain__domain-name'>
<strong>{domain}</strong>
</div>
<div className='domain__buttons'>
<IconButton
active
icon='unlock'
iconComponent={LockOpenIcon}
title={intl.formatMessage(messages.unblockDomain, { domain })}
onClick={handleDomainUnblock}
<div className='domain__buttons'>
<Button onClick={handleDomainUnblock}>
<FormattedMessage
id='account.unblock_domain_short'
defaultMessage='Unblock'
/>
</div>
</Button>
</div>
</div>
);

View file

@ -1,248 +0,0 @@
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import escapeTextContentForBrowser from 'escape-html';
import spring from 'react-motion/lib/spring';
import CheckIcon from '@/material-icons/400-24px/check.svg?react';
import { Icon } from 'mastodon/components/icon';
import emojify from 'mastodon/features/emoji/emoji';
import Motion from 'mastodon/features/ui/util/optional_motion';
import { identityContextPropShape, withIdentity } from 'mastodon/identity_context';
import { RelativeTimestamp } from './relative_timestamp';
const messages = defineMessages({
closed: {
id: 'poll.closed',
defaultMessage: 'Closed',
},
voted: {
id: 'poll.voted',
defaultMessage: 'You voted for this answer',
},
votes: {
id: 'poll.votes',
defaultMessage: '{votes, plural, one {# vote} other {# votes}}',
},
});
class Poll extends ImmutablePureComponent {
static propTypes = {
identity: identityContextPropShape,
poll: ImmutablePropTypes.record.isRequired,
status: ImmutablePropTypes.map.isRequired,
lang: PropTypes.string,
intl: PropTypes.object.isRequired,
disabled: PropTypes.bool,
refresh: PropTypes.func,
onVote: PropTypes.func,
onInteractionModal: PropTypes.func,
};
state = {
selected: {},
expired: null,
};
static getDerivedStateFromProps (props, state) {
const { poll } = props;
const expires_at = poll.get('expires_at');
const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < Date.now();
return (expired === state.expired) ? null : { expired };
}
componentDidMount () {
this._setupTimer();
}
componentDidUpdate () {
this._setupTimer();
}
componentWillUnmount () {
clearTimeout(this._timer);
}
_setupTimer () {
const { poll } = this.props;
clearTimeout(this._timer);
if (!this.state.expired) {
const delay = (new Date(poll.get('expires_at'))).getTime() - Date.now();
this._timer = setTimeout(() => {
this.setState({ expired: true });
}, delay);
}
}
_toggleOption = value => {
if (this.props.poll.get('multiple')) {
const tmp = { ...this.state.selected };
if (tmp[value]) {
delete tmp[value];
} else {
tmp[value] = true;
}
this.setState({ selected: tmp });
} else {
const tmp = {};
tmp[value] = true;
this.setState({ selected: tmp });
}
};
handleOptionChange = ({ target: { value } }) => {
this._toggleOption(value);
};
handleOptionKeyPress = (e) => {
if (e.key === 'Enter' || e.key === ' ') {
this._toggleOption(e.target.getAttribute('data-index'));
e.stopPropagation();
e.preventDefault();
}
};
handleVote = () => {
if (this.props.disabled) {
return;
}
if (this.props.identity.signedIn) {
this.props.onVote(Object.keys(this.state.selected));
} else {
this.props.onInteractionModal('vote', this.props.status);
}
};
handleRefresh = () => {
if (this.props.disabled) {
return;
}
this.props.refresh();
};
handleReveal = () => {
this.setState({ revealed: true });
};
renderOption (option, optionIndex, showResults) {
const { poll, lang, disabled, intl } = this.props;
const pollVotesCount = poll.get('voters_count') || poll.get('votes_count');
const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100;
const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count'));
const active = !!this.state.selected[`${optionIndex}`];
const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex));
const title = option.getIn(['translation', 'title']) || option.get('title');
let titleHtml = option.getIn(['translation', 'titleHtml']) || option.get('titleHtml');
if (!titleHtml) {
const emojiMap = emojiMap(poll);
titleHtml = emojify(escapeTextContentForBrowser(title), emojiMap);
}
return (
<li key={option.get('title')}>
<label className={classNames('poll__option', { selectable: !showResults })}>
<input
name='vote-options'
type={poll.get('multiple') ? 'checkbox' : 'radio'}
value={optionIndex}
checked={active}
onChange={this.handleOptionChange}
disabled={disabled}
/>
{!showResults && (
<span
className={classNames('poll__input', { checkbox: poll.get('multiple'), active })}
tabIndex={0}
role={poll.get('multiple') ? 'checkbox' : 'radio'}
onKeyPress={this.handleOptionKeyPress}
aria-checked={active}
aria-label={title}
lang={lang}
data-index={optionIndex}
/>
)}
{showResults && (
<span
className='poll__number'
title={intl.formatMessage(messages.votes, {
votes: option.get('votes_count'),
})}
>
{Math.round(percent)}%
</span>
)}
<span
className='poll__option__text translate'
lang={lang}
dangerouslySetInnerHTML={{ __html: titleHtml }}
/>
{!!voted && <span className='poll__voted'>
<Icon id='check' icon={CheckIcon} className='poll__voted__mark' title={intl.formatMessage(messages.voted)} />
</span>}
</label>
{showResults && (
<Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}>
{({ width }) =>
<span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} />
}
</Motion>
)}
</li>
);
}
render () {
const { poll, intl } = this.props;
const { revealed, expired } = this.state;
if (!poll) {
return null;
}
const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />;
const showResults = poll.get('voted') || revealed || expired;
const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item);
let votesCount = null;
if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) {
votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />;
} else {
votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />;
}
return (
<div className='poll'>
<ul>
{poll.get('options').map((option, i) => this.renderOption(option, i, showResults))}
</ul>
<div className='poll__footer'>
{!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>}
{!showResults && <><button className='poll__link' onClick={this.handleReveal}><FormattedMessage id='poll.reveal' defaultMessage='See results' /></button> · </>}
{showResults && !this.props.disabled && <><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </>}
{votesCount}
{poll.get('expires_at') && <> · {timeRemaining}</>}
</div>
</div>
);
}
}
export default injectIntl(withIdentity(Poll));

View file

@ -0,0 +1,337 @@
import type { KeyboardEventHandler } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import classNames from 'classnames';
import { animated, useSpring } from '@react-spring/web';
import escapeTextContentForBrowser from 'escape-html';
import CheckIcon from '@/material-icons/400-24px/check.svg?react';
import { openModal } from 'mastodon/actions/modal';
import { fetchPoll, vote } from 'mastodon/actions/polls';
import { Icon } from 'mastodon/components/icon';
import emojify from 'mastodon/features/emoji/emoji';
import { useIdentity } from 'mastodon/identity_context';
import { reduceMotion } from 'mastodon/initial_state';
import { makeEmojiMap } from 'mastodon/models/custom_emoji';
import type * as Model from 'mastodon/models/poll';
import type { Status } from 'mastodon/models/status';
import { useAppDispatch, useAppSelector } from 'mastodon/store';
import { RelativeTimestamp } from './relative_timestamp';
const messages = defineMessages({
closed: {
id: 'poll.closed',
defaultMessage: 'Closed',
},
voted: {
id: 'poll.voted',
defaultMessage: 'You voted for this answer',
},
votes: {
id: 'poll.votes',
defaultMessage: '{votes, plural, one {# vote} other {# votes}}',
},
});
interface PollProps {
pollId: string;
status: Status;
lang?: string;
disabled?: boolean;
}
export const Poll: React.FC<PollProps> = ({ pollId, disabled, status }) => {
// Third party hooks
const poll = useAppSelector((state) => state.polls[pollId]);
const identity = useIdentity();
const intl = useIntl();
const dispatch = useAppDispatch();
// State
const [revealed, setRevealed] = useState(false);
const [selected, setSelected] = useState<Record<string, boolean>>({});
// Derived values
const expired = useMemo(() => {
if (!poll) {
return false;
}
const expiresAt = poll.expires_at;
return poll.expired || new Date(expiresAt).getTime() < Date.now();
}, [poll]);
const timeRemaining = useMemo(() => {
if (!poll) {
return null;
}
if (expired) {
return intl.formatMessage(messages.closed);
}
return <RelativeTimestamp timestamp={poll.expires_at} futureDate />;
}, [expired, intl, poll]);
const votesCount = useMemo(() => {
if (!poll) {
return null;
}
if (poll.voters_count) {
return (
<FormattedMessage
id='poll.total_people'
defaultMessage='{count, plural, one {# person} other {# people}}'
values={{ count: poll.voters_count }}
/>
);
}
return (
<FormattedMessage
id='poll.total_votes'
defaultMessage='{count, plural, one {# vote} other {# votes}}'
values={{ count: poll.votes_count }}
/>
);
}, [poll]);
const voteDisabled =
disabled || Object.values(selected).every((item) => !item);
// Event handlers
const handleVote = useCallback(() => {
if (voteDisabled) {
return;
}
if (identity.signedIn) {
void dispatch(vote({ pollId, choices: Object.keys(selected) }));
} else {
dispatch(
openModal({
modalType: 'INTERACTION',
modalProps: {
type: 'vote',
accountId: status.getIn(['account', 'id']),
url: status.get('uri'),
},
}),
);
}
}, [voteDisabled, dispatch, identity, pollId, selected, status]);
const handleReveal = useCallback(() => {
setRevealed(true);
}, []);
const handleRefresh = useCallback(() => {
if (disabled) {
return;
}
void dispatch(fetchPoll({ pollId }));
}, [disabled, dispatch, pollId]);
const handleOptionChange = useCallback(
(choiceIndex: number) => {
if (!poll) {
return;
}
if (poll.multiple) {
setSelected((prev) => ({
...prev,
[choiceIndex]: !prev[choiceIndex],
}));
} else {
setSelected({ [choiceIndex]: true });
}
},
[poll],
);
if (!poll) {
return null;
}
const showResults = poll.voted || revealed || expired;
return (
<div className='poll'>
<ul>
{poll.options.map((option, i) => (
<PollOption
key={option.title || i}
index={i}
poll={poll}
option={option}
showResults={showResults}
active={!!selected[i]}
onChange={handleOptionChange}
/>
))}
</ul>
<div className='poll__footer'>
{!showResults && (
<button
className='button button-secondary'
disabled={voteDisabled}
onClick={handleVote}
>
<FormattedMessage id='poll.vote' defaultMessage='Vote' />
</button>
)}
{!showResults && (
<>
<button className='poll__link' onClick={handleReveal}>
<FormattedMessage id='poll.reveal' defaultMessage='See results' />
</button>{' '}
·{' '}
</>
)}
{showResults && !disabled && (
<>
<button className='poll__link' onClick={handleRefresh}>
<FormattedMessage id='poll.refresh' defaultMessage='Refresh' />
</button>{' '}
·{' '}
</>
)}
{votesCount}
{poll.expires_at && <> · {timeRemaining}</>}
</div>
</div>
);
};
type PollOptionProps = Pick<PollProps, 'disabled' | 'lang'> & {
active: boolean;
onChange: (index: number) => void;
poll: Model.Poll;
option: Model.PollOption;
index: number;
showResults?: boolean;
};
const PollOption: React.FC<PollOptionProps> = (props) => {
const { active, lang, disabled, poll, option, index, showResults, onChange } =
props;
const voted = option.voted || poll.own_votes?.includes(index);
const title = option.translation?.title ?? option.title;
const intl = useIntl();
// Derived values
const percent = useMemo(() => {
const pollVotesCount = poll.voters_count ?? poll.votes_count;
return pollVotesCount === 0
? 0
: (option.votes_count / pollVotesCount) * 100;
}, [option, poll]);
const isLeading = useMemo(
() =>
poll.options
.filter((other) => other.title !== option.title)
.every((other) => option.votes_count >= other.votes_count),
[poll, option],
);
const titleHtml = useMemo(() => {
let titleHtml = option.translation?.titleHtml ?? option.titleHtml;
if (!titleHtml) {
const emojiMap = makeEmojiMap(poll.emojis);
titleHtml = emojify(escapeTextContentForBrowser(title), emojiMap);
}
return titleHtml;
}, [option, poll, title]);
// Handlers
const handleOptionChange = useCallback(() => {
onChange(index);
}, [index, onChange]);
const handleOptionKeyPress: KeyboardEventHandler = useCallback(
(event) => {
if (event.key === 'Enter' || event.key === ' ') {
onChange(index);
event.stopPropagation();
event.preventDefault();
}
},
[index, onChange],
);
const widthSpring = useSpring({
from: {
width: '0%',
},
to: {
width: `${percent}%`,
},
immediate: reduceMotion,
});
return (
<li>
<label
className={classNames('poll__option', { selectable: !showResults })}
>
<input
name='vote-options'
type={poll.multiple ? 'checkbox' : 'radio'}
value={index}
checked={active}
onChange={handleOptionChange}
disabled={disabled}
/>
{!showResults && (
<span
className={classNames('poll__input', {
checkbox: poll.multiple,
active,
})}
tabIndex={0}
role={poll.multiple ? 'checkbox' : 'radio'}
onKeyDown={handleOptionKeyPress}
aria-checked={active}
aria-label={title}
lang={lang}
data-index={index}
/>
)}
{showResults && (
<span
className='poll__number'
title={intl.formatMessage(messages.votes, {
votes: option.votes_count,
})}
>
{Math.round(percent)}%
</span>
)}
<span
className='poll__option__text translate'
lang={lang}
dangerouslySetInnerHTML={{ __html: titleHtml }}
/>
{!!voted && (
<span className='poll__voted'>
<Icon
id='check'
icon={CheckIcon}
className='poll__voted__mark'
title={intl.formatMessage(messages.voted)}
/>
</span>
)}
</label>
{showResults && (
<animated.span
className={classNames('poll__chart', { leading: isLeading })}
style={widthSpring}
/>
)}
</li>
);
};

View file

@ -1,5 +1,5 @@
import type { PropsWithChildren } from 'react';
import React from 'react';
import type React from 'react';
import { Router as OriginalRouter, useHistory } from 'react-router';

View file

@ -11,7 +11,7 @@ import { connect } from 'react-redux';
import ChevronRightIcon from '@/material-icons/400-24px/chevron_right.svg?react';
import { Icon } from 'mastodon/components/icon';
import PollContainer from 'mastodon/containers/poll_container';
import { Poll } from 'mastodon/components/poll';
import { identityContextPropShape, withIdentity } from 'mastodon/identity_context';
import { autoPlayGif, languages as preloadedLanguages } from 'mastodon/initial_state';
@ -250,7 +250,7 @@ class StatusContent extends PureComponent {
);
const poll = !!status.get('poll') && (
<PollContainer pollId={status.get('poll')} status={status} lang={language} />
<Poll pollId={status.get('poll')} status={status} lang={language} />
);
if (this.props.onClick) {