[Glitch] Profile redesign: Account fields grid

Port dcbf7ab8dc74271eb24614369867c9cb430751cd to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
This commit is contained in:
Echo 2026-02-25 17:59:18 +01:00 committed by Claire
parent f6d6dc2605
commit 7c631b9ffb
18 changed files with 487 additions and 410 deletions

View File

@ -20,18 +20,7 @@ export interface EmojiHTMLProps {
} }
export const EmojiHTML = polymorphicForwardRef<'div', EmojiHTMLProps>( export const EmojiHTML = polymorphicForwardRef<'div', EmojiHTMLProps>(
( ({ extraEmojis, htmlString, onElement, onAttribute, ...props }, ref) => {
{
extraEmojis,
htmlString,
as: asProp = 'div', // Rename for syntax highlighting
className,
onElement,
onAttribute,
...props
},
ref,
) => {
const contents = useMemo( const contents = useMemo(
() => () =>
htmlStringToComponents(htmlString, { htmlStringToComponents(htmlString, {
@ -44,12 +33,7 @@ export const EmojiHTML = polymorphicForwardRef<'div', EmojiHTMLProps>(
return ( return (
<CustomEmojiProvider emojis={extraEmojis}> <CustomEmojiProvider emojis={extraEmojis}>
<AnimateEmojiProvider <AnimateEmojiProvider {...props} ref={ref}>
{...props}
as={asProp}
className={className}
ref={ref}
>
{contents} {contents}
</AnimateEmojiProvider> </AnimateEmojiProvider>
</CustomEmojiProvider> </CustomEmojiProvider>

View File

@ -23,7 +23,17 @@ export type MiniCardProps = OmitUnion<
export const MiniCard = forwardRef<HTMLDivElement, MiniCardProps>( export const MiniCard = forwardRef<HTMLDivElement, MiniCardProps>(
( (
{ label, value, className, hidden, icon, iconId, iconClassName, ...props }, {
label,
value,
className,
hidden,
icon,
iconId,
iconClassName,
children,
...props
},
ref, ref,
) => { ) => {
if (!label) { if (!label) {
@ -50,6 +60,7 @@ export const MiniCard = forwardRef<HTMLDivElement, MiniCardProps>(
)} )}
<dt className={classes.label}>{label}</dt> <dt className={classes.label}>{label}</dt>
<dd className={classes.value}>{value}</dd> <dd className={classes.value}>{value}</dd>
{children}
</div> </div>
); );
}, },

View File

@ -1,125 +0,0 @@
import type { FC } from 'react';
import { FormattedMessage } from 'react-intl';
import { useParams } from 'react-router';
import { AccountBio } from '@/flavours/glitch/components/account_bio';
import { Column } from '@/flavours/glitch/components/column';
import { ColumnBackButton } from '@/flavours/glitch/components/column_back_button';
import { LoadingIndicator } from '@/flavours/glitch/components/loading_indicator';
import BundleColumnError from '@/flavours/glitch/features/ui/components/bundle_column_error';
import type { AccountId } from '@/flavours/glitch/hooks/useAccountId';
import { useAccountId } from '@/flavours/glitch/hooks/useAccountId';
import { useAccountVisibility } from '@/flavours/glitch/hooks/useAccountVisibility';
import { createAppSelector, useAppSelector } from '@/flavours/glitch/store';
import { AccountHeader } from '../account_timeline/components/account_header';
import { AccountHeaderFields } from '../account_timeline/components/fields';
import { LimitedAccountHint } from '../account_timeline/components/limited_account_hint';
import classes from './styles.module.css';
const selectIsProfileEmpty = createAppSelector(
[(state) => state.accounts, (_, accountId: AccountId) => accountId],
(accounts, accountId) => {
// Null means still loading, otherwise it's a boolean.
if (!accountId) {
return null;
}
const account = accounts.get(accountId);
if (!account) {
return null;
}
return !account.note && !account.fields.size;
},
);
export const AccountAbout: FC<{ multiColumn: boolean }> = ({ multiColumn }) => {
const accountId = useAccountId();
const { blockedBy, hidden, suspended } = useAccountVisibility(accountId);
const forceEmptyState = blockedBy || hidden || suspended;
const isProfileEmpty = useAppSelector((state) =>
selectIsProfileEmpty(state, accountId),
);
if (accountId === null) {
return <BundleColumnError multiColumn={multiColumn} errorType='routing' />;
}
if (!accountId || isProfileEmpty === null) {
return (
<Column bindToDocument={!multiColumn}>
<LoadingIndicator />
</Column>
);
}
const showEmptyMessage = forceEmptyState || isProfileEmpty;
return (
<Column bindToDocument={!multiColumn}>
<ColumnBackButton />
<div className='scrollable scrollable--flex'>
<AccountHeader accountId={accountId} hideTabs={forceEmptyState} />
<div className={classes.wrapper}>
{!showEmptyMessage ? (
<>
<AccountBio
accountId={accountId}
className={`${classes.bio} account__header__content`}
/>
<AccountHeaderFields accountId={accountId} />
</>
) : (
<div className='empty-column-indicator'>
<EmptyMessage accountId={accountId} />
</div>
)}
</div>
</div>
</Column>
);
};
const EmptyMessage: FC<{ accountId: string }> = ({ accountId }) => {
const { blockedBy, hidden, suspended } = useAccountVisibility(accountId);
const currentUserId = useAppSelector(
(state) => state.meta.get('me') as string | null,
);
const { acct } = useParams<{ acct?: string }>();
if (suspended) {
return (
<FormattedMessage
id='empty_column.account_suspended'
defaultMessage='Account suspended'
/>
);
} else if (hidden) {
return <LimitedAccountHint accountId={accountId} />;
} else if (blockedBy) {
return (
<FormattedMessage
id='empty_column.account_unavailable'
defaultMessage='Profile unavailable'
/>
);
} else if (accountId === currentUserId) {
return (
<FormattedMessage
id='empty_column.account_about.me'
defaultMessage='You have not added any information about yourself yet.'
/>
);
}
return (
<FormattedMessage
id='empty_column.account_about.other'
defaultMessage='{acct} has not added any information about themselves yet.'
values={{ acct }}
/>
);
};

View File

@ -1,7 +0,0 @@
.wrapper {
padding: 16px;
}
.bio {
color: var(--color-text-primary);
}

View File

@ -1,5 +1,12 @@
import type { AccountFieldShape } from '@/flavours/glitch/models/account';
import { isServerFeatureEnabled } from '@/flavours/glitch/utils/environment'; import { isServerFeatureEnabled } from '@/flavours/glitch/utils/environment';
export function isRedesignEnabled() { export function isRedesignEnabled() {
return isServerFeatureEnabled('profile_redesign'); return isServerFeatureEnabled('profile_redesign');
} }
export interface AccountField extends AccountFieldShape {
nameHasEmojis: boolean;
value_plain: string;
valueHasEmojis: boolean;
}

View File

@ -210,18 +210,14 @@ export const AccountHeader: React.FC<{
<AccountNote accountId={accountId} /> <AccountNote accountId={accountId} />
))} ))}
{(!isRedesign || layout === 'single-column') && ( <AccountBio
<> accountId={accountId}
<AccountBio className={classNames(
accountId={accountId} 'account__header__content',
className={classNames( isRedesign && redesignClasses.bio,
'account__header__content', )}
isRedesign && redesignClasses.bio, />
)} <AccountHeaderFields accountId={accountId} />
/>
<AccountHeaderFields accountId={accountId} />
</>
)}
</div> </div>
</div> </div>
)} )}

View File

@ -1,28 +1,31 @@
import { useCallback, useMemo, useState } from 'react'; import { useCallback, useMemo, useRef, useState } from 'react';
import type { FC, Key } from 'react'; import type { FC } from 'react';
import { defineMessage, FormattedMessage, useIntl } from 'react-intl'; import { defineMessage, FormattedMessage, useIntl } from 'react-intl';
import classNames from 'classnames'; import classNames from 'classnames';
import htmlConfig from '@/config/html-tags.json'; import { openModal } from '@/flavours/glitch/actions/modal';
import { AccountFields } from '@/flavours/glitch/components/account_fields'; import { AccountFields } from '@/flavours/glitch/components/account_fields';
import { CustomEmojiProvider } from '@/flavours/glitch/components/emoji/context'; import { CustomEmojiProvider } from '@/flavours/glitch/components/emoji/context';
import type { EmojiHTMLProps } from '@/flavours/glitch/components/emoji/html'; import type { EmojiHTMLProps } from '@/flavours/glitch/components/emoji/html';
import { EmojiHTML } from '@/flavours/glitch/components/emoji/html'; import { EmojiHTML } from '@/flavours/glitch/components/emoji/html';
import { FormattedDateWrapper } from '@/flavours/glitch/components/formatted_date'; import { FormattedDateWrapper } from '@/flavours/glitch/components/formatted_date';
import { Icon } from '@/flavours/glitch/components/icon'; import { Icon } from '@/flavours/glitch/components/icon';
import { IconButton } from '@/flavours/glitch/components/icon_button';
import { MiniCard } from '@/flavours/glitch/components/mini_card';
import { useElementHandledLink } from '@/flavours/glitch/components/status/handled_link'; import { useElementHandledLink } from '@/flavours/glitch/components/status/handled_link';
import { useAccount } from '@/flavours/glitch/hooks/useAccount'; import { useAccount } from '@/flavours/glitch/hooks/useAccount';
import type { import { useResizeObserver } from '@/flavours/glitch/hooks/useObserver';
Account, import type { Account } from '@/flavours/glitch/models/account';
AccountFieldShape, import { useAppDispatch } from '@/flavours/glitch/store';
} from '@/flavours/glitch/models/account';
import type { OnElementHandler } from '@/flavours/glitch/utils/html';
import IconVerified from '@/images/icons/icon_verified.svg?react'; import IconVerified from '@/images/icons/icon_verified.svg?react';
import MoreIcon from '@/material-icons/400-24px/more_horiz.svg?react';
import { cleanExtraEmojis } from '../../emoji/normalize'; import { cleanExtraEmojis } from '../../emoji/normalize';
import type { AccountField } from '../common';
import { isRedesignEnabled } from '../common'; import { isRedesignEnabled } from '../common';
import { useFieldHtml } from '../hooks/useFieldHtml';
import classes from './redesign.module.scss'; import classes from './redesign.module.scss';
@ -77,172 +80,310 @@ const RedesignAccountHeaderFields: FC<{ account: Account }> = ({ account }) => {
() => cleanExtraEmojis(account.emojis), () => cleanExtraEmojis(account.emojis),
[account.emojis], [account.emojis],
); );
const textHasCustomEmoji = useCallback( const fields: AccountField[] = useMemo(() => {
(text?: string | null) => { const fields = account.fields.toJS();
if (!emojis || !text) { if (!emojis) {
return false; return fields.map((field) => ({
} ...field,
for (const emoji of Object.keys(emojis)) { nameHasEmojis: false,
if (text.includes(`:${emoji}:`)) { value_plain: field.value_plain ?? '',
return true; valueHasEmojis: false,
} }));
} }
return false;
}, const shortcodes = Object.keys(emojis);
[emojis], return fields.map((field) => ({
); ...field,
nameHasEmojis: shortcodes.some((code) =>
field.name.includes(`:${code}:`),
),
value_plain: field.value_plain ?? '',
valueHasEmojis: shortcodes.some((code) =>
field.value_plain?.includes(`:${code}:`),
),
}));
}, [account.fields, emojis]);
const htmlHandlers = useElementHandledLink({ const htmlHandlers = useElementHandledLink({
hashtagAccountId: account.id, hashtagAccountId: account.id,
}); });
if (account.fields.isEmpty()) { const { wrapperRef } = useColumnWrap();
if (fields.length === 0) {
return null; return null;
} }
return ( return (
<CustomEmojiProvider emojis={emojis}> <CustomEmojiProvider emojis={emojis}>
<dl className={classes.fieldList}> <dl className={classes.fieldList} ref={wrapperRef}>
{account.fields.map((field, key) => ( {fields.map((field, key) => (
<FieldRow <FieldRow key={key} field={field} htmlHandlers={htmlHandlers} />
key={key}
{...field.toJSON()}
htmlHandlers={htmlHandlers}
textHasCustomEmoji={textHasCustomEmoji}
/>
))} ))}
</dl> </dl>
</CustomEmojiProvider> </CustomEmojiProvider>
); );
}; };
const FieldRow: FC< const FieldRow: FC<{
{ htmlHandlers: ReturnType<typeof useElementHandledLink>;
textHasCustomEmoji: (text?: string | null) => boolean; field: AccountField;
htmlHandlers: ReturnType<typeof useElementHandledLink>; }> = ({ htmlHandlers, field }) => {
} & AccountFieldShape
> = ({
textHasCustomEmoji,
htmlHandlers,
name,
name_emojified,
value_emojified,
value_plain,
verified_at,
}) => {
const intl = useIntl(); const intl = useIntl();
const [showAll, setShowAll] = useState(false); const {
const handleClick = useCallback(() => { name,
setShowAll((prev) => !prev); name_emojified,
}, []); nameHasEmojis,
value_emojified,
value_plain,
valueHasEmojis,
verified_at,
} = field;
const { wrapperRef, isLabelOverflowing, isValueOverflowing } =
useFieldOverflow();
const dispatch = useAppDispatch();
const handleOverflowClick = useCallback(() => {
dispatch(
openModal({
modalType: 'ACCOUNT_FIELD_OVERFLOW',
modalProps: { field },
}),
);
}, [dispatch, field]);
return ( return (
/* eslint-disable -- This method of showing field contents is not very accessible, but it's what we've got for now */ <MiniCard
<div
className={classNames( className={classNames(
classes.fieldRow, classes.fieldItem,
verified_at && classes.fieldVerified, verified_at && classes.fieldVerified,
showAll && classes.fieldShowAll,
)} )}
onClick={handleClick} label={
/* eslint-enable */
>
<FieldHTML
as='dt'
text={name}
textEmojified={name_emojified}
textHasCustomEmoji={textHasCustomEmoji(name)}
titleLength={50}
className='translate'
{...htmlHandlers}
/>
<dd>
<FieldHTML <FieldHTML
as='span' text={name}
text={value_plain ?? ''} textEmojified={name_emojified}
textEmojified={value_emojified} textHasCustomEmoji={nameHasEmojis}
textHasCustomEmoji={textHasCustomEmoji(value_plain ?? '')} className='translate'
titleLength={120} isOverflowing={isLabelOverflowing}
onOverflowClick={handleOverflowClick}
{...htmlHandlers} {...htmlHandlers}
/> />
}
{verified_at && ( value={
<Icon <FieldHTML
id='verified' text={value_plain}
icon={IconVerified} textEmojified={value_emojified}
className={classes.fieldVerifiedIcon} textHasCustomEmoji={valueHasEmojis}
aria-label={intl.formatMessage(verifyMessage, { isOverflowing={isValueOverflowing}
date: intl.formatDate(verified_at, dateFormatOptions), onOverflowClick={handleOverflowClick}
})} {...htmlHandlers}
noFill />
/> }
)} ref={wrapperRef}
</dd> >
</div> {verified_at && (
<Icon
id='verified'
icon={IconVerified}
className={classes.fieldVerifiedIcon}
aria-label={intl.formatMessage(verifyMessage, {
date: intl.formatDate(verified_at, dateFormatOptions),
})}
noFill
/>
)}
</MiniCard>
); );
}; };
const FieldHTML: FC< type FieldHTMLProps = {
{ text: string;
as?: 'span' | 'dt'; textEmojified: string;
text: string; textHasCustomEmoji: boolean;
textEmojified: string; isOverflowing?: boolean;
textHasCustomEmoji: boolean; onOverflowClick?: () => void;
titleLength: number; } & Omit<EmojiHTMLProps, 'htmlString'>;
} & Omit<EmojiHTMLProps, 'htmlString'>
> = ({ const FieldHTML: FC<FieldHTMLProps> = ({
as,
className, className,
extraEmojis, extraEmojis,
text, text,
textEmojified, textEmojified,
textHasCustomEmoji, textHasCustomEmoji,
titleLength, isOverflowing,
onOverflowClick,
onElement, onElement,
...props ...props
}) => { }) => {
const handleElement: OnElementHandler = useCallback( const intl = useIntl();
(element, props, children, extra) => { const handleElement = useFieldHtml(textHasCustomEmoji, onElement);
if (element instanceof HTMLAnchorElement) {
// Don't allow custom emoji and links in the same field to prevent verification spoofing.
if (textHasCustomEmoji) {
return (
<span {...filterAttributesForSpan(props)} key={props.key as Key}>
{children}
</span>
);
}
return onElement?.(element, props, children, extra);
}
return undefined;
},
[onElement, textHasCustomEmoji],
);
return ( const html = (
<EmojiHTML <EmojiHTML
as={as} as='span'
htmlString={textEmojified} htmlString={textEmojified}
title={showTitleOnLength(text, titleLength)}
className={className} className={className}
onElement={handleElement} onElement={handleElement}
data-contents
{...props} {...props}
/> />
); );
if (!isOverflowing) {
return html;
}
return (
<>
{html}
<IconButton
icon='ellipsis'
iconComponent={MoreIcon}
title={intl.formatMessage({
id: 'account.field_overflow',
defaultMessage: 'Show full content',
})}
className={classes.fieldOverflowButton}
onClick={onOverflowClick}
/>
</>
);
}; };
function filterAttributesForSpan(props: Record<string, unknown>) { function useColumnWrap() {
const validAttributes: Record<string, unknown> = {}; const listRef = useRef<HTMLDListElement | null>(null);
for (const key of Object.keys(props)) {
if (key in htmlConfig.tags.span.attributes) { const handleRecalculate = useCallback(() => {
validAttributes[key] = props[key]; const listEle = listRef.current;
if (!listEle) {
return;
} }
}
return validAttributes; // Calculate dimensions from styles and element size to determine column spans.
const styles = getComputedStyle(listEle);
const gap = parseFloat(styles.columnGap || styles.gap || '0');
const columnCount = parseInt(styles.getPropertyValue('--cols')) || 2;
const listWidth = listEle.offsetWidth;
const colWidth = (listWidth - gap * (columnCount - 1)) / columnCount;
// Matrix to hold the grid layout.
const itemGrid: { ele: HTMLElement; span: number }[][] = [];
// First, determine the column span for each item and populate the grid matrix.
let currentRow = 0;
for (const child of listEle.children) {
if (!(child instanceof HTMLElement)) {
continue;
}
// This uses a data attribute to detect which elements to measure that overflow.
const contents = child.querySelectorAll('[data-contents]');
const childStyles = getComputedStyle(child);
const padding =
parseFloat(childStyles.paddingLeft) +
parseFloat(childStyles.paddingRight);
const contentWidth =
Math.max(
...Array.from(contents).map((content) => content.scrollWidth),
) + padding;
const contentSpan = Math.ceil(contentWidth / colWidth);
const maxColSpan = Math.min(contentSpan, columnCount);
const curRow = itemGrid[currentRow] ?? [];
const availableCols =
columnCount - curRow.reduce((carry, curr) => carry + curr.span, 0);
// Move to next row if current item doesn't fit.
if (maxColSpan > availableCols) {
currentRow++;
}
itemGrid[currentRow] = (itemGrid[currentRow] ?? []).concat({
ele: child,
span: maxColSpan,
});
}
// Next, iterate through the grid matrix and set the column spans and row breaks.
for (const row of itemGrid) {
let remainingRowSpan = columnCount;
for (let i = 0; i < row.length; i++) {
const item = row[i];
if (!item) {
break;
}
const { ele, span } = item;
if (i < row.length - 1) {
ele.dataset.cols = span.toString();
remainingRowSpan -= span;
} else {
// Last item in the row takes up remaining space to fill the row.
ele.dataset.cols = remainingRowSpan.toString();
break;
}
}
}
}, []);
const observer = useResizeObserver(handleRecalculate);
const wrapperRefCallback = useCallback(
(element: HTMLDListElement | null) => {
if (element) {
listRef.current = element;
observer.observe(element);
}
},
[observer],
);
return { wrapperRef: wrapperRefCallback };
} }
function showTitleOnLength(value: string | null, maxLength: number) { function useFieldOverflow() {
if (value && value.length > maxLength) { const [isLabelOverflowing, setIsLabelOverflowing] = useState(false);
return value; const [isValueOverflowing, setIsValueOverflowing] = useState(false);
}
return undefined; const wrapperRef = useRef<HTMLElement | null>(null);
const handleRecalculate = useCallback(() => {
const wrapperEle = wrapperRef.current;
if (!wrapperEle) return;
const wrapperStyles = getComputedStyle(wrapperEle);
const maxWidth =
wrapperEle.offsetWidth -
(parseFloat(wrapperStyles.paddingLeft) +
parseFloat(wrapperStyles.paddingRight));
const label = wrapperEle.querySelector<HTMLSpanElement>(
'dt > [data-contents]',
);
const value = wrapperEle.querySelector<HTMLSpanElement>(
'dd > [data-contents]',
);
setIsLabelOverflowing(label ? label.scrollWidth > maxWidth : false);
setIsValueOverflowing(value ? value.scrollWidth > maxWidth : false);
}, []);
const observer = useResizeObserver(handleRecalculate);
const wrapperRefCallback = useCallback(
(element: HTMLElement | null) => {
if (element) {
wrapperRef.current = element;
observer.observe(element);
}
},
[observer],
);
return {
isLabelOverflowing,
isValueOverflowing,
wrapperRef: wrapperRefCallback,
};
} }

