-
Notifications
You must be signed in to change notification settings - Fork 773
Extract reusable clipboard hook and standardize media queries #1006
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
Merged
+189
−83
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6de9eb4
Extract reusable clipboard hook and standardize media queries
juliusmarminge bf7e673
Update apps/web/src/hooks/useCopyToClipboard.ts
juliusmarminge 7d16b8e
Fix breakpoint mismatch and stabilize copyToClipboard reference
cursoragent 6b03ce9
fix: invoke onError callback when Clipboard API is unavailable
cursoragent fb4f027
Merge origin/main into feature/web/clipboard-hook-media-query
juliusmarminge b28cdbf
fix: invoke onError callback when Clipboard API is unavailable
cursor[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,20 @@ | ||
| import { memo, useCallback, useState } from "react"; | ||
| import { memo } from "react"; | ||
| import { CopyIcon, CheckIcon } from "lucide-react"; | ||
| import { Button } from "../ui/button"; | ||
| import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; | ||
|
|
||
| export const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) { | ||
| const [copied, setCopied] = useState(false); | ||
|
|
||
| const handleCopy = useCallback(() => { | ||
| void navigator.clipboard.writeText(text); | ||
| setCopied(true); | ||
| setTimeout(() => setCopied(false), 2000); | ||
| }, [text]); | ||
| const { copyToClipboard, isCopied } = useCopyToClipboard(); | ||
|
|
||
| return ( | ||
| <Button type="button" size="xs" variant="outline" onClick={handleCopy} title="Copy message"> | ||
| {copied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />} | ||
| <Button | ||
| type="button" | ||
| size="xs" | ||
| variant="outline" | ||
| onClick={() => copyToClipboard(text)} | ||
| title="Copy message" | ||
| > | ||
| {isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />} | ||
| </Button> | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import * as React from "react"; | ||
|
|
||
| export function useCopyToClipboard<TContext = void>({ | ||
| timeout = 2000, | ||
| onCopy, | ||
| onError, | ||
| }: { | ||
| timeout?: number; | ||
| onCopy?: (ctx: TContext) => void; | ||
| onError?: (error: Error, ctx: TContext) => void; | ||
| } = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } { | ||
| const [isCopied, setIsCopied] = React.useState(false); | ||
| const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null); | ||
|
|
||
| const copyToClipboard = (value: string, ctx: TContext): void => { | ||
| if (typeof window === "undefined" || !navigator.clipboard.writeText) { | ||
| return; | ||
| } | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (!value) return; | ||
|
|
||
| navigator.clipboard.writeText(value).then( | ||
| () => { | ||
| if (timeoutIdRef.current) { | ||
| clearTimeout(timeoutIdRef.current); | ||
| } | ||
| setIsCopied(true); | ||
|
|
||
| if (onCopy) { | ||
| onCopy(ctx); | ||
| } | ||
|
|
||
| if (timeout !== 0) { | ||
| timeoutIdRef.current = setTimeout(() => { | ||
| setIsCopied(false); | ||
| timeoutIdRef.current = null; | ||
| }, timeout); | ||
| } | ||
| }, | ||
| (error) => { | ||
| if (onError) { | ||
| onError(error, ctx); | ||
| } else { | ||
| console.error(error); | ||
| } | ||
| }, | ||
| ); | ||
| }; | ||
cursor[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Cleanup timeout on unmount | ||
| React.useEffect(() => { | ||
| return (): void => { | ||
| if (timeoutIdRef.current) { | ||
| clearTimeout(timeoutIdRef.current); | ||
| } | ||
| }; | ||
| }, []); | ||
|
|
||
| return { copyToClipboard, isCopied }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,87 @@ | ||
| import { useEffect, useState } from "react"; | ||
| import { useCallback, useSyncExternalStore } from "react"; | ||
|
|
||
| function getMediaQueryMatch(query: string): boolean { | ||
| if (typeof window === "undefined") { | ||
| return false; | ||
| const BREAKPOINTS = { | ||
| "2xl": 1536, | ||
| "3xl": 1600, | ||
| "4xl": 2000, | ||
| lg: 1024, | ||
| md: 800, | ||
cursor[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| sm: 640, | ||
| xl: 1280, | ||
| } as const; | ||
|
|
||
| type Breakpoint = keyof typeof BREAKPOINTS; | ||
|
|
||
| type BreakpointQuery = Breakpoint | `max-${Breakpoint}` | `${Breakpoint}:max-${Breakpoint}`; | ||
|
|
||
| function resolveMin(value: Breakpoint | number): string { | ||
| const px = typeof value === "number" ? value : BREAKPOINTS[value]; | ||
| return `(min-width: ${px}px)`; | ||
| } | ||
|
|
||
| function resolveMax(value: Breakpoint | number): string { | ||
| const px = typeof value === "number" ? value : BREAKPOINTS[value]; | ||
| return `(max-width: ${px - 1}px)`; | ||
| } | ||
|
|
||
| function parseQuery(query: BreakpointQuery | MediaQueryInput | (string & {})): string { | ||
| if (typeof query !== "string") { | ||
| const parts: string[] = []; | ||
| if (query.min != null) parts.push(resolveMin(query.min)); | ||
| if (query.max != null) parts.push(resolveMax(query.max)); | ||
| if (query.pointer === "coarse") parts.push("(pointer: coarse)"); | ||
| if (query.pointer === "fine") parts.push("(pointer: fine)"); | ||
| if (parts.length === 0) return "(min-width: 0px)"; | ||
| return parts.join(" and "); | ||
| } | ||
|
|
||
| if (query.startsWith("(")) return query; | ||
|
|
||
| const parts: string[] = []; | ||
| for (const segment of query.split(":")) { | ||
| if (segment.startsWith("max-")) { | ||
| const bp = segment.slice(4); | ||
| if (bp in BREAKPOINTS) parts.push(resolveMax(bp as Breakpoint)); | ||
| } else if (segment in BREAKPOINTS) { | ||
| parts.push(resolveMin(segment as Breakpoint)); | ||
| } | ||
| } | ||
| return window.matchMedia(query).matches; | ||
|
|
||
| return parts.length > 0 ? parts.join(" and ") : query; | ||
| } | ||
|
|
||
| function getServerSnapshot(): boolean { | ||
| return false; | ||
| } | ||
|
|
||
| export function useMediaQuery(query: string): boolean { | ||
| const [matches, setMatches] = useState(() => getMediaQueryMatch(query)); | ||
| export type MediaQueryInput = { | ||
| min?: Breakpoint | number; | ||
| max?: Breakpoint | number; | ||
| /** Touch-like input (finger). Use "fine" for mouse/trackpad. */ | ||
| pointer?: "coarse" | "fine"; | ||
| }; | ||
|
|
||
| export function useMediaQuery(query: BreakpointQuery | MediaQueryInput | (string & {})): boolean { | ||
| const mediaQuery = parseQuery(query); | ||
|
|
||
| useEffect(() => { | ||
| const mediaQueryList = window.matchMedia(query); | ||
| const handleChange = () => { | ||
| setMatches(mediaQueryList.matches); | ||
| }; | ||
| const subscribe = useCallback( | ||
| (callback: () => void) => { | ||
| if (typeof window === "undefined") return () => {}; | ||
| const mql = window.matchMedia(mediaQuery); | ||
| mql.addEventListener("change", callback); | ||
| return () => mql.removeEventListener("change", callback); | ||
| }, | ||
| [mediaQuery], | ||
| ); | ||
|
|
||
| setMatches(mediaQueryList.matches); | ||
| mediaQueryList.addEventListener("change", handleChange); | ||
| return () => { | ||
| mediaQueryList.removeEventListener("change", handleChange); | ||
| }; | ||
| }, [query]); | ||
| const getSnapshot = useCallback(() => { | ||
| if (typeof window === "undefined") return false; | ||
| return window.matchMedia(mediaQuery).matches; | ||
| }, [mediaQuery]); | ||
|
|
||
| return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); | ||
| } | ||
|
|
||
| return matches; | ||
| export function useIsMobile(): boolean { | ||
| return useMediaQuery("max-md"); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.