Skip to content
Open
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
152 changes: 106 additions & 46 deletions components/SelectionShare.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { LinkIcon } from '@heroicons/react/24/solid';
import debounce from 'lodash.debounce';
import { useEffect, useMemo, useState } from 'react';
import ClickAwayListener from 'react-click-away-listener';
import { usePopper } from 'react-popper';

import HNIcon from '../content/HNIcon.svg';
import RedditIcon from '../content/RedditIcon.svg';
import TwitterIcon from '../content/TwitterIcon.svg';
import popperStyles from '../styles/Popper.module.css';
import { isUnderContentContainer } from './Container';
import { gtag } from './GTag';
import { LinkIcon } from "@heroicons/react/24/solid";
import debounce from "lodash.debounce";
import { useEffect, useMemo, useState } from "react";
import ClickAwayListener from "react-click-away-listener";
import { usePopper } from "react-popper";

import HNIcon from "../content/HNIcon.svg";
import RedditIcon from "../content/RedditIcon.svg";
import TwitterIcon from "../content/TwitterIcon.svg";
import popperStyles from "../styles/Popper.module.css";
import { isUnderContentContainer } from "./Container";
import { gtag } from "./GTag";

type VirtualElement = {
getBoundingClientRect: () => DOMRect;
Expand All @@ -18,8 +18,9 @@ type VirtualElement = {

type ShareButtonProps = {
callback?: () => void;
onError?: () => void;
title: string;
type: 'link' | 'twitter' | 'reddit' | 'hn';
type: "link" | "twitter" | "reddit" | "hn";
shareUrl: string;
shareTitle?: string;
className?: string;
Expand All @@ -29,6 +30,7 @@ type ShareButtonProps = {
export function ShareButton(props: ShareButtonProps) {
const {
callback,
onError,
title,
type,
shareUrl,
Expand All @@ -45,60 +47,113 @@ export function ShareButton(props: ShareButtonProps) {
};

const shareFuncs = {
link: () => {
navigator.clipboard.writeText(shareUrl);
link: async () => {
// Helper function for textarea fallback
const copyWithFallback = (): boolean => {
const textArea = document.createElement("textarea");
textArea.value = shareUrl;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
let success = false;
try {
success = document.execCommand("copy");
} catch {
success = false;
}
document.body.removeChild(textArea);
return success;
};

gtag('event', 'selection_share_clipboard', {
share_url: shareUrl,
});
try {
// Try the modern Clipboard API first
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(shareUrl);
} else {
// Fallback for older browsers
if (!copyWithFallback()) {
return false;
}
}

gtag("event", "selection_share_clipboard", {
share_url: shareUrl,
});

return true;
} catch (err) {
// Clipboard API failed (permissions, non-secure context, etc.)
// Try fallback before giving up
console.warn("Clipboard API failed, trying fallback:", err);
if (copyWithFallback()) {
gtag("event", "selection_share_clipboard", {
share_url: shareUrl,
});
return true;
}
console.error("Failed to copy to clipboard:", err);
return false;
}
},
twitter: () => {
window.open(
`https://twitter.com/intent/tweet/?url=${encodeURIComponent(
shareUrl
shareUrl,
)}&text=${
shareTitle ?? 'Shared from the Annotated Zanzibar Paper by AuthZed'
shareTitle ?? "Shared from the Annotated Zanzibar Paper by AuthZed"
}`,
'_blank'
"_blank",
);

gtag('event', 'selection_share_twitter', {
gtag("event", "selection_share_twitter", {
share_url: shareUrl,
});
},
reddit: () => {
window.open(
`https://reddit.com/submit/?url=${encodeURIComponent(
shareUrl
shareUrl,
)}&resubmit=true&title=${
shareTitle ?? 'Selection from the Annotated Zanzibar Paper by AuthZed'
shareTitle ?? "Selection from the Annotated Zanzibar Paper by AuthZed"
}`,
'_blank'
"_blank",
);

gtag('event', 'selection_share_reddit', {
gtag("event", "selection_share_reddit", {
share_url: shareUrl,
});
},
hn: () => {
window.open(
`https://news.ycombinator.com/submitlink?u=${encodeURIComponent(
shareUrl
shareUrl,
)}&t=${
shareTitle ?? 'Selection from the Annotated Zanzibar Paper by AuthZed'
shareTitle ?? "Selection from the Annotated Zanzibar Paper by AuthZed"
}`,
'_blank'
"_blank",
);

gtag('event', 'selection_share_hn', {
gtag("event", "selection_share_hn", {
share_url: shareUrl,
});
},
};

const onClick = () => {
shareFuncs[type]();
callback && callback();
const onClick = async () => {
if (type === "link") {
const success = await shareFuncs.link();
if (success) {
callback?.();
} else {
onError?.();
}
} else {
shareFuncs[type]();
callback?.();
}
};

const Icon = icons[type];
Expand All @@ -111,18 +166,18 @@ export function ShareButton(props: ShareButtonProps) {

function SelectionShare() {
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(
null
null,
);
const [arrowElement, setArrowElement] = useState<HTMLDivElement | null>(null);
const [virtualRef, setVirtualRef] = useState<VirtualElement | undefined>(
undefined
undefined,
);
const [visible, setVisible] = useState(false);
const [shareUrl, setShareUrl] = useState('');
const [statusMsg, setStatusMsg] = useState('');
const [shareUrl, setShareUrl] = useState("");
const [statusMsg, setStatusMsg] = useState("");
const { styles, attributes } = usePopper(virtualRef, popperElement, {
placement: 'top',
modifiers: [{ name: 'arrow', options: { element: arrowElement } }],
placement: "top",
modifiers: [{ name: "arrow", options: { element: arrowElement } }],
});

const debouncedSelectionHandler = useMemo(
Expand All @@ -138,25 +193,25 @@ function SelectionShare() {
setVirtualRef(range);
setVisible(true);
setShareUrl(document.URL);
setStatusMsg('');
setStatusMsg("");

gtag('event', 'selection_share_viewed', {
gtag("event", "selection_share_viewed", {
share_url: document.URL,
selection_length: range.toString().length,
});

return;
}
}, 200),
[]
[],
);

useEffect(() => {
document.addEventListener('selectionchange', debouncedSelectionHandler);
document.addEventListener("selectionchange", debouncedSelectionHandler);
return () => {
document.removeEventListener(
'selectionchange',
debouncedSelectionHandler
"selectionchange",
debouncedSelectionHandler,
);
debouncedSelectionHandler.cancel();
};
Expand All @@ -183,7 +238,12 @@ function SelectionShare() {
shareUrl={shareUrl}
className={`${popperStyles.button} border-l-0`}
iconClassName={popperStyles.icon}
callback={() => setStatusMsg('URL copied to your clipboard!')}
callback={() => setStatusMsg("URL copied to your clipboard!")}
onError={() =>
setStatusMsg(
"Couldn't copy URL. Try selecting it manually.",
)
}
title="Copy share URL to clipboard"
/>
<ShareButton
Expand Down