View File

@ -214,64 +214,90 @@ svg.badgeIcon {
} }
.fieldList { .fieldList {
--cols: 4;
position: relative;
display: grid; display: grid;
grid-template-columns: 160px 1fr; grid-template-columns: repeat(var(--cols), 1fr);
column-gap: 12px; gap: 12px;
margin: 16px 0; margin: 16px 0;
border-top: 0.5px solid var(--color-border-primary);
@container (width < 420px) { @container (width < 420px) {
grid-template-columns: 100px 1fr; --cols: 2;
} }
} }
.fieldRow { .fieldItem {
display: grid; --col-span: 1;
grid-column: 1 / -1;
align-items: start;
grid-template-columns: subgrid;
padding: 8px;
border-bottom: 0.5px solid var(--color-border-primary);
> :is(dt, dd) { grid-column: span var(--col-span);
&:not(.fieldShowAll) { position: relative;
display: -webkit-box;
-webkit-box-orient: vertical; @for $col from 2 through 4 {
-webkit-line-clamp: 2; &[data-cols='#{$col}'] {
line-clamp: 2; --col-span: #{$col};
overflow: hidden;
text-overflow: ellipsis;
} }
} }
> dt { dt {
color: var(--color-text-secondary); font-weight: normal;
} }
> dd { dd {
display: flex; font-weight: 500;
align-items: center;
gap: 4px;
} }
a { :is(dt, dd) {
color: inherit; text-overflow: initial;
text-decoration: none;
&:hover, // Override the MiniCard link styles
&:focus { a {
text-decoration: underline; color: inherit;
font-weight: inherit;
&:hover,
&:focus {
color: inherit;
text-decoration: underline;
}
} }
} }
} }
.fieldVerified { .fieldVerified {
background-color: var(--color-bg-success-softer); background-color: var(--color-bg-success-softer);
dt {
padding-right: 24px;
}
} }
.fieldVerifiedIcon { .fieldVerifiedIcon {
width: 16px; width: 16px;
height: 16px; height: 16px;
position: absolute;
top: 8px;
right: 8px;
}
.fieldOverflowButton {
--default-bg-color: var(--color-bg-secondary-solid);
--hover-bg-color: color-mix(
in oklab,
var(--color-bg-brand-base),
var(--default-bg-color) var(--overlay-strength-brand)
);
position: absolute;
right: 8px;
padding: 0 2px;
transition: background-color 0.2s ease-in-out;
border: 2px solid var(--color-bg-primary);
> svg {
width: 16px;
height: 12px;
}
} }
.fieldNumbersWrapper { .fieldNumbersWrapper {

View File

@ -5,23 +5,15 @@ import { FormattedMessage } from 'react-intl';
import type { NavLinkProps } from 'react-router-dom'; import type { NavLinkProps } from 'react-router-dom';
import { NavLink } from 'react-router-dom'; import { NavLink } from 'react-router-dom';
import { useLayout } from '@/flavours/glitch/hooks/useLayout';
import { isRedesignEnabled } from '../common'; import { isRedesignEnabled } from '../common';
import classes from './redesign.module.scss'; import classes from './redesign.module.scss';
export const AccountTabs: FC<{ acct: string }> = ({ acct }) => { export const AccountTabs: FC<{ acct: string }> = ({ acct }) => {
const { layout } = useLayout();
if (isRedesignEnabled()) { if (isRedesignEnabled()) {
return ( return (
<div className={classes.tabs}> <div className={classes.tabs}>
{layout !== 'single-column' && ( <NavLink isActive={isActive} to={`/@${acct}`}>
<NavLink exact to={`/@${acct}/about`}>
<FormattedMessage id='account.about' defaultMessage='About' />
</NavLink>
)}
<NavLink isActive={isActive} to={`/@${acct}/posts`}>
<FormattedMessage id='account.activity' defaultMessage='Activity' /> <FormattedMessage id='account.activity' defaultMessage='Activity' />
</NavLink> </NavLink>
<NavLink exact to={`/@${acct}/media`}> <NavLink exact to={`/@${acct}/media`}>

View File

@ -0,0 +1,38 @@
import type { Key } from 'react';
import { useCallback } from 'react';
import htmlConfig from '@/config/html-tags.json';
import type { OnElementHandler } from '@/flavours/glitch/utils/html';
export function useFieldHtml(
hasCustomEmoji: boolean,
onElement?: OnElementHandler,
): OnElementHandler {
return useCallback(
(element, props, children, extra) => {
if (element instanceof HTMLAnchorElement) {
// Don't allow custom emoji and links in the same field to prevent verification spoofing.
if (hasCustomEmoji) {
return (
<span {...filterAttributesForSpan(props)} key={props.key as Key}>
{children}
</span>
);
}
return onElement?.(element, props, children, extra);
}
return undefined;
},
[onElement, hasCustomEmoji],
);
}
function filterAttributesForSpan(props: Record<string, unknown>) {
const validAttributes: Record<string, unknown> = {};
for (const key of Object.keys(props)) {
if (key in htmlConfig.tags.span.attributes) {
validAttributes[key] = props[key];
}
}
return validAttributes;
}

View File

@ -0,0 +1,44 @@
import type { FC } from 'react';
import { FormattedMessage } from 'react-intl';
import { EmojiHTML } from '@/flavours/glitch/components/emoji/html';
import type { AccountField } from '../common';
import { useFieldHtml } from '../hooks/useFieldHtml';
import classes from './styles.module.css';
export const AccountFieldModal: FC<{
onClose: () => void;
field: AccountField;
}> = ({ onClose, field }) => {
const handleLabelElement = useFieldHtml(field.nameHasEmojis);
const handleValueElement = useFieldHtml(field.valueHasEmojis);
return (
<div className='modal-root__modal safety-action-modal'>
<div className='safety-action-modal__top'>
<div className='safety-action-modal__confirmation'>
<EmojiHTML
as='p'
htmlString={field.name_emojified}
onElement={handleLabelElement}
/>
<EmojiHTML
as='p'
htmlString={field.value_emojified}
onElement={handleValueElement}
className={classes.fieldValue}
/>
</div>
</div>
<div className='safety-action-modal__bottom'>
<div className='safety-action-modal__actions'>
<button onClick={onClose} className='link-button' type='button'>
<FormattedMessage id='lightbox.close' defaultMessage='Close' />
</button>
</div>
</div>
</div>
);
};

View File

@ -13,7 +13,7 @@ import { useAppDispatch, useAppSelector } from '@/flavours/glitch/store';
import { ConfirmationModal } from '../../ui/components/confirmation_modals'; import { ConfirmationModal } from '../../ui/components/confirmation_modals';
import classes from './modals.module.css'; import classes from './styles.module.css';
const messages = defineMessages({ const messages = defineMessages({
newTitle: { newTitle: {

View File

@ -19,3 +19,9 @@
outline: var(--outline-focus-default); outline: var(--outline-focus-default);
outline-offset: 2px; outline-offset: 2px;
} }
.fieldValue {
color: var(--color-text-primary);
font-weight: 600;
margin-top: 4px;
}

View File

@ -100,6 +100,7 @@ export const MODAL_COMPONENTS = {
'ANNUAL_REPORT': AnnualReportModal, 'ANNUAL_REPORT': AnnualReportModal,
'COMPOSE_PRIVACY': () => Promise.resolve({ default: VisibilityModal }), 'COMPOSE_PRIVACY': () => Promise.resolve({ default: VisibilityModal }),
'ACCOUNT_NOTE': () => import('@/flavours/glitch/features/account_timeline/modals/note_modal').then(module => ({ default: module.AccountNoteModal })), 'ACCOUNT_NOTE': () => import('@/flavours/glitch/features/account_timeline/modals/note_modal').then(module => ({ default: module.AccountNoteModal })),
'ACCOUNT_FIELD_OVERFLOW': () => import('@/flavours/glitch/features/account_timeline/modals/field_modal').then(module => ({ default: module.AccountFieldModal })),
'ACCOUNT_EDIT_NAME': () => import('@/flavours/glitch/features/account_edit/components/name_modal').then(module => ({ default: module.NameModal })), 'ACCOUNT_EDIT_NAME': () => import('@/flavours/glitch/features/account_edit/components/name_modal').then(module => ({ default: module.NameModal })),
'ACCOUNT_EDIT_BIO': () => import('@/flavours/glitch/features/account_edit/components/bio_modal').then(module => ({ default: module.BioModal })), 'ACCOUNT_EDIT_BIO': () => import('@/flavours/glitch/features/account_edit/components/bio_modal').then(module => ({ default: module.BioModal })),
}; };

View File

@ -25,7 +25,7 @@ import { layoutFromWindow } from 'flavours/glitch/is_mobile';
import { selectUnreadNotificationGroupsCount } from 'flavours/glitch/selectors/notifications'; import { selectUnreadNotificationGroupsCount } from 'flavours/glitch/selectors/notifications';
import { WithRouterPropTypes } from 'flavours/glitch/utils/react_router'; import { WithRouterPropTypes } from 'flavours/glitch/utils/react_router';
import { checkAnnualReport } from '@/flavours/glitch/reducers/slices/annual_report'; import { checkAnnualReport } from '@/flavours/glitch/reducers/slices/annual_report';
import { isClientFeatureEnabled, isServerFeatureEnabled } from '@/flavours/glitch/utils/environment'; import { isClientFeatureEnabled } from '@/flavours/glitch/utils/environment';
import { uploadCompose, resetCompose, changeComposeSpoilerness } from '../../actions/compose'; import { uploadCompose, resetCompose, changeComposeSpoilerness } from '../../actions/compose';
import { clearHeight } from '../../actions/height_cache'; import { clearHeight } from '../../actions/height_cache';
@ -83,7 +83,6 @@ import {
PrivacyPolicy, PrivacyPolicy,
TermsOfService, TermsOfService,
AccountFeatured, AccountFeatured,
AccountAbout,
AccountEdit, AccountEdit,
AccountEditFeaturedTags, AccountEditFeaturedTags,
Quotes, Quotes,
@ -174,36 +173,6 @@ class SwitchingColumnsArea extends PureComponent {
} }
const profileRedesignRoutes = []; const profileRedesignRoutes = [];
if (isServerFeatureEnabled('profile_redesign')) {
profileRedesignRoutes.push(
<WrappedRoute key="posts" path={['/@:acct/posts', '/accounts/:id/posts']} exact component={AccountTimeline} content={children} />,
);
// Check if we're in single-column mode. Confusingly, the singleColumn prop includes mobile.
if (this.props.layout === 'single-column') {
// When in single column mode (desktop w/o advanced view), redirect both the root and about to the posts tab.
profileRedesignRoutes.push(
<Redirect key="acct-redirect" from='/@:acct' to='/@:acct/posts' exact />,
<Redirect key="id-redirect" from='/accounts/:id' to='/accounts/:id/posts' exact />,
<Redirect key="about-acct-redirect" from='/@:acct/about' to='/@:acct/posts' exact />,
<Redirect key="about-id-redirect" from='/accounts/:id/about' to='/accounts/:id/posts' exact />,
);
} else {
// Otherwise, provide and redirect to the /about page.
profileRedesignRoutes.push(
<WrappedRoute key="about" path={['/@:acct/about', '/accounts/:id/about']} component={AccountAbout} content={children} />,
<Redirect key="acct-redirect" from='/@:acct' to='/@:acct/about' exact />,
<Redirect key="id-redirect" from='/accounts/:id' to='/accounts/:id/about' exact />
);
}
} else {
profileRedesignRoutes.push(
<WrappedRoute path={['/@:acct', '/accounts/:id']} exact component={AccountTimeline} content={children} />,
// If the redesign is not enabled but someone shares an /about link, redirect to the root.
<Redirect key="about-acct-redirect" from='/@:acct/about' to='/@:acct' exact />,
<Redirect key="about-id-redirect" from='/accounts/:id/about' to='/accounts/:id' exact />
);
}
if (isClientFeatureEnabled('profile_editing')) { if (isClientFeatureEnabled('profile_editing')) {
profileRedesignRoutes.push( profileRedesignRoutes.push(
<WrappedRoute key="edit" path='/profile/edit' component={AccountEdit} content={children} />, <WrappedRoute key="edit" path='/profile/edit' component={AccountEdit} content={children} />,
@ -265,6 +234,7 @@ class SwitchingColumnsArea extends PureComponent {
{...profileRedesignRoutes} {...profileRedesignRoutes}
<WrappedRoute path={['/@:acct', '/accounts/:id']} exact component={AccountTimeline} content={children} />
<WrappedRoute path={['/@:acct/featured', '/accounts/:id/featured']} component={AccountFeatured} content={children} /> <WrappedRoute path={['/@:acct/featured', '/accounts/:id/featured']} component={AccountFeatured} content={children} />
<WrappedRoute path='/@:acct/tagged/:tagged?' exact component={AccountTimeline} content={children} /> <WrappedRoute path='/@:acct/tagged/:tagged?' exact component={AccountTimeline} content={children} />
<WrappedRoute path={['/@:acct/with_replies', '/accounts/:id/with_replies']} component={AccountTimeline} content={children} componentParams={{ withReplies: true }} /> <WrappedRoute path={['/@:acct/with_replies', '/accounts/:id/with_replies']} component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />

View File

@ -93,11 +93,6 @@ export function AccountFeatured() {
return import('../../account_featured'); return import('../../account_featured');
} }
export function AccountAbout() {
return import('../../account_about')
.then((module) => ({ default: module.AccountAbout }));
}
export function AccountEdit() { export function AccountEdit() {
return import('../../account_edit') return import('../../account_edit')
.then((module) => ({ default: module.AccountEdit })); .then((module) => ({ default: module.AccountEdit }));

View File

@ -0,0 +1,29 @@
import { useEffect, useRef } from 'react';
export function useResizeObserver(callback: ResizeObserverCallback) {
const observerRef = useRef<ResizeObserver | null>(null);
observerRef.current ??= new ResizeObserver(callback);
useEffect(() => {
const observer = observerRef.current;
return () => {
observer?.disconnect();
};
}, []);
return observerRef.current;
}
export function useMutationObserver(callback: MutationCallback) {
const observerRef = useRef<MutationObserver | null>(null);
observerRef.current ??= new MutationObserver(callback);
useEffect(() => {
const observer = observerRef.current;
return () => {
observer?.disconnect();
};
}, []);
return observerRef.current;
}

View File

@ -1,6 +1,8 @@
import type { MutableRefObject, RefCallback } from 'react'; import type { MutableRefObject, RefCallback } from 'react';
import { useState, useRef, useCallback, useEffect } from 'react'; import { useState, useRef, useCallback, useEffect } from 'react';
import { useMutationObserver, useResizeObserver } from './useObserver';
/** /**
* Hook to manage overflow of items in a container with a "more" button. * Hook to manage overflow of items in a container with a "more" button.
* *
@ -182,48 +184,30 @@ export function useOverflowObservers({
// This is the item container element. // This is the item container element.
const listRef = useRef<HTMLElement | null>(null); const listRef = useRef<HTMLElement | null>(null);
// Set up observers to watch for size and content changes. const resizeObserver = useResizeObserver(onRecalculate);
const resizeObserverRef = useRef<ResizeObserver | null>(null);
const mutationObserverRef = useRef<MutationObserver | null>(null);
// Helper to get or create the resize observer.
const resizeObserver = useCallback(() => {
const observer = (resizeObserverRef.current ??= new ResizeObserver(
onRecalculate,
));
return observer;
}, [onRecalculate]);
// Iterate through children and observe them for size changes. // Iterate through children and observe them for size changes.
const handleChildrenChange = useCallback(() => { const handleChildrenChange = useCallback(() => {
const listEle = listRef.current; const listEle = listRef.current;
const observer = resizeObserver();
if (listEle) { if (listEle) {
for (const child of listEle.children) { for (const child of listEle.children) {
if (child instanceof HTMLElement) { if (child instanceof HTMLElement) {
observer.observe(child); resizeObserver.observe(child);
} }
} }
} }
onRecalculate(); onRecalculate();
}, [onRecalculate, resizeObserver]); }, [onRecalculate, resizeObserver]);
// Helper to get or create the mutation observer. const mutationObserver = useMutationObserver(handleChildrenChange);
const mutationObserver = useCallback(() => {
const observer = (mutationObserverRef.current ??= new MutationObserver(
handleChildrenChange,
));
return observer;
}, [handleChildrenChange]);
// Set up observers. // Set up observers.
const handleObserve = useCallback(() => { const handleObserve = useCallback(() => {
if (wrapperRef.current) { if (wrapperRef.current) {
resizeObserver().observe(wrapperRef.current); resizeObserver.observe(wrapperRef.current);
} }
if (listRef.current) { if (listRef.current) {
mutationObserver().observe(listRef.current, { childList: true }); mutationObserver.observe(listRef.current, { childList: true });
handleChildrenChange(); handleChildrenChange();
} }
}, [handleChildrenChange, mutationObserver, resizeObserver]); }, [handleChildrenChange, mutationObserver, resizeObserver]);
@ -233,12 +217,12 @@ export function useOverflowObservers({
const wrapperRefCallback = useCallback( const wrapperRefCallback = useCallback(
(node: HTMLElement | null) => { (node: HTMLElement | null) => {
if (node) { if (node) {
wrapperRef.current = node; wrapperRef.current = node; // eslint-disable-line react-hooks/immutability -- https://github.com/facebook/react/issues/34955
handleObserve(); handleObserve();
if (typeof onWrapperRef === 'function') { if (typeof onWrapperRef === 'function') {
onWrapperRef(node); onWrapperRef(node);
} else if (onWrapperRef && 'current' in onWrapperRef) { } else if (onWrapperRef && 'current' in onWrapperRef) {
onWrapperRef.current = node; onWrapperRef.current = node; // eslint-disable-line react-hooks/immutability -- https://github.com/facebook/react/issues/34955
} }
} }
}, },
@ -254,28 +238,13 @@ export function useOverflowObservers({
if (typeof onListRef === 'function') { if (typeof onListRef === 'function') {
onListRef(node); onListRef(node);
} else if (onListRef && 'current' in onListRef) { } else if (onListRef && 'current' in onListRef) {
onListRef.current = node; onListRef.current = node; // eslint-disable-line react-hooks/immutability -- https://github.com/facebook/react/issues/34955
} }
} }
}, },
[handleObserve, onListRef], [handleObserve, onListRef],
); );
useEffect(() => {
handleObserve();
return () => {
if (resizeObserverRef.current) {
resizeObserverRef.current.disconnect();
resizeObserverRef.current = null;
}
if (mutationObserverRef.current) {
mutationObserverRef.current.disconnect();
mutationObserverRef.current = null;
}
};
}, [handleObserve]);
return { return {
wrapperRefCallback, wrapperRefCallback,
listRefCallback, listRefCallback,