Skip to content

Commit

Permalink
PORTALS-3241: add a short io button that can be styled by the portal
Browse files Browse the repository at this point in the history
  • Loading branch information
jay-hodgson committed Sep 12, 2024
1 parent b90c11f commit a8c48bd
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Meta, StoryObj } from '@storybook/react'
import SharePageLinkButton from './SharePageLinkButton'

const meta = {
title: 'UI/SharePageLinkButton',
component: SharePageLinkButton,
} satisfies Meta
export default meta
type Story = StoryObj<typeof meta>

export const SharePageLinkButtonStory: Story = {
args: {
buttonProps: {
sx: { position: 'fixed', right: '20px' },
},
},
parameters: {
stack: 'mock',
msw: {
handlers: [],
},
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { useCallback } from 'react'
import { useMutation } from '@tanstack/react-query'
import { displayToast } from '../ToastMessage'
import IconSvg from '../IconSvg'
import { Button, ButtonProps } from '@mui/material'

export type SharePageLinkButtonProps = {
shortIoPublicApiKey?: string
domain?: string
buttonProps?: ButtonProps
}

export const SharePageLinkButton: React.FunctionComponent<
SharePageLinkButtonProps
> = ({ shortIoPublicApiKey, domain = 'sageb.io', buttonProps }) => {
const copyToClipboard = useCallback((value: string) => {
navigator.clipboard.writeText(value).then(() => {
displayToast('Page URL copied to the clipboard', 'success')
})
}, [])
// create short io link (if not already created)
const { mutate: createShortUrl } = useMutation({
mutationFn: async () => {
if (!shortIoPublicApiKey) {
return window.location.href
} else {
const response = await fetch('https://api.short.io/links/public', {
method: 'POST',
headers: {
Authorization: shortIoPublicApiKey,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
originalURL: window.location.href,
domain: domain,
}),
})

if (!response.ok) {
const responseText = await response.text()
throw new Error(responseText)
}
const jsonResponse = await response.json()
return jsonResponse.shortURL
}
},
onSuccess: data => {
copyToClipboard(data)
},
onError: error => {
console.error(error)
copyToClipboard(window.location.href)
},
})

return (
<Button
variant="contained"
onClick={() => {
createShortUrl()
}}
{...buttonProps}
>
<IconSvg icon="contentCopy" wrap={false} sx={{ mr: '5px' }} />
Share Page Link
</Button>
)
}

export default SharePageLinkButton
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import SharePageLinkButton from './SharePageLinkButton'
import type { SharePageLinkButtonProps } from './SharePageLinkButton'
export { SharePageLinkButton, SharePageLinkButtonProps }
export default SharePageLinkButton

0 comments on commit a8c48bd

Please sign in to comment.