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

Feature/code block copy #349

Merged
merged 4 commits into from
Apr 20, 2021
Merged

Feature/code block copy #349

merged 4 commits into from
Apr 20, 2021

Conversation

jmfulgham
Copy link
Contributor

Add copy functionality to code blocks on hover.

image

@jmfulgham jmfulgham linked an issue Apr 16, 2021 that may be closed by this pull request
if (text) {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
Copy link
Collaborator

@andyrichardson andyrichardson Apr 19, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oversight on my part - we probably want the "copied" text to last for N seconds following the last click (which won't work with the current approach.

To get around this, we could either store the copied state in an object (allowing us to know when a subsequent copy has taken place thanks to the referential update)

const copied = useState({ state: true });

useEffect(() => {
 // ...
}, [copied])

Here's a sandbox example comparing the two.

Or if you prefer, we could implement a debounced "clearCopiedState" function - this is a little more explicit but takes more work so might be easier to avoid.

// Somewhere in utils
export const debounce = <T extends Function>(fn: T, delay: number): T => {
  let timeout;
  (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(() => fn(...args), delay);
  }
});

// In component
const clearCopiedState = useCallback(() => debounce(() => setCopied(false), 1000), []);

// ...
setCopied(true);
clearCopiedState();

@jmfulgham jmfulgham merged commit cf4948e into master Apr 20, 2021
@andyrichardson andyrichardson deleted the feature/code-block-copy branch April 20, 2021 14:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add copy to clipboard functionality to code blocks
2 participants