Compare commits

..

No commits in common. "6592d71a4649af35ecb4d46abbb22b76dc913d71" and "1a1fee8918e181c3adeff0bb71566fa0b8cd4e97" have entirely different histories.

7 changed files with 240 additions and 228 deletions

View file

@ -11,19 +11,114 @@ import {
} from "solid-js";
import { createStore } from "solid-js/store";
type TimelineFetchTips = {
direction?: "new" | "old";
};
type Timeline = {
list(params: {
/** Return results older than this ID. */
readonly maxId?: string;
/** Return results newer than this ID. */
readonly sinceId?: string;
/** Get a list of items with ID greater than this value excluding this ID */
readonly minId?: string;
/** Maximum number of results to return per page. Defaults to 40. NOTE: Pagination is done with the Link header from the response. */
readonly limit?: number;
}): mastodon.Paginator<mastodon.v1.Status[], unknown>;
};
export function useTimeline(
timeline: Accessor<Timeline>,
cfg?: {
/**
* Use full refresh mode. This mode ignores paging, it will refetch the specified number
* of toots at every refetch().
*/
fullRefresh?: number;
},
) {
let otl: Timeline | undefined;
let npager: mastodon.Paginator<mastodon.v1.Status[], unknown> | undefined;
let opager: mastodon.Paginator<mastodon.v1.Status[], unknown> | undefined;
const [snapshot, { refetch }] = createResource<
{
records: mastodon.v1.Status[];
direction: "new" | "old" | "items";
tlChanged: boolean;
},
[Timeline],
TimelineFetchTips | undefined
>(
() => [timeline()] as const,
async ([tl], info) => {
let tlChanged = false;
if (otl !== tl) {
npager = opager = undefined;
otl = tl;
tlChanged = true;
}
const fullRefresh = cfg?.fullRefresh;
if (typeof fullRefresh !== "undefined") {
const records = await tl
.list({
limit: fullRefresh,
})
.next();
return {
direction: "items",
records: records.value ?? [],
end: records.done,
tlChanged,
};
}
const direction =
typeof info.refetching !== "boolean"
? (info.refetching?.direction ?? "old")
: "old";
if (direction === "old") {
if (!opager) {
opager = tl.list({}).setDirection("next");
}
const next = await opager.next();
return {
direction,
records: next.value ?? [],
end: next.done,
tlChanged,
};
} else {
if (!npager) {
npager = tl.list({}).setDirection("prev");
}
const next = await npager.next();
const page = next.value ?? [];
return { direction, records: page, end: next.done, tlChanged };
}
},
);
const [store, setStore] = createStore([] as mastodon.v1.Status[]);
createEffect(() => {
const shot = snapshot();
if (!shot) return;
const { direction, records, tlChanged } = shot;
if (tlChanged) {
setStore(() => []);
}
if (direction === "new") {
setStore((x) => [...records, ...x]);
} else if (direction === "old") {
setStore((x) => [...x, ...records]);
} else if (direction === "items") {
setStore(() => records);
}
});
return [
store,
snapshot,
{
refetch,
mutate: setStore,
},
] as const;
}
export function createTimelineSnapshot(
timeline: Accessor<Timeline>,
limit: Accessor<number>,
@ -81,13 +176,30 @@ export function createTimelineSnapshot(
export type TimelineFetchDirection = mastodon.Direction;
export type TimelineChunk = {
tl: Timeline;
pager: mastodon.Paginator<mastodon.v1.Status[], unknown>;
chunk: readonly mastodon.v1.Status[];
done?: boolean;
direction: TimelineFetchDirection;
limit: number;
};
function checkOrCreatePager(
timeline: Timeline,
limit: number,
lastPager: TimelineChunk["pager"] | undefined,
newDirection: TimelineFetchDirection,
) {
if (!lastPager) {
return timeline.list({ }).setDirection(newDirection);
} else {
let pager = lastPager;
if (pager.getDirection() !== newDirection) {
pager = pager.setDirection(newDirection);
}
return pager;
}
}
type TreeNode<T> = {
parent?: TreeNode<T>;
value: T;
@ -114,38 +226,6 @@ export function createTimeline(
const lookup = new ReactiveMap<string, TreeNode<mastodon.v1.Status>>();
const [threads, setThreads] = createStore([] as mastodon.v1.Status["id"][]);
let vpMaxId: string | undefined, vpMinId: string | undefined;
const fetchExtendingPage = async (
tl: Timeline,
direction: TimelineFetchDirection,
limit: number,
) => {
switch (direction) {
case "next": {
const page = await tl
.list({ limit, sinceId: vpMaxId })
.setDirection(direction)
.next();
if ((page.value?.length ?? 0) > 0) {
vpMaxId = page.value![0].id;
}
return page;
}
case "prev": {
const page = await tl
.list({ limit, maxId: vpMinId })
.setDirection(direction)
.next();
if ((page.value?.length ?? 0) > 0) {
vpMinId = page.value![page.value!.length - 1].id;
}
return page;
}
}
};
const [chunk, { refetch }] = createResource(
() => [timeline(), limit()] as const,
async (
@ -157,16 +237,17 @@ export function createTimeline(
) => {
const direction =
typeof info.refetching === "boolean" ? "prev" : info.refetching;
const rebuildTimeline = tl !== info.value?.tl;
const rebuildTimeline = limit !== info.value?.limit;
const pager = rebuildTimeline
? checkOrCreatePager(tl, limit, undefined, direction)
: checkOrCreatePager(tl, limit, info.value?.pager, direction);
if (rebuildTimeline) {
vpMaxId = undefined;
vpMinId = undefined;
lookup.clear();
setThreads([]);
}
const posts = await fetchExtendingPage(tl, direction, limit);
const posts = await pager.next();
return {
tl,
pager,
chunk: posts.value ?? [],
done: posts.done,
direction,
@ -180,18 +261,17 @@ export function createTimeline(
if (!chk) {
return;
}
console.debug("fetched chunk", chk);
const existence = [] as boolean[];
for (const [idx, status] of chk.chunk.entries()) {
existence[idx] = !!untrack(() => lookup.get(status.id));
batch(() => {
for (const status of chk.chunk) {
lookup.set(status.id, {
value: status,
});
}
for (const status of chk.chunk) {
const node = untrack(() => lookup.get(status.id))!;
const node = lookup.get(status.id)!;
if (status.inReplyToId) {
const parent = lookup.get(status.inReplyToId);
if (parent) {
@ -204,16 +284,10 @@ export function createTimeline(
}
}
}
const nThreadIds = chk.chunk
.filter((x, i) => !existence[i])
.map((x) => x.id);
batch(() => {
if (chk.direction === "prev") {
setThreads((threads) => [...threads, ...nThreadIds]);
} else if (chk.direction === "next") {
setThreads((threads) => [...nThreadIds, ...threads]);
if (chk.direction === "next") {
setThreads((threads) => [...threads, ...chk.chunk.map((x) => x.id)]);
} else if (chk.direction === "prev") {
setThreads((threads) => [...chk.chunk.map((x) => x.id), ...threads]);
}
setThreads((threads) =>

View file

@ -270,9 +270,7 @@ const Home: ParentComponent = (props) => {
</TimeSourceProvider>
<Suspense>
<HeroSourceProvider value={[heroSrc, setHeroSrc]}>
<BottomSheet open={!!child()} onClose={() => navigate(-1)}>
{child()}
</BottomSheet>
<BottomSheet open={!!child()}>{child()}</BottomSheet>
</HeroSourceProvider>
</Suspense>
</Scaffold>

View file

@ -66,7 +66,7 @@ const MediaAttachmentGrid: Component<{
css`
.attachments {
column-count: ${columnCount().toString()};
column-count: ${columnCount.toString()};
}
`;
return (

View file

@ -52,7 +52,7 @@ const PullDownToRefresh: Component<{
let lts = -1;
let ds = 0;
let holding = false;
const K = 20;
const K = 10;
const updatePullDown = (ts: number) => {
released = false;
try {
@ -60,9 +60,8 @@ const PullDownToRefresh: Component<{
const dt = lts !== -1 ? ts - lts : 1 / 60;
const vspring = holding ? 0 : K * x * dt;
v = ds / dt - vspring;
const final = Math.max(Math.min(x + v * dt, stopPos()), 0);
setPullDown(final);
setPullDown(Math.max(Math.min(x + v * dt, stopPos()), 0));
if (Math.abs(x) > 1 || Math.abs(v) > 1) {
requestAnimationFrame(updatePullDown);
@ -70,6 +69,15 @@ const PullDownToRefresh: Component<{
v = 0;
lts = -1;
}
if (
!holding &&
untrack(pullDown) >= stopPos() &&
!props.loading &&
props.onRefresh
) {
setTimeout(props.onRefresh, 0);
}
} finally {
ds = 0;
released = true;
@ -81,11 +89,6 @@ const PullDownToRefresh: Component<{
const onWheelNotUpdated = () => {
wheelTimeout = undefined;
holding = false;
if (released) {
released = false;
requestAnimationFrame(updatePullDown);
}
};
const handleLinkedWheel = (event: WheelEvent) => {
@ -94,18 +97,11 @@ const PullDownToRefresh: Component<{
const d = untrack(pullDown);
if (d > 1) event.preventDefault();
ds = -(event.deltaY / window.devicePixelRatio / 2);
holding = d < stopPos();
if (wheelTimeout) {
clearTimeout(wheelTimeout);
}
if (d >= stopPos() && !props.loading) {
props.onRefresh?.();
holding = false;
wheelTimeout = undefined;
} else {
holding = true;
wheelTimeout = setTimeout(onWheelNotUpdated, 200);
}
if (released) {
released = false;
@ -155,8 +151,12 @@ const PullDownToRefresh: Component<{
lastTouchId = undefined;
lastTouchScreenY = 0;
holding = false;
if (untrack(pullDown) >= stopPos() && !props.loading) {
props.onRefresh?.();
if (
untrack(indicatorOfsY) >= stopPos() &&
!props.loading &&
props.onRefresh
) {
setTimeout(props.onRefresh, 0);
} else {
if (released) {
released = false;
@ -203,7 +203,9 @@ const PullDownToRefresh: Component<{
background-color: var(--tutu-color-surface);
> :global(.refresh-icon) {
transform: rotate(${`${(indicatorOfsY() / 160 / 2).toString()}turn`});
transform: rotate(
${`${((indicatorOfsY() / 160) * 180).toString()}deg`}
);
will-change: transform;
}

View file

@ -111,17 +111,13 @@ type TootActionGroupProps<T extends mastodon.v1.Status> = {
onRetoot?: (value: T) => void;
onFavourite?: (value: T) => void;
onBookmark?: (value: T) => void;
onReply?: (
value: T,
event: MouseEvent & { currentTarget: HTMLButtonElement },
) => void;
onReply?: (value: T) => void;
};
type TootCardProps = {
status: mastodon.v1.Status;
actionable?: boolean;
evaluated?: boolean;
thread?: "top" | "bottom" | "middle";
} & TootActionGroupProps<mastodon.v1.Status> &
JSX.HTMLElementTags["article"];
@ -129,40 +125,19 @@ function isolatedCallback(e: MouseEvent) {
e.stopPropagation();
}
export function findRootToot(element: HTMLElement) {
let current: HTMLElement | null = element;
while (current && !current.classList.contains(tootStyle.toot)) {
current = current.parentElement;
}
if (!current) {
throw Error(
`the element must be placed under a element with ${tootStyle.toot}`,
);
}
return current;
}
function TootActionGroup<T extends mastodon.v1.Status>(
props: TootActionGroupProps<T> & { value: T },
) {
let actGrpElement: HTMLDivElement;
const toot = () => props.value;
return (
<div
ref={actGrpElement!}
class={tootStyle.tootBottomActionGrp}
onClick={isolatedCallback}
>
<Show when={props.onReply}>
<div class={tootStyle.tootBottomActionGrp} onClick={isolatedCallback}>
<Button
class={tootStyle.tootActionWithCount}
onClick={[props.onReply!, props.value]}
onClick={() => props.onReply?.(toot())}
>
<ReplyAll />
<span>{toot().repliesCount}</span>
</Button>
</Show>
<Button
class={tootStyle.tootActionWithCount}
style={{
@ -313,7 +288,7 @@ const RegularToot: Component<TootCardProps> = (props) => {
let rootRef: HTMLElement;
const [managed, managedActionGroup, rest] = splitProps(
props,
["status", "lang", "class", "actionable", "evaluated", "thread"],
["status", "lang", "class", "actionable", "evaluated"],
["onRetoot", "onFavourite", "onBookmark", "onReply"],
);
const now = useTimeSource();
@ -325,42 +300,6 @@ const RegularToot: Component<TootCardProps> = (props) => {
margin-left: calc(var(--toot-avatar-size) + var(--card-pad) + 8px);
margin-block: 8px;
}
.thread-top,
.thread-mid,
.thread-btm {
position: relative;
&::before {
content: "";
position: absolute;
left: 36px;
background-color: var(--tutu-color-secondary);
width: 2px;
display: block;
}
}
.thread-mid {
&::before {
top: 0;
bottom: 0;
}
}
.thread-top {
&::before {
top: 16px;
bottom: 0;
}
}
.thread-btm {
&::before {
top: 0;
height: 16px;
}
}
`;
return (
@ -369,9 +308,6 @@ const RegularToot: Component<TootCardProps> = (props) => {
classList={{
[tootStyle.toot]: true,
[tootStyle.expanded]: managed.evaluated,
"thread-top": managed.thread === "top",
"thread-mid": managed.thread === "middle",
"thread-btm": managed.thread === "bottom",
[managed.class || ""]: true,
}}
ref={rootRef!}

View file

@ -9,19 +9,14 @@ import {
} from "solid-js";
import CompactToot from "./CompactToot";
import { useTimeSource } from "../platform/timesrc";
import RegularToot, { findRootToot } from "./RegularToot";
import RegularToot from "./RegularToot";
import cardStyle from "../material/cards.module.css";
import { css } from "solid-styled";
type TootActionTarget = {
client: mastodon.rest.Client;
status: mastodon.v1.Status;
};
type TootActions = {
onBoost(client: mastodon.rest.Client, status: mastodon.v1.Status): void;
onBookmark(client: mastodon.rest.Client, status: mastodon.v1.Status): void;
onReply(target: TootActionTarget, element: HTMLElement): void;
onReply(client: mastodon.rest.Client, status: mastodon.v1.Status): void;
};
type ThreadProps = {
@ -42,48 +37,55 @@ const Thread: Component<ThreadProps> = (props) => {
props.onBookmark(props.client, status);
};
const reply = (
status: mastodon.v1.Status,
event: MouseEvent & { currentTarget: HTMLElement },
) => {
const element = findRootToot(event.currentTarget);
props.onReply({ client: props.client, status }, element);
const reply = (status: mastodon.v1.Status) => {
props.onReply(props.client, status);
};
css`
.thread {
article {
transition:
margin 90ms var(--tutu-anim-curve-sharp),
var(--tutu-transition-shadow);
user-select: none;
cursor: pointer;
}
`
.thread-line {
position: relative;
&::before {
content: "";
position: absolute;
left: 36px;
top: 16px;
bottom: 0;
background-color: var(--tutu-color-secondary);
width: 2px;
display: block;
}
}
`;
return (
<article ref={props.ref} class="thread">
<article
ref={props.ref}
classList={{
"thread-line": props.toots.length > 1,
}}
>
<For each={props.toots}>
{(status, index) => {
const useThread = props.toots.length > 1;
const threadPosition = useThread
? index() === 0
? "top"
: index() === props.toots.length - 1
? "bottom"
: "middle"
: undefined;
return (
{(status, index) => (
<RegularToot
data-status-id={status.id}
data-thread-sort={index()}
status={status}
thread={threadPosition}
class={cardStyle.card}
class={`${cardStyle.card}`}
evaluated={props.isExpended(status)}
actionable={props.isExpended(status)}
onBookmark={(s) => bookmark(s)}
onRetoot={(s) => boost(s)}
onReply={reply}
onReply={(s) => reply(s)}
onClick={[props.onItemClick, status]}
/>
);
}}
)}
</For>
</article>
);

View file

@ -21,6 +21,7 @@ const TimelinePanel: Component<{
client: mastodon.rest.Client;
name: "home" | "public";
prefetch?: boolean;
fullRefetch?: number;
openFullScreenToot: (
toot: mastodon.v1.Status,
@ -90,7 +91,7 @@ const TimelinePanel: Component<{
<PullDownToRefresh
linkedElement={scrollLinked()}
loading={snapshot.loading}
onRefresh={() => refetchTimeline("next")}
onRefresh={() => refetchTimeline("prev")}
/>
<div
ref={(e) =>
@ -112,28 +113,27 @@ const TimelinePanel: Component<{
</Show>
<For each={timeline.list}>
{(itemId, index) => {
let element: HTMLElement | undefined;
const path = timeline.getPath(itemId)!;
const toots = path.reverse().map((x) => x.value);
return (
<Thread
ref={element}
toots={toots}
onBoost={onBoost}
onBookmark={onBookmark}
onReply={({ status }, element) =>
onReply={(client, status) =>
props.openFullScreenToot(status, element, true)
}
client={props.client}
isExpended={(status) => status.id === expandedThreadId()}
onItemClick={(status, event) => {
onItemClick={(status) => {
setTyping(false);
if (status.id !== expandedThreadId()) {
setExpandedThreadId((x) => (x ? undefined : status.id));
} else {
props.openFullScreenToot(
status,
event.currentTarget as HTMLElement,
);
props.openFullScreenToot(status, element);
}
}}
/>
@ -171,10 +171,10 @@ const TimelinePanel: Component<{
Retry
</Button>
</Match>
<Match when={true}>
<Match when={typeof props.fullRefetch === "undefined"}>
<Button
variant="contained"
onClick={[refetchTimeline, "prev"]}
onClick={[refetchTimeline, "next"]}
disabled={snapshot.loading}
>
Load More