Merge pull request #4441 from urbit/james/chatmessage

chat: ChatMessage spacing refactor
This commit is contained in:
matildepark 2021-02-19 14:50:06 -05:00 committed by GitHub
commit e9a9863b22
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 449 additions and 390 deletions

View File

@ -1,3 +1,4 @@
/* eslint-disable max-lines-per-function */
import React, {
useState,
useEffect,
@ -17,7 +18,14 @@ import {
useShowNickname,
useHovering
} from '~/logic/lib/util';
import { Group, Association, Contacts, Post, Groups, Associations } from '@urbit/api';
import {
Group,
Association,
Contacts,
Post,
Groups,
Associations
} from '~/types';
import TextContent from './content/text';
import CodeContent from './content/code';
import RemoteContent from '~/views/components/RemoteContent';
@ -28,34 +36,47 @@ import Timestamp from '~/views/components/Timestamp';
export const DATESTAMP_FORMAT = '[~]YYYY.M.D';
export const UnreadMarker = React.forwardRef(({ dayBreak, when }, ref) => (
<Row
flexShrink={0}
ref={ref}
color='blue'
alignItems='center'
fontSize='0'
position='absolute'
width='100%'
py='2'
>
<Rule borderColor='blue' display={['none', 'block']} m='0' width='2rem' />
<Text flexShrink='0' display='block' zIndex='2' mx='4' color='blue'>
New messages below
</Text>
<Rule borderColor='blue' flexGrow='1' m='0' />
<Rule style={{ width: 'calc(50% - 48px)' }} borderColor='blue' m='0' />
</Row>
));
interface DayBreakProps {
when: string;
shimTop?: boolean;
}
export const DayBreak = ({ when }) => (
<Row pb='3' alignItems='center' justifyContent='center' width='100%'>
<Text gray>
export const DayBreak = ({ when, shimTop = false }: DayBreakProps) => (
<Row
px={2}
height={5}
mb={2}
justifyContent='center'
alignItems='center'
mt={shimTop ? '-8px' : '0'}
>
<Rule borderColor='lightGray' />
<Text gray flexShrink='0' fontSize={0} px={2}>
{moment(when).calendar(null, { sameElse: DATESTAMP_FORMAT })}
</Text>
<Rule borderColor='lightGray' />
</Row>
);
export const UnreadMarker = React.forwardRef(({ dayBreak, when }, ref) => (
<Row
position='absolute'
ref={ref}
px={2}
mt={2}
height={5}
justifyContent='center'
alignItems='center'
width='100%'
>
<Rule borderColor='lightBlue' />
<Text color='blue' fontSize={0} flexShrink='0' px={2}>
New messages below
</Text>
<Rule borderColor='lightBlue' />
</Row>
));
interface ChatMessageProps {
measure(element): void;
msg: Post;
@ -74,6 +95,7 @@ interface ChatMessageProps {
history: unknown;
api: GlobalApi;
highlighted?: boolean;
renderSigil?: boolean;
}
export default class ChatMessage extends Component<ChatMessageProps> {
@ -114,19 +136,26 @@ export default class ChatMessage extends Component<ChatMessageProps> {
associations
} = this.props;
const renderSigil = Boolean(
(nextMsg && msg.author !== nextMsg.author) || !nextMsg || msg.number === 1
);
let { renderSigil } = this.props;
if (renderSigil === undefined) {
renderSigil = Boolean(
(nextMsg && msg.author !== nextMsg.author) ||
!nextMsg ||
msg.number === 1
);
}
const dayBreak =
nextMsg &&
new Date(msg['time-sent']).getDate() !==
new Date(nextMsg['time-sent']).getDate();
const containerClass = `${
renderSigil ? 'cf pl2 lh-copy' : 'items-top cf hide-child'
} ${isPending ? 'o-40' : ''} ${className}`;
const containerClass = `${isPending ? 'o-40' : ''} ${className}`;
const timestamp = moment.unix(msg['time-sent'] / 1000);
const timestamp = moment
.unix(msg['time-sent'] / 1000)
.format(renderSigil ? 'h:mm A' : 'h:mm');
const reboundMeasure = (event) => {
return measure(this.divRef.current);
@ -157,34 +186,24 @@ export default class ChatMessage extends Component<ChatMessageProps> {
return (
<Box
bg={highlighted ? 'washedBlue' : 'white'}
flexShrink={0}
width='100%'
display='flex'
flexWrap='wrap'
pt={this.props.pt ? this.props.pt : renderSigil ? 3 : 0}
pr={3}
pb={isLastMessage ? 3 : 0}
ref={this.divRef}
pt={renderSigil ? 2 : 0}
pb={2}
className={containerClass}
style={style}
mb={1}
position='relative'
>
{dayBreak && !isLastRead ? <DayBreak when={msg['time-sent']} /> : null}
{dayBreak && !isLastRead ? (
<DayBreak when={msg['time-sent']} shimTop={renderSigil} />
) : null}
{renderSigil ? (
<MessageWithSigil {...messageProps} />
<>
<MessageAuthor pb={'2px'} {...messageProps} />
<Message pl={5} pr={3} {...messageProps} />
</>
) : (
<MessageWithoutSigil {...messageProps} />
<Message pl={5} pr={3} timestampHover {...messageProps} />
)}
<Box
flexShrink={0}
fontSize={0}
position='relative'
width='100%'
overflow='visible'
style={unreadContainerStyle}
>
<Box style={unreadContainerStyle}>
{isLastRead ? (
<UnreadMarker
dayBreak={dayBreak}
@ -198,40 +217,25 @@ export default class ChatMessage extends Component<ChatMessageProps> {
}
}
interface MessageProps {
msg: Post;
timestamp: string;
group: Group;
association: Association;
contacts: Contacts;
containerClass: string;
isPending: boolean;
style: any;
measure(element): void;
scrollWindow: HTMLDivElement;
associations: Associations;
groups: Groups;
}
export const MessageAuthor = ({
timestamp,
contacts,
msg,
measure,
group,
api,
associations,
groups,
scrollWindow,
...rest
}) => {
const dark = useLocalState((state) => state.dark);
export const MessageWithSigil = (props) => {
const {
msg,
contacts,
association,
associations,
groups,
group,
measure,
api,
history,
scrollWindow,
fontSize
} = props;
const dark = useLocalState(state => state.dark);
const stamp = moment.unix(msg['time-sent'] / 1000);
const contact = `~${msg.author}` in contacts ? contacts[`~${msg.author}`] : false;
const datestamp = moment
.unix(msg['time-sent'] / 1000)
.format(DATESTAMP_FORMAT);
const contact =
`~${msg.author}` in contacts ? contacts[`~${msg.author}`] : false;
const showNickname = useShowNickname(contact);
const { hideAvatars } =
useLocalState(({ hideAvatars }) =>
@ -255,7 +259,7 @@ export const MessageWithSigil = (props) => {
const [showOverlay, setShowOverlay] = useState(false);
const toggleOverlay = () => {
setShowOverlay(value => !value);
setShowOverlay((value) => !value);
};
const showCopyNotice = () => {
@ -289,17 +293,16 @@ export const MessageWithSigil = (props) => {
padding={2}
/>
);
return (
<>
<Box display='flex' alignItems='center' {...rest}>
<Box
onClick={() => {
setShowOverlay(true);
}}
className='fl v-top pt1'
height={16}
pr={3}
pr={2}
pl={2}
cursor='pointer'
position='relative'
>
{showOverlay && (
@ -328,11 +331,11 @@ export const MessageWithSigil = (props) => {
>
<Text
fontSize={0}
mr={3}
mr={2}
flexShrink={0}
mono={nameMono}
fontWeight={nameMono ? '400' : '500'}
className={'mw5 db truncate pointer'}
className={'pointer'}
onClick={() => {
writeText(`~${msg.author}`);
showCopyNotice();
@ -341,36 +344,25 @@ export const MessageWithSigil = (props) => {
>
{displayName}
</Text>
<Timestamp stamp={stamp} fontSize={0}/>
<Text flexShrink={0} fontSize={0} gray>
{timestamp}
</Text>
<Text
flexShrink={0}
fontSize={0}
gray
ml={2}
display={['none', hovering ? 'block' : 'none']}
>
{datestamp}
</Text>
</Box>
<ContentBox flexShrink={0} fontSize={fontSize ? fontSize : '14px'}>
{msg.contents.map((c, i) => (
<MessageContent
key={i}
contacts={contacts}
content={c}
measure={measure}
scrollWindow={scrollWindow}
fontSize={fontSize}
group={group}
api={api}
associations={associations}
groups={groups}
/>
))}
</ContentBox>
</Box>
</>
</Box>
);
};
const ContentBox = styled(Box)`
& > :first-child {
margin-left: 0px;
}
`;
export const MessageWithoutSigil = ({
export const Message = ({
timestamp,
contacts,
msg,
@ -379,115 +371,95 @@ export const MessageWithoutSigil = ({
api,
associations,
groups,
scrollWindow
scrollWindow,
timestampHover,
...rest
}) => {
const { hovering, bind } = useHovering();
return (
<>
<Timestamp
stamp={timestamp}
date={false}
display={hovering ? 'block' : 'none'}
pt='2px'
lineHeight='tall'
position='absolute'
left={1}
/>
<ContentBox
flexShrink={0}
fontSize='14px'
className='clamp-message'
style={{ flexGrow: 1 }}
{...bind}
pl={6}
>
{msg.contents.map((c, i) => (
<MessageContent
key={i}
contacts={contacts}
content={c}
group={group}
measure={measure}
scrollWindow={scrollWindow}
groups={groups}
associations={associations}
api={api}
/>
))}
</ContentBox>
</>
);
};
export const MessageContent = ({
content,
contacts,
api,
associations,
groups,
measure,
scrollWindow,
fontSize,
group
}) => {
if ('code' in content) {
return <CodeContent content={content} />;
} else if ('url' in content) {
return (
<Box
mx='2px'
flexShrink={0}
fontSize={fontSize ? fontSize : '14px'}
lineHeight='tall'
color='black'
>
<RemoteContent
url={content.url}
onLoad={measure}
imageProps={{
style: {
maxWidth: 'min(100%,18rem)',
display: 'block'
}
}}
videoProps={{
style: {
maxWidth: '18rem',
display: 'block'
}
}}
textProps={{
style: {
fontSize: 'inherit',
borderBottom: '1px solid',
textDecoration: 'none'
}
}}
/>
<Box position='relative' {...rest}>
{timestampHover ? (
<Text
display={hovering ? 'block' : 'none'}
position='absolute'
left='0'
top='3px'
fontSize={0}
gray
>
{timestamp}
</Text>
) : (
<></>
)}
<Box {...bind}>
{msg.contents.map((content, i) => {
switch (Object.keys(content)[0]) {
case 'text':
return (
<TextContent
associations={associations}
groups={groups}
measure={measure}
api={api}
fontSize={1}
lineHeight={'20px'}
content={content}
/>
);
case 'code':
return <CodeContent content={content} />;
case 'url':
return (
<Box
flexShrink={0}
fontSize={1}
lineHeight='20px'
color='black'
>
<RemoteContent
url={content.url}
onLoad={measure}
imageProps={{
style: {
maxWidth: 'min(100%,18rem)',
display: 'inline-block',
marginTop: '0.5rem'
}
}}
videoProps={{
style: {
maxWidth: '18rem',
display: 'block',
marginTop: '0.5rem'
}
}}
textProps={{
style: {
fontSize: 'inherit',
borderBottom: '1px solid',
textDecoration: 'none'
}
}}
/>
</Box>
);
case 'mention':
return (
<Mention
group={group}
scrollWindow={scrollWindow}
ship={content.mention}
contact={contacts?.[`~${content.mention}`]}
/>
);
default:
return null;
}
})}
</Box>
);
} else if ('text' in content) {
return (
<TextContent
associations={associations}
groups={groups}
measure={measure}
api={api}
fontSize={fontSize}
content={content}
/>);
} else if ('mention' in content) {
return (
<Mention
group={group}
scrollWindow={scrollWindow}
ship={content.mention}
contact={contacts?.[`~${content.mention}`]}
/>
);
} else {
return null;
}
</Box>
);
};
export const MessagePlaceholder = ({

View File

@ -4,7 +4,15 @@ import _ from 'lodash';
import bigInt, { BigInteger } from 'big-integer';
import { Col } from '@tlon/indigo-react';
import { Patp, Contacts, Association, Associations, Group, Groups, Graph } from '@urbit/api';
import {
Patp,
Contacts,
Association,
Associations,
Group,
Groups,
Graph
} from '@urbit/api';
import GlobalApi from '~/logic/api/global';
@ -33,7 +41,7 @@ type ChatWindowProps = RouteComponentProps<{
scrollTo?: number;
associations: Associations;
groups: Groups;
}
};
interface ChatWindowState {
fetchPending: boolean;
@ -42,7 +50,10 @@ interface ChatWindowState {
unreadIndex: BigInteger;
}
export default class ChatWindow extends Component<ChatWindowProps, ChatWindowState> {
export default class ChatWindow extends Component<
ChatWindowProps,
ChatWindowState
> {
private virtualList: VirtualScroller | null;
private unreadMarkerRef: React.RefObject<HTMLDivElement>;
private prevSize = 0;
@ -79,7 +90,7 @@ export default class ChatWindow extends Component<ChatWindowProps, ChatWindowSta
window.addEventListener('blur', this.handleWindowBlur);
window.addEventListener('focus', this.handleWindowFocus);
setTimeout(() => {
if(this.props.scrollTo) {
if (this.props.scrollTo) {
this.scrollToUnread();
}
@ -95,7 +106,7 @@ export default class ChatWindow extends Component<ChatWindowProps, ChatWindowSta
calculateUnreadIndex() {
const { graph, unreadCount } = this.props;
const unreadIndex = graph.keys()[unreadCount];
if(!unreadIndex || unreadCount === 0) {
if (!unreadIndex || unreadCount === 0) {
this.setState({
unreadIndex: bigInt.zero
});
@ -128,8 +139,8 @@ export default class ChatWindow extends Component<ChatWindowProps, ChatWindowSta
this.calculateUnreadIndex();
}
if(this.prevSize !== graph.size) {
if(this.state.unreadIndex.eq(bigInt.zero)) {
if (this.prevSize !== graph.size) {
if (this.state.unreadIndex.eq(bigInt.zero)) {
this.calculateUnreadIndex();
this.scrollToUnread();
}
@ -153,7 +164,7 @@ export default class ChatWindow extends Component<ChatWindowProps, ChatWindowSta
scrollToUnread() {
const { unreadIndex } = this.state;
if(unreadIndex.eq(bigInt.zero)) {
if (unreadIndex.eq(bigInt.zero)) {
return;
}
@ -162,10 +173,8 @@ export default class ChatWindow extends Component<ChatWindowProps, ChatWindowSta
dismissUnread() {
const { association } = this.props;
if (this.state.fetchPending)
return;
if (this.props.unreadCount === 0)
return;
if (this.state.fetchPending) return;
if (this.props.unreadCount === 0) return;
this.props.api.hark.markCountAsRead(association, '/', 'message');
this.props.api.hark.markCountAsRead(association, '/', 'mention');
}
@ -173,26 +182,31 @@ return;
async fetchMessages(newer: boolean, force = false): Promise<void> {
const { api, station, graph } = this.props;
if ( this.state.fetchPending && !force) {
return new Promise((resolve, reject) => {});
if (this.state.fetchPending && !force) {
return new Promise((resolve, reject) => {});
}
this.setState({ fetchPending: true });
const [,, ship, name] = station.split('/');
const [, , ship, name] = station.split('/');
const currSize = graph.size;
if(newer && !this.loadedNewest) {
if (newer && !this.loadedNewest) {
const [index] = graph.peekLargest()!;
await api.graph.getYoungerSiblings(ship,name, 20, `/${index.toString()}`);
if(currSize === graph.size) {
await api.graph.getYoungerSiblings(
ship,
name,
20,
`/${index.toString()}`
);
if (currSize === graph.size) {
console.log('loaded all newest');
this.loadedNewest = true;
}
} else if(!newer && !this.loadedOldest) {
} else if (!newer && !this.loadedOldest) {
const [index] = graph.peekSmallest()!;
await api.graph.getOlderSiblings(ship,name, 20, `/${index.toString()}`);
await api.graph.getOlderSiblings(ship, name, 20, `/${index.toString()}`);
this.calculateUnreadIndex();
if(currSize === graph.size) {
if (currSize === graph.size) {
console.log('loaded all oldest');
this.loadedOldest = true;
}
@ -209,17 +223,14 @@ return;
}
dismissIfLineVisible() {
if (this.props.unreadCount === 0)
return;
if (!this.unreadMarkerRef.current || !this.virtualList?.window)
return;
if (this.props.unreadCount === 0) return;
if (!this.unreadMarkerRef.current || !this.virtualList?.window) return;
const parent = this.unreadMarkerRef.current.parentElement?.parentElement;
if (!parent)
return;
if (!parent) return;
const { scrollTop, scrollHeight, offsetHeight } = this.virtualList.window;
if (
(scrollHeight - parent.offsetTop > scrollTop)
&& (scrollHeight - parent.offsetTop < scrollTop + offsetHeight)
scrollHeight - parent.offsetTop > scrollTop &&
scrollHeight - parent.offsetTop < scrollTop + offsetHeight
) {
this.dismissUnread();
}
@ -241,26 +252,39 @@ return;
} = this.props;
const unreadMarkerRef = this.unreadMarkerRef;
const messageProps = { association, group, contacts, unreadMarkerRef, history, api, groups, associations };
const messageProps = {
association,
group,
contacts,
unreadMarkerRef,
history,
api,
groups,
associations
};
const keys = graph.keys().reverse();
const unreadIndex = graph.keys()[this.props.unreadCount];
const unreadMsg = unreadIndex && graph.get(unreadIndex);
return (
<Col height='100%' overflow='hidden' position="relative">
<Col height='100%' overflow='hidden' position='relative'>
<UnreadNotice
unreadCount={unreadCount}
unreadMsg={unreadCount === 1 && unreadMsg && unreadMsg?.post.author === window.ship ? false : unreadMsg}
unreadMsg={
unreadCount === 1 &&
unreadMsg &&
unreadMsg?.post.author === window.ship
? false
: unreadMsg
}
dismissUnread={this.dismissUnread}
onClick={this.scrollToUnread}
/>
<VirtualScroller
ref={(list) => {
this.virtualList = list;
}}
origin="bottom"
this.virtualList = list;
}}
origin='bottom'
style={{ height: '100%' }}
onStartReached={() => {
this.setState({ idle: false });
@ -271,20 +295,35 @@ return;
size={graph.size}
renderer={({ index, measure, scrollWindow }) => {
const msg = graph.get(index)?.post;
if (!msg)
return null;
if (!msg) return null;
if (!this.state.initialized) {
return <MessagePlaceholder key={index.toString()} height="64px" index={index} />;
return (
<MessagePlaceholder
key={index.toString()}
height='64px'
index={index}
/>
);
}
const isPending: boolean = 'pending' in msg && Boolean(msg.pending);
const isLastMessage = index.eq(graph.peekLargest()?.[0] ?? bigInt.zero);
const isLastMessage = index.eq(
graph.peekLargest()?.[0] ?? bigInt.zero
);
const highlighted = bigInt(this.props.scrollTo || -1).eq(index);
const graphIdx = keys.findIndex(idx => idx.eq(index));
const prevIdx = keys[graphIdx+1];
const nextIdx = keys[graphIdx-1];
const graphIdx = keys.findIndex((idx) => idx.eq(index));
const prevIdx = keys[graphIdx + 1];
const nextIdx = keys[graphIdx - 1];
const isLastRead: boolean = this.state.unreadIndex.eq(index);
const props = { measure, highlighted, scrollWindow, isPending, isLastRead, isLastMessage, msg, ...messageProps };
const props = {
measure,
highlighted,
scrollWindow,
isPending,
isLastRead,
isLastMessage,
msg,
...messageProps
};
return (
<ChatMessage
key={index.toString()}
@ -302,4 +341,3 @@ return null;
);
}
}

View File

@ -4,7 +4,7 @@ import ReactMarkdown from 'react-markdown';
import RemarkDisableTokenizers from 'remark-disable-tokenizers';
import urbitOb from 'urbit-ob';
import { Text } from '@tlon/indigo-react';
import { GroupLink } from "~/views/components/GroupLink";
import { GroupLink } from '~/views/components/GroupLink';
const DISABLED_BLOCK_TOKENS = [
'indentedCode',
@ -26,44 +26,60 @@ const DISABLED_INLINE_TOKENS = [
];
const renderers = {
inlineCode: ({language, value}) => {
return <Text mono p='1' backgroundColor='washedGray' fontSize='0' style={{ whiteSpace: 'preWrap'}}>{value}</Text>
inlineCode: ({ language, value }) => {
return (
<Text
mono
p='1'
backgroundColor='washedGray'
fontSize='0'
style={{ whiteSpace: 'preWrap' }}
>
{value}
</Text>
);
},
paragraph: ({ children }) => {
return (<Text fontSize="1">{children}</Text>);
return (
<Text fontSize='1' lineHeight={'20px'}>
{children}
</Text>
);
},
code: ({language, value}) => {
return <Text
p='1'
className='clamp-message'
display='block'
borderRadius='1'
mono
fontSize='0'
backgroundColor='washedGray'
overflowX='auto'
style={{ whiteSpace: 'pre'}}>
{value}
</Text>
code: ({ language, value }) => {
return (
<Text
p='1'
className='clamp-message'
display='block'
borderRadius='1'
mono
fontSize='0'
backgroundColor='washedGray'
overflowX='auto'
style={{ whiteSpace: 'pre' }}
>
{value}
</Text>
);
}
};
const MessageMarkdown = React.memo(props => {
const MessageMarkdown = React.memo((props) => {
const { source, ...rest } = props;
const blockCode = source.split('```');
const codeLines = blockCode.map(codes => codes.split("\n"));
const codeLines = blockCode.map((codes) => codes.split('\n'));
const lines = codeLines.reduce((acc, val, i) => {
if((i % 2) === 1) {
if (i % 2 === 1) {
return [...acc, `\`\`\`${val.join('\n')}\`\`\``];
} else {
return [...acc, ...val];
}
}, []);
return lines.map((line, i) => (
<>
{ i !== 0 && <br />}
{i !== 0 && <br />}
<ReactMarkdown
{...rest}
source={line}
@ -71,25 +87,31 @@ const MessageMarkdown = React.memo(props => {
renderers={renderers}
allowNode={(node, index, parent) => {
if (
node.type === 'blockquote'
&& parent.type === 'root'
&& node.children.length
&& node.children[0].type === 'paragraph'
&& node.children[0].position.start.offset < 2
node.type === 'blockquote' &&
parent.type === 'root' &&
node.children.length &&
node.children[0].type === 'paragraph' &&
node.children[0].position.start.offset < 2
) {
node.children[0].children[0].value = '>' + node.children[0].children[0].value;
node.children[0].children[0].value =
'>' + node.children[0].children[0].value;
return false;
}
return true;
}}
plugins={[[RemarkDisableTokenizers, {
block: DISABLED_BLOCK_TOKENS,
inline: DISABLED_INLINE_TOKENS
}]]}
/>
plugins={[
[
RemarkDisableTokenizers,
{
block: DISABLED_BLOCK_TOKENS,
inline: DISABLED_INLINE_TOKENS
}
]
]}
/>
</>
))
));
});
export default function TextContent(props) {
@ -98,12 +120,13 @@ export default function TextContent(props) {
const group = content.text.match(
/([~][/])?(~[a-z]{3,6})(-[a-z]{6})?([/])(([a-z0-9-])+([/-])?)+/
);
const isGroupLink = ((group !== null) // matched possible chatroom
&& (group[2].length > 2) // possible ship?
&& (urbitOb.isValidPatp(group[2]) // valid patp?
&& (group[0] === content.text))) // entire message is room name?
const isGroupLink =
group !== null && // matched possible chatroom
group[2].length > 2 && // possible ship?
urbitOb.isValidPatp(group[2]) && // valid patp?
group[0] === content.text; // entire message is room name?
if(isGroupLink) {
if (isGroupLink) {
const resource = `/ship/${content.text}`;
return (
<GroupLink
@ -120,7 +143,13 @@ export default function TextContent(props) {
);
} else {
return (
<Text mx="2px" flexShrink={0} color='black' fontSize={props.fontSize ? props.fontSize : '14px'} lineHeight="tall" style={{ overflowWrap: 'break-word' }}>
<Text
flexShrink={0}
color='black'
fontSize={props.fontSize ? props.fontSize : '14px'}
lineHeight={props.lineHeight ? props.lineHeight : '20px'}
style={{ overflowWrap: 'break-word' }}
>
<MessageMarkdown source={content.text} />
</Text>
);

View File

@ -1,28 +1,27 @@
import React, { ReactElement, useCallback } from 'react';
import React, { ReactNode, useCallback } from 'react';
import moment from 'moment';
import _ from 'lodash';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
import { Row, Box, Col, Text, Anchor, Icon, Action } from '@tlon/indigo-react';
import { Link, useHistory } from 'react-router-dom';
import _ from 'lodash';
import {
GraphNotifIndex,
GraphNotificationContents,
Associations,
Rolodex,
Groups
} from '@urbit/api';
} from '~/types';
import { Header } from './header';
import { cite, deSig, pluralize } from '~/logic/lib/util';
import { Sigil } from '~/logic/lib/sigil';
import RichText from '~/views/components/RichText';
import GlobalApi from '~/logic/api/global';
import ReactMarkdown from 'react-markdown';
import { getSnippet } from '~/logic/lib/publish';
import styled from 'styled-components';
import { MentionText } from '~/views/components/MentionText';
import { MessageWithoutSigil } from '../chat/components/ChatMessage';
import Timestamp from '~/views/components/Timestamp';
import ChatMessage from '../chat/components/ChatMessage';
function getGraphModuleIcon(module: string): string {
function getGraphModuleIcon(module: string) {
if (module === 'link') {
return 'Collection';
}
@ -58,16 +57,24 @@ function describeNotification(description: string, plural: boolean): string {
}
}
const GraphUrl = ({ url, title }): ReactElement => (
<Box borderRadius="2" p="2" bg="scales.black05">
<Anchor underline={false} target="_blank" color="black" href={url}>
<Icon verticalAlign="bottom" mr="2" icon="ArrowExternal" />
const GraphUrl = ({ url, title }) => (
<Box borderRadius='2' p='2' bg='scales.black05'>
<Anchor underline={false} target='_blank' color='black' href={url}>
<Icon verticalAlign='bottom' mr='2' icon='ArrowExternal' />
{title}
</Anchor>
</Box>
);
const GraphNodeContent = ({ group, post, contacts, mod, index }): ReactElement => {
const GraphNodeContent = ({
group,
post,
contacts,
mod,
description,
index,
remoteContentPolicy
}) => {
const { contents } = post;
const idx = index.slice(1).split('/');
if (mod === 'link') {
@ -75,39 +82,39 @@ const GraphNodeContent = ({ group, post, contacts, mod, index }): ReactElement =
const [{ text }, { url }] = contents;
return <GraphUrl title={text} url={url} />;
} else if (idx.length === 3) {
return <MentionText
content={contents}
contacts={contacts}
group={group}
/>;
return (
<MentionText content={contents} contacts={contacts} group={group} />
);
}
return null;
}
if (mod === 'publish') {
if (idx[1] === '2') {
return <MentionText
content={contents}
group={group}
contacts={contacts}
fontSize='14px'
lineHeight="tall"
/>;
return (
<MentionText
content={contents}
group={group}
contacts={contacts}
fontSize='14px'
lineHeight='tall'
/>
);
} else if (idx[1] === '1') {
const [{ text: header }, { text: body }] = contents;
const snippet = getSnippet(body);
return (
<Col>
<Box mb="2" fontWeight="500">
<Box mb='2' fontWeight='500'>
<Text>{header}</Text>
</Box>
<Box overflow="hidden" maxHeight="400px" position="relative">
<Text lineHeight="tall">{snippet}</Text>
<Box overflow='hidden' maxHeight='400px' position='relative'>
<Text lineHeight='tall'>{snippet}</Text>
<FilterBox
width="100%"
zIndex="1"
height="calc(100% - 2em)"
bottom="-4px"
position="absolute"
width='100%'
zIndex='1'
height='calc(100% - 2em)'
bottom='-4px'
position='absolute'
/>
</Box>
</Col>
@ -115,31 +122,40 @@ const GraphNodeContent = ({ group, post, contacts, mod, index }): ReactElement =
}
}
if(mod === 'chat') {
if (mod === 'chat') {
return (
<Row
width="100%"
flexShrink={0}
flexGrow={1}
flexWrap="wrap"
width='100%'
flexShrink={0}
flexGrow={1}
flexWrap='wrap'
marginLeft='-32px'
>
<MessageWithoutSigil
containerClass="items-top cf hide-child"
measure={() => {}}
group={group}
contacts={contacts}
groups={{}}
associations={{ graph: {}, groups: {} }}
msg={post}
fontSize='0'
pt='2'
/>
</Row>);
<ChatMessage
renderSigil={false}
containerClass='items-top cf hide-child'
measure={() => {}}
group={group}
contacts={contacts}
groups={{}}
associations={{ graph: {}, groups: {} }}
msg={post}
fontSize='0'
pt='2'
/>
</Row>
);
}
return null;
};
function getNodeUrl(mod: string, hidden: boolean, groupPath: string, graph: string, index: string): string {
function getNodeUrl(
mod: string,
hidden: boolean,
groupPath: string,
graph: string,
index: string
) {
if (hidden && mod === 'chat') {
groupPath = '/messages';
} else if (hidden) {
@ -181,40 +197,46 @@ const GraphNode = ({
ship={`~${author}`}
size={16}
icon
color={'#000000'}
classes="mix-blend-diff"
color={`#000000`}
classes='mix-blend-diff'
padding={2}
/>
) : <Box style={{ width: '16px' }}></Box>;
) : (
<Box style={{ width: '16px' }}></Box>
);
const groupContacts = contacts[groupPath] ?? {};
const nodeUrl = getNodeUrl(mod, group?.hidden, groupPath, graph, index);
const onClick = useCallback(() => {
if(!read) {
if (!read) {
onRead();
}
history.push(nodeUrl);
}, [read, onRead]);
return (
<Row onClick={onClick} gapX="2" pt={showContact ? 2 : 0}>
<Row onClick={onClick} gapX='2' pt={showContact ? 2 : 0}>
<Col>{img}</Col>
<Col flexGrow={1} alignItems="flex-start">
{showContact && <Row
mb="2"
height="16px"
alignItems="center"
p="1"
backgroundColor="white"
>
<Text mono title={author}>
{cite(author)}
</Text>
<Timestamp stamp={moment(time)} date={false} ml={2} />
</Row>}
<Row width="100%" p="1" flexDirection="column">
<Col flexGrow={1} alignItems='flex-start'>
{showContact && (
<Row
mb='2'
height='16px'
alignItems='center'
p='1'
backgroundColor='white'
>
<Text mono title={author}>
{cite(author)}
</Text>
<Text ml='2' gray>
{moment(time).format('HH:mm')}
</Text>
</Row>
)}
<Row width='100%' p='1' flexDirection='column'>
<GraphNodeContent
contacts={groupContacts}
post={post}
@ -256,7 +278,7 @@ export function GraphNotification(props: {
return api.hark['read'](timebox, { graph: index });
}, [api, timebox, index, read]);
return (
return (
<>
<Header
onClick={onClick}
@ -271,7 +293,7 @@ return (
description={desc}
associations={props.associations}
/>
<Box flexGrow={1} width="100%" pl={5} gridArea="main">
<Box flexGrow={1} width='100%' pl={5} gridArea='main'>
{_.map(contents, (content, idx) => (
<GraphNode
post={content}

View File

@ -48,21 +48,19 @@ export function Mention(props: {
const group = props.group ?? { hidden: true };
const [showOverlay, setShowOverlay] = useState(false);
const toggleOverlay = useCallback(
() => {
setShowOverlay(value => !value);
},
[showOverlay]
);
const toggleOverlay = useCallback(() => {
setShowOverlay((value) => !value);
}, [showOverlay]);
return (
<Box position='relative' display='inline-block' cursor='pointer'>
<Text
onClick={() => toggleOverlay()}
mx='2px'
px='2px'
mx={1}
px={1}
bg='washedBlue'
color='blue'
fontSize={showNickname ? 1 : 0}
mono={!showNickname}
>
{name}