Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(zbugs): useWatchQuery #3307

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions apps/zbugs/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import {
createSchema,
createTableSchema,
definePermissions,
NOBODY_CAN,
type ExpressionBuilder,
type TableSchema,
type Row,
NOBODY_CAN,
type TableSchema,
} from '@rocicorp/zero';
import type {Condition} from 'zero-protocol/src/ast.js';

Expand Down Expand Up @@ -183,6 +183,8 @@ const userPrefSchema = createTableSchema({

export type IssueRow = Row<typeof issueSchema>;
export type CommentRow = Row<typeof commentSchema>;
export type EmojiRow = Row<typeof emojiSchema>;
export type UserRow = Row<typeof userSchema>;
export type Schema = typeof schema;

/** The contents of the zbugs JWT */
Expand Down
6 changes: 3 additions & 3 deletions apps/zbugs/src/components/emoji-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ type Props = {
issueID: string;
commentID?: string | undefined;
emojis: readonly Emoji[];
recentEmojis?: readonly Emoji[] | undefined;
recentEmojiIDs?: readonly string[] | undefined;
removeRecentEmoji?: ((id: string) => void) | undefined;
};

export const EmojiPanel = memo(
forwardRef(
(
{issueID, commentID, emojis, recentEmojis, removeRecentEmoji}: Props,
{issueID, commentID, emojis, recentEmojiIDs, removeRecentEmoji}: Props,
ref: ForwardedRef<HTMLDivElement>,
) => {
const subjectID = commentID ?? issueID;
Expand Down Expand Up @@ -102,7 +102,7 @@ export const EmojiPanel = memo(
normalizedEmoji={normalizedEmoji}
emojis={emojis}
addOrRemoveEmoji={addOrRemoveEmoji}
recentEmojis={recentEmojis}
recentEmojiIDs={recentEmojiIDs}
removeRecentEmoji={removeRecentEmoji}
subjectID={subjectID}
/>
Expand Down
60 changes: 36 additions & 24 deletions apps/zbugs/src/components/emoji-pill.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {useQuery} from '@rocicorp/zero/react';
import classNames from 'classnames';
import {useEffect, useState} from 'react';
import {useIntersectionObserver} from 'usehooks-ts';
Expand Down Expand Up @@ -27,7 +28,7 @@ type Props = {
normalizedEmoji: string;
emojis: Emoji[];
addOrRemoveEmoji: AddOrRemoveEmoji;
recentEmojis?: readonly Emoji[] | undefined;
recentEmojiIDs?: readonly string[] | undefined;
removeRecentEmoji?: ((id: string) => void) | undefined;
subjectID: string;
};
Expand All @@ -36,7 +37,7 @@ export function EmojiPill({
normalizedEmoji,
emojis,
addOrRemoveEmoji,
recentEmojis,
recentEmojiIDs,
removeRecentEmoji,
subjectID,
}: Props) {
Expand All @@ -45,26 +46,26 @@ export function EmojiPill({
const mine = findEmojiForCreator(emojis, z.userID) !== undefined;
const [forceShow, setForceShow] = useState(false);
const [wasTriggered, setWasTriggered] = useState(false);
const [triggeredEmojis, setTriggeredEmojis] = useState<Emoji[]>([]);
const [triggeredEmojiIDs, setTriggeredEmojiIDs] = useState<string[]>([]);
const {isIntersecting, ref} = useIntersectionObserver({
threshold: 0.5,
freezeOnceVisible: true,
});
const documentHasFocus = useDocumentHasFocus();

useEffect(() => {
if (!recentEmojis) {
if (!recentEmojiIDs) {
return;
}
const newTriggeredEmojis: Emoji[] = [];
for (const emoji of recentEmojis) {
if (emojis.some(e => e.id === emoji.id)) {
const newTriggeredEmojiIDs: string[] = [];
for (const id of recentEmojiIDs) {
if (emojis.some(e => e.id === id)) {
setWasTriggered(true);
newTriggeredEmojis.push(emoji);
newTriggeredEmojiIDs.push(id);
}
}
setTriggeredEmojis(newTriggeredEmojis);
}, [emojis, recentEmojis, subjectID]);
setTriggeredEmojiIDs(newTriggeredEmojiIDs);
}, [emojis, recentEmojiIDs, subjectID]);

useEffect(() => {
if (wasTriggered && isIntersecting && !forceShow) {
Expand All @@ -74,22 +75,22 @@ export function EmojiPill({

useEffect(() => {
if (forceShow && documentHasFocus && removeRecentEmoji) {
const id = setTimeout(() => {
const timer = setTimeout(() => {
setForceShow(false);
setWasTriggered(false);
const [first, ...rest] = triggeredEmojis;
if (first) {
removeRecentEmoji(first.id);
const [firstID, ...restIDs] = triggeredEmojiIDs;
if (firstID) {
removeRecentEmoji(firstID);
}
setTriggeredEmojis(rest);
setTriggeredEmojiIDs(restIDs);
}, triggeredTooltipDuration);

return () => clearTimeout(id);
return () => clearTimeout(timer);
}
return () => void 0;
}, [triggeredEmojis, documentHasFocus, forceShow, removeRecentEmoji]);
}, [triggeredEmojiIDs, documentHasFocus, forceShow, removeRecentEmoji]);

const triggered = triggeredEmojis.length > 0;
const triggered = triggeredEmojiIDs.length > 0;

return (
<Tooltip open={forceShow || undefined}>
Expand Down Expand Up @@ -118,8 +119,8 @@ export function EmojiPill({
</TooltipTrigger>

<TooltipContent className={classNames({triggered})}>
{triggeredEmojis.length > 0 ? (
<TriggeredTooltipContent emojis={triggeredEmojis} />
{triggeredEmojiIDs.length > 0 ? (
<TriggeredTooltipContent emojiIDs={triggeredEmojiIDs} />
) : (
formatEmojiCreatorList(emojis, z.userID)
)}
Expand All @@ -128,12 +129,23 @@ export function EmojiPill({
);
}

function TriggeredTooltipContent({emojis}: {emojis: Emoji[]}) {
const emoji = emojis[0];
function TriggeredTooltipContent({emojiIDs}: {emojiIDs: string[]}) {
const emojiID = emojiIDs[0];
const z = useZero();
const [emoji] = useQuery(
z.query.emoji
.where('id', emojiID)
.related('creator', creator => creator.one())
.one(),
);
if (!emoji || !emoji.creator) {
return null;
}

return (
<>
<img className="tooltip-emoji-icon" src={emoji.creator?.avatar} />
{emoji.creator?.login}
<img className="tooltip-emoji-icon" src={emoji.creator.avatar} />
{emoji.creator.login}
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/zbugs/src/components/filter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import labelIcon from '../assets/icons/label.svg';
import {useZero} from '../hooks/use-zero.js';
import {Button} from './button.js';
import {Combobox} from './combobox.js';
import UserPicker from './user-picker.js';
import {UserPicker} from './user-picker.js';

export type Selection =
| {creator: string}
Expand Down
132 changes: 63 additions & 69 deletions apps/zbugs/src/components/user-picker.tsx
Original file line number Diff line number Diff line change
@@ -1,92 +1,86 @@
import {type Row} from '@rocicorp/zero';
import {useQuery} from '@rocicorp/zero/react';
import {useEffect, useMemo, useState} from 'react';
import {type Schema} from '../../schema.js';
import {memo, useEffect, useMemo, useState} from 'react';
import {type UserRow} from '../../schema.js';
import avatarIcon from '../assets/icons/avatar-default.svg';
import {useZero} from '../hooks/use-zero.js';
import {Combobox} from './combobox.js';

type Props = {
onSelect?: ((user: User | undefined) => void) | undefined;
onSelect?: ((user: UserRow | undefined) => void) | undefined;
selected?: {login?: string | undefined} | undefined;
disabled?: boolean | undefined;
unselectedLabel?: string | undefined;
placeholder?: string | undefined;
};

type User = Row<Schema['tables']['user']>;
export const UserPicker = memo(
({onSelect, selected, disabled, unselectedLabel, placeholder}: Props) => {
const z = useZero();

export default function UserPicker({
onSelect,
selected,
disabled,
unselectedLabel,
placeholder,
}: Props) {
const z = useZero();
const [unsortedUsers] = useQuery(z.query.user);
// TODO: Support case-insensitive sorting in ZQL.
const users = useMemo(
() => unsortedUsers.toSorted((a, b) => a.login.localeCompare(b.login)),
[unsortedUsers],
);

const [unsortedUsers] = useQuery(z.query.user);
// TODO: Support case-insensitive sorting in ZQL.
const users = useMemo(
() => unsortedUsers.toSorted((a, b) => a.login.localeCompare(b.login)),
[unsortedUsers],
);

// Preload the avatar icons so they show up instantly when opening the
// dropdown.
const [avatars, setAvatars] = useState<Record<string, string>>({});
useEffect(() => {
let canceled = false;
async function preload() {
const avatars = await Promise.all(users.map(c => preloadAvatar(c)));
if (canceled) {
return;
// Preload the avatar icons so they show up instantly when opening the
// dropdown.
const [avatars, setAvatars] = useState<Record<string, string>>({});
useEffect(() => {
let canceled = false;
async function preload() {
const avatars = await Promise.all(users.map(c => preloadAvatar(c)));
if (canceled) {
return;
}
setAvatars(Object.fromEntries(avatars));
}
setAvatars(Object.fromEntries(avatars));
}
void preload();
return () => {
canceled = true;
};
}, [users]);
void preload();
return () => {
canceled = true;
};
}, [users]);

const handleSelect = (user: User | undefined) => {
onSelect?.(user);
};
const handleSelect = (user: UserRow | undefined) => {
onSelect?.(user);
};

const selectedUser = selected && users.find(u => u.login === selected.login);
const selectedUser =
selected && users.find(u => u.login === selected.login);

const unselectedItem = {
text: unselectedLabel ?? 'Select',
icon: avatarIcon,
value: undefined,
};
const defaultItem = {
text: placeholder ?? 'Select a user...',
icon: avatarIcon,
value: undefined,
};
const unselectedItem = {
text: unselectedLabel ?? 'Select',
icon: avatarIcon,
value: undefined,
};
const defaultItem = {
text: placeholder ?? 'Select a user...',
icon: avatarIcon,
value: undefined,
};

return (
<Combobox
disabled={disabled}
onChange={c => handleSelect(c)}
items={[
unselectedItem,
...users.map(u => ({
text: u.login,
value: u,
icon: avatars[u.id],
})),
]}
defaultItem={defaultItem}
selectedValue={selectedUser ?? undefined}
className="user-picker"
/>
);
}
return (
<Combobox
disabled={disabled}
onChange={c => handleSelect(c)}
items={[
unselectedItem,
...users.map(u => ({
text: u.login,
value: u,
icon: avatars[u.id],
})),
]}
defaultItem={defaultItem}
selectedValue={selectedUser ?? undefined}
className="user-picker"
/>
);
},
);

function preloadAvatar(user: User) {
function preloadAvatar(user: UserRow): Promise<[string, string]> {
return new Promise<[string, string]>((res, rej) => {
fetch(user.avatar)
.then(response => response.blob())
Expand Down
7 changes: 3 additions & 4 deletions apps/zbugs/src/emoji-utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type {Row} from '@rocicorp/zero';
import {assert} from 'shared/src/asserts.js';
import type {Schema} from '../schema.js';
import type {EmojiRow, UserRow} from '../schema.js';

export type Emoji = Row<Schema['tables']['emoji']> & {
readonly creator: Row<Schema['tables']['user']> | undefined;
export type Emoji = EmojiRow & {
readonly creator: UserRow | undefined;
};

export function formatEmojiCreatorList(
Expand Down
Loading
Loading