Merge pull request #4823 from urbit/lf/more-virt-perf

VirtualScroller: performance enhancements
This commit is contained in:
matildepark 2021-04-27 16:46:19 -04:00 committed by GitHub
commit 6bf0bf82cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 453 additions and 445 deletions

View File

@ -5,7 +5,7 @@
/- glob
/+ default-agent, verb, dbug
|%
++ hash 0v3.g6u13.haedt.jt4hd.61ek5.6t30q
++ hash 0v3.hls3k.gsbae.rm6pr.p6qve.46dh8
+$ state-0 [%0 hash=@uv glob=(unit (each glob:glob tid=@ta))]
+$ all-states
$% state-0

View File

@ -24,6 +24,6 @@
<div id="portal-root"></div>
<script src="/~landscape/js/channel.js"></script>
<script src="/~landscape/js/session.js"></script>
<script src="/~landscape/js/bundle/index.59e682153138f604d358.js"></script>
<script src="/~landscape/js/bundle/index.b253f1f3f824fdeb29d3.js"></script>
</body>
</html>

View File

@ -43,8 +43,8 @@ export function useVirtualResizeState(s: boolean) {
[_setState, save]
);
useLayoutEffect(() => {
restore();
useEffect(() => {
requestAnimationFrame(restore);
}, [state]);
return [state, setState] as const;
@ -58,7 +58,7 @@ export function useVirtualResizeProp(prop: Primitive) {
save();
}
useLayoutEffect(() => {
useEffect(() => {
requestAnimationFrame(restore);
}, [prop]);

View File

@ -1,5 +1,6 @@
import _ from 'lodash';
import BigIntOrderedMap from "@urbit/api/lib/BigIntOrderedMap";
import produce from 'immer';
import bigInt, { BigInteger } from "big-integer";
import useGraphState, { GraphState } from '../state/graph';
import { reduceState } from '../state/base';
@ -51,23 +52,18 @@ const keys = (json, state: GraphState): GraphState => {
const processNode = (node) => {
// is empty
if (!node.children) {
node.children = new BigIntOrderedMap();
return node;
return produce(node, draft => {
draft.children = new BigIntOrderedMap();
});
}
// is graph
let converted = new BigIntOrderedMap();
for (let idx in node.children) {
let item = node.children[idx];
let index = bigInt(idx);
converted.set(
index,
processNode(item)
);
}
node.children = converted;
return node;
return produce(node, draft => {
draft.children = new BigIntOrderedMap()
.gas(_.map(draft.children, (item, idx) =>
[bigInt(idx), processNode(item)] as [BigInteger, any]
));
});
};
@ -85,17 +81,10 @@ const addGraph = (json, state: GraphState): GraphState => {
state.graphTimesentMap[resource] = {};
for (let idx in data.graph) {
let item = data.graph[idx];
let index = bigInt(idx);
state.graphs[resource] = state.graphs[resource].gas(Object.keys(data.graph).map(idx => {
return [bigInt(idx), processNode(data.graph[idx])];
}));
let node = processNode(item);
state.graphs[resource].set(
index,
node
);
}
state.graphKeys.add(resource);
}
return state;
@ -116,7 +105,7 @@ const removeGraph = (json, state: GraphState): GraphState => {
};
const mapifyChildren = (children) => {
return new BigIntOrderedMap(
return new BigIntOrderedMap().gas(
_.map(children, (node, idx) => {
idx = idx && idx.startsWith('/') ? idx.slice(1) : idx;
const nd = {...node, children: mapifyChildren(node.children || {}) };
@ -128,8 +117,7 @@ const addNodes = (json, state) => {
const _addNode = (graph, index, node) => {
// set child of graph
if (index.length === 1) {
graph.set(index[0], node);
return graph;
return graph.set(index[0], node);
}
// set parent of graph
@ -138,19 +126,20 @@ const addNodes = (json, state) => {
console.error('parent node does not exist, cannot add child');
return graph;
}
parNode.children = _addNode(parNode.children, index.slice(1), node);
graph.set(index[0], parNode);
return graph;
return graph.set(index[0], produce(parNode, draft => {
draft.children = _addNode(draft.children, index.slice(1), node);
}));
};
const _remove = (graph, index) => {
if (index.length === 1) {
graph.delete(index[0]);
return graph.delete(index[0]);
} else {
const child = graph.get(index[0]);
if (child) {
child.children = _remove(child.children, index.slice(1));
graph.set(index[0], child);
return graph.set(index[0], produce(child, draft => {
draft.children = _remove(draft.children, index.slice(1));
}));
}
}
@ -166,10 +155,9 @@ const addNodes = (json, state) => {
return bigInt(ind);
});
graph = _remove(graph, indexArr);
delete state.graphTimesentMap[resource][timestamp];
return _remove(graph, indexArr);
}
return graph;
};
@ -208,11 +196,12 @@ const addNodes = (json, state) => {
return aArr.length - bArr.length;
});
let graph = state.graphs[resource];
indices.forEach((index) => {
let node = data.nodes[index];
graph = _removePending(graph, node.post, resource);
const old = state.graphs[resource].size;
state.graphs[resource] = _removePending(state.graphs[resource], node.post, resource);
const newSize = state.graphs[resource].size;
if (index.split('/').length === 0) { return; }
let indexArr = index.split('/').slice(1).map((ind) => {
@ -225,17 +214,21 @@ const addNodes = (json, state) => {
state.graphTimesentMap[resource][node.post['time-sent']] = index;
}
node.children = mapifyChildren(node?.children || {});
graph = _addNode(
graph,
state.graphs[resource] = _addNode(
state.graphs[resource],
indexArr,
node
produce(node, draft => {
draft.children = mapifyChildren(draft?.children || {});
})
);
if(newSize !== old) {
console.log(`${resource}, (${old}, ${newSize}, ${state.graphs[resource].size})`);
}
});
state.graphs[resource] = graph;
}
return state;
};
@ -243,13 +236,15 @@ const addNodes = (json, state) => {
const removeNodes = (json, state: GraphState): GraphState => {
const _remove = (graph, index) => {
if (index.length === 1) {
graph.delete(index[0]);
return graph.delete(index[0]);
} else {
const child = graph.get(index[0]);
if (child) {
_remove(child.children, index.slice(1));
graph.set(index[0], child);
return graph.set(index[0], produce(draft => {
draft.children = _remove(draft.children, index.slice(1))
}));
}
return graph;
}
};
@ -264,7 +259,7 @@ const removeNodes = (json, state: GraphState): GraphState => {
let indexArr = index.split('/').slice(1).map((ind) => {
return bigInt(ind);
});
_remove(state.graphs[res], indexArr);
state.graphs[res] = _remove(state.graphs[res], indexArr);
});
}
return state;

View File

@ -329,9 +329,9 @@ function added(json: any, state: HarkState): HarkState {
);
if (arrIdx !== -1) {
timebox[arrIdx] = { index, notification };
state.notifications.set(time, timebox);
state.notifications = state.notifications.set(time, timebox);
} else {
state.notifications.set(time, [...timebox, { index, notification }]);
state.notifications = state.notifications.set(time, [...timebox, { index, notification }]);
}
}
return state;
@ -350,7 +350,7 @@ const timebox = (json: any, state: HarkState): HarkState => {
if (data) {
const time = makePatDa(data.time);
if (!data.archive) {
state.notifications.set(time, data.notifications);
state.notifications = state.notifications.set(time, data.notifications);
}
}
return state;
@ -403,7 +403,7 @@ function setRead(
return state;
}
timebox[arrIdx].notification.read = read;
state.notifications.set(patDa, timebox);
state.notifications = state.notifications.set(patDa, timebox);
return state;
}

View File

@ -128,6 +128,8 @@ const useGraphState = createState<GraphState>('Graph', {
// });
// graphReducer(node);
// },
}, ['graphs', 'graphKeys', 'looseNodes']);
}, ['graphs', 'graphKeys', 'looseNodes', 'graphTimesentMap']);
window.useGraphState = useGraphState;
export default useGraphState;

View File

@ -28,9 +28,9 @@ type ChatResourceProps = StoreState & {
association: Association;
api: GlobalApi;
baseUrl: string;
} & RouteComponentProps;
};
export function ChatResource(props: ChatResourceProps) {
function ChatResource(props: ChatResourceProps) {
const station = props.association.resource;
const groupPath = props.association.group;
const groups = useGroupState(state => state.groups);
@ -40,7 +40,7 @@ export function ChatResource(props: ChatResourceProps) {
const graphPath = station.slice(7);
const graph = graphs[graphPath];
const unreads = useHarkState(state => state.unreads);
const unreadCount = unreads.graph?.[station]?.['/']?.unreads || 0;
const unreadCount = unreads.graph?.[station]?.['/']?.unreads as number || 0;
const graphTimesentMap = useGraphState(state => state.graphTimesentMap);
const [,, owner, name] = station.split('/');
const ourContact = contacts?.[`~${window.ship}`];
@ -48,7 +48,7 @@ export function ChatResource(props: ChatResourceProps) {
const canWrite = isWriter(group, station);
useEffect(() => {
const count = 100 + unreadCount;
const count = Math.min(400, 100 + unreadCount);
props.api.graph.getNewest(owner, name, count);
}, [station]);
@ -165,10 +165,9 @@ export function ChatResource(props: ChatResourceProps) {
{dragging && <SubmitDragger />}
<ChatWindow
key={station}
history={props.history}
graph={graph}
graphSize={graph.size}
unreadCount={unreadCount}
unreadCount={unreadCount as number}
showOurContact={ !showBanner && hasLoadedAllowed }
association={props.association}
pendingSize={Object.keys(graphTimesentMap[graphPath] || {}).length}
@ -196,3 +195,8 @@ export function ChatResource(props: ChatResourceProps) {
</Col>
);
}
ChatResource.whyDidYouRender = true;
export { ChatResource };

View File

@ -3,6 +3,7 @@ import bigInt from 'big-integer';
import React, {
useState,
useEffect,
useMemo,
useRef,
Component,
PureComponent,
@ -40,11 +41,12 @@ import styled from 'styled-components';
import useLocalState from '~/logic/state/local';
import useSettingsState, { selectCalmState } from '~/logic/state/settings';
import Timestamp from '~/views/components/Timestamp';
import useContactState from '~/logic/state/contact';
import useContactState, {useContact} from '~/logic/state/contact';
import { useIdlingState } from '~/logic/lib/idling';
import ProfileOverlay from '~/views/components/ProfileOverlay';
import {useCopy} from '~/logic/lib/useCopy';
import {GraphContentWide} from '~/views/landscape/components/Graph/GraphContentWide';
import {Contact} from '@urbit/api';
export const DATESTAMP_FORMAT = '[~]YYYY.M.D';
@ -80,7 +82,7 @@ export const DayBreak = ({ when, shimTop = false }: DayBreakProps) => (
);
export const UnreadMarker = React.forwardRef(
({ dayBreak, when, api, association }, ref) => {
({ dayBreak, when, api, association }: any, ref) => {
const [visible, setVisible] = useState(false);
const idling = useIdlingState();
const dismiss = useCallback(() => {
@ -141,7 +143,7 @@ const MessageActionItem = (props) => {
);
};
const MessageActions = ({ api, onReply, association, history, msg, group }) => {
const MessageActions = ({ api, onReply, association, msg, group }) => {
const isAdmin = () => group.tags.role.admin.has(window.ship);
const isOwn = () => msg.author === window.ship;
const { doCopy, copyDisplay } = useCopy(`web+urbitgraph://group${association.group.slice(5)}/graph${association.resource.slice(5)}${msg.index}`, 'Copy Message Link');
@ -241,29 +243,18 @@ interface ChatMessageProps {
className?: string;
isPending: boolean;
style?: unknown;
scrollWindow: HTMLDivElement;
isLastMessage?: boolean;
unreadMarkerRef: React.RefObject<HTMLDivElement>;
history: unknown;
api: GlobalApi;
highlighted?: boolean;
renderSigil?: boolean;
hideHover?: boolean;
innerRef: (el: HTMLDivElement | null) => void;
onReply?: (msg: Post) => void;
showOurContact: boolean;
}
class ChatMessage extends Component<ChatMessageProps> {
private divRef: React.RefObject<HTMLDivElement>;
constructor(props) {
super(props);
this.divRef = React.createRef();
}
componentDidMount() {}
render() {
function ChatMessage(props: ChatMessageProps) {
let { highlighted } = this.props;
const {
msg,
@ -275,15 +266,20 @@ class ChatMessage extends Component<ChatMessageProps> {
className = '',
isPending,
style,
scrollWindow,
isLastMessage,
unreadMarkerRef,
history,
api,
showOurContact,
fontSize,
hideHover
} = this.props;
} = props;
let onReply = props?.onReply ?? (() => {});
const transcluded = props?.transcluded ?? 0;
const renderSigil = props.renderSigil ?? (Boolean(nextMsg && msg.author !== nextMsg.author) ||
!nextMsg ||
msg.number === 1
);
const ourMention = msg?.contents?.some((e) => {
return e?.mention && e?.mention === window.ship;
@ -295,46 +291,35 @@ class ChatMessage extends Component<ChatMessageProps> {
}
}
let onReply = this.props?.onReply ?? (() => {});
const transcluded = this.props?.transcluded ?? 0;
let { renderSigil } = this.props;
if (renderSigil === undefined) {
renderSigil = Boolean(
(nextMsg && msg.author !== nextMsg.author) ||
!nextMsg ||
msg.number === 1
);
}
const date = daToUnix(bigInt(msg.index.split('/')[1]));
const nextDate = nextMsg ? (
const date = useMemo(() => daToUnix(bigInt(msg.index.split('/')[1])), [msg.index]);
const nextDate = useMemo(() => nextMsg ? (
daToUnix(bigInt(nextMsg.index.split('/')[1]))
) : null;
) : null,
[nextMsg]
);
const dayBreak =
nextMsg &&
const dayBreak = useMemo(() =>
nextDate &&
new Date(date).getDate() !==
new Date(nextDate).getDate();
new Date(nextDate).getDate()
, [nextDate, date])
const containerClass = `${isPending ? 'o-40' : ''} ${className}`;
const timestamp = moment
const timestamp = useMemo(() => moment
.unix(date / 1000)
.format(renderSigil ? 'h:mm A' : 'h:mm');
.format(renderSigil ? 'h:mm A' : 'h:mm'),
[date, renderSigil]
);
const messageProps = {
msg,
timestamp,
association,
group,
style,
containerClass,
isPending,
showOurContact,
history,
api,
scrollWindow,
highlighted,
fontSize,
hideHover,
@ -342,13 +327,24 @@ class ChatMessage extends Component<ChatMessageProps> {
onReply
};
const message = useMemo(() => (
<Message
msg={msg}
timestamp={timestamp}
timestampHover={!renderSigil}
api={api}
transcluded={transcluded}
showOurContact={showOurContact}
/>
), [renderSigil, msg, timestamp, api, transcluded, showOurContact]);
const unreadContainerStyle = {
height: isLastRead ? '2rem' : '0'
};
return (
<Box
ref={this.props.innerRef}
ref={props.innerRef}
pt={renderSigil ? 2 : 0}
width="100%"
pb={isLastMessage ? '20px' : 0}
@ -361,11 +357,11 @@ class ChatMessage extends Component<ChatMessageProps> {
{renderSigil ? (
<MessageWrapper {...messageProps}>
<MessageAuthor pb={1} {...messageProps} />
<Message pl={'44px'} pr={4} {...messageProps} />
{message}
</MessageWrapper>
) : (
<MessageWrapper {...messageProps}>
<Message pl={'44px'} pr={4} timestampHover {...messageProps} />
{message}
</MessageWrapper>
)}
<Box style={unreadContainerStyle}>
@ -382,39 +378,33 @@ class ChatMessage extends Component<ChatMessageProps> {
</Box>
);
}
}
export default React.forwardRef((props, ref) => (
export default React.forwardRef((props: Omit<ChatMessageProps, 'innerRef'>, ref: any) => (
<ChatMessage {...props} innerRef={ref} />
));
export const MessageAuthor = ({
timestamp,
msg,
group,
api,
history,
scrollWindow,
showOurContact,
...rest
}) => {
const osDark = useLocalState((state) => state.dark);
const theme = useSettingsState((s) => s.display.theme);
const dark = theme === 'dark' || (theme === 'auto' && osDark);
const contacts = useContactState((state) => state.contacts);
let contact: Contact | null = useContact(`~${msg.author}`);
const date = daToUnix(bigInt(msg.index.split('/')[1]));
const datestamp = moment
.unix(date / 1000)
.format(DATESTAMP_FORMAT);
const contact =
contact =
((msg.author === window.ship && showOurContact) ||
msg.author !== window.ship) &&
`~${msg.author}` in contacts
? contacts[`~${msg.author}`]
: undefined;
msg.author !== window.ship)
? contact
: null;
const showNickname = useShowNickname(contact);
const { hideAvatars } = useSettingsState(selectCalmState);
@ -467,7 +457,7 @@ export const MessageAuthor = ({
</Box>
);
return (
<Box display='flex' alignItems='flex-start' {...rest}>
<Box display='flex' alignItems='flex-start'>
<Box
height={24}
pr={2}
@ -519,20 +509,20 @@ export const MessageAuthor = ({
);
};
export const Message = ({
type MessageProps = { timestamp: string; timestampHover: boolean; }
& Pick<ChatMessageProps, "msg" | "api" | "transcluded" | "showOurContact">
export const Message = React.memo(({
timestamp,
msg,
group,
api,
scrollWindow,
timestampHover,
transcluded,
showOurContact,
...rest
}) => {
showOurContact
}: MessageProps) => {
const { hovering, bind } = useHovering();
return (
<Box width="100%" position='relative' {...rest}>
<Box pl="44px" width="100%" position='relative'>
{timestampHover ? (
<Text
display={hovering ? 'block' : 'none'}
@ -559,7 +549,9 @@ export const Message = ({
/>
</Box>
);
};
});
Message.displayName = 'Message';
export const MessagePlaceholder = ({
height,

View File

@ -1,4 +1,4 @@
import React, { Component } from 'react';
import React, { useEffect, Component, useRef, useState, useCallback } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import _ from 'lodash';
import bigInt, { BigInteger } from 'big-integer';
@ -30,10 +30,13 @@ const DEFAULT_BACKLOG_SIZE = 100;
const IDLE_THRESHOLD = 64;
const MAX_BACKLOG_SIZE = 1000;
type ChatWindowProps = RouteComponentProps<{
ship: Patp;
station: string;
}> & {
const getCurrGraphSize = (ship: string, name: string) => {
const { graphs } = useGraphState.getState();
const graph = graphs[`${ship}/${name}`];
return graph.size;
};
type ChatWindowProps = {
unreadCount: number;
graph: Graph;
graphSize: number;
@ -44,6 +47,8 @@ type ChatWindowProps = RouteComponentProps<{
api: GlobalApi;
scrollTo?: BigInteger;
onReply: (msg: Post) => void;
pendingSize?: number;
showOurContact: boolean;
};
interface ChatWindowState {
@ -55,6 +60,7 @@ interface ChatWindowState {
const virtScrollerStyle = { height: '100%' };
class ChatWindow extends Component<
ChatWindowProps,
ChatWindowState
@ -81,6 +87,7 @@ class ChatWindow extends Component<
this.handleWindowBlur = this.handleWindowBlur.bind(this);
this.handleWindowFocus = this.handleWindowFocus.bind(this);
this.stayLockedIfActive = this.stayLockedIfActive.bind(this);
this.fetchMessages = this.fetchMessages.bind(this);
this.virtualList = null;
this.unreadMarkerRef = React.createRef();
@ -109,9 +116,11 @@ class ChatWindow extends Component<
}
const unreadIndex = graph.keys()[unreadCount];
if (!unreadIndex || unreadCount === 0) {
if(state.unreadIndex.neq(bigInt.zero)) {
this.setState({
unreadIndex: bigInt.zero
});
}
return;
}
this.setState({
@ -122,7 +131,7 @@ class ChatWindow extends Component<
dismissedInitialUnread() {
const { unreadCount, graph } = this.props;
return this.state.unreadIndex.neq(bigInt.zero) &&
return this.state.unreadIndex.eq(bigInt.zero) ? unreadCount > graph.size :
this.state.unreadIndex.neq(graph.keys()?.[unreadCount]?.[0] ?? bigInt.zero);
}
@ -138,7 +147,7 @@ class ChatWindow extends Component<
}
componentDidUpdate(prevProps: ChatWindowProps, prevState) {
const { history, graph, unreadCount, graphSize, station } = this.props;
const { graph, unreadCount, graphSize, station } = this.props;
if(unreadCount === 0 && prevProps.unreadCount !== unreadCount) {
this.unreadSet = true;
}
@ -195,31 +204,35 @@ class ChatWindow extends Component<
this.props.api.hark.markCountAsRead(association, '/', 'message');
}
setActive = () => {
if(this.state.idle) {
this.setState({ idle: false });
}
}
fetchMessages = async (newer: boolean): Promise<boolean> => {
async fetchMessages(newer: boolean): Promise<boolean> {
const { api, station, graph } = this.props;
const pageSize = 100;
const [, , ship, name] = station.split('/');
const expectedSize = graph.size + pageSize;
if (newer) {
const [index] = graph.peekLargest()!;
const index = graph.peekLargest()?.[0];
if(!index) {
console.log(`no index for: ${graph}`);
return true;
}
await api.graph.getYoungerSiblings(
ship,
name,
pageSize,
`/${index.toString()}`
);
return expectedSize !== graph.size;
return expectedSize !== getCurrGraphSize(ship.slice(1), name);
} else {
const [index] = graph.peekSmallest()!;
console.log('x');
const index = graph.peekSmallest()?.[0];
if(!index) {
console.log(`no index for: ${graph}`);
return true;
}
await api.graph.getOlderSiblings(ship, name, pageSize, `/${index.toString()}`);
const done = expectedSize !== graph.size;
const done = expectedSize !== getCurrGraphSize(ship.slice(1), name);
if(done) {
this.calculateUnreadIndex();
}
@ -238,12 +251,9 @@ class ChatWindow extends Component<
const {
api,
association,
group,
showOurContact,
graph,
history,
groups,
associations,
group,
onReply
} = this.props;
const { unreadMarkerRef } = this;
@ -252,10 +262,8 @@ class ChatWindow extends Component<
group,
showOurContact,
unreadMarkerRef,
history,
api,
groups,
associations,
group,
onReply
};
@ -275,10 +283,10 @@ class ChatWindow extends Component<
graph.peekLargest()?.[0] ?? bigInt.zero
);
const highlighted = index.eq(this.props.scrollTo ?? bigInt.zero);
const keys = graph.keys().reverse();
const keys = graph.keys();
const graphIdx = keys.findIndex((idx) => idx.eq(index));
const prevIdx = keys[graphIdx + 1];
const nextIdx = keys[graphIdx - 1];
const prevIdx = keys[graphIdx - 1];
const nextIdx = keys[graphIdx + 1];
const isLastRead: boolean = this.state.unreadIndex.eq(index);
const props = {
highlighted,
@ -308,12 +316,8 @@ class ChatWindow extends Component<
association,
group,
graph,
history,
groups,
associations,
showOurContact,
pendingSize,
onReply,
pendingSize = 0,
} = this.props;
const unreadMarkerRef = this.unreadMarkerRef;
@ -321,16 +325,10 @@ class ChatWindow extends Component<
association,
group,
unreadMarkerRef,
history,
api,
associations
};
const unreadMsg = graph.get(this.state.unreadIndex);
// hack to force a re-render when we toggle showing contact
const contactsModified =
showOurContact ? 0 : 100;
return (
<Col height='100%' overflow='hidden' position='relative'>
{ this.dismissedInitialUnread() &&
@ -353,12 +351,11 @@ class ChatWindow extends Component<
offset={unreadCount}
origin='bottom'
style={virtScrollerStyle}
onStartReached={this.setActive}
onBottomLoaded={this.onBottomLoaded}
onScroll={this.onScroll}
data={graph}
size={graph.size}
pendingSize={pendingSize + contactsModified}
pendingSize={pendingSize}
id={association.resource}
averageHeight={22}
renderer={this.renderer}
@ -369,8 +366,5 @@ class ChatWindow extends Component<
}
}
export default withState(ChatWindow, [
[useGroupState, ['groups']],
[useMetadataState, ['associations']],
[useGraphState, ['pendingSize']]
]);
export default ChatWindow

View File

@ -8,22 +8,11 @@ import Timestamp from '~/views/components/Timestamp';
export const UnreadNotice = (props) => {
const { unreadCount, unreadMsg, dismissUnread, onClick } = props;
if (!unreadMsg || unreadCount === 0) {
if (unreadCount === 0) {
return null;
}
const stamp = moment.unix(unreadMsg.post['time-sent'] / 1000);
let datestamp = moment
.unix(unreadMsg.post['time-sent'] / 1000)
.format('YYYY.M.D');
const timestamp = moment
.unix(unreadMsg.post['time-sent'] / 1000)
.format('HH:mm');
if (datestamp === moment().format('YYYY.M.D')) {
datestamp = null;
}
const stamp = unreadMsg && moment.unix(unreadMsg.post['time-sent'] / 1000);
return (
<Box
@ -52,15 +41,20 @@ export const UnreadNotice = (props) => {
whiteSpace='pre'
overflow='hidden'
display='flex'
cursor='pointer'
cursor={unreadMsg ? 'pointer' : null}
onClick={onClick}
>
{unreadCount} new message{unreadCount > 1 ? 's' : ''} since{' '}
{unreadCount} new message{unreadCount > 1 ? 's' : ''}
{unreadMsg && (
<>
{' '}since{' '}
<Timestamp stamp={stamp} color='black' date={true} fontSize={1} />
</>
)}
</Text>
<Icon
icon='X'
ml='4'
ml={unreadMsg ? 4 : 1}
color='black'
cursor='pointer'
textAlign='right'

View File

@ -23,7 +23,7 @@ type LinkResourceProps = StoreState & {
association: Association;
api: GlobalApi;
baseUrl: string;
} & RouteComponentProps;
};
export function LinkResource(props: LinkResourceProps) {
const {

View File

@ -6,7 +6,7 @@ import React, {
Component,
} from "react";
import { Col, Text } from "@tlon/indigo-react";
import { Box, Col, Text } from "@tlon/indigo-react";
import bigInt from "big-integer";
import { Association, Graph, Unreads, Group, Rolodex } from "@urbit/api";
@ -48,7 +48,7 @@ class LinkWindow extends Component<LinkWindowProps, {}> {
return isWriter(group, association.resource);
}
renderItem = ({ index, scrollWindow }) => {
renderItem = React.forwardRef(({ index, scrollWindow }, ref) => {
const { props } = this;
const { association, graph, api } = props;
const [, , ship, name] = association.resource.split("/");
@ -80,12 +80,14 @@ class LinkWindow extends Component<LinkWindowProps, {}> {
api={api}
/>
</Col>
<LinkItem {...linkProps} />
<LinkItem ref={ref} {...linkProps} />
</React.Fragment>
);
}
return <LinkItem key={index.toString()} {...linkProps} />;
};
return <Box ref={ref}>
<LinkItem ref={ref} key={index.toString()} {...linkProps} />;
</Box>
});
render() {
const { graph, api, association } = this.props;

View File

@ -19,7 +19,7 @@ interface LinkItemProps {
node: GraphNode;
association: Association;
resource: string; api: GlobalApi; group: Group; path: string; }
export const LinkItem = (props: LinkItemProps): ReactElement => {
export const LinkItem = React.forwardRef((props: LinkItemProps, ref): ReactElement => {
const {
association,
node,
@ -30,7 +30,6 @@ export const LinkItem = (props: LinkItemProps): ReactElement => {
...rest
} = props;
const ref = useRef<HTMLDivElement | null>(null);
const remoteRef = useRef<typeof RemoteContent | null>(null);
const index = node.post.index.split('/')[1];
@ -210,5 +209,5 @@ export const LinkItem = (props: LinkItemProps): ReactElement => {
</Row>
</Box>);
};
});

View File

@ -11,7 +11,7 @@ type PublishResourceProps = StoreState & {
association: Association;
api: GlobalApi;
baseUrl: string;
} & RouteComponentProps;
};
export function PublishResource(props: PublishResourceProps) {
const { association, api, baseUrl, notebooks } = props;

View File

@ -1,4 +1,4 @@
import React, { Component, useCallback } from 'react';
import React, { Component, useCallback, SyntheticEvent } from 'react';
import _ from 'lodash';
import normalizeWheel from 'normalize-wheel';
import bigInt, { BigInteger } from 'big-integer';
@ -76,7 +76,7 @@ interface VirtualScrollerProps<T> {
}
interface VirtualScrollerState<T> {
visibleItems: BigIntOrderedMap<T>;
visibleItems: BigInteger[];
scrollbar: number;
loaded: {
top: boolean;
@ -91,10 +91,9 @@ const log = (level: LogLevel, message: string) => {
if(logLevel.includes(level)) {
console.log(`[${level}]: ${message}`);
}
}
const ZONE_SIZE = IS_IOS ? 10 : 40;
const ZONE_SIZE = IS_IOS ? 10 : 80;
// nb: in this file, an index refers to a BigInteger and an offset refers to a
@ -114,7 +113,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
/**
* A map of child refs, used to calculate scroll position
*/
private childRefs = new BigIntOrderedMap<HTMLElement>();
private childRefs = new Map<string, HTMLElement>();
/**
* A set of child refs which have been unmounted
*/
@ -149,7 +148,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
constructor(props: VirtualScrollerProps<T>) {
super(props);
this.state = {
visibleItems: new BigIntOrderedMap(),
visibleItems: [],
scrollbar: 0,
loaded: {
top: false,
@ -160,10 +159,11 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
this.updateVisible = this.updateVisible.bind(this);
this.invertedKeyHandler = this.invertedKeyHandler.bind(this);
this.onScroll = IS_IOS ? _.debounce(this.onScroll.bind(this), 400) : this.onScroll.bind(this);
this.onScroll = IS_IOS ? _.debounce(this.onScroll.bind(this), 200) : this.onScroll.bind(this);
this.scrollKeyMap = this.scrollKeyMap.bind(this);
this.setWindow = this.setWindow.bind(this);
this.restore = this.restore.bind(this);
this.startOffset = this.startOffset.bind(this);
}
componentDidMount() {
@ -181,7 +181,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
}
[...this.orphans].forEach(o => {
const index = bigInt(o);
this.childRefs.delete(index);
this.childRefs.delete(index.toString());
});
this.orphans.clear();
};
@ -206,13 +206,10 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
componentDidUpdate(prevProps: VirtualScrollerProps<T>, _prevState: VirtualScrollerState<T>) {
const { id, size, data, offset, pendingSize } = this.props;
const { visibleItems } = this.state;
if(size !== prevProps.size || pendingSize !== prevProps.pendingSize) {
if(this.scrollLocked && visibleItems?.peekLargest() && data?.peekLargest()) {
if(!visibleItems.peekLargest()[0].eq(data.peekLargest()[0])) {
if(this.scrollLocked) {
this.updateVisible(0);
}
this.resetScroll();
}
}
@ -228,11 +225,13 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
}
startOffset() {
const startIndex = this.state?.visibleItems?.peekLargest()?.[0];
const { data } = this.props;
const startIndex = this.state.visibleItems?.[0];
if(!startIndex) {
return 0;
}
const offset = [...this.props.data].findIndex(([i]) => i.eq(startIndex))
const dataList = Array.from(data);
const offset = dataList.findIndex(([i]) => i.eq(startIndex))
if(offset === -1) {
// TODO: revisit when we remove nodes for any other reason than
// pending indices being removed
@ -252,19 +251,17 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
log('reflow', `from: ${this.startOffset()} to: ${newOffset}`);
const { data, onCalculateVisibleItems } = this.props;
const visibleItems = new BigIntOrderedMap<any>(
[...data].slice(newOffset, newOffset + this.pageSize)
);
const visibleItems = data.keys().slice(newOffset, newOffset + this.pageSize);
this.save();
this.setState({
visibleItems,
}, () => {
});
requestAnimationFrame(() => {
this.restore();
});
});
}
scrollKeyMap(): Map<string, number> {
@ -296,7 +293,6 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
setWindow(element) {
if (!element)
return;
console.log('resetting window');
this.save();
if (this.window) {
@ -309,8 +305,8 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
const { averageHeight } = this.props;
this.window = element;
this.pageSize = Math.floor(element.offsetHeight / Math.floor(averageHeight / 5.5));
this.pageDelta = Math.floor(this.pageSize / 3);
this.pageSize = Math.floor(element.offsetHeight / Math.floor(averageHeight / 2));
this.pageDelta = Math.floor(this.pageSize / 4);
if (this.props.origin === 'bottom') {
element.addEventListener('wheel', (event) => {
event.preventDefault();
@ -356,7 +352,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
}
};
onScroll(event: UIEvent) {
onScroll(event: SyntheticEvent<HTMLElement, ScrollEvent>) {
this.updateScroll();
if(!this.window) {
// bail if we're going to adjust scroll anyway
@ -371,6 +367,8 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
const { scrollTop, scrollHeight } = this.window;
const startOffset = this.startOffset();
const scrollEnd = scrollTop + windowHeight;
if (scrollTop < ZONE_SIZE) {
log('scroll', `Entered start zone ${scrollTop}`);
if (startOffset === 0) {
@ -417,17 +415,23 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
}
if(this.scrollLocked) {
this.resetScroll();
requestAnimationFrame(() => {
this.savedIndex = null;
this.savedDistance = 0;
this.saveDepth--;
});
return;
}
let ref = this.childRefs.get(this.savedIndex)
let ref = this.childRefs.get(this.savedIndex.toString())
if(!ref) {
return;
}
const newScrollTop = this.window.scrollHeight - ref.offsetTop - this.savedDistance;
const newScrollTop = this.props.origin === 'top'
? this.savedDistance + ref.offsetTop
: this.window.scrollHeight - ref.offsetTop - this.savedDistance;
this.window.scrollTo(0, newScrollTop);
requestAnimationFrame(() => {
@ -435,10 +439,11 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
this.savedDistance = 0;
this.saveDepth--;
});
}
scrollToIndex = (index: BigInteger) => {
let ref = this.childRefs.get(index);
let ref = this.childRefs.get(index.toString());
if(!ref) {
const offset = [...this.props.data].findIndex(([idx]) => idx.eq(index));
if(offset === -1) {
@ -446,7 +451,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
}
this.updateVisible(Math.max(offset - this.pageDelta, 0));
requestAnimationFrame(() => {
ref = this.childRefs.get(index);
ref = this.childRefs.get(index.toString());
this.savedIndex = null;
this.savedDistance = 0;
this.saveDepth = 0;
@ -467,17 +472,20 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
return;
}
if(this.saveDepth !== 0) {
console.log('bail', 'deep save');
return;
}
this.saveDepth++;
log('scroll', 'saving...');
let bottomIndex: BigInteger | null = null;
this.saveDepth++;
const { visibleItems } = this.state;
let bottomIndex = visibleItems[visibleItems.length - 1];
const { scrollTop, scrollHeight } = this.window;
const topSpacing = scrollHeight - scrollTop;
[...Array.from(this.state.visibleItems)].reverse().forEach(([index, datum]) => {
const el = this.childRefs.get(index);
const topSpacing = this.props.origin === 'top' ? scrollTop : scrollHeight - scrollTop;
const items = this.props.origin === 'top' ? visibleItems : [...visibleItems].reverse();
items.forEach((index) => {
const el = this.childRefs.get(index.toString());
if(!el) {
return;
}
@ -490,20 +498,22 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
if(!bottomIndex) {
// weird, shouldn't really happen
this.saveDepth--;
log('bail', 'no index found');
return;
}
this.savedIndex = bottomIndex;
const ref = this.childRefs.get(bottomIndex)!;
const ref = this.childRefs.get(bottomIndex.toString())!;
const { offsetTop } = ref;
this.savedDistance = topSpacing - offsetTop
}
shiftLayout = { save: this.save.bind(this), restore: this.restore.bind(this) };
// disabled until we work out race conditions with loading new nodes
shiftLayout = { save: () => {}, restore: () => {} };
setRef = (element: HTMLElement | null, index: BigInteger) => {
if(element) {
this.childRefs.set(index, element);
this.childRefs.set(index.toString(), element);
this.orphans.delete(index.toString());
} else {
this.orphans.add(index.toString());
@ -525,12 +535,11 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
const isTop = origin === 'top';
const indexesToRender = isTop ? visibleItems.keys() : visibleItems.keys().reverse();
const transform = isTop ? 'scale3d(1, 1, 1)' : 'scale3d(1, -1, 1)';
const children = isTop ? visibleItems : [...visibleItems].reverse();
const atStart = (this.props.data.peekLargest()?.[0] ?? bigInt.zero).eq(visibleItems.peekLargest()?.[0] || bigInt.zero);
const atEnd = this.state.loaded.top;
const atStart = (this.props.data.peekLargest()?.[0] ?? bigInt.zero).eq(visibleItems?.[0] || bigInt.zero);
const atEnd = (this.props.data.peekSmallest()?.[0] ?? bigInt.zero).eq(visibleItems?.[visibleItems.length -1 ] || bigInt.zero);
return (
<>
@ -542,7 +551,7 @@ export default class VirtualScroller<T> extends Component<VirtualScrollerProps<T
<LoadingSpinner />
</Center>)}
<VirtualContext.Provider value={this.shiftLayout}>
{indexesToRender.map(index => (
{children.map(index => (
<VirtualChild
key={index.toString()}
setRef={this.setRef}
@ -575,8 +584,10 @@ function VirtualChild(props: VirtualChildProps) {
const ref = useCallback((el: HTMLElement | null) => {
setRef(el, props.index);
}, [setRef, props.index])
// VirtualChild should always be keyed on the index, so the index should be
// valid for the entire lifecycle of the component, hence no dependencies
}, []);
return (<Renderer ref={ref} {...rest} />);
return <Renderer ref={ref} {...rest} />
};

View File

@ -124,7 +124,6 @@ export function GroupsPane(props: GroupsPaneProps) {
>
<Resource
{...props}
{...routeProps}
association={association}
baseUrl={baseUrl}
/>

View File

@ -2,7 +2,7 @@ import React from 'react';
import bigInt from 'big-integer';
import VirtualScroller from "~/views/components/VirtualScroller";
import PostItem from './PostItem/PostItem';
import { Col } from '@tlon/indigo-react';
import { Col, Box } from '@tlon/indigo-react';
import { resourceFromPath } from '~/logic/lib/group';
@ -15,7 +15,12 @@ export class PostFeed extends React.Component {
super(props);
this.isFetching = false;
this.renderItem = React.forwardRef(({ index, scrollWindow }, ref) => {
this.fetchPosts = this.fetchPosts.bind(this);
this.doNotFetch = this.doNotFetch.bind(this);
}
renderItem = React.forwardRef(({ index, scrollWindow }, ref) => {
const {
graph,
graphPath,
@ -46,13 +51,13 @@ export class PostFeed extends React.Component {
<React.Fragment key={index.toString()}>
<Col
key={index.toString()}
ref={ref}
mb="3"
width="100%"
flexShrink={0}
>
<PostItem
key={parentNode.post.index}
ref={ref}
parentPost={grandparentNode?.post}
node={parentNode}
parentNode={grandparentNode}
@ -69,7 +74,6 @@ export class PostFeed extends React.Component {
/>
</Col>
<PostItem
ref={ref}
node={node}
graphPath={graphPath}
association={association}
@ -88,9 +92,8 @@ export class PostFeed extends React.Component {
}
return (
<Box key={index.toString()} ref={ref}>
<PostItem
key={index.toString()}
ref={ref}
node={node}
graphPath={graphPath}
association={association}
@ -104,12 +107,10 @@ export class PostFeed extends React.Component {
vip={vip}
group={group}
/>
</Box>
);
});
this.fetchPosts = this.fetchPosts.bind(this);
this.doNotFetch = this.doNotFetch.bind(this);
}
async fetchPosts(newer) {
const { graph, graphPath, api } = this.props;

View File

@ -15,12 +15,14 @@ import useGroupState from '~/logic/state/group';
import useContactState from '~/logic/state/contact';
import useHarkState from '~/logic/state/hark';
import useMetadataState from '~/logic/state/metadata';
import {Workspace} from '~/types';
type ResourceProps = StoreState & {
association: Association;
api: GlobalApi;
baseUrl: string;
} & RouteComponentProps;
workspace: Workspace;
};
export function Resource(props: ResourceProps): ReactElement {
const { association, api, notificationsGraphConfig } = props;

View File

@ -1,6 +1,10 @@
import { immerable } from 'immer';
import produce, { immerable, castImmutable, castDraft, setAutoFreeze, enablePatches } from 'immer';
import bigInt, { BigInteger } from "big-integer";
setAutoFreeze(false);
enablePatches();
function sortBigInt(a: BigInteger, b: BigInteger) {
if (a.lt(b)) {
return 1;
@ -11,19 +15,18 @@ function sortBigInt(a: BigInteger, b: BigInteger) {
}
}
export default class BigIntOrderedMap<V> implements Iterable<[BigInteger, V]> {
private root: Record<string, V> = {}
private cachedIter: [BigInteger, V][] | null = null;
root: Record<string, V> = {}
cachedIter: [BigInteger, V][] = [];
[immerable] = true;
constructor(items: [BigInteger, V][] = []) {
items.forEach(([key, val]) => {
this.set(key, val);
});
this.generateCachedIter();
}
get size() {
return this.cachedIter?.length ?? Object.keys(this.root).length;
return Object.keys(this.root).length;
}
@ -31,14 +34,30 @@ export default class BigIntOrderedMap<V> implements Iterable<[BigInteger, V]> {
return this.root[key.toString()] ?? null;
}
gas(items: [BigInteger, V][]) {
return produce(this, draft => {
items.forEach(([key, value]) => {
draft.root[key.toString()] = castDraft(value);
});
draft.generateCachedIter();
},
(patches) => {
//console.log(`gassed with ${JSON.stringify(patches, null, 2)}`);
});
}
set(key: BigInteger, value: V) {
this.root[key.toString()] = value;
this.cachedIter = null;
return produce(this, draft => {
draft.root[key.toString()] = castDraft(value);
draft.generateCachedIter();
});
}
clear() {
this.cachedIter = null;
this.root = {}
return produce(this, draft => {
draft.cachedIter = [];
draft.root = {}
});
}
has(key: BigInteger) {
@ -46,17 +65,15 @@ export default class BigIntOrderedMap<V> implements Iterable<[BigInteger, V]> {
}
delete(key: BigInteger) {
const had = this.has(key);
if(had) {
delete this.root[key.toString()];
this.cachedIter = null;
}
return had;
return produce(this, draft => {
delete draft.root[key.toString()];
draft.cachedIter = draft.cachedIter.filter(([x]) => x.eq(key));
});
}
[Symbol.iterator](): IterableIterator<[BigInteger, V]> {
let idx = 0;
const result = this.generateCachedIter();
let result = [...this.cachedIter];
return {
[Symbol.iterator]: this[Symbol.iterator],
next: (): IteratorResult<[BigInteger, V]> => {
@ -79,19 +96,15 @@ export default class BigIntOrderedMap<V> implements Iterable<[BigInteger, V]> {
}
keys() {
return Object.keys(this.root).map(k => bigInt(k)).sort(sortBigInt)
return Array.from(this).map(([k,v]) => k);
}
private generateCachedIter() {
if(this.cachedIter) {
return this.cachedIter;
}
generateCachedIter() {
const result = Object.keys(this.root).map(key => {
const num = bigInt(key);
return [num, this.root[key]] as [BigInteger, V];
}).sort(([a], [b]) => sortBigInt(a,b));
this.cachedIter = result;
return result;
}
}