diff --git a/.changeset/bright-windows-wave.md b/.changeset/bright-windows-wave.md new file mode 100644 index 00000000..fbf62b74 --- /dev/null +++ b/.changeset/bright-windows-wave.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Add an `onShareWindowOpen` callback to popup-based share buttons. It receives the opened share window, or `null` when a popup blocker prevented it from opening, so apps can detect blocked popups and offer a fallback, as requested in #525. diff --git a/.changeset/calm-letters-break.md b/.changeset/calm-letters-break.md new file mode 100644 index 00000000..7544c403 --- /dev/null +++ b/.changeset/calm-letters-break.md @@ -0,0 +1,7 @@ +--- +'react-share': major +--- + +Change the default `EmailShareButton` `separator` from `" "` to `"\n"` so the shared URL appears on its own line below the email body. The new `buildEmailShareUrl` helper uses the same default. + +Reported in #582, where the URL was run together with the body text. Pass `separator=" "` to keep the previous formatting. diff --git a/.changeset/clear-servers-meet.md b/.changeset/clear-servers-meet.md new file mode 100644 index 00000000..622da8a3 --- /dev/null +++ b/.changeset/clear-servers-meet.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Mark the published ESM and CJS bundles with a `"use client"` directive so share buttons can be imported directly from React Server Components, such as Next.js App Router pages, without a local client wrapper. Requested in #491. diff --git a/.changeset/early-popups-open.md b/.changeset/early-popups-open.md new file mode 100644 index 00000000..0adda01d --- /dev/null +++ b/.changeset/early-popups-open.md @@ -0,0 +1,7 @@ +--- +'react-share': major +--- + +Open the share popup synchronously when `beforeOnClick` returns a promise, then load the share URL into it once the promise resolves. If the promise rejects, sharing is cancelled and the popup is closed. + +Previously the popup was opened only after awaiting `beforeOnClick`. By then the click's user activation had expired, so Safari and other browsers with strict popup blockers silently blocked the share window (#525, #506, #529). Rejections from `beforeOnClick` also used to surface as unhandled promise rejections. diff --git a/.changeset/fresh-colors-land.md b/.changeset/fresh-colors-land.md new file mode 100644 index 00000000..d5e2dfed --- /dev/null +++ b/.changeset/fresh-colors-land.md @@ -0,0 +1,5 @@ +--- +'react-share': patch +--- + +Update five raw icons to their networks' current brand colors: `BlueskyIcon` (`#0560FF`), `LineIcon` (`#06C755`), `PinterestIcon` (`#E60023`), `TumblrIcon` (`#001935`), and `GabIcon` (`#30CE7D`). They used older or approximate colors before. The legacy icons keep their v5 colors. diff --git a/.changeset/fresh-hosts-point.md b/.changeset/fresh-hosts-point.md new file mode 100644 index 00000000..155eccda --- /dev/null +++ b/.changeset/fresh-hosts-point.md @@ -0,0 +1,7 @@ +--- +'react-share': patch +--- + +Use the current share endpoints for X (`https://x.com/intent/post`), Threads (`https://www.threads.com/intent/post`), and Telegram (`https://t.me/share/url`). + +The old `twitter.com`, `threads.net`, and `telegram.me` hosts only keep working through redirects, which add an extra hop and can drop the share intent if those redirects are retired. Requested in #536. diff --git a/.changeset/full-marks-grow.md b/.changeset/full-marks-grow.md new file mode 100644 index 00000000..ccf5d0fc --- /dev/null +++ b/.changeset/full-marks-grow.md @@ -0,0 +1,5 @@ +--- +'react-share': patch +--- + +Draw the raw `LinkedinIcon` and `GabIcon` at full size. They reused the small glyphs from the badge icons without their backgrounds, so they filled less than half of the icon box and looked tiny next to the other raw icons. `LinkedinIcon` now uses the full rounded-square "in" mark in LinkedIn's current `#0A66C2` blue, and `GabIcon` puts the wordmark on a rounded green square. diff --git a/.changeset/mean-pans-marry.md b/.changeset/mean-pans-marry.md new file mode 100644 index 00000000..ff9336ac --- /dev/null +++ b/.changeset/mean-pans-marry.md @@ -0,0 +1,5 @@ +--- +'react-share': major +--- + +Remove all deprecated share count exports in v6, including the underlying share count implementation and the `jsonp` dependency that previously powered them. diff --git a/.changeset/navy-pencils-draw.md b/.changeset/navy-pencils-draw.md new file mode 100644 index 00000000..239159bb --- /dev/null +++ b/.changeset/navy-pencils-draw.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Draw the raw `LivejournalIcon` pencil in navy and white like the official LiveJournal logo. The pencil used to be cut out of the blue circle, so it took on the page background instead of its own colors. diff --git a/.changeset/new-ok-logo.md b/.changeset/new-ok-logo.md new file mode 100644 index 00000000..1cbc3827 --- /dev/null +++ b/.changeset/new-ok-logo.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Update the raw `OKIcon` to the 2023 OK logo: a white figure on an orange (`#FF7700`) rounded square, as served on ok.ru. The previous bare glyph was the old mark in an older orange. diff --git a/.changeset/new-threads-icon.md b/.changeset/new-threads-icon.md new file mode 100644 index 00000000..26e68bcc --- /dev/null +++ b/.changeset/new-threads-icon.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Update the raw `ThreadsIcon` to the 2026 Threads app icon: a white glyph on a black rounded square. The previous bare glyph was the old mark and looked lighter than the other raw icons. diff --git a/.changeset/odd-lions-share.md b/.changeset/odd-lions-share.md new file mode 100644 index 00000000..142e56b2 --- /dev/null +++ b/.changeset/odd-lions-share.md @@ -0,0 +1,5 @@ +--- +'react-share': major +--- + +Remove the deprecated `TwitterShareButton` and `TwitterIcon` aliases in v6. Use `XShareButton` and `XIcon` instead. diff --git a/.changeset/plain-glyphs-swap.md b/.changeset/plain-glyphs-swap.md new file mode 100644 index 00000000..89804d68 --- /dev/null +++ b/.changeset/plain-glyphs-swap.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Use the Lucide mail and share glyphs for the raw `EmailIcon` and `NativeShareIcon`. The previous glyphs were small badge glyphs on a 64x64 viewBox and looked undersized next to the other raw icons. diff --git a/.changeset/quiet-pockets-close.md b/.changeset/quiet-pockets-close.md new file mode 100644 index 00000000..0edca288 --- /dev/null +++ b/.changeset/quiet-pockets-close.md @@ -0,0 +1,7 @@ +--- +'react-share': major +--- + +Remove `PocketShareButton`, `PocketIcon`, `PocketLegacyIcon`, and `buildPocketShareUrl`, as well as `WorkplaceShareButton`, `WorkplaceIcon`, `WorkplaceLegacyIcon`, and `buildWorkplaceShareUrl`. + +Pocket shut down in July 2025 and Workplace from Meta shut down in June 2026, so these buttons could only open dead share pages. diff --git a/.changeset/round-badges-return.md b/.changeset/round-badges-return.md new file mode 100644 index 00000000..31af6923 --- /dev/null +++ b/.changeset/round-badges-return.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Put glyph-only raw icons on circle badges so every raw icon has a similar visual weight, like the v5 badges had. `XIcon`, `WeiboIcon`, `BlueskyIcon`, `EmailIcon`, `NativeShareIcon`, `InstapaperIcon`, and `TumblrIcon` now sit on a circle. The glyph is always drawn in white, so it stays legible on dark backgrounds. `NativeShareIcon` now uses a fixed blue (`#0A84FF`) instead of the current text color, which would hide the white glyph on dark pages. diff --git a/.changeset/silent-peaches-smell.md b/.changeset/silent-peaches-smell.md new file mode 100644 index 00000000..2fedf774 --- /dev/null +++ b/.changeset/silent-peaches-smell.md @@ -0,0 +1,7 @@ +--- +'react-share': minor +--- + +Add an explicit `mobileBehavior` prop to `FacebookMessengerShareButton`, `TelegramShareButton`, `ViberShareButton`, and `WhatsappShareButton`. + +This follows recurring mobile browser and app-handoff reports in #577, #551, #529, and #357. The new prop keeps web sharing as the default while allowing best-effort app-link behavior with `mobileBehavior="app"` or `mobileBehavior="auto"`. diff --git a/.changeset/small-keys-smash.md b/.changeset/small-keys-smash.md new file mode 100644 index 00000000..e3461828 --- /dev/null +++ b/.changeset/small-keys-smash.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Add low-level helper exports for advanced usage in v6, including per-network `build*ShareUrl` helpers and `openShareWindow(url, options)`. diff --git a/.changeset/sour-bulldogs-hunt.md b/.changeset/sour-bulldogs-hunt.md new file mode 100644 index 00000000..b95cc994 --- /dev/null +++ b/.changeset/sour-bulldogs-hunt.md @@ -0,0 +1,5 @@ +--- +'react-share': major +--- + +Drop React 17 support in v6 and require React 18 or 19 via `peerDependencies`. diff --git a/.changeset/swifty-bulldogs-shop.md b/.changeset/swifty-bulldogs-shop.md new file mode 100644 index 00000000..1812c408 --- /dev/null +++ b/.changeset/swifty-bulldogs-shop.md @@ -0,0 +1,7 @@ +--- +'react-share': major +--- + +Remove `title`, `summary`, and `source` from `LinkedinShareButton` and make `buildLinkedinShareUrl` URL-only. + +This follows the long-running LinkedIn compatibility problems in #550 and #362. LinkedIn no longer provides a reliable public URL-based way to prefill those fields, so v6 stops exposing them as if they were dependable. diff --git a/.changeset/tender-rivers-fly.md b/.changeset/tender-rivers-fly.md new file mode 100644 index 00000000..2d6fc6ae --- /dev/null +++ b/.changeset/tender-rivers-fly.md @@ -0,0 +1,7 @@ +--- +'react-share': minor +--- + +Add `canNativeShare(data)`, `shareNative(data)`, `NativeShareButton`, and a generic `NativeShareIcon` for browser-native sharing flows. + +This gives mobile and PWA use cases a first-class Web Share API path instead of forcing them through network-specific popup URLs, which is especially relevant for requests like #576 and the iOS/PWA limitations described in #551. diff --git a/.changeset/three-icons-divide.md b/.changeset/three-icons-divide.md new file mode 100644 index 00000000..8e38ba59 --- /dev/null +++ b/.changeset/three-icons-divide.md @@ -0,0 +1,11 @@ +--- +'react-share': major +--- + +Split the icon exports into raw and legacy families for v6. + +The existing `*Icon` exports now render SVG logos that are closer to the underlying network marks. The previous badge-style icons remain available as `*LegacyIcon` exports with the existing `round`, `borderRadius`, `bgStyle`, and `iconFillColor` props. + +If you want to preserve the v5 visuals, rename imports such as `FacebookIcon` to `FacebookLegacyIcon`, `XIcon` to `XLegacyIcon`, and `WhatsappIcon` to `WhatsappLegacyIcon`. + +If you keep the `*Icon` names, note that raw icons default to `size={24}` instead of `64`, and no longer accept `round`, `borderRadius`, `bgStyle`, or `iconFillColor`. diff --git a/.changeset/white-details-stay.md b/.changeset/white-details-stay.md new file mode 100644 index 00000000..5a6c0866 --- /dev/null +++ b/.changeset/white-details-stay.md @@ -0,0 +1,5 @@ +--- +'react-share': minor +--- + +Keep raw icon details white on dark backgrounds. Details cut out of the brand shape, such as the Facebook "f", the LinkedIn "in", the LINE lettering, and the inside of the WhatsApp and Viber bubbles, used to show the page background through them, so the logos turned into dark blobs on dark pages. `color` still recolors the brand-colored part of the icon. diff --git a/.changeset/wise-moles-travel.md b/.changeset/wise-moles-travel.md new file mode 100644 index 00000000..e24a906a --- /dev/null +++ b/.changeset/wise-moles-travel.md @@ -0,0 +1,5 @@ +--- +'react-share': major +--- + +Remove the deprecated `hashtags`, `related`, and `via` props from `ThreadsShareButton` in v6. Those props were ignored in v5 and were kept only for compatibility ahead of this major release. diff --git a/.changeset/wise-years-rest.md b/.changeset/wise-years-rest.md new file mode 100644 index 00000000..af9aa0ec --- /dev/null +++ b/.changeset/wise-years-rest.md @@ -0,0 +1,12 @@ +--- +'react-share': major +--- + +Replace the share button `title` prop with explicit v6 payload names: + +- `text` for Bluesky, Gab, Line, Telegram, Threads, and X +- `message` for WhatsApp and Viber +- `shareTitle` for Hatena, Instapaper, LiveJournal, Mail.ru, OK, Reddit, VK, and Weibo +- `postTitle` for Tumblr + +`htmlTitle` remains the native button tooltip/title attribute. diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 00000000..1fb54810 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "demo", + "runtimeExecutable": "npx", + "runtimeArgs": ["vite", "--config", "vite.demo.config.js", "--port", "5199", "--strictPort"], + "port": 5199 + } + ] +} diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..76dfe126 --- /dev/null +++ b/.npmrc @@ -0,0 +1,3 @@ +# eslint-plugin-react, eslint-plugin-import, and eslint-plugin-jsx-a11y +# have not published ESLint 10 peer ranges yet. +legacy-peer-deps=true diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md index d5860201..c0b00716 100644 --- a/README.md +++ b/README.md @@ -2,146 +2,200 @@ [![NPM](https://img.shields.io/npm/v/react-share.svg)](https://www.npmjs.com/package/react-share) ![npm bundle size](https://img.shields.io/bundlephobia/min/react-share) [![downloads](https://img.shields.io/npm/dm/react-share.svg?label=monthly%20downloads)](https://www.npmjs.com/package/react-share) [![downloads](https://img.shields.io/npm/dt/react-share.svg?label=total%20downloads)](https://www.npmjs.com/package/react-share) -> Social media share buttons and share counts for your React apps. +> Social media share buttons for your React apps. + +![Share buttons screenshot](example.svg) + +## Contents + +- [Features](#features) +- [Installation](#installation) +- [Quick start](#quick-start) +- [Supported networks](#supported-networks) +- [Share buttons](#share-buttons) +- [Native sharing](#native-sharing) +- [Mobile app handoff](#mobile-app-handoff) +- [Icons](#icons) +- [Building share URLs yourself](#building-share-urls-yourself) +- [Accessibility](#accessibility) +- [Troubleshooting](#troubleshooting) +- [Compatibility and versioning](#compatibility-and-versioning) +- [Development](#development) +- [License](#license) -![Share buttons screenshot](example.png) +## Features + +- No external script loading, i.e. no dependencies on network SDKs. +- Tree-shakeable ES modules: import only the buttons and icons you use. +- Share buttons for [22 networks](#supported-networks). +- Opens a popup share window instead of navigating away. +- A [native share button](#native-sharing) and helpers for the browser Web Share API. +- Opt-in [mobile app handoff](#mobile-app-handoff) for selected messaging networks. +- Bundled network icons in two styles, or bring your own icons. +- Marked with `"use client"`, so it works from React Server Components. -## Install +## Installation ```shell npm install react-share ``` -## Features +react-share 6 supports React 18 and 19. See [Compatibility and versioning](#compatibility-and-versioning) for older versions. -- no external script loading, i.e. no dependencies on SDKs -- supports tree shaking with ES modules -- opens a popup share-window -- share buttons for: - - [Bluesky](#blueskysharebutton) - - [Email](#emailsharebutton) - - [Facebook](#facebooksharebutton) - - [Facebook Messenger](#facebookmessengersharebutton) - - [Gab](#gabsharebutton) - - [Hatena](#hatenasharebutton) - - [Instapaper](#instapapersharebutton) - - [Line](#linesharebutton) - - [LinkedIn](#linkedinsharebutton) - - [LiveJournal](#livejournalsharebutton) - - [Mail.Ru](#mailrusharebutton) - - [Odnoklassniki](#oksharebutton) - - [Pinterest](#pinterestsharebutton) - - [Pocket](#pocketsharebutton) - - [Reddit](#redditsharebutton) - - [Telegram](#telegramsharebutton) - - [Threads](#threadssharebutton) - - [Tumblr](#tumblrsharebutton) - - [Viber](#vibersharebutton) - - [VK](#vksharebutton) - - [Weibo](#weibosharebutton) - - [Whatsapp](#whatsappsharebutton) - - [Workplace](#workplacesharebutton) - - [X](#xsharebutton) -- [share counts](#share-counts) (deprecated) -- social media icons included in the library -- supports also custom icons - -## Demo - -- [Deployed demo](https://npm-react-share-demo.netlify.app) (from [`./demo`](./demo/)) - -- Locally: clone the repository and run `npm install && npm run demo`. - -## React compatibility +Upgrading from v5? Follow the [v5 to v6 migration guide](./docs/migrate-v5-to-v6.md). -| Version | Compatible React versions | -| ------- | ----------------------------- | -| 5 | `17`, `18`, `19` | -| 4 | `^16.3`, `17`, `18` | -| 3.0.1 | `^16.3.` | -| 3 | `15`, `16` | -| 2 | `15`, `16` | -| 1 | `0.13.x`, `0.14.x`, `15.x.x`. | +## Quick start -## API +Each network has a share button and a matching icon. Put the icon (or any other content) inside the button, and give icon-only buttons an `aria-label`: -### Share buttons +```jsx +import { FacebookShareButton, FacebookIcon, XShareButton, XIcon } from "react-share"; + +const shareUrl = "https://example.com/article"; + +export function ShareBar() { + return ( +
+ + + + + + + +
+ ); +} +``` + +Clicking a button opens the network's share page in a popup window. + +See every button in action in the [deployed demo](https://npm-react-share-demo.netlify.app) (source in [`./demo`](./demo/)). + +## Supported networks + +| Network | Button | Icon | Network-specific props | +| ------------------ | --------------------------------------------------------------- | ----------------------- | -------------------------------------------------- | +| Bluesky | [`BlueskyShareButton`](#blueskysharebutton) | `BlueskyIcon` | `text`, `separator` | +| Email | [`EmailShareButton`](#emailsharebutton) | `EmailIcon` | `subject`, `body`, `separator` | +| Facebook | [`FacebookShareButton`](#facebooksharebutton) | `FacebookIcon` | `hashtag` | +| Facebook Messenger | [`FacebookMessengerShareButton`](#facebookmessengersharebutton) | `FacebookMessengerIcon` | **`appId`**, `redirectUri`, `to`, `mobileBehavior` | +| Gab | [`GabShareButton`](#gabsharebutton) | `GabIcon` | `text` | +| Hatena | [`HatenaShareButton`](#hatenasharebutton) | `HatenaIcon` | `shareTitle` | +| Instapaper | [`InstapaperShareButton`](#instapapersharebutton) | `InstapaperIcon` | `shareTitle`, `description` | +| Line | [`LineShareButton`](#linesharebutton) | `LineIcon` | `text` | +| LinkedIn | [`LinkedinShareButton`](#linkedinsharebutton) | `LinkedinIcon` | – | +| LiveJournal | [`LivejournalShareButton`](#livejournalsharebutton) | `LivejournalIcon` | `shareTitle`, `description` | +| Mail.Ru | [`MailruShareButton`](#mailrusharebutton) | `MailruIcon` | `shareTitle`, `description`, `imageUrl` | +| Odnoklassniki | [`OKShareButton`](#oksharebutton) | `OKIcon` | `shareTitle`, `description`, `image` | +| Pinterest | [`PinterestShareButton`](#pinterestsharebutton) | `PinterestIcon` | **`media`**, `description`, `pinId` | +| Reddit | [`RedditShareButton`](#redditsharebutton) | `RedditIcon` | `shareTitle` | +| Telegram | [`TelegramShareButton`](#telegramsharebutton) | `TelegramIcon` | `text`, `mobileBehavior` | +| Threads | [`ThreadsShareButton`](#threadssharebutton) | `ThreadsIcon` | `text` | +| Tumblr | [`TumblrShareButton`](#tumblrsharebutton) | `TumblrIcon` | `postTitle`, `tags`, `caption`, `posttype` | +| Viber | [`ViberShareButton`](#vibersharebutton) | `ViberIcon` | `message`, `separator`, `mobileBehavior` | +| VK | [`VKShareButton`](#vksharebutton) | `VKIcon` | `shareTitle`, `image`, `noParse`, `noVkLinks` | +| Weibo | [`WeiboShareButton`](#weibosharebutton) | `WeiboIcon` | `shareTitle`, `image` | +| WhatsApp | [`WhatsappShareButton`](#whatsappsharebutton) | `WhatsappIcon` | `message`, `separator`, `mobileBehavior` | +| X | [`XShareButton`](#xsharebutton) | `XIcon` | `text`, `via`, `hashtags`, `related` | +| Device share sheet | [`NativeShareButton`](#nativesharebutton) | `NativeShareIcon` | `title`, `text`, `url`, `files` | + +Required props are in **bold**. Every icon also has a badge-style `*LegacyIcon` variant (see [Icons](#icons)), and every network button has a matching `build*ShareUrl` helper (see [Building share URLs yourself](#building-share-urls-yourself)). + +## Share buttons All share buttons render a native ` + ); + }, +); + +NativeShareButton.displayName = 'NativeShareButton'; diff --git a/src/NativeShareIcon.tsx b/src/NativeShareIcon.tsx new file mode 100644 index 00000000..3447336c --- /dev/null +++ b/src/NativeShareIcon.tsx @@ -0,0 +1,12 @@ +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; + +// Lucide "share" (ISC license). +export function NativeShareIcon(props: RawIconProps) { + return ( + + + + + + ); +} diff --git a/src/NativeShareLegacyIcon.tsx b/src/NativeShareLegacyIcon.tsx new file mode 100644 index 00000000..6670cb2d --- /dev/null +++ b/src/NativeShareLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function NativeShareLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/OKIcon.tsx b/src/OKIcon.tsx index e288161f..d34d798c 100644 --- a/src/OKIcon.tsx +++ b/src/OKIcon.tsx @@ -1,9 +1,18 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function OKIcon(props: IconProps) { +// OK 2023 logo. +export function OKIcon(props: RawIconProps) { return ( - - - + + + + + ); } diff --git a/src/OKLegacyIcon.tsx b/src/OKLegacyIcon.tsx new file mode 100644 index 00000000..49f1ffc7 --- /dev/null +++ b/src/OKLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function OKLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/OKShareButton.tsx b/src/OKShareButton.tsx index 45e9c735..792fe388 100644 --- a/src/OKShareButton.tsx +++ b/src/OKShareButton.tsx @@ -1,11 +1,11 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; function okLink( url: string, - { title, description, image }: { title?: string; description?: string; image?: string }, + { shareTitle, description, image }: { shareTitle?: string; description?: string; image?: string }, ) { assert(url, 'ok.url'); @@ -13,31 +13,33 @@ function okLink( 'https://connect.ok.ru/offer' + objectToGetParams({ url, - title, + title: shareTitle, description, imageUrl: image, }) ); } +export const buildOKShareUrl = okLink; + type OKShareButtonProps = Omit< - ShareButtonProps<{ title?: string; description?: string; image?: string }>, + ShareButtonProps<{ shareTitle?: string; description?: string; image?: string }>, 'title' > & { description?: string; image?: string; - title?: string; + shareTitle?: string; }; -const OKShareButton = forwardRef( - ({ description, image, title, ...props }, ref) => ( +export const OKShareButton = forwardRef( + ({ description, image, shareTitle, ...props }, ref) => ( ( ); OKShareButton.displayName = 'OKShareButton'; - -export default OKShareButton; diff --git a/src/OKShareCount.ts b/src/OKShareCount.ts deleted file mode 100644 index dbcadcb6..00000000 --- a/src/OKShareCount.ts +++ /dev/null @@ -1,58 +0,0 @@ -import jsonp from 'jsonp'; - -import objectToGetParams from './utils/objectToGetParams'; -import createShareCount from './hocs/createShareCount'; - -declare global { - interface Window { - OK: { - Share: { - count: (index: number, _count: number) => void; - }; - callbacks: ((count?: number) => void)[]; - }; - ODKL: { - updateCount: (index: string, count: string) => void; - }; - } -} - -function getOKShareCount(shareUrl: string, callback: (shareCount?: number) => void) { - if (!window.OK) { - window.OK = { - Share: { - count: function count(index, _count) { - window.OK.callbacks[index]?.(_count); - }, - }, - callbacks: [], - }; - } - - const url = 'https://connect.ok.ru/dk'; - const index = window.OK.callbacks.length; - - window.ODKL = { - updateCount(index, count) { - const callbackIndex = index === '' ? 0 : parseInt(index.replace('react-share-', ''), 10); - window.OK.callbacks[callbackIndex]?.(count === '' ? undefined : parseInt(count, 10)); - }, - }; - window.OK.callbacks.push(callback); - - return jsonp( - url + - objectToGetParams({ - 'st.cmd': 'extLike', - uid: `react-share-${index}`, - ref: shareUrl, - }), - ); -} - -/** - * @deprecated Share counts are deprecated and will be removed in v6. - */ -const OKShareCount = createShareCount(getOKShareCount); - -export default OKShareCount; diff --git a/src/PinterestIcon.tsx b/src/PinterestIcon.tsx index 8906f693..0915677b 100644 --- a/src/PinterestIcon.tsx +++ b/src/PinterestIcon.tsx @@ -1,9 +1,19 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function PinterestIcon(props: IconProps) { +export function PinterestIcon(props: RawIconProps) { return ( - - - + + + + + } + color="#E60023" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/PinterestLegacyIcon.tsx b/src/PinterestLegacyIcon.tsx new file mode 100644 index 00000000..e7d76cef --- /dev/null +++ b/src/PinterestLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function PinterestLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/PinterestShareButton.tsx b/src/PinterestShareButton.tsx index 8118191c..3b7d5b3a 100644 --- a/src/PinterestShareButton.tsx +++ b/src/PinterestShareButton.tsx @@ -1,7 +1,7 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; type PinterestShareProps = { media: string; @@ -29,13 +29,15 @@ function pinterestLink(url: string, { media, description, pinId }: PinterestShar ); } -const PinterestShareButton = forwardRef( +export const buildPinterestShareUrl = pinterestLink; + +export const PinterestShareButton = forwardRef( ({ description, media, pinId, ...props }, ref) => ( void) { - const url = 'https://api.pinterest.com/v1/urls/count.json'; - - jsonp( - url + - objectToGetParams({ - url: shareUrl, - }), - (err, data) => { - callback(data ? data.count : undefined); - }, - ); -} - -/** - * @deprecated Share counts are deprecated and will be removed in v6. - */ -const PinterestShareCount = createShareCount(getPinterestShareCount); - -export default PinterestShareCount; diff --git a/src/PocketIcon.tsx b/src/PocketIcon.tsx deleted file mode 100644 index 885634d4..00000000 --- a/src/PocketIcon.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import IconBase, { type IconProps } from './icons/IconBase'; - -export default function PocketIcon(props: IconProps) { - return ( - - - - ); -} diff --git a/src/PocketShareButton.tsx b/src/PocketShareButton.tsx deleted file mode 100644 index 02c233b1..00000000 --- a/src/PocketShareButton.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; - -type PocketShareButtonProps = Omit, 'title'> & { - title?: string; -}; - -function pocketLink(url: string, { title }: { title?: string }) { - assert(url, 'pocket.url'); - - return ( - 'https://getpocket.com/save' + - objectToGetParams({ - url, - title, - }) - ); -} - -const PocketShareButton = forwardRef( - ({ title, ...props }, ref) => ( - - ), -); - -PocketShareButton.displayName = 'PocketShareButton'; - -export default PocketShareButton; diff --git a/src/RedditIcon.tsx b/src/RedditIcon.tsx index d2d9a1cb..2bad7a52 100644 --- a/src/RedditIcon.tsx +++ b/src/RedditIcon.tsx @@ -1,9 +1,14 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function RedditIcon(props: IconProps) { +export function RedditIcon(props: RawIconProps) { return ( - - - + } + color="#FF4500" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/RedditLegacyIcon.tsx b/src/RedditLegacyIcon.tsx new file mode 100644 index 00000000..ef342448 --- /dev/null +++ b/src/RedditLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function RedditLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/RedditShareButton.tsx b/src/RedditShareButton.tsx index b6d683ca..9c64c76c 100644 --- a/src/RedditShareButton.tsx +++ b/src/RedditShareButton.tsx @@ -1,32 +1,34 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; -type RedditShareButtonProps = Omit, 'title'> & { - title?: string; +type RedditShareButtonProps = Omit, 'title'> & { + shareTitle?: string; }; -function redditLink(url: string, { title }: { title?: string }) { +function redditLink(url: string, { shareTitle }: { shareTitle?: string }) { assert(url, 'reddit.url'); return ( 'https://www.reddit.com/submit' + objectToGetParams({ url, - title, + title: shareTitle, }) ); } -const RedditShareButton = forwardRef( - ({ title, ...props }, ref) => ( +export const buildRedditShareUrl = redditLink; + +export const RedditShareButton = forwardRef( + ({ shareTitle, ...props }, ref) => ( ( ); RedditShareButton.displayName = 'RedditShareButton'; - -export default RedditShareButton; diff --git a/src/RedditShareCount.ts b/src/RedditShareCount.ts deleted file mode 100644 index 269feea5..00000000 --- a/src/RedditShareCount.ts +++ /dev/null @@ -1,26 +0,0 @@ -import jsonp from 'jsonp'; - -import createShareCount from './hocs/createShareCount'; - -function getRedditShareCount(shareUrl: string, callback: (shareCount?: number) => void) { - const endpoint = `https://www.reddit.com/api/info.json?limit=1&url=${shareUrl}`; - - jsonp(endpoint, { param: 'jsonp' }, (err, response) => { - callback( - !err && - response && - response.data && - response.data.children.length > 0 && - response.data.children[0].data.score - ? response.data.children[0].data.score - : undefined, - ); - }); -} - -/** - * @deprecated Share counts are deprecated and will be removed in v6. - */ -const RedditShareCount = createShareCount(getRedditShareCount); - -export default RedditShareCount; diff --git a/src/ShareButton.tsx b/src/ShareButton.tsx index 13bee377..db7d4843 100644 --- a/src/ShareButton.tsx +++ b/src/ShareButton.tsx @@ -1,12 +1,11 @@ -import { Children, isValidElement } from 'react'; import type React from 'react'; import cx from 'classnames'; +import { openShareWindow, type LinkBehavior, type WindowPosition } from './shareWindow'; +import { getButtonBorderRadius, hasTextContent, isPromise } from './utils/buttonHelpers'; type NetworkLink = (url: string, options: LinkOptions) => string; -type WindowPosition = 'windowCenter' | 'screenCenter'; type NativeButtonProps = Omit, 'onClick'>; -type IconShapeProps = { borderRadius?: number; round?: boolean }; const DEFAULT_ARIA_LABELS = { bluesky: 'Share on Bluesky', @@ -22,121 +21,24 @@ const DEFAULT_ARIA_LABELS = { mailru: 'Share on Mail.ru', ok: 'Share on OK', pinterest: 'Pin on Pinterest', - pocket: 'Save to Pocket', reddit: 'Share on Reddit', telegram: 'Share on Telegram', threads: 'Share on Threads', tumblr: 'Share on Tumblr', - twitter: 'Share on X', viber: 'Share on Viber', vk: 'Share on VK', weibo: 'Share on Weibo', whatsapp: 'Share on WhatsApp', - workplace: 'Share on Workplace', + x: 'Share on X', } as const; -const isPromise = (obj: unknown): obj is Promise => - !!obj && - (typeof obj === 'object' || typeof obj === 'function') && - 'then' in obj && - typeof (obj as Promise).then === 'function'; - -const getBoxPositionOnWindowCenter = (width: number, height: number) => ({ - left: window.outerWidth / 2 + (window.screenX || window.screenLeft || 0) - width / 2, - top: window.outerHeight / 2 + (window.screenY || window.screenTop || 0) - height / 2, -}); - -const getBoxPositionOnScreenCenter = (width: number, height: number) => ({ - top: (window.screen.height - height) / 2, - left: (window.screen.width - width) / 2, -}); - -function getButtonBorderRadius(children: React.ReactNode) { - const childNodes = Children.toArray(children); - - if (childNodes.length !== 1) { - return undefined; - } - - const [child] = childNodes; - - if (!isValidElement(child)) { - return undefined; - } - - if (child.props.round) { - return '50%'; - } - - return child.props.borderRadius ?? 0; -} - -function hasTextContent(children: React.ReactNode): boolean { - return Children.toArray(children).some(child => { - if (typeof child === 'string') { - return child.trim().length > 0; - } - - if (typeof child === 'number') { - return true; - } - - if (!isValidElement<{ children?: React.ReactNode }>(child)) { - return false; - } - - return hasTextContent(child.props.children); - }); -} - -function windowOpen( - url: string, - { height, width, ...configRest }: { height: number; width: number; [key: string]: unknown }, - onClose?: (dialog: Window | null) => void, -) { - const config: { [key: string]: string | number } = { - height, - width, - location: 'no', - toolbar: 'no', - status: 'no', - directories: 'no', - menubar: 'no', - scrollbars: 'yes', - resizable: 'no', - centerscreen: 'yes', - chrome: 'yes', - ...configRest, - }; - - const shareDialog = window.open( - url, - '', - Object.keys(config) - .map(key => `${key}=${config[key]}`) - .join(', '), - ); - - if (onClose) { - const interval = window.setInterval(() => { - try { - if (shareDialog === null || shareDialog.closed) { - window.clearInterval(interval); - onClose(shareDialog); - } - } catch (e) { - console.error(e); - } - }, 1000); - } - - return shareDialog; -} - export interface Props extends NativeButtonProps { /** * Takes a function that returns a Promise to be fulfilled before calling * `onClick`. If you do not return promise, `onClick` is called immediately. + * When a Promise is returned, the share popup opens immediately and loads the + * share URL once the Promise resolves. Rejecting the Promise cancels sharing + * and closes the popup. */ beforeOnClick?: () => Promise | void; children: React.ReactNode; @@ -151,10 +53,11 @@ export interface Props extends NativeButtonProps { forwardedRef?: React.Ref; /** * Passes as the native `title` attribute for the `button` element. - * This uses `htmlTitle` instead of `title` because many share buttons - * already use `title` for the share payload sent to the target network. + * This uses `htmlTitle` instead of `title` so it does not collide with + * share payload props exposed by the button components. */ htmlTitle?: HTMLButtonElement['title']; + linkBehavior?: LinkBehavior; networkName: string; networkLink: NetworkLink; onClick?: (event: React.MouseEvent, link: string) => void; @@ -162,6 +65,11 @@ export interface Props extends NativeButtonProps { * Takes a function to be called after closing share dialog. */ onShareWindowClose?: () => void; + /** + * Takes a function to be called with the opened share window, or `null` + * when a popup blocker prevented it from opening. + */ + onShareWindowOpen?: (shareWindow: Window | null) => void; openShareDialogOnClick?: boolean; opts: LinkOptions; resetButtonStyle?: boolean; @@ -177,10 +85,10 @@ export interface Props extends NativeButtonProps { export type ShareButtonProps> = Omit< Props, - 'forwardedRef' | 'networkLink' | 'networkName' | 'opts' + 'forwardedRef' | 'linkBehavior' | 'networkLink' | 'networkName' | 'opts' >; -export default function ShareButton>({ +export function ShareButton>({ 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, beforeOnClick, @@ -190,10 +98,12 @@ export default function ShareButton> disabledStyle = { opacity: 0.6 }, forwardedRef, htmlTitle, + linkBehavior = 'popup', networkLink, networkName, // deconstructed from ...rest to prevent passing it to the button element onClick, onShareWindowClose, + onShareWindowOpen, openShareDialogOnClick = true, opts, resetButtonStyle = true, @@ -222,24 +132,42 @@ export default function ShareButton> event.preventDefault(); - if (beforeOnClick) { - const returnVal = beforeOnClick(); + const returnVal = beforeOnClick?.(); + const opensPopup = openShareDialogOnClick && linkBehavior === 'popup'; + const windowOptions = { + height: windowHeight, + onClose: onShareWindowClose, + position: windowPosition, + width: windowWidth, + }; - if (isPromise(returnVal)) { + if (isPromise(returnVal)) { + // Popup blockers only allow window.open during the click's user activation, + // which is gone after an await, so open a blank popup now and load the link later. + const shareWindow = opensPopup ? openShareWindow('about:blank', windowOptions) : null; + + try { await returnVal; + } catch { + shareWindow?.close(); + return; } - } - if (openShareDialogOnClick) { - const windowConfig = { - height: windowHeight, - width: windowWidth, - ...(windowPosition === 'windowCenter' - ? getBoxPositionOnWindowCenter(windowWidth, windowHeight) - : getBoxPositionOnScreenCenter(windowWidth, windowHeight)), - }; + if (shareWindow && !shareWindow.closed) { + shareWindow.location.replace(link); + } + + if (opensPopup) { + onShareWindowOpen?.(shareWindow); + } + } else if (opensPopup) { + const shareWindow = openShareWindow(link, windowOptions); + + onShareWindowOpen?.(shareWindow); + } - windowOpen(link, windowConfig, onShareWindowClose); + if (openShareDialogOnClick && linkBehavior === 'navigate') { + window.location.href = link; } if (onClick) { diff --git a/src/TelegramIcon.tsx b/src/TelegramIcon.tsx index 89821351..700833b6 100644 --- a/src/TelegramIcon.tsx +++ b/src/TelegramIcon.tsx @@ -1,9 +1,14 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function TelegramIcon(props: IconProps) { +export function TelegramIcon(props: RawIconProps) { return ( - - - + } + color="#26A5E4" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/TelegramLegacyIcon.tsx b/src/TelegramLegacyIcon.tsx new file mode 100644 index 00000000..f505a502 --- /dev/null +++ b/src/TelegramLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function TelegramLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/TelegramShareButton.tsx b/src/TelegramShareButton.tsx index 8199109e..3a82c9d3 100644 --- a/src/TelegramShareButton.tsx +++ b/src/TelegramShareButton.tsx @@ -1,38 +1,61 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { type MobileBehavior, resolveMobileShareStrategy } from './mobile'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; -type TelegramShareButtonProps = Omit, 'title'> & { - title?: string; +type TelegramShareButtonProps = Omit, 'title'> & { + mobileBehavior?: MobileBehavior; + text?: string; }; -function telegramLink(url: string, { title }: { title?: string }) { +function telegramLink(url: string, { text }: { text?: string }) { assert(url, 'telegram.url'); return ( - 'https://telegram.me/share/url' + + 'https://t.me/share/url' + objectToGetParams({ url, - text: title, + text, }) ); } -const TelegramShareButton = forwardRef( - ({ title, ...props }, ref) => ( - - ), +export const buildTelegramShareUrl = telegramLink; + +function telegramAppLink(url: string, { text }: { text?: string }) { + assert(url, 'telegram.url'); + + return ( + 'tg://msg_url' + + objectToGetParams({ + url, + text, + }) + ); +} + +export const TelegramShareButton = forwardRef( + ({ mobileBehavior, text, ...props }, ref) => { + const { linkBehavior, networkLink } = resolveMobileShareStrategy( + mobileBehavior, + buildTelegramShareUrl, + telegramAppLink, + ); + + return ( + + ); + }, ); TelegramShareButton.displayName = 'TelegramShareButton'; - -export default TelegramShareButton; diff --git a/src/ThreadsIcon.tsx b/src/ThreadsIcon.tsx index f2252bef..b71d78c3 100644 --- a/src/ThreadsIcon.tsx +++ b/src/ThreadsIcon.tsx @@ -1,9 +1,14 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function ThreadsIcon(props: IconProps) { +// Threads 2026 app icon. +export function ThreadsIcon(props: RawIconProps) { return ( - - - + + + + ); } diff --git a/src/ThreadsLegacyIcon.tsx b/src/ThreadsLegacyIcon.tsx new file mode 100644 index 00000000..c4be13b6 --- /dev/null +++ b/src/ThreadsLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function ThreadsLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/ThreadsShareButton.tsx b/src/ThreadsShareButton.tsx index 903d1bcb..24e26727 100644 --- a/src/ThreadsShareButton.tsx +++ b/src/ThreadsShareButton.tsx @@ -1,50 +1,38 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; -function threadsLink(url: string, { title }: { title?: string }) { +function threadsLink(url: string, { text }: { text?: string }) { assert(url, 'threads.url'); return ( - 'https://threads.net/intent/post' + + 'https://www.threads.com/intent/post' + objectToGetParams({ url, - text: title, + text, }) ); } -type ThreadsShareButtonProps = Omit, 'title'> & { - /** @deprecated This prop is ignored and will be removed in v6. */ - hashtags?: string[]; - /** @deprecated This prop is ignored and will be removed in v6. */ - related?: string[]; - title?: string; - /** @deprecated This prop is ignored and will be removed in v6. */ - via?: string; -}; +export const buildThreadsShareUrl = threadsLink; -const ThreadsShareButton = forwardRef( - ({ hashtags, related, title, via, ...props }, ref) => { - void hashtags; - void related; - void via; +type ThreadsShareButtonProps = Omit, 'title'> & { + text?: string; +}; - return ( - - ); - }, +export const ThreadsShareButton = forwardRef( + ({ text, ...props }, ref) => ( + + ), ); ThreadsShareButton.displayName = 'ThreadsShareButton'; - -export default ThreadsShareButton; diff --git a/src/TumblrIcon.tsx b/src/TumblrIcon.tsx index eff51356..806c9579 100644 --- a/src/TumblrIcon.tsx +++ b/src/TumblrIcon.tsx @@ -1,9 +1,9 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function TumblrIcon(props: IconProps) { +export function TumblrIcon(props: RawIconProps) { return ( - - - + + + ); } diff --git a/src/TumblrLegacyIcon.tsx b/src/TumblrLegacyIcon.tsx new file mode 100644 index 00000000..a484ec49 --- /dev/null +++ b/src/TumblrLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function TumblrLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/TumblrShareButton.tsx b/src/TumblrShareButton.tsx index f469f664..4bd77251 100644 --- a/src/TumblrShareButton.tsx +++ b/src/TumblrShareButton.tsx @@ -1,16 +1,16 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; function tumblrLink( url: string, { - title, + postTitle, caption, tags, posttype, - }: { title?: string; caption?: string; tags?: string; posttype?: 'link' | string }, + }: { postTitle?: string; caption?: string; tags?: string; posttype?: 'link' | string }, ) { assert(url, 'tumblr.url'); @@ -18,7 +18,7 @@ function tumblrLink( 'https://www.tumblr.com/widgets/share/tool' + objectToGetParams({ canonicalUrl: url, - title, + title: postTitle, caption, tags, posttype, @@ -26,8 +26,10 @@ function tumblrLink( ); } +export const buildTumblrShareUrl = tumblrLink; + type Options = { - title?: string; + postTitle?: string; caption?: string; posttype?: 'link' | string; }; @@ -35,15 +37,15 @@ type Options = { type TumblrShareButtonProps = Omit, 'title'> & Options & { tags?: string[] }; -const TumblrShareButton = forwardRef( - ({ caption, posttype, tags, title, ...props }, ref) => ( +export const TumblrShareButton = forwardRef( + ({ caption, postTitle, posttype, tags, ...props }, ref) => ( ( ); TumblrShareButton.displayName = 'TumblrShareButton'; - -export default TumblrShareButton; diff --git a/src/TumblrShareCount.ts b/src/TumblrShareCount.ts deleted file mode 100644 index ebf39ac4..00000000 --- a/src/TumblrShareCount.ts +++ /dev/null @@ -1,25 +0,0 @@ -import jsonp from 'jsonp'; - -import objectToGetParams from './utils/objectToGetParams'; -import createShareCount from './hocs/createShareCount'; - -function getTumblrShareCount(shareUrl: string, callback: (shareCount?: number) => void) { - const endpoint = 'https://api.tumblr.com/v2/share/stats'; - - return jsonp( - endpoint + - objectToGetParams({ - url: shareUrl, - }), - (err, data) => { - callback(!err && data && data.response ? data.response.note_count : undefined); - }, - ); -} - -/** - * @deprecated Share counts are deprecated and will be removed in v6. - */ -const TumblrShareCount = createShareCount(getTumblrShareCount); - -export default TumblrShareCount; diff --git a/src/TwitterIcon.tsx b/src/TwitterIcon.tsx deleted file mode 100644 index 15fc28ae..00000000 --- a/src/TwitterIcon.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import IconBase, { type IconProps } from './icons/IconBase'; - -export default function TwitterIcon(props: IconProps) { - return ( - - - - ); -} diff --git a/src/TwitterShareButton.tsx b/src/TwitterShareButton.tsx deleted file mode 100644 index 30e66bf3..00000000 --- a/src/TwitterShareButton.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { forwardRef, type ComponentPropsWithoutRef } from 'react'; -import XShareButton from './XShareButton'; - -type TwitterShareButtonProps = ComponentPropsWithoutRef; - -/** @deprecated Use XShareButton instead. */ -const TwitterShareButton = forwardRef((props, ref) => ( - -)); - -TwitterShareButton.displayName = 'TwitterShareButton'; - -export default TwitterShareButton; diff --git a/src/VKIcon.tsx b/src/VKIcon.tsx index af559ec2..64b7e08c 100644 --- a/src/VKIcon.tsx +++ b/src/VKIcon.tsx @@ -1,9 +1,14 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function VKIcon(props: IconProps) { +export function VKIcon(props: RawIconProps) { return ( - - - + } + color="#0077FF" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/VKLegacyIcon.tsx b/src/VKLegacyIcon.tsx new file mode 100644 index 00000000..35e49d45 --- /dev/null +++ b/src/VKLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function VKLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/VKShareButton.tsx b/src/VKShareButton.tsx index 0c8c5dff..e6075e54 100644 --- a/src/VKShareButton.tsx +++ b/src/VKShareButton.tsx @@ -1,10 +1,10 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; type Options = { - title?: string; + shareTitle?: string; image?: string; noParse?: boolean; noVkLinks?: boolean; @@ -12,14 +12,14 @@ type Options = { type VKShareButtonProps = Omit, 'title'> & Options; -function vkLink(url: string, { title, image, noParse, noVkLinks }: Options) { +function vkLink(url: string, { shareTitle, image, noParse, noVkLinks }: Options) { assert(url, 'vk.url'); return ( 'https://vk.com/share.php' + objectToGetParams({ url, - title, + title: shareTitle, image, noparse: noParse ? 1 : 0, no_vk_links: noVkLinks ? 1 : 0, @@ -27,15 +27,17 @@ function vkLink(url: string, { title, image, noParse, noVkLinks }: Options) { ); } -const VKShareButton = forwardRef( - ({ image, noParse, noVkLinks, title, ...props }, ref) => ( +export const buildVKShareUrl = vkLink; + +export const VKShareButton = forwardRef( + ({ image, noParse, noVkLinks, shareTitle, ...props }, ref) => ( ( ); VKShareButton.displayName = 'VKShareButton'; - -export default VKShareButton; diff --git a/src/VKShareCount.ts b/src/VKShareCount.ts deleted file mode 100644 index f9596ced..00000000 --- a/src/VKShareCount.ts +++ /dev/null @@ -1,44 +0,0 @@ -import jsonp from 'jsonp'; - -import objectToGetParams from './utils/objectToGetParams'; -import createShareCount from './hocs/createShareCount'; - -declare global { - interface Window { - VK: { - Share?: { - count: (index: number, count: number) => void; - }; - callbacks?: ((count?: number) => void)[]; - }; - } -} - -function getVKShareCount(shareUrl: string, callback: (shareCount?: number) => void) { - if (!window.VK) window.VK = {}; - window.VK.Share = { - count: (index, count) => window.VK.callbacks?.[index]?.(count), - }; - window.VK.callbacks = []; - - const url = 'https://vk.com/share.php'; - const index = window.VK.callbacks.length; - - window.VK.callbacks.push(callback); - - return jsonp( - url + - objectToGetParams({ - act: 'count', - index, - url: shareUrl, - }), - ); -} - -/** - * @deprecated Share counts are deprecated and will be removed in v6. - */ -const VKShareCount = createShareCount(getVKShareCount); - -export default VKShareCount; diff --git a/src/ViberIcon.tsx b/src/ViberIcon.tsx index 98ac90d4..e7da8d30 100644 --- a/src/ViberIcon.tsx +++ b/src/ViberIcon.tsx @@ -1,9 +1,16 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function ViberIcon(props: IconProps) { +export function ViberIcon(props: RawIconProps) { return ( - - - + + } + color="#7360F2" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/ViberLegacyIcon.tsx b/src/ViberLegacyIcon.tsx new file mode 100644 index 00000000..95f19292 --- /dev/null +++ b/src/ViberLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function ViberLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/ViberShareButton.tsx b/src/ViberShareButton.tsx index 6606c089..85ac6695 100644 --- a/src/ViberShareButton.tsx +++ b/src/ViberShareButton.tsx @@ -1,43 +1,57 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { type MobileBehavior, resolveMobileShareStrategy } from './mobile'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; type ViberShareButtonProps = Omit< - ShareButtonProps<{ title?: string; separator?: string }>, + ShareButtonProps<{ message?: string; separator?: string }>, 'title' > & { + message?: string; + mobileBehavior?: MobileBehavior; separator?: string; - title?: string; }; -function viberLink(url: string, { title, separator }: { title?: string; separator?: string }) { +function viberLink( + url: string, + { message, separator = ' ' }: { message?: string; separator?: string }, +) { assert(url, 'viber.url'); return ( 'viber://forward' + objectToGetParams({ - text: title ? title + separator + url : url, + text: message ? message + separator + url : url, }) ); } -const ViberShareButton = forwardRef( - ({ separator, title, ...props }, ref) => ( - - ), +export const buildViberShareUrl = viberLink; + +export const ViberShareButton = forwardRef( + ({ message, mobileBehavior, separator, ...props }, ref) => { + const { linkBehavior, networkLink } = resolveMobileShareStrategy( + mobileBehavior, + buildViberShareUrl, + buildViberShareUrl, + ); + + return ( + + ); + }, ); ViberShareButton.displayName = 'ViberShareButton'; - -export default ViberShareButton; diff --git a/src/WeiboIcon.tsx b/src/WeiboIcon.tsx index 8596579b..5d7e775f 100644 --- a/src/WeiboIcon.tsx +++ b/src/WeiboIcon.tsx @@ -1,9 +1,9 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function WeiboIcon(props: IconProps) { +export function WeiboIcon(props: RawIconProps) { return ( - - - + + + ); } diff --git a/src/WeiboLegacyIcon.tsx b/src/WeiboLegacyIcon.tsx new file mode 100644 index 00000000..41432df1 --- /dev/null +++ b/src/WeiboLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function WeiboLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/WeiboShareButton.tsx b/src/WeiboShareButton.tsx index 4802b7a4..54b5bf9c 100644 --- a/src/WeiboShareButton.tsx +++ b/src/WeiboShareButton.tsx @@ -1,35 +1,40 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; -type WeiboShareButtonProps = Omit, 'title'> & { +type WeiboShareButtonProps = Omit< + ShareButtonProps<{ shareTitle?: string; image?: string }>, + 'title' +> & { image?: string; - title?: string; + shareTitle?: string; }; -function weiboLink(url: string, { title, image }: { title?: string; image?: string }) { +function weiboLink(url: string, { shareTitle, image }: { shareTitle?: string; image?: string }) { assert(url, 'weibo.url'); return ( 'http://service.weibo.com/share/share.php' + objectToGetParams({ url, - title, + title: shareTitle, pic: image, }) ); } -const WeiboShareButton = forwardRef( - ({ image, title, ...props }, ref) => ( +export const buildWeiboShareUrl = weiboLink; + +export const WeiboShareButton = forwardRef( + ({ image, shareTitle, ...props }, ref) => ( ( ); WeiboShareButton.displayName = 'WeiboShareButton'; - -export default WeiboShareButton; diff --git a/src/WhatsappIcon.tsx b/src/WhatsappIcon.tsx index f50425ec..a1fa8307 100644 --- a/src/WhatsappIcon.tsx +++ b/src/WhatsappIcon.tsx @@ -1,9 +1,16 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function WhatsappIcon(props: IconProps) { +export function WhatsappIcon(props: RawIconProps) { return ( - - - + + } + color="#25D366" + viewBox="0 0 24 24" + {...props} + > + + ); } diff --git a/src/WhatsappLegacyIcon.tsx b/src/WhatsappLegacyIcon.tsx new file mode 100644 index 00000000..5553f260 --- /dev/null +++ b/src/WhatsappLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function WhatsappLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/WhatsappShareButton.tsx b/src/WhatsappShareButton.tsx index b4536aa3..04d961c1 100644 --- a/src/WhatsappShareButton.tsx +++ b/src/WhatsappShareButton.tsx @@ -1,43 +1,70 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { type MobileBehavior, resolveMobileShareStrategy } from './mobile'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; type WhatsappShareButtonProps = Omit< - ShareButtonProps<{ title?: string; separator?: string }>, + ShareButtonProps<{ message?: string; separator?: string }>, 'title' > & { + message?: string; + mobileBehavior?: MobileBehavior; separator?: string; - title?: string; }; -function whatsappLink(url: string, { title, separator }: { title?: string; separator?: string }) { +function whatsappLink( + url: string, + { message, separator = ' ' }: { message?: string; separator?: string }, +) { assert(url, 'whatsapp.url'); return ( 'https://api.whatsapp.com/send' + objectToGetParams({ - text: title ? title + separator + url : url, + text: message ? message + separator + url : url, }) ); } -const WhatsappShareButton = forwardRef( - ({ separator, title, ...props }, ref) => ( - - ), +export const buildWhatsappShareUrl = whatsappLink; + +function whatsappAppLink( + url: string, + { message, separator = ' ' }: { message?: string; separator?: string }, +) { + assert(url, 'whatsapp.url'); + return ( + 'whatsapp://send' + + objectToGetParams({ + text: message ? message + separator + url : url, + }) + ); +} + +export const WhatsappShareButton = forwardRef( + ({ message, mobileBehavior, separator, ...props }, ref) => { + const { linkBehavior, networkLink } = resolveMobileShareStrategy( + mobileBehavior, + buildWhatsappShareUrl, + whatsappAppLink, + ); + + return ( + + ); + }, ); WhatsappShareButton.displayName = 'WhatsappShareButton'; - -export default WhatsappShareButton; diff --git a/src/WorkplaceIcon.tsx b/src/WorkplaceIcon.tsx deleted file mode 100644 index c30945fa..00000000 --- a/src/WorkplaceIcon.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import IconBase, { type IconProps } from './icons/IconBase'; - -export default function WorkplaceIcon(props: IconProps) { - return ( - - - - ); -} diff --git a/src/WorkplaceShareButton.tsx b/src/WorkplaceShareButton.tsx deleted file mode 100644 index c05a1763..00000000 --- a/src/WorkplaceShareButton.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; - -type WorkplaceShareButtonProps = ShareButtonProps<{ quote?: string; hashtag?: string }> & { - hashtag?: string; - quote?: string; -}; - -function workplaceLink(url: string, { quote, hashtag }: { quote?: string; hashtag?: string }) { - assert(url, 'workplace.url'); - - return ( - 'https://work.facebook.com/sharer.php' + - objectToGetParams({ - u: url, - quote, - hashtag, - }) - ); -} - -const WorkplaceShareButton = forwardRef( - ({ hashtag, quote, ...props }, ref) => ( - - ), -); - -WorkplaceShareButton.displayName = 'WorkplaceShareButton'; - -export default WorkplaceShareButton; diff --git a/src/XIcon.tsx b/src/XIcon.tsx index 65b830f2..8fec90e9 100644 --- a/src/XIcon.tsx +++ b/src/XIcon.tsx @@ -1,9 +1,9 @@ -import IconBase, { type IconProps } from './icons/IconBase'; +import { RawIconBase, type RawIconProps } from './icons/RawIconBase'; -export default function XIcon(props: IconProps) { +export function XIcon(props: RawIconProps) { return ( - - - + + + ); } diff --git a/src/XLegacyIcon.tsx b/src/XLegacyIcon.tsx new file mode 100644 index 00000000..0696b8a6 --- /dev/null +++ b/src/XLegacyIcon.tsx @@ -0,0 +1,9 @@ +import { LegacyIconBase, type LegacyIconProps } from './icons/LegacyIconBase'; + +export function XLegacyIcon(props: LegacyIconProps) { + return ( + + + + ); +} diff --git a/src/XShareButton.tsx b/src/XShareButton.tsx index 25abc327..d44e5ca3 100644 --- a/src/XShareButton.tsx +++ b/src/XShareButton.tsx @@ -1,26 +1,26 @@ import { forwardRef } from 'react'; -import assert from './utils/assert'; -import objectToGetParams from './utils/objectToGetParams'; -import ShareButton, { type ShareButtonProps } from './ShareButton'; +import { assert } from './utils/assert'; +import { objectToGetParams } from './utils/objectToGetParams'; +import { ShareButton, type ShareButtonProps } from './ShareButton'; function xLink( url: string, { - title, + text, via, hashtags = [], related = [], - }: { title?: string; via?: string; hashtags?: string[]; related?: string[] }, + }: { text?: string; via?: string; hashtags?: string[]; related?: string[] }, ) { assert(url, 'x.url'); assert(Array.isArray(hashtags), 'x.hashtags is not an array'); assert(Array.isArray(related), 'x.related is not an array'); return ( - 'https://twitter.com/intent/tweet' + + 'https://x.com/intent/post' + objectToGetParams({ url, - text: title, + text, via, hashtags: hashtags.length > 0 ? hashtags.join(',') : undefined, related: related.length > 0 ? related.join(',') : undefined, @@ -28,31 +28,33 @@ function xLink( ); } +export const buildXShareUrl = xLink; + type XShareButtonProps = Omit< ShareButtonProps<{ - title?: string; + text?: string; via?: string; hashtags?: string[]; related?: string[]; }>, 'title' > & { - title?: string; + text?: string; via?: string; hashtags?: string[]; related?: string[]; }; -const XShareButton = forwardRef( - ({ hashtags, related, title, via, ...props }, ref) => ( +export const XShareButton = forwardRef( + ({ hashtags, related, text, via, ...props }, ref) => ( ( ); XShareButton.displayName = 'XShareButton'; - -export default XShareButton; diff --git a/src/hocs/createShareCount.tsx b/src/hocs/createShareCount.tsx deleted file mode 100644 index ffedc9ab..00000000 --- a/src/hocs/createShareCount.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import cx from 'classnames'; -import { useIsMounted } from '../hooks/useIsMounted'; - -type ShareCountContainerProps = Omit, 'children'>; - -type SocialMediaShareCountProps = ShareCountContainerProps & { - children?: (shareCount: number) => React.ReactNode; - getCount: (url: string, callback: (shareCount?: number) => void) => void; - url: string; -}; - -type ShareCountProps = Omit; - -export function SocialMediaShareCount({ - children = (shareCount: number) => shareCount, - className, - getCount, - url, - ...rest -}: SocialMediaShareCountProps) { - const isMounted = useIsMounted(); - const [count, setCount] = useState(undefined); - const [isLoading, setIsLoading] = useState(false); - - useEffect(() => { - setIsLoading(true); - - getCount(url, count => { - if (isMounted()) { - setCount(count); - setIsLoading(false); - } - }); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [url]); - - return ( - - {!isLoading && count !== undefined && children(count)} - - ); -} - -export default function createShareCount(getCount: SocialMediaShareCountProps['getCount']) { - const ShareCount = (props: ShareCountProps) => ( - - ); - - ShareCount.displayName = `ShareCount(${getCount.name})`; - - return ShareCount; -} diff --git a/src/icons/IconBase.tsx b/src/icons/LegacyIconBase.tsx similarity index 89% rename from src/icons/IconBase.tsx rename to src/icons/LegacyIconBase.tsx index 280f989a..43b34922 100644 --- a/src/icons/IconBase.tsx +++ b/src/icons/LegacyIconBase.tsx @@ -3,7 +3,7 @@ import { Children, cloneElement, isValidElement } from 'react'; type IconSvgProps = Omit, 'width' | 'height'>; -export type IconProps = IconSvgProps & { +export type LegacyIconProps = IconSvgProps & { bgStyle?: CSSProperties; borderRadius?: number; iconFillColor?: string; @@ -11,7 +11,7 @@ export type IconProps = IconSvgProps & { size?: number | string; }; -type IconBaseProps = IconProps & { +type LegacyIconBaseProps = LegacyIconProps & { children: ReactNode; color: string; }; @@ -26,7 +26,7 @@ function withDefaultFill(children: ReactNode, iconFillColor: string) { }); } -export default function IconBase({ +export function LegacyIconBase({ bgStyle = {}, borderRadius = 0, children, @@ -35,7 +35,7 @@ export default function IconBase({ round = false, size = 64, ...rest -}: IconBaseProps) { +}: LegacyIconBaseProps) { const content = withDefaultFill(children, iconFillColor); return ( diff --git a/src/icons/RawIconBase.tsx b/src/icons/RawIconBase.tsx new file mode 100644 index 00000000..0ee6731d --- /dev/null +++ b/src/icons/RawIconBase.tsx @@ -0,0 +1,70 @@ +import type { ReactNode, SVGProps } from 'react'; + +export type RawIconProps = Omit, 'width' | 'height'> & { + size?: number | string; +}; + +type RawIconBaseProps = RawIconProps & { + /** + * White shape painted behind the mark, inset within its outline, so the + * details cut out of the mark stay white on dark backgrounds. + */ + backdrop?: ReactNode; + /** + * Put the glyph on a filled circle, scaled around the center of the 24x24 + * viewBox. Used for glyph-only marks so they match the visual weight of the + * circular brand marks. The glyph is always drawn in white. + */ + badge?: { + scale: number; + }; + children: ReactNode; + color?: string; + outlined?: boolean; + viewBox?: string; +}; + +const outlinePaint = { + fill: 'none', + strokeLinecap: 'round' as const, + strokeLinejoin: 'round' as const, + strokeWidth: 2, +}; + +function glyphPaint(outlined: boolean, color: string | undefined) { + return outlined ? { ...outlinePaint, stroke: color } : { fill: color }; +} + +export function RawIconBase({ + backdrop, + badge, + children, + color, + fill, + outlined = false, + size = 24, + viewBox = '0 0 24 24', + ...rest +}: RawIconBaseProps) { + const paint = fill ?? color; + + if (badge) { + const transform = `translate(12 12) scale(${badge.scale}) translate(-12 -12)`; + + return ( + + + + {children} + + + ); + } + + return ( + + {backdrop && {backdrop}} + {children} + + ); +} diff --git a/src/index.ts b/src/index.ts index e09c6d15..6ef3ad05 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,65 +1,97 @@ -export { default as BlueskyIcon } from './BlueskyIcon'; -export { default as BlueskyShareButton } from './BlueskyShareButton'; -export { default as EmailIcon } from './EmailIcon'; -export { default as EmailShareButton } from './EmailShareButton'; -export { default as FacebookIcon } from './FacebookIcon'; -export { default as FacebookMessengerIcon } from './FacebookMessengerIcon'; -export { default as FacebookMessengerShareButton } from './FacebookMessengerShareButton'; -export { default as FacebookShareButton } from './FacebookShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as FacebookShareCount } from './FacebookShareCount'; -export { default as HatenaIcon } from './HatenaIcon'; -export { default as HatenaShareButton } from './HatenaShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as HatenaShareCount } from './HatenaShareCount'; -export { default as InstapaperIcon } from './InstapaperIcon'; -export { default as InstapaperShareButton } from './InstapaperShareButton'; -export { default as LineIcon } from './LineIcon'; -export { default as LineShareButton } from './LineShareButton'; -export { default as LinkedinIcon } from './LinkedinIcon'; -export { default as LinkedinShareButton } from './LinkedinShareButton'; -export { default as LivejournalIcon } from './LivejournalIcon'; -export { default as LivejournalShareButton } from './LivejournalShareButton'; -export { default as MailruIcon } from './MailruIcon'; -export { default as MailruShareButton } from './MailruShareButton'; -export { default as OKIcon } from './OKIcon'; -export { default as OKShareButton } from './OKShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as OKShareCount } from './OKShareCount'; -export { default as PinterestIcon } from './PinterestIcon'; -export { default as PinterestShareButton } from './PinterestShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as PinterestShareCount } from './PinterestShareCount'; -export { default as PocketIcon } from './PocketIcon'; -export { default as PocketShareButton } from './PocketShareButton'; -export { default as RedditIcon } from './RedditIcon'; -export { default as RedditShareButton } from './RedditShareButton'; -export { default as GabShareButton } from './GabShareButton'; -export { default as GabIcon } from './GabIcon'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as RedditShareCount } from './RedditShareCount'; -export { default as TelegramIcon } from './TelegramIcon'; -export { default as TelegramShareButton } from './TelegramShareButton'; -export { default as ThreadsIcon } from './ThreadsIcon'; -export { default as ThreadsShareButton } from './ThreadsShareButton'; -export { default as TumblrIcon } from './TumblrIcon'; -export { default as TumblrShareButton } from './TumblrShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as TumblrShareCount } from './TumblrShareCount'; -export { default as TwitterIcon } from './TwitterIcon'; -export { default as XShareButton } from './XShareButton'; -/** @deprecated Use XShareButton instead. */ -export { default as TwitterShareButton } from './TwitterShareButton'; -export { default as ViberIcon } from './ViberIcon'; -export { default as ViberShareButton } from './ViberShareButton'; -export { default as VKIcon } from './VKIcon'; -export { default as VKShareButton } from './VKShareButton'; -/** @deprecated Share counts are deprecated and will be removed in v6. */ -export { default as VKShareCount } from './VKShareCount'; -export { default as WeiboIcon } from './WeiboIcon'; -export { default as WeiboShareButton } from './WeiboShareButton'; -export { default as WhatsappIcon } from './WhatsappIcon'; -export { default as WhatsappShareButton } from './WhatsappShareButton'; -export { default as WorkplaceIcon } from './WorkplaceIcon'; -export { default as WorkplaceShareButton } from './WorkplaceShareButton'; -export { default as XIcon } from './XIcon'; +export { BlueskyIcon } from './BlueskyIcon'; +export { BlueskyLegacyIcon } from './BlueskyLegacyIcon'; +export { BlueskyShareButton } from './BlueskyShareButton'; +export { buildBlueskyShareUrl } from './BlueskyShareButton'; +export { EmailIcon } from './EmailIcon'; +export { EmailLegacyIcon } from './EmailLegacyIcon'; +export { EmailShareButton } from './EmailShareButton'; +export { buildEmailShareUrl } from './EmailShareButton'; +export { FacebookIcon } from './FacebookIcon'; +export { FacebookLegacyIcon } from './FacebookLegacyIcon'; +export { FacebookMessengerIcon } from './FacebookMessengerIcon'; +export { FacebookMessengerLegacyIcon } from './FacebookMessengerLegacyIcon'; +export { FacebookMessengerShareButton } from './FacebookMessengerShareButton'; +export { buildFacebookMessengerShareUrl } from './FacebookMessengerShareButton'; +export { FacebookShareButton } from './FacebookShareButton'; +export { buildFacebookShareUrl } from './FacebookShareButton'; +export { GabIcon } from './GabIcon'; +export { GabLegacyIcon } from './GabLegacyIcon'; +export { GabShareButton } from './GabShareButton'; +export { buildGabShareUrl } from './GabShareButton'; +export { HatenaIcon } from './HatenaIcon'; +export { HatenaLegacyIcon } from './HatenaLegacyIcon'; +export { HatenaShareButton } from './HatenaShareButton'; +export { buildHatenaShareUrl } from './HatenaShareButton'; +export { InstapaperIcon } from './InstapaperIcon'; +export { InstapaperLegacyIcon } from './InstapaperLegacyIcon'; +export { InstapaperShareButton } from './InstapaperShareButton'; +export { buildInstapaperShareUrl } from './InstapaperShareButton'; +export { LineIcon } from './LineIcon'; +export { LineLegacyIcon } from './LineLegacyIcon'; +export { LineShareButton } from './LineShareButton'; +export { buildLineShareUrl } from './LineShareButton'; +export { LinkedinIcon } from './LinkedinIcon'; +export { LinkedinLegacyIcon } from './LinkedinLegacyIcon'; +export { LinkedinShareButton } from './LinkedinShareButton'; +export { buildLinkedinShareUrl } from './LinkedinShareButton'; +export { LivejournalIcon } from './LivejournalIcon'; +export { LivejournalLegacyIcon } from './LivejournalLegacyIcon'; +export { LivejournalShareButton } from './LivejournalShareButton'; +export { buildLivejournalShareUrl } from './LivejournalShareButton'; +export { MailruIcon } from './MailruIcon'; +export { MailruLegacyIcon } from './MailruLegacyIcon'; +export { MailruShareButton } from './MailruShareButton'; +export { buildMailruShareUrl } from './MailruShareButton'; +export { NativeShareButton } from './NativeShareButton'; +export { NativeShareIcon } from './NativeShareIcon'; +export { NativeShareLegacyIcon } from './NativeShareLegacyIcon'; +export { canNativeShare } from './nativeShare'; +export { shareNative } from './nativeShare'; +export type { NativeShareData } from './nativeShare'; +export { OKIcon } from './OKIcon'; +export { OKLegacyIcon } from './OKLegacyIcon'; +export { OKShareButton } from './OKShareButton'; +export { buildOKShareUrl } from './OKShareButton'; +export { PinterestIcon } from './PinterestIcon'; +export { PinterestLegacyIcon } from './PinterestLegacyIcon'; +export { PinterestShareButton } from './PinterestShareButton'; +export { buildPinterestShareUrl } from './PinterestShareButton'; +export { RedditIcon } from './RedditIcon'; +export { RedditLegacyIcon } from './RedditLegacyIcon'; +export { RedditShareButton } from './RedditShareButton'; +export { buildRedditShareUrl } from './RedditShareButton'; +export { TelegramIcon } from './TelegramIcon'; +export { TelegramLegacyIcon } from './TelegramLegacyIcon'; +export { TelegramShareButton } from './TelegramShareButton'; +export { buildTelegramShareUrl } from './TelegramShareButton'; +export { ThreadsIcon } from './ThreadsIcon'; +export { ThreadsLegacyIcon } from './ThreadsLegacyIcon'; +export { ThreadsShareButton } from './ThreadsShareButton'; +export { buildThreadsShareUrl } from './ThreadsShareButton'; +export { TumblrIcon } from './TumblrIcon'; +export { TumblrLegacyIcon } from './TumblrLegacyIcon'; +export { TumblrShareButton } from './TumblrShareButton'; +export { buildTumblrShareUrl } from './TumblrShareButton'; +export { XShareButton } from './XShareButton'; +export { buildXShareUrl } from './XShareButton'; +export { ViberIcon } from './ViberIcon'; +export { ViberLegacyIcon } from './ViberLegacyIcon'; +export { ViberShareButton } from './ViberShareButton'; +export { buildViberShareUrl } from './ViberShareButton'; +export { VKIcon } from './VKIcon'; +export { VKLegacyIcon } from './VKLegacyIcon'; +export { VKShareButton } from './VKShareButton'; +export { buildVKShareUrl } from './VKShareButton'; +export { WeiboIcon } from './WeiboIcon'; +export { WeiboLegacyIcon } from './WeiboLegacyIcon'; +export { WeiboShareButton } from './WeiboShareButton'; +export { buildWeiboShareUrl } from './WeiboShareButton'; +export { WhatsappIcon } from './WhatsappIcon'; +export { WhatsappLegacyIcon } from './WhatsappLegacyIcon'; +export { WhatsappShareButton } from './WhatsappShareButton'; +export { buildWhatsappShareUrl } from './WhatsappShareButton'; +export { XIcon } from './XIcon'; +export { XLegacyIcon } from './XLegacyIcon'; +export { openShareWindow } from './shareWindow'; +export type { ShareWindowOptions } from './shareWindow'; +export type { WindowPosition } from './shareWindow'; diff --git a/src/mobile.ts b/src/mobile.ts new file mode 100644 index 00000000..ea3b0d4c --- /dev/null +++ b/src/mobile.ts @@ -0,0 +1,63 @@ +export type MobileBehavior = 'web' | 'app' | 'auto'; + +type LinkBehavior = 'popup' | 'navigate'; +type LinkBuilder = (url: string, options: LinkOptions) => string; + +type ResolvedShareStrategy = { + linkBehavior: LinkBehavior; + networkLink: LinkBuilder; +}; + +function matchesMobileUserAgent(userAgent: string) { + return /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/i.test(userAgent); +} + +export function isMobileShareEnvironment() { + if (typeof navigator === 'undefined') { + return false; + } + + if ('userAgentData' in navigator) { + const userAgentData = navigator.userAgentData as { mobile?: boolean }; + + if (typeof userAgentData.mobile === 'boolean') { + return userAgentData.mobile; + } + } + + if (matchesMobileUserAgent(navigator.userAgent)) { + return true; + } + + return navigator.maxTouchPoints > 1 && /Mac/i.test(navigator.platform); +} + +export function resolveMobileShareStrategy( + mobileBehavior: MobileBehavior | undefined, + webLink: LinkBuilder, + appLink: LinkBuilder, +): ResolvedShareStrategy { + switch (mobileBehavior) { + case 'app': + return { + linkBehavior: 'navigate', + networkLink: appLink, + }; + case 'auto': + return isMobileShareEnvironment() + ? { + linkBehavior: 'navigate', + networkLink: appLink, + } + : { + linkBehavior: 'popup', + networkLink: webLink, + }; + case 'web': + default: + return { + linkBehavior: 'popup', + networkLink: webLink, + }; + } +} diff --git a/src/nativeShare.ts b/src/nativeShare.ts new file mode 100644 index 00000000..f2f096a6 --- /dev/null +++ b/src/nativeShare.ts @@ -0,0 +1,52 @@ +export type NativeShareData = Pick; + +function normalizeNativeShareData(data: NativeShareData): ShareData { + return { + ...(data.title ? { title: data.title } : {}), + ...(data.text ? { text: data.text } : {}), + ...(data.url ? { url: data.url } : {}), + ...(data.files?.length ? { files: data.files } : {}), + }; +} + +function hasSharePayload(data: NativeShareData) { + return Boolean(data.title || data.text || data.url || data.files?.length); +} + +export function canNativeShare(data: NativeShareData = {}) { + if (typeof navigator === 'undefined' || typeof navigator.share !== 'function') { + return false; + } + + if (!hasSharePayload(data)) { + return false; + } + + const shareData = normalizeNativeShareData(data); + + if (shareData.files?.length) { + return typeof navigator.canShare === 'function' && navigator.canShare(shareData); + } + + if (typeof navigator.canShare === 'function') { + try { + return navigator.canShare(shareData); + } catch { + return true; + } + } + + return true; +} + +export async function shareNative(data: NativeShareData) { + if (!canNativeShare(data)) { + throw new Error( + data.files?.length + ? 'native share with files is not supported' + : 'native share is not supported', + ); + } + + await navigator.share(normalizeNativeShareData(data)); +} diff --git a/src/shareWindow.ts b/src/shareWindow.ts new file mode 100644 index 00000000..121819f1 --- /dev/null +++ b/src/shareWindow.ts @@ -0,0 +1,64 @@ +export type WindowPosition = 'windowCenter' | 'screenCenter'; +export type LinkBehavior = 'popup' | 'navigate'; + +export type ShareWindowOptions = { + height?: number; + onClose?: (dialog: Window | null) => void; + position?: WindowPosition; + width?: number; +}; + +const getBoxPositionOnWindowCenter = (width: number, height: number) => ({ + left: window.outerWidth / 2 + (window.screenX || window.screenLeft || 0) - width / 2, + top: window.outerHeight / 2 + (window.screenY || window.screenTop || 0) - height / 2, +}); + +const getBoxPositionOnScreenCenter = (width: number, height: number) => ({ + top: (window.screen.height - height) / 2, + left: (window.screen.width - width) / 2, +}); + +export function openShareWindow( + url: string, + { height = 400, onClose, position = 'windowCenter', width = 550 }: ShareWindowOptions = {}, +) { + const config: { [key: string]: string | number } = { + height, + width, + location: 'no', + toolbar: 'no', + status: 'no', + directories: 'no', + menubar: 'no', + scrollbars: 'yes', + resizable: 'no', + centerscreen: 'yes', + chrome: 'yes', + ...(position === 'windowCenter' + ? getBoxPositionOnWindowCenter(width, height) + : getBoxPositionOnScreenCenter(width, height)), + }; + + const shareDialog = window.open( + url, + '', + Object.keys(config) + .map(key => `${key}=${config[key]}`) + .join(', '), + ); + + if (onClose) { + const interval = window.setInterval(() => { + try { + if (shareDialog === null || shareDialog.closed) { + window.clearInterval(interval); + onClose(shareDialog); + } + } catch (error) { + console.error(error); + } + }, 1000); + } + + return shareDialog; +} diff --git a/src/utils/assert.ts b/src/utils/assert.ts index 81370f13..e21126ed 100644 --- a/src/utils/assert.ts +++ b/src/utils/assert.ts @@ -5,7 +5,7 @@ class AssertionError extends Error { } } -export default function assert(value: unknown, message: string) { +export function assert(value: unknown, message: string) { if (!value) { throw new AssertionError(message); } diff --git a/src/utils/buttonHelpers.ts b/src/utils/buttonHelpers.ts new file mode 100644 index 00000000..7fae93e3 --- /dev/null +++ b/src/utils/buttonHelpers.ts @@ -0,0 +1,48 @@ +import { Children, isValidElement } from 'react'; +import type React from 'react'; + +type IconShapeProps = { borderRadius?: number; round?: boolean }; + +export const isPromise = (obj: unknown): obj is Promise => + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + 'then' in obj && + typeof (obj as Promise).then === 'function'; + +export function getButtonBorderRadius(children: React.ReactNode) { + const childNodes = Children.toArray(children); + + if (childNodes.length !== 1) { + return undefined; + } + + const [child] = childNodes; + + if (!isValidElement(child)) { + return undefined; + } + + if (child.props.round) { + return '50%'; + } + + return child.props.borderRadius ?? 0; +} + +export function hasTextContent(children: React.ReactNode): boolean { + return Children.toArray(children).some(child => { + if (typeof child === 'string') { + return child.trim().length > 0; + } + + if (typeof child === 'number') { + return true; + } + + if (!isValidElement<{ children?: React.ReactNode }>(child)) { + return false; + } + + return hasTextContent(child.props.children); + }); +} diff --git a/src/utils/objectToGetParams.ts b/src/utils/objectToGetParams.ts index 94d65293..ba5f55dd 100644 --- a/src/utils/objectToGetParams.ts +++ b/src/utils/objectToGetParams.ts @@ -1,6 +1,4 @@ -export default function objectToGetParams(object: { - [key: string]: string | number | undefined | null; -}) { +export function objectToGetParams(object: { [key: string]: string | number | undefined | null }) { const params = Object.entries(object) .filter(([, value]) => value !== undefined && value !== null) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); diff --git a/test/EmailShareButton.test.tsx b/test/EmailShareButton.test.tsx index 17f54507..08d89d61 100644 --- a/test/EmailShareButton.test.tsx +++ b/test/EmailShareButton.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import EmailShareButton from '../src/EmailShareButton'; +import { EmailShareButton } from '../src/EmailShareButton'; describe('EmailShareButton', () => { it('navigates to a mailto link instead of opening a popup', () => { @@ -30,9 +30,7 @@ describe('EmailShareButton', () => { fireEvent.click(screen.getByRole('button', { name: 'Share by email' })); expect(openSpy).not.toHaveBeenCalled(); - expect(hrefState.value).toBe( - 'mailto:?subject=Subject&body=Body%20https%3A%2F%2Fexample.com', - ); + expect(hrefState.value).toBe('mailto:?subject=Subject&body=Body%0Ahttps%3A%2F%2Fexample.com'); }); it('uses the shared url as the body when no body is provided', () => { diff --git a/test/ExampleImage.test.tsx b/test/ExampleImage.test.tsx new file mode 100644 index 00000000..0195ab6a --- /dev/null +++ b/test/ExampleImage.test.tsx @@ -0,0 +1,46 @@ +import React from 'react'; +import { render } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { Demo } from '../demo/Demo'; + +const ICON_SIZE = 64; +const GAP = 16; +const PADDING = 16; + +// Builds the README preview (example.svg) from the icons the demo renders, +// in demo order. Run `npm run update-example` after changing icons or the +// demo; CI fails while the committed file is stale. +function renderExampleSvg() { + const { container } = render(); + const icons = Array.from(container.querySelectorAll('svg')); + const width = PADDING * 2 + icons.length * ICON_SIZE + (icons.length - 1) * GAP; + const height = PADDING * 2 + ICON_SIZE; + + const lines = icons.map((icon, index) => { + const placed = icon.cloneNode(true) as SVGSVGElement; + + placed.setAttribute('x', String(PADDING + index * (ICON_SIZE + GAP))); + placed.setAttribute('y', String(PADDING)); + placed.setAttribute('width', String(ICON_SIZE)); + placed.setAttribute('height', String(ICON_SIZE)); + + return ` ${placed.outerHTML}`; + }); + + return [ + ``, + ...lines, + '', + '', + ].join('\n'); +} + +describe('README example image', () => { + it('matches the icons rendered by the demo', async () => { + const svg = renderExampleSvg(); + + expect(svg.match(/ { + function stubLocation() { + const hrefState = { value: 'https://example.test/' }; + + Object.defineProperty(window, 'location', { + configurable: true, + value: { + get href() { + return hrefState.value; + }, + set href(value: string) { + hrefState.value = value; + }, + }, + }); + + return hrefState; + } + it('defaults redirectUri to the shared url', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); @@ -45,4 +63,45 @@ describe('FacebookMessengerShareButton', () => { expect.any(String), ); }); + + it('uses a Messenger app deep link when mobileBehavior is app', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + const hrefState = stubLocation(); + + render( + + Share in Messenger + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share in Messenger' })); + + expect(openSpy).not.toHaveBeenCalled(); + expect(hrefState.value).toBe( + 'fb-messenger://share?link=https%3A%2F%2Fexample.com&redirect_uri=https%3A%2F%2Fexample.com&app_id=123', + ); + }); + + it('keeps the web dialog on desktop when mobileBehavior is auto', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + + Object.defineProperty(window.navigator, 'userAgent', { + configurable: true, + value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', + }); + + render( + + Share in Messenger + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share in Messenger' })); + + expect(openSpy).toHaveBeenCalledWith( + 'https://www.facebook.com/dialog/send?link=https%3A%2F%2Fexample.com&redirect_uri=https%3A%2F%2Fexample.com&app_id=123', + '', + expect.any(String), + ); + }); }); diff --git a/test/IconBase.test.tsx b/test/IconBase.test.tsx deleted file mode 100644 index 96d554dd..00000000 --- a/test/IconBase.test.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import React from 'react'; -import { render, screen } from '@testing-library/react'; -import { describe, expect, it } from 'vitest'; - -import FacebookIcon from '../src/FacebookIcon'; -import FacebookMessengerIcon from '../src/FacebookMessengerIcon'; -import HatenaIcon from '../src/HatenaIcon'; -import IconBase from '../src/icons/IconBase'; -import LineIcon from '../src/LineIcon'; -import LivejournalIcon from '../src/LivejournalIcon'; -import MailruIcon from '../src/MailruIcon'; -import OKIcon from '../src/OKIcon'; -import PinterestIcon from '../src/PinterestIcon'; -import RedditIcon from '../src/RedditIcon'; -import TelegramIcon from '../src/TelegramIcon'; -import TumblrIcon from '../src/TumblrIcon'; -import VKIcon from '../src/VKIcon'; -import ViberIcon from '../src/ViberIcon'; -import WeiboIcon from '../src/WeiboIcon'; -import WorkplaceIcon from '../src/WorkplaceIcon'; - -describe('IconBase', () => { - it('renders exported icons with the shared rectangular background by default', () => { - render(); - - const svg = screen.getByTestId('icon'); - const rect = svg.querySelector('rect'); - const path = svg.querySelector('path'); - - expect(svg).toHaveAttribute('width', '64'); - expect(svg).toHaveAttribute('height', '64'); - expect(rect).toHaveAttribute('fill', '#0866FF'); - expect(path).toHaveAttribute('fill', 'white'); - }); - - it('keeps the reviewed brand background colors for current v5 icon badges', () => { - const cases = [ - ['facebook-messenger', FacebookMessengerIcon, '#0866FF'], - ['hatena', HatenaIcon, '#00A4DE'], - ['line', LineIcon, '#06C755'], - ['livejournal', LivejournalIcon, '#00B0EA'], - ['mailru', MailruIcon, '#005FF9'], - ['ok', OKIcon, '#FF7700'], - ['pinterest', PinterestIcon, '#E60023'], - ['reddit', RedditIcon, '#FF4500'], - ['telegram', TelegramIcon, '#26A5E4'], - ['tumblr', TumblrIcon, '#36465D'], - ['vk', VKIcon, '#0077FF'], - ['viber', ViberIcon, '#7360F2'], - ['weibo', WeiboIcon, '#E6162D'], - ['workplace', WorkplaceIcon, '#4526CE'], - ] as const; - - for (const [name, Component, color] of cases) { - render(); - - const rect = screen.getByTestId(name).querySelector('rect'); - - expect(rect).toHaveAttribute('fill', color); - } - }); - - it('renders a round icon with custom style props', () => { - render( - - - , - ); - - const svg = screen.getByLabelText('round icon'); - const circle = svg.querySelector('circle'); - const rect = svg.querySelector('rect'); - const path = svg.querySelector('path'); - - expect(svg).toHaveAttribute('width', '32'); - expect(svg).toHaveAttribute('height', '32'); - expect(circle).toHaveStyle({ opacity: '0.5' }); - expect(rect).toBeNull(); - expect(path).toHaveAttribute('fill', 'black'); - }); - - it('applies borderRadius when rendering a non-round icon', () => { - render( - - - , - ); - - const rect = screen.getByLabelText('rounded rect').querySelector('rect'); - - expect(rect).toHaveAttribute('rx', '12'); - expect(rect).toHaveAttribute('ry', '12'); - }); -}); diff --git a/test/IconFamilies.test.tsx b/test/IconFamilies.test.tsx new file mode 100644 index 00000000..9e3235b1 --- /dev/null +++ b/test/IconFamilies.test.tsx @@ -0,0 +1,257 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { EmailIcon } from '../src/EmailIcon'; +import { FacebookIcon } from '../src/FacebookIcon'; +import { FacebookLegacyIcon } from '../src/FacebookLegacyIcon'; +import { LinkedinIcon } from '../src/LinkedinIcon'; +import { LivejournalIcon } from '../src/LivejournalIcon'; +import { MailruIcon } from '../src/MailruIcon'; +import { NativeShareIcon } from '../src/NativeShareIcon'; +import { NativeShareLegacyIcon } from '../src/NativeShareLegacyIcon'; +import { OKIcon } from '../src/OKIcon'; +import { ThreadsIcon } from '../src/ThreadsIcon'; +import { ViberIcon } from '../src/ViberIcon'; +import { WhatsappIcon } from '../src/WhatsappIcon'; +import { XIcon } from '../src/XIcon'; +import { RawIconBase } from '../src/icons/RawIconBase'; + +describe('raw icon family', () => { + it('renders brand marks in their default brand color', () => { + render(); + + const svg = screen.getByTestId('mailru-icon'); + + expect(svg).toHaveAttribute('width', '24'); + expect(svg).toHaveAttribute('height', '24'); + expect(svg).toHaveAttribute('fill', '#005FF9'); + expect(svg.children).toHaveLength(1); + expect(svg.querySelector('rect')).toBeNull(); + expect(svg.querySelector('circle')).toBeNull(); + }); + + it('fills the inside of outline bubble marks with white', () => { + render( + <> + + + , + ); + + for (const testId of ['whatsapp-icon', 'viber-icon']) { + const [backdrop, mark] = Array.from(screen.getByTestId(testId).children); + + expect(backdrop).toHaveAttribute('fill', 'white'); + expect(backdrop?.querySelector('path')).toBeInTheDocument(); + expect(mark?.tagName).toBe('path'); + } + }); + + it('draws the LiveJournal pencil in fixed navy and white', () => { + render(); + + const svg = screen.getByTestId('livejournal-icon'); + const fills = Array.from(svg.querySelectorAll('path')).map(path => path.getAttribute('fill')); + + expect(svg).toHaveAttribute('fill', '#123456'); + expect(svg.querySelector('circle')).not.toHaveAttribute('fill'); + expect(fills).toEqual([null, '#15374C', 'white', '#15374C']); + }); + + it('keeps cut-out details white with a backdrop behind the mark', () => { + render(); + + const svg = screen.getByTestId('facebook-icon'); + const [backdrop, mark] = Array.from(svg.children); + + expect(svg).toHaveAttribute('fill', '#0866FF'); + expect(backdrop?.tagName).toBe('g'); + expect(backdrop).toHaveAttribute('fill', 'white'); + expect(backdrop?.querySelector('circle')).toHaveAttribute('r', '11'); + expect(mark?.tagName).toBe('path'); + expect(mark).not.toHaveAttribute('fill'); + }); + + it('draws LinkedIn as a full-size mark', () => { + render(); + + const svg = screen.getByTestId('linkedin-icon'); + + expect(svg).toHaveAttribute('width', '32'); + expect(svg).toHaveAttribute('height', '32'); + expect(svg).toHaveAttribute('fill', '#0A66C2'); + expect(svg).toHaveAttribute('viewBox', '0 0 24 24'); + expect(svg.querySelector(':scope > g[fill="white"] > rect')).toHaveAttribute('width', '22'); + }); + + it('draws glyph-only icons in white on a circle', () => { + render(); + + const svg = screen.getByTestId('x-icon'); + const [circle, glyph] = Array.from(svg.children); + + expect(svg).toHaveAttribute('width', '32'); + expect(svg).toHaveAttribute('viewBox', '0 0 24 24'); + expect(svg).toHaveAttribute('fill', '#000000'); + expect(svg.querySelector('mask')).toBeNull(); + expect(circle?.tagName).toBe('circle'); + expect(circle).toHaveAttribute('r', '12'); + expect(glyph).toHaveAttribute('fill', 'white'); + expect(glyph).toHaveAttribute('transform', 'translate(12 12) scale(0.5) translate(-12 -12)'); + }); + + it('draws the Threads app icon with a fixed white glyph', () => { + render(); + + const svg = screen.getByTestId('threads-icon'); + const fills = Array.from(svg.querySelectorAll('path')).map(path => path.getAttribute('fill')); + + expect(svg).toHaveAttribute('fill', '#123456'); + expect(svg).toHaveAttribute('viewBox', '0 0 24 24'); + expect(fills).toEqual([null, 'white']); + }); + + it('draws the OK logo with a fixed white figure', () => { + render(); + + const svg = screen.getByTestId('ok-icon'); + const fills = Array.from(svg.querySelectorAll('path')).map(path => path.getAttribute('fill')); + + expect(svg).toHaveAttribute('fill', '#FF7700'); + expect(svg).toHaveAttribute('viewBox', '0 0 24 24'); + expect(fills).toEqual([null, 'white', 'white']); + }); + + it('draws outlined glyphs in white on the circle with a round stroke', () => { + render(); + + const svg = screen.getByTestId('email-icon'); + const glyph = svg.querySelector(':scope > g[transform]'); + + expect(svg).toHaveAttribute('fill', '#7f7f7f'); + expect(svg).not.toHaveAttribute('stroke'); + expect(svg.querySelector('mask')).toBeNull(); + expect(glyph).toHaveAttribute('fill', 'none'); + expect(glyph).toHaveAttribute('stroke', 'white'); + expect(glyph).toHaveAttribute('stroke-width', '2'); + expect(glyph).toHaveAttribute('stroke-linecap', 'round'); + expect(glyph).toHaveAttribute('stroke-linejoin', 'round'); + }); + + it('recolors raw icons through the color and fill props', () => { + render( + <> + + + + , + ); + + expect(screen.getByTestId('facebook-color')).toHaveAttribute('fill', '#123456'); + expect(screen.getByTestId('email-color')).toHaveAttribute('fill', '#123456'); + expect(screen.getByTestId('email-fill')).toHaveAttribute('fill', '#654321'); + }); + + it('draws the native share glyph in white on a fixed blue circle', () => { + render(); + + const svg = screen.getByTestId('native-share-icon'); + + expect(svg).toHaveAttribute('fill', '#0A84FF'); + expect(svg.querySelector(':scope > g[transform]')).toHaveAttribute('stroke', 'white'); + }); + + it('strokes outlined glyphs in the icon color without a circle', () => { + render( + + + , + ); + + const svg = screen.getByTestId('outlined-icon'); + + expect(svg).toHaveAttribute('fill', 'none'); + expect(svg).toHaveAttribute('stroke', '#123456'); + expect(svg).toHaveAttribute('stroke-width', '2'); + expect(svg.querySelector('circle')).toBeNull(); + }); + + it('passes standard svg props through the raw icon base', () => { + render( + + + , + ); + + const svg = screen.getByTestId('raw-icon'); + + expect(svg).toHaveAttribute('width', '32'); + expect(svg).toHaveAttribute('height', '32'); + expect(svg).toHaveAttribute('fill', '#123456'); + expect(svg).toHaveAttribute('viewBox', '0 0 32 32'); + }); +}); + +describe('legacy icon family', () => { + it('renders the existing badge background by default', () => { + render( + , + ); + + const svg = screen.getByTestId('facebook-legacy-icon'); + const rect = svg.querySelector('rect'); + const path = svg.querySelector('path'); + + expect(svg).toHaveAttribute('width', '64'); + expect(svg).toHaveAttribute('height', '64'); + expect(rect).toHaveAttribute('fill', '#0866FF'); + expect(path).toHaveAttribute('fill', 'white'); + }); + + it('preserves round, bgStyle, and iconFillColor support on legacy icons', () => { + render( + , + ); + + const svg = screen.getByTestId('native-share-legacy-icon'); + const circle = svg.querySelector('circle'); + const rect = svg.querySelector('rect'); + const path = svg.querySelector('path'); + + expect(svg).toHaveAttribute('width', '32'); + expect(svg).toHaveAttribute('height', '32'); + expect(circle).toHaveStyle({ opacity: '0.5' }); + expect(rect).toBeNull(); + expect(path).toHaveAttribute('fill', 'black'); + }); + + it('applies borderRadius when rendering a legacy rectangular icon', () => { + render( + , + ); + + const rect = screen.getByTestId('rounded-legacy-icon').querySelector('rect'); + + expect(rect).toHaveAttribute('rx', '12'); + expect(rect).toHaveAttribute('ry', '12'); + }); +}); diff --git a/test/MobileShareButtons.test.tsx b/test/MobileShareButtons.test.tsx new file mode 100644 index 00000000..fd610029 --- /dev/null +++ b/test/MobileShareButtons.test.tsx @@ -0,0 +1,100 @@ +import React from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { TelegramShareButton } from '../src/TelegramShareButton'; +import { ViberShareButton } from '../src/ViberShareButton'; + +function stubLocation() { + const hrefState = { value: 'https://example.test/' }; + + Object.defineProperty(window, 'location', { + configurable: true, + value: { + get href() { + return hrefState.value; + }, + set href(value: string) { + hrefState.value = value; + }, + }, + }); + + return hrefState; +} + +function setDesktopUserAgent() { + Object.defineProperty(window.navigator, 'userAgent', { + configurable: true, + value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', + }); +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('mobile share buttons', () => { + it('uses a Telegram app link when mobileBehavior is app', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + const hrefState = stubLocation(); + + render( + + Share on Telegram + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share on Telegram' })); + + expect(openSpy).not.toHaveBeenCalled(); + expect(hrefState.value).toBe('tg://msg_url?url=https%3A%2F%2Fexample.com&text=Example'); + }); + + it('keeps the Telegram web URL on desktop when mobileBehavior is auto', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + setDesktopUserAgent(); + + render( + + Share on Telegram + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share on Telegram' })); + + expect(openSpy).toHaveBeenCalledWith( + 'https://t.me/share/url?url=https%3A%2F%2Fexample.com&text=Example', + '', + expect.any(String), + ); + }); + + it('navigates directly for Viber when mobileBehavior is app', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + const hrefState = stubLocation(); + + render( + + Share on Viber + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share on Viber' })); + + expect(openSpy).not.toHaveBeenCalled(); + expect(hrefState.value).toBe('viber://forward?text=Example%20https%3A%2F%2Fexample.com'); + }); + + it('does not forward mobileBehavior to the DOM', () => { + render( + + Share on Telegram + , + ); + + expect(screen.getByRole('button', { name: 'Share on Telegram' })).not.toHaveAttribute( + 'mobileBehavior', + ); + }); +}); diff --git a/test/NativeShare.test.tsx b/test/NativeShare.test.tsx new file mode 100644 index 00000000..4798e815 --- /dev/null +++ b/test/NativeShare.test.tsx @@ -0,0 +1,101 @@ +import React, { createRef } from 'react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { NativeShareButton } from '../src/NativeShareButton'; +import { canNativeShare, shareNative } from '../src/nativeShare'; + +describe('native share', () => { + beforeEach(() => { + Object.defineProperty(window.navigator, 'canShare', { + configurable: true, + value: undefined, + }); + Object.defineProperty(window.navigator, 'share', { + configurable: true, + value: undefined, + }); + }); + + it('returns false when navigator.share is unavailable', () => { + expect(canNativeShare({ text: 'Example' })).toBe(false); + }); + + it('uses navigator.canShare for file-sharing capability checks', () => { + const canShareMock = vi.fn().mockReturnValue(true); + + Object.defineProperty(window.navigator, 'share', { + configurable: true, + value: vi.fn(), + }); + Object.defineProperty(window.navigator, 'canShare', { + configurable: true, + value: canShareMock, + }); + + const file = new File(['example'], 'example.pdf', { type: 'application/pdf' }); + + expect(canNativeShare({ files: [file], title: 'Example' })).toBe(true); + expect(canShareMock).toHaveBeenCalledWith({ files: [file], title: 'Example' }); + }); + + it('rejects predictably when native share is unavailable', async () => { + await expect(shareNative({ text: 'Example' })).rejects.toThrow('native share is not supported'); + }); + + it('triggers native share only after the user clicks the button', async () => { + const shareMock = vi.fn().mockResolvedValue(undefined); + + Object.defineProperty(window.navigator, 'share', { + configurable: true, + value: shareMock, + }); + + render( + + Share natively + , + ); + + expect(shareMock).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Share natively' })); + + await waitFor(() => { + expect(shareMock).toHaveBeenCalledWith({ + text: 'Example', + url: 'https://example.com', + }); + }); + }); + + it('forwards refs to the underlying button', () => { + const ref = createRef(); + + render( + + Share natively + , + ); + + expect(ref.current).toBe(screen.getByRole('button', { name: 'Share natively' })); + }); + + it('ignores share sheet cancellation by the user', async () => { + const shareMock = vi.fn().mockRejectedValue(new DOMException('Share canceled', 'AbortError')); + + Object.defineProperty(window.navigator, 'share', { + configurable: true, + value: shareMock, + }); + + render(Share natively); + + fireEvent.click(screen.getByRole('button', { name: 'Share natively' })); + + await waitFor(() => { + expect(shareMock).toHaveBeenCalled(); + }); + await new Promise(resolve => setTimeout(resolve, 0)); + }); +}); diff --git a/test/NetworkShareButtons.test.tsx b/test/NetworkShareButtons.test.tsx index 811cf0dd..646feed9 100644 --- a/test/NetworkShareButtons.test.tsx +++ b/test/NetworkShareButtons.test.tsx @@ -2,24 +2,22 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import BlueskyShareButton from '../src/BlueskyShareButton'; -import FacebookShareButton from '../src/FacebookShareButton'; -import GabShareButton from '../src/GabShareButton'; -import HatenaShareButton from '../src/HatenaShareButton'; -import InstapaperShareButton from '../src/InstapaperShareButton'; -import LineShareButton from '../src/LineShareButton'; -import LinkedinShareButton from '../src/LinkedinShareButton'; -import LivejournalShareButton from '../src/LivejournalShareButton'; -import MailruShareButton from '../src/MailruShareButton'; -import OKShareButton from '../src/OKShareButton'; -import PocketShareButton from '../src/PocketShareButton'; -import TelegramShareButton from '../src/TelegramShareButton'; -import ThreadsShareButton from '../src/ThreadsShareButton'; -import TumblrShareButton from '../src/TumblrShareButton'; -import ViberShareButton from '../src/ViberShareButton'; -import VKShareButton from '../src/VKShareButton'; -import WeiboShareButton from '../src/WeiboShareButton'; -import WorkplaceShareButton from '../src/WorkplaceShareButton'; +import { BlueskyShareButton } from '../src/BlueskyShareButton'; +import { FacebookShareButton } from '../src/FacebookShareButton'; +import { GabShareButton } from '../src/GabShareButton'; +import { HatenaShareButton } from '../src/HatenaShareButton'; +import { InstapaperShareButton } from '../src/InstapaperShareButton'; +import { LineShareButton } from '../src/LineShareButton'; +import { LinkedinShareButton } from '../src/LinkedinShareButton'; +import { LivejournalShareButton } from '../src/LivejournalShareButton'; +import { MailruShareButton } from '../src/MailruShareButton'; +import { OKShareButton } from '../src/OKShareButton'; +import { TelegramShareButton } from '../src/TelegramShareButton'; +import { ThreadsShareButton } from '../src/ThreadsShareButton'; +import { TumblrShareButton } from '../src/TumblrShareButton'; +import { ViberShareButton } from '../src/ViberShareButton'; +import { VKShareButton } from '../src/VKShareButton'; +import { WeiboShareButton } from '../src/WeiboShareButton'; type ShareButtonCase = { children: string; @@ -34,7 +32,7 @@ const shareButtonCases: ShareButtonCase[] = [ Component: BlueskyShareButton, expectedUrl: 'https://bsky.app/intent/compose?text=Example%20title%20https%3A%2F%2Fexample.com', props: { - title: 'Example title', + text: 'Example title', url: 'https://example.com', }, }, @@ -53,7 +51,7 @@ const shareButtonCases: ShareButtonCase[] = [ Component: GabShareButton, expectedUrl: 'https://gab.com/compose?url=https%3A%2F%2Fexample.com&text=Example%20title', props: { - title: 'Example title', + text: 'Example title', url: 'https://example.com', }, }, @@ -62,7 +60,7 @@ const shareButtonCases: ShareButtonCase[] = [ Component: HatenaShareButton, expectedUrl: 'http://b.hatena.ne.jp/add?mode=confirm&url=https://example.com&title=Example', props: { - title: 'Example', + shareTitle: 'Example', url: 'https://example.com', }, }, @@ -73,7 +71,7 @@ const shareButtonCases: ShareButtonCase[] = [ 'http://www.instapaper.com/hello2?url=https%3A%2F%2Fexample.com&title=Example%20title&description=Example%20description', props: { description: 'Example description', - title: 'Example title', + shareTitle: 'Example title', url: 'https://example.com', }, }, @@ -83,19 +81,15 @@ const shareButtonCases: ShareButtonCase[] = [ expectedUrl: 'https://social-plugins.line.me/lineit/share?url=https%3A%2F%2Fexample.com&text=Example%20title', props: { - title: 'Example title', + text: 'Example title', url: 'https://example.com', }, }, { children: 'Share on LinkedIn', Component: LinkedinShareButton, - expectedUrl: - 'https://linkedin.com/shareArticle?url=https%3A%2F%2Fexample.com&mini=true&title=Example%20title&summary=Example%20summary&source=Example%20source', + expectedUrl: 'https://linkedin.com/shareArticle?url=https%3A%2F%2Fexample.com&mini=true', props: { - source: 'Example source', - summary: 'Example summary', - title: 'Example title', url: 'https://example.com', }, }, @@ -106,7 +100,7 @@ const shareButtonCases: ShareButtonCase[] = [ 'https://www.livejournal.com/update.bml?subject=Example%20title&event=Example%20description', props: { description: 'Example description', - title: 'Example title', + shareTitle: 'Example title', url: 'https://example.com', }, }, @@ -118,7 +112,7 @@ const shareButtonCases: ShareButtonCase[] = [ props: { description: 'Example description', imageUrl: 'https://example.com/image.png', - title: 'Example title', + shareTitle: 'Example title', url: 'https://example.com', }, }, @@ -130,34 +124,26 @@ const shareButtonCases: ShareButtonCase[] = [ props: { description: 'Example description', image: 'https://example.com/image.png', - title: 'Example title', - url: 'https://example.com', - }, - }, - { - children: 'Share on Pocket', - Component: PocketShareButton, - expectedUrl: 'https://getpocket.com/save?url=https%3A%2F%2Fexample.com&title=Example%20title', - props: { - title: 'Example title', + shareTitle: 'Example title', url: 'https://example.com', }, }, { children: 'Share on Telegram', Component: TelegramShareButton, - expectedUrl: 'https://telegram.me/share/url?url=https%3A%2F%2Fexample.com&text=Example%20title', + expectedUrl: 'https://t.me/share/url?url=https%3A%2F%2Fexample.com&text=Example%20title', props: { - title: 'Example title', + text: 'Example title', url: 'https://example.com', }, }, { children: 'Share on Threads', Component: ThreadsShareButton, - expectedUrl: 'https://threads.net/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title', + expectedUrl: + 'https://www.threads.com/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title', props: { - title: 'Example title', + text: 'Example title', url: 'https://example.com', }, }, @@ -168,8 +154,8 @@ const shareButtonCases: ShareButtonCase[] = [ 'https://www.tumblr.com/widgets/share/tool?canonicalUrl=https%3A%2F%2Fexample.com&title=Example%20title&caption=Example%20caption&tags=react%2Cshare&posttype=link', props: { caption: 'Example caption', + postTitle: 'Example title', tags: ['react', 'share'], - title: 'Example title', url: 'https://example.com', }, }, @@ -178,7 +164,7 @@ const shareButtonCases: ShareButtonCase[] = [ Component: ViberShareButton, expectedUrl: 'viber://forward?text=Example%20title%20https%3A%2F%2Fexample.com', props: { - title: 'Example title', + message: 'Example title', url: 'https://example.com', }, }, @@ -191,7 +177,7 @@ const shareButtonCases: ShareButtonCase[] = [ image: 'https://example.com/image.png', noParse: true, noVkLinks: true, - title: 'Example title', + shareTitle: 'Example title', url: 'https://example.com', }, }, @@ -202,36 +188,23 @@ const shareButtonCases: ShareButtonCase[] = [ 'http://service.weibo.com/share/share.php?url=https%3A%2F%2Fexample.com&title=Example%20title&pic=https%3A%2F%2Fexample.com%2Fimage.png', props: { image: 'https://example.com/image.png', - title: 'Example title', - url: 'https://example.com', - }, - }, - { - children: 'Share on Workplace', - Component: WorkplaceShareButton, - expectedUrl: - 'https://work.facebook.com/sharer.php?u=https%3A%2F%2Fexample.com"e=Example%20quote&hashtag=%23reactshare', - props: { - hashtag: '#reactshare', - quote: 'Example quote', + shareTitle: 'Example title', url: 'https://example.com', }, }, ]; describe('network share buttons', () => { - it.each(shareButtonCases)('builds the expected share URL for $children', ({ - Component, - children, - expectedUrl, - props, - }) => { - const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + it.each(shareButtonCases)( + 'builds the expected share URL for $children', + ({ Component, children, expectedUrl, props }) => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); - render({children}); + render({children}); - fireEvent.click(screen.getByRole('button', { name: children })); + fireEvent.click(screen.getByRole('button', { name: children })); - expect(openSpy).toHaveBeenCalledWith(expectedUrl, '', expect.any(String)); - }); + expect(openSpy).toHaveBeenCalledWith(expectedUrl, '', expect.any(String)); + }, + ); }); diff --git a/test/NetworkShareCounts.test.tsx b/test/NetworkShareCounts.test.tsx deleted file mode 100644 index 1a9aab18..00000000 --- a/test/NetworkShareCounts.test.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import React from 'react'; -import { act, render, screen, waitFor } from '@testing-library/react'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('jsonp', () => ({ - default: vi.fn(), -})); - -import jsonp from 'jsonp'; - -import FacebookShareCount from '../src/FacebookShareCount'; -import HatenaShareCount from '../src/HatenaShareCount'; -import OKShareCount from '../src/OKShareCount'; -import PinterestShareCount from '../src/PinterestShareCount'; -import RedditShareCount from '../src/RedditShareCount'; -import TumblrShareCount from '../src/TumblrShareCount'; -import VKShareCount from '../src/VKShareCount'; - -const jsonpMock = vi.mocked(jsonp); - -const getJsonpCallback = (callIndex: number) => { - const call = jsonpMock.mock.calls[callIndex]; - - if (!call) { - throw new Error(`Expected jsonp call ${callIndex} to exist`); - } - - const callback = call.at(-1); - - if (typeof callback !== 'function') { - throw new Error(`Expected jsonp call ${callIndex} to end with a callback`); - } - - return callback; -}; - -describe('network share count modules', () => { - beforeEach(() => { - jsonpMock.mockReset(); - Reflect.deleteProperty(window, 'OK'); - Reflect.deleteProperty(window, 'ODKL'); - Reflect.deleteProperty(window, 'VK'); - }); - - it('requests and resolves Facebook share counts', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://graph.facebook.com/?id=https://example.com&fields=og_object{engagement}', - expect.any(Function), - ); - - act(() => { - const callback = getJsonpCallback(0) as ( - err: Error | null, - data?: { og_object?: { engagement?: { count?: number } } }, - ) => void; - - callback(null, { og_object: { engagement: { count: 12 } } }); - }); - - await waitFor(() => expect(screen.getByText('12')).toBeInTheDocument()); - }); - - it('requests and resolves Hatena share counts', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://bookmark.hatenaapis.com/count/entry?url=https%3A%2F%2Fexample.com', - expect.any(Function), - ); - - act(() => { - const callback = getJsonpCallback(0) as (err: Error | null, data?: number) => void; - - callback(null, 8); - }); - - await waitFor(() => expect(screen.getByText('8')).toBeInTheDocument()); - }); - - it('requests and resolves Pinterest share counts', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://api.pinterest.com/v1/urls/count.json?url=https%3A%2F%2Fexample.com', - expect.any(Function), - ); - - act(() => { - const callback = getJsonpCallback(0) as ( - err: Error | null, - data?: { count?: number }, - ) => void; - - callback(null, { count: 15 }); - }); - - await waitFor(() => expect(screen.getByText('15')).toBeInTheDocument()); - }); - - it('requests and resolves Reddit share counts', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://www.reddit.com/api/info.json?limit=1&url=https://example.com', - { param: 'jsonp' }, - expect.any(Function), - ); - - act(() => { - const callback = getJsonpCallback(0) as ( - err: Error | null, - data?: { data?: { children: Array<{ data: { score?: number } }> } }, - ) => void; - - callback(null, { data: { children: [{ data: { score: 6 } }] } }); - }); - - await waitFor(() => expect(screen.getByText('6')).toBeInTheDocument()); - }); - - it('requests and resolves Tumblr share counts', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://api.tumblr.com/v2/share/stats?url=https%3A%2F%2Fexample.com', - expect.any(Function), - ); - - act(() => { - const callback = getJsonpCallback(0) as ( - err: Error | null, - data?: { response?: { note_count?: number } }, - ) => void; - - callback(null, { response: { note_count: 19 } }); - }); - - await waitFor(() => expect(screen.getByText('19')).toBeInTheDocument()); - }); - - it('registers OK callbacks and resolves counts through ODKL', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://connect.ok.ru/dk?st.cmd=extLike&uid=react-share-0&ref=https%3A%2F%2Fexample.com', - ); - - act(() => { - window.ODKL.updateCount('react-share-0', '11'); - }); - - await waitFor(() => expect(screen.getByText('11')).toBeInTheDocument()); - }); - - it('registers VK callbacks and resolves counts through VK.Share.count', async () => { - render(); - - expect(jsonpMock).toHaveBeenCalledWith( - 'https://vk.com/share.php?act=count&index=0&url=https%3A%2F%2Fexample.com', - ); - - act(() => { - window.VK.Share?.count(0, 4); - }); - - await waitFor(() => expect(screen.getByText('4')).toBeInTheDocument()); - }); -}); diff --git a/test/PackageBuilds.test.ts b/test/PackageBuilds.test.ts index ec34eac9..b7042ce0 100644 --- a/test/PackageBuilds.test.ts +++ b/test/PackageBuilds.test.ts @@ -31,10 +31,18 @@ const isUsableExport = (value: unknown) => const representativeExportNames = [ 'FacebookShareButton', + 'FacebookLegacyIcon', + 'NativeShareIcon', + 'NativeShareLegacyIcon', + 'NativeShareButton', 'XShareButton', - 'TwitterShareButton', + 'canNativeShare', + 'buildFacebookShareUrl', + 'buildXShareUrl', 'FacebookIcon', - 'PinterestShareCount', + 'XIcon', + 'openShareWindow', + 'shareNative', ] as const; describe('package builds', () => { @@ -58,14 +66,24 @@ describe('package builds', () => { await expect(access(distPaths.typesCjs)).resolves.toBeUndefined(); }); - it('marks share count exports as deprecated in the built type declarations', async () => { + it.each([ + ['ESM', distPaths.esm], + ['CJS', distPaths.cjs], + ])('marks the %s build as a client module for React Server Components', async (_, distPath) => { + const bundle = await readFile(distPath, 'utf8'); + + expect(bundle.startsWith('"use client";')).toBe(true); + }); + + it('does not emit removed v6 exports in the built type declarations', async () => { const declarationBundle = await readFile(distPaths.types, 'utf8'); - expect(declarationBundle).toContain('@deprecated Share counts are deprecated and will be removed in v6.'); - expect(declarationBundle).toContain('@deprecated Use XShareButton instead.'); - expect(declarationBundle).toContain('FacebookShareCount'); - expect(declarationBundle).toContain('PinterestShareCount'); - expect(declarationBundle).toContain('TwitterShareButton'); + expect(declarationBundle).not.toContain('FacebookShareCount'); + expect(declarationBundle).not.toContain('PinterestShareCount'); + expect(declarationBundle).not.toContain('TwitterShareButton'); + expect(declarationBundle).not.toContain('TwitterIcon'); + expect(declarationBundle).not.toContain('PocketShareButton'); + expect(declarationBundle).not.toContain('WorkplaceShareButton'); }); it('exports the same public surface from the ESM and CJS builds', async () => { diff --git a/test/PackageExports.test.tsx b/test/PackageExports.test.tsx index 7d342383..8f0534ef 100644 --- a/test/PackageExports.test.tsx +++ b/test/PackageExports.test.tsx @@ -10,13 +10,34 @@ const iconExportNames = Object.keys(ReactShare) const representativeExportNames = [ 'FacebookShareButton', + 'FacebookLegacyIcon', + 'NativeShareIcon', + 'NativeShareLegacyIcon', + 'NativeShareButton', 'XShareButton', - 'TwitterShareButton', - 'FacebookShareCount', + 'canNativeShare', + 'buildFacebookShareUrl', + 'buildXShareUrl', 'FacebookIcon', 'XIcon', + 'openShareWindow', + 'shareNative', ] as const; +const removedExportNames = [ + 'TwitterShareButton', + 'TwitterIcon', + 'FacebookShareCount', + 'PocketShareButton', + 'PocketIcon', + 'PocketLegacyIcon', + 'buildPocketShareUrl', + 'WorkplaceShareButton', + 'WorkplaceIcon', + 'WorkplaceLegacyIcon', + 'buildWorkplaceShareUrl', +]; + describe('package exports', () => { it('exports representative public symbols', () => { for (const exportName of representativeExportNames) { @@ -24,6 +45,10 @@ describe('package exports', () => { } }); + it.each(removedExportNames)('does not export removed symbol %s', exportName => { + expect(ReactShare).not.toHaveProperty(exportName); + }); + it('exports icon components', () => { expect(iconExportNames.length).toBeGreaterThan(0); }); diff --git a/test/PinterestShareButton.test.tsx b/test/PinterestShareButton.test.tsx index 561d23ba..363b1e0c 100644 --- a/test/PinterestShareButton.test.tsx +++ b/test/PinterestShareButton.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import PinterestShareButton from '../src/PinterestShareButton'; +import { PinterestShareButton } from '../src/PinterestShareButton'; describe('PinterestShareButton', () => { it('builds a create-pin url when media is provided', () => { @@ -31,7 +31,11 @@ describe('PinterestShareButton', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - + Pin it , ); diff --git a/test/RedditShareButton.test.tsx b/test/RedditShareButton.test.tsx index cd521ef0..ea005bb7 100644 --- a/test/RedditShareButton.test.tsx +++ b/test/RedditShareButton.test.tsx @@ -2,14 +2,14 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import RedditShareButton from '../src/RedditShareButton'; +import { RedditShareButton } from '../src/RedditShareButton'; describe('RedditShareButton', () => { it('uses the current Reddit share URL', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - + Share to Reddit , ); diff --git a/test/ShareButton.test.tsx b/test/ShareButton.test.tsx index 063a7e19..9feebe3d 100644 --- a/test/ShareButton.test.tsx +++ b/test/ShareButton.test.tsx @@ -2,8 +2,9 @@ import React from 'react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import FacebookIcon from '../src/FacebookIcon'; -import ShareButton from '../src/ShareButton'; +import { FacebookIcon } from '../src/FacebookIcon'; +import { FacebookLegacyIcon } from '../src/FacebookLegacyIcon'; +import { ShareButton } from '../src/ShareButton'; describe('ShareButton', () => { afterEach(() => { @@ -67,6 +68,111 @@ describe('ShareButton', () => { expect(steps).toEqual(['before:start', 'before:end', 'click']); }); + it('opens the popup synchronously when beforeOnClick is async', async () => { + let resolveBeforeOnClick = () => {}; + const shareWindow = { close: vi.fn(), closed: false, location: { replace: vi.fn() } }; + const openSpy = vi.spyOn(window, 'open').mockReturnValue(shareWindow as unknown as Window); + const onClick = vi.fn(); + + render( + + new Promise(resolve => { + resolveBeforeOnClick = resolve; + }) + } + networkLink={(url: string) => `${url}/share`} + networkName="test" + onClick={onClick} + opts={{}} + url="https://example.com" + > + Share + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share' })); + + // Popup blockers only allow window.open during the click's user activation. + expect(openSpy).toHaveBeenCalledWith('about:blank', '', expect.stringContaining('height=400')); + expect(shareWindow.location.replace).not.toHaveBeenCalled(); + + resolveBeforeOnClick(); + + await waitFor(() => expect(onClick).toHaveBeenCalledTimes(1)); + expect(openSpy).toHaveBeenCalledTimes(1); + expect(shareWindow.location.replace).toHaveBeenCalledWith('https://example.com/share'); + }); + + it('cancels sharing and closes the popup when async beforeOnClick rejects', async () => { + const shareWindow = { close: vi.fn(), closed: false, location: { replace: vi.fn() } }; + vi.spyOn(window, 'open').mockReturnValue(shareWindow as unknown as Window); + const onClick = vi.fn(); + + render( + Promise.reject(new Error('cancelled'))} + networkLink={(url: string) => url} + networkName="test" + onClick={onClick} + opts={{}} + url="https://example.com" + > + Share + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share' })); + + await waitFor(() => expect(shareWindow.close).toHaveBeenCalledTimes(1)); + expect(shareWindow.location.replace).not.toHaveBeenCalled(); + expect(onClick).not.toHaveBeenCalled(); + }); + + it('passes the opened share window to onShareWindowOpen', () => { + const shareWindow = { closed: false }; + vi.spyOn(window, 'open').mockReturnValue(shareWindow as unknown as Window); + const onShareWindowOpen = vi.fn(); + + render( + url} + networkName="test" + onShareWindowOpen={onShareWindowOpen} + opts={{}} + url="https://example.com" + > + Share + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share' })); + + expect(onShareWindowOpen).toHaveBeenCalledWith(shareWindow); + }); + + it('passes null to onShareWindowOpen when the popup is blocked', async () => { + vi.spyOn(window, 'open').mockReturnValue(null); + const onShareWindowOpen = vi.fn(); + + render( + Promise.resolve()} + networkLink={(url: string) => url} + networkName="test" + onShareWindowOpen={onShareWindowOpen} + opts={{}} + url="https://example.com" + > + Share + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share' })); + + await waitFor(() => expect(onShareWindowOpen).toHaveBeenCalledWith(null)); + }); + it('skips window.open when openShareDialogOnClick is false', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); @@ -328,7 +434,7 @@ describe('ShareButton', () => { opts={{}} url="https://example.com" > - + , ); @@ -343,7 +449,7 @@ describe('ShareButton', () => { opts={{}} url="https://example.com" > - + , ); @@ -362,7 +468,7 @@ describe('ShareButton', () => { opts={{}} url="https://example.com" > - + , ); @@ -383,7 +489,7 @@ describe('ShareButton', () => { opts={{}} url="https://example.com" > - + , ); @@ -417,7 +523,7 @@ describe('ShareButton', () => { opts={{}} url="https://example.com" > - + , ); @@ -433,7 +539,7 @@ describe('ShareButton', () => { style={{ borderRadius: 4, display: 'inline-block', outlineOffset: 3 }} url="https://example.com" > - + , ); diff --git a/test/ShareButtonComponents.test.tsx b/test/ShareButtonComponents.test.tsx index 2ee4dcf3..3fef20f5 100644 --- a/test/ShareButtonComponents.test.tsx +++ b/test/ShareButtonComponents.test.tsx @@ -1,13 +1,12 @@ import React, { createRef } from 'react'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; -import EmailIcon from '../src/EmailIcon'; -import EmailShareButton from '../src/EmailShareButton'; -import PinterestIcon from '../src/PinterestIcon'; -import PinterestShareButton from '../src/PinterestShareButton'; -import ThreadsShareButton from '../src/ThreadsShareButton'; -import TumblrShareButton from '../src/TumblrShareButton'; +import { EmailIcon } from '../src/EmailIcon'; +import { EmailShareButton } from '../src/EmailShareButton'; +import { PinterestIcon } from '../src/PinterestIcon'; +import { PinterestShareButton } from '../src/PinterestShareButton'; +import { TumblrShareButton } from '../src/TumblrShareButton'; describe('share button components', () => { it('does not forward network-specific props to the DOM', () => { @@ -49,8 +48,8 @@ describe('share button components', () => { caption="Example caption" openShareDialogOnClick={false} posttype="photo" + postTitle="Example title" tags={['react', 'share']} - title="Example title" url="https://example.com" > Share on Tumblr @@ -64,39 +63,10 @@ describe('share button components', () => { expect(button).not.toHaveAttribute('posttype'); }); - it('keeps legacy Threads props as ignored no-ops', () => { - const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); - - render( - - Share on Threads - , - ); - - const button = screen.getByRole('button', { name: 'Share on Threads' }); - - fireEvent.click(button); - - expect(button).not.toHaveAttribute('hashtags'); - expect(button).not.toHaveAttribute('related'); - expect(button).not.toHaveAttribute('via'); - expect(openSpy).toHaveBeenCalledWith( - 'https://threads.net/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title', - '', - expect.any(String), - ); - }); - it('adds the email fallback label for icon-only buttons', () => { render( - + , ); @@ -106,7 +76,7 @@ describe('share button components', () => { it('adds the Pinterest fallback label for icon-only buttons', () => { render( - + , ); diff --git a/test/ShareHelpers.test.ts b/test/ShareHelpers.test.ts new file mode 100644 index 00000000..c652db86 --- /dev/null +++ b/test/ShareHelpers.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + buildBlueskyShareUrl, + buildEmailShareUrl, + buildFacebookShareUrl, + buildLinkedinShareUrl, + buildViberShareUrl, + buildWhatsappShareUrl, + buildXShareUrl, + openShareWindow, +} from '../src'; + +describe('share helpers', () => { + it('builds a Facebook share URL directly', () => { + expect(buildFacebookShareUrl('https://example.com', { hashtag: '#reactshare' })).toBe( + 'https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fexample.com&hashtag=%23reactshare', + ); + }); + + it('builds an X share URL directly', () => { + expect( + buildXShareUrl('https://example.com', { + hashtags: ['react', 'share'], + related: ['openai'], + text: 'Example title', + via: 'reactshare', + }), + ).toBe( + 'https://x.com/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title&via=reactshare&hashtags=react%2Cshare&related=openai', + ); + }); + + it('builds a LinkedIn share URL directly from only the URL', () => { + expect(buildLinkedinShareUrl('https://example.com')).toBe( + 'https://linkedin.com/shareArticle?url=https%3A%2F%2Fexample.com&mini=true', + ); + }); + + it.each([ + [ + 'Bluesky', + () => buildBlueskyShareUrl('https://example.com', { text: 'Hello' }), + 'https://bsky.app/intent/compose?text=Hello%20https%3A%2F%2Fexample.com', + ], + [ + 'Email', + () => buildEmailShareUrl('https://example.com', { body: 'Hello' }), + 'mailto:?body=Hello%0Ahttps%3A%2F%2Fexample.com', + ], + [ + 'Viber', + () => buildViberShareUrl('https://example.com', { message: 'Hello' }), + 'viber://forward?text=Hello%20https%3A%2F%2Fexample.com', + ], + [ + 'WhatsApp', + () => buildWhatsappShareUrl('https://example.com', { message: 'Hello' }), + 'https://api.whatsapp.com/send?text=Hello%20https%3A%2F%2Fexample.com', + ], + ])('defaults the separator when building a %s share URL directly', (_, build, expected) => { + expect(build()).toBe(expected); + }); + + it('opens a centered share window with the requested size', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + + Object.defineProperty(window, 'screen', { + configurable: true, + value: { height: 900, width: 1600 }, + }); + + openShareWindow('https://example.com/share', { + height: 500, + position: 'screenCenter', + width: 600, + }); + + expect(openSpy).toHaveBeenCalledWith( + 'https://example.com/share', + '', + expect.stringContaining('height=500'), + ); + expect(openSpy).toHaveBeenCalledWith( + 'https://example.com/share', + '', + expect.stringContaining('width=600'), + ); + expect(openSpy).toHaveBeenCalledWith( + 'https://example.com/share', + '', + expect.stringContaining('top=200'), + ); + expect(openSpy).toHaveBeenCalledWith( + 'https://example.com/share', + '', + expect.stringContaining('left=500'), + ); + }); +}); diff --git a/test/SocialMediaShareCount.test.tsx b/test/SocialMediaShareCount.test.tsx deleted file mode 100644 index 669c71c8..00000000 --- a/test/SocialMediaShareCount.test.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import React from 'react'; -import { act, render, screen, waitFor } from '@testing-library/react'; -import { describe, expect, it, vi } from 'vitest'; - -import createShareCount, { SocialMediaShareCount } from '../src/hocs/createShareCount'; - -describe('SocialMediaShareCount', () => { - it('renders children with the resolved count', async () => { - let callback: ((shareCount?: number) => void) | undefined; - - render( - { - callback = cb; - }} - url="https://example.com" - > - {count => Count: {count}} - , - ); - - expect(screen.queryByText('Count: 12')).toBeNull(); - - act(() => { - callback?.(12); - }); - - await waitFor(() => expect(screen.getByText('Count: 12')).toBeInTheDocument()); - }); - - it('re-fetches when the url changes', async () => { - const getCount = vi - .fn<(url: string, callback: (shareCount?: number) => void) => void>() - .mockImplementation((url, callback) => { - callback(url === 'https://example.com/one' ? 1 : 2); - }); - - const { rerender } = render( - , - ); - - await waitFor(() => expect(screen.getByText('1')).toBeInTheDocument()); - - rerender(); - - await waitFor(() => expect(screen.getByText('2')).toBeInTheDocument()); - expect(getCount).toHaveBeenNthCalledWith( - 1, - 'https://example.com/one', - expect.any(Function), - ); - expect(getCount).toHaveBeenNthCalledWith( - 2, - 'https://example.com/two', - expect.any(Function), - ); - }); - - it('does not update state after unmount', () => { - let callback: ((shareCount?: number) => void) | undefined; - - const { unmount } = render( - { - callback = cb; - }} - url="https://example.com" - />, - ); - - unmount(); - - expect(() => { - act(() => { - callback?.(10); - }); - }).not.toThrow(); - }); - - it('creates share count components with the provided getCount implementation', async () => { - const ShareCount = createShareCount((_, callback) => callback(7)); - - render(); - - await waitFor(() => expect(screen.getByText('7')).toBeInTheDocument()); - }); -}); diff --git a/test/Utilities.test.ts b/test/Utilities.test.ts index d185b119..fd394a57 100644 --- a/test/Utilities.test.ts +++ b/test/Utilities.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import assert from '../src/utils/assert'; -import objectToGetParams from '../src/utils/objectToGetParams'; +import { assert } from '../src/utils/assert'; +import { objectToGetParams } from '../src/utils/objectToGetParams'; describe('utilities', () => { it('encodes query parameters and skips nullish values', () => { diff --git a/test/WhatsappShareButton.test.tsx b/test/WhatsappShareButton.test.tsx index 29d24f47..2855de4e 100644 --- a/test/WhatsappShareButton.test.tsx +++ b/test/WhatsappShareButton.test.tsx @@ -2,14 +2,71 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import WhatsappShareButton from '../src/WhatsappShareButton'; +import { WhatsappShareButton } from '../src/WhatsappShareButton'; describe('WhatsappShareButton', () => { + function stubLocation() { + const hrefState = { value: 'https://example.test/' }; + + Object.defineProperty(window, 'location', { + configurable: true, + value: { + get href() { + return hrefState.value; + }, + set href(value: string) { + hrefState.value = value; + }, + }, + }); + + return hrefState; + } + it('uses the api host for generated share links', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - + + Share to WhatsApp + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share to WhatsApp' })); + + expect(openSpy).toHaveBeenCalledWith( + 'https://api.whatsapp.com/send?text=Example%20https%3A%2F%2Fexample.com', + '', + expect.any(String), + ); + }); + + it('uses the app deep link when mobileBehavior is app', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + const hrefState = stubLocation(); + + render( + + Share to WhatsApp + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Share to WhatsApp' })); + + expect(openSpy).not.toHaveBeenCalled(); + expect(hrefState.value).toBe('whatsapp://send?text=Example%20https%3A%2F%2Fexample.com'); + }); + + it('keeps the web URL on desktop when mobileBehavior is auto', () => { + const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); + + Object.defineProperty(window.navigator, 'userAgent', { + configurable: true, + value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', + }); + + render( + Share to WhatsApp , ); diff --git a/test/TwitterShareButton.test.tsx b/test/XShareButton.test.tsx similarity index 62% rename from test/TwitterShareButton.test.tsx rename to test/XShareButton.test.tsx index 6b3ef182..2cee7294 100644 --- a/test/TwitterShareButton.test.tsx +++ b/test/XShareButton.test.tsx @@ -2,34 +2,28 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import XShareButton from '../src/XShareButton'; -import TwitterShareButton from '../src/TwitterShareButton'; - -const shareButtons = [ - ['XShareButton', XShareButton], - ['TwitterShareButton', TwitterShareButton], -] as const; - -describe.each(shareButtons)('%s', (_, ShareButtonComponent) => { +import { XIcon } from '../src/XIcon'; +import { XShareButton } from '../src/XShareButton'; +describe('XShareButton', () => { it('builds a share url with hashtags and related accounts', () => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - Share on X - , + , ); fireEvent.click(screen.getByRole('button', { name: 'Share on X' })); expect(openSpy).toHaveBeenCalledWith( - 'https://twitter.com/intent/tweet?url=https%3A%2F%2Fexample.com&text=Example%20title&via=reactshare&hashtags=react%2Cshare&related=openai%2Cvitejs', + 'https://x.com/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title&via=reactshare&hashtags=react%2Cshare&related=openai%2Cvitejs', '', expect.any(String), ); @@ -39,15 +33,15 @@ describe.each(shareButtons)('%s', (_, ShareButtonComponent) => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - Share on X - , + , ); const button = screen.getByRole('button', { name: 'Share on X' }); @@ -58,7 +52,7 @@ describe.each(shareButtons)('%s', (_, ShareButtonComponent) => { expect(button).not.toHaveAttribute('hashtags'); expect(button).not.toHaveAttribute('related'); expect(openSpy).toHaveBeenCalledWith( - 'https://twitter.com/intent/tweet?url=https%3A%2F%2Fexample.com&text=Share%20title&hashtags=react&related=openai', + 'https://x.com/intent/post?url=https%3A%2F%2Fexample.com&text=Share%20title&hashtags=react&related=openai', '', expect.any(String), ); @@ -68,17 +62,27 @@ describe.each(shareButtons)('%s', (_, ShareButtonComponent) => { const openSpy = vi.spyOn(window, 'open').mockReturnValue(null); render( - + Share on X - , + , ); fireEvent.click(screen.getByRole('button', { name: 'Share on X' })); expect(openSpy).toHaveBeenCalledWith( - 'https://twitter.com/intent/tweet?url=https%3A%2F%2Fexample.com&text=Example%20title', + 'https://x.com/intent/post?url=https%3A%2F%2Fexample.com&text=Example%20title', '', expect.any(String), ); }); + + it('applies the default X aria-label to icon-only buttons', () => { + render( + + + , + ); + + expect(screen.getByRole('button', { name: 'Share on X' })).toBeInTheDocument(); + }); }); diff --git a/vite.config.js b/vite.config.js index 8d3df208..43c2d7f7 100644 --- a/vite.config.js +++ b/vite.config.js @@ -35,6 +35,11 @@ export default defineConfig({ minify: false, rollupOptions: { external: externalDeps, + output: { + // Share buttons attach click handlers, so React Server Components must + // treat the package as a client module. + banner: '"use client";', + }, }, }, });