Skip to content

Commit

Permalink
Hide cursors that haven't moved in 5s.
Browse files Browse the repository at this point in the history
  • Loading branch information
aboodman committed Mar 6, 2021
1 parent 274a271 commit a91dc7c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
2 changes: 2 additions & 0 deletions frontend/cursor.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
line-height: 1em;
pointer-events: none;
cursor: pointer;
opacity: 0;
transition: opacity 100ms linear;
}

.pointer {
Expand Down
55 changes: 53 additions & 2 deletions frontend/cursor.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,65 @@
import { Data } from "./data";
import styles from "./cursor.module.css";
import { useEffect, useState } from "react";

const hideCursorDelay = 5000;

interface Position {
pos: {
x: number;
y: number;
};
ts: number;
}

export function Cursor({ data, clientID }: { data: Data; clientID: string }) {
const userInfo = data.useUserInfo(clientID);
const cursor = data.useCursor(clientID);
if (!userInfo || !cursor) {
const [lastPosition, setLastPosition] = useState<Position | null>(null);
const [seenFirstChange, setSeenFirstChange] = useState(false);
const [, setPoke] = useState({});

if (cursor) {
if (lastPosition == null) {
setLastPosition({ pos: cursor, ts: Date.now() });
} else if (
lastPosition.pos.x != cursor.x ||
lastPosition.pos.y != cursor.y
) {
setLastPosition({ pos: cursor, ts: Date.now() });
setSeenFirstChange(true);
}
}

let visible = false;
let elapsed = null;
let remaining = 0;
if (seenFirstChange && lastPosition) {
elapsed = Date.now() - lastPosition.ts;
remaining = hideCursorDelay - elapsed;
visible = remaining > 0;
}

useEffect(() => {
if (remaining > 0) {
console.log(`Cursor ${clientID} - setting timer for ${remaining}ms`);
const timerID = setTimeout(() => setPoke({}), remaining);
return () => clearTimeout(timerID);
}
});

console.log(
`Cursor ${clientID} - elapsed ${elapsed}, remaining: ${remaining}, visible: ${visible}`
);
if (!cursor || !userInfo) {
return null;
}

return (
<div className={styles.cursor} style={{ left: cursor.x, top: cursor.y }}>
<div
className={styles.cursor}
style={{ left: cursor.x, top: cursor.y, opacity: visible ? 1 : 0 }}
>
<div className={styles.pointer} style={{ color: userInfo.color }}>
</div>
Expand Down

0 comments on commit a91dc7c

Please sign in to comment.