Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(example): Copy svg to clipboard #4

Merged
merged 4 commits into from
Feb 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions example/components/alert.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import * as React from 'react'
import styled, { css, keyframes, Keyframes } from 'styled-components'

const flyIn = keyframes`
from {
opacity: 0;
visibility: visible;
transform: translateX(-50%) translateY(-5px);
}
to {
opacity: 1;
visibility: visible;
transform: translateX(-50%) translateY(0px);
}
`

const fadeOut = keyframes`
from {
opacity: 1;
visibility: visible;
}
to {
opacity: 0;
visibility: hidden;
}
`

const animation = (props: {
animation: Keyframes
animationLength: number
}) => {
return css`
animation: ${props.animation} ${props.animationLength}ms forwards ease-out;
`
}

const AlertWrapper = styled.div`
position: relative;
overflow: inherit;
`

const StyledAlert = styled.div`
position: absolute;
margin-top: 5px;
padding: 4px 10px;
width: 100px;
z-index: 10;
background-color: var(--color-alert-background);
color: var(--color-alert-text);
font-weight: 500;
text-align: center;
border-radius: 3px;
font-size: 14px;
left: 50%;
transform: translateX(-50%);
opacity: 0;
visibility: hidden;

${animation};
`

export default function Alert({
children,
animationLength,
visibilityDuration,
alertText,
onFinish,
}) {
const [alertFading, setAlertFading] = React.useState(false)

React.useEffect(() => {
if (alertText) {
setTimeout(
() => setAlertFading(true),
visibilityDuration - animationLength
)
setTimeout(() => {
onFinish()
setAlertFading(false)
}, visibilityDuration)
}
}, [alertText])

return (
<AlertWrapper>
{children}
{alertText ? (
<StyledAlert
aria-live="polite"
role="alert"
animation={alertFading ? fadeOut : flyIn}
animationLength={animationLength}
>
{alertText.message}
</StyledAlert>
) : null}
</AlertWrapper>
)
}
24 changes: 22 additions & 2 deletions example/components/toolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as React from 'react'
import state from '../state'
import state, { useSelector } from '../state'
import Alert from './alert'
import copySvgToClipboard from '../utils/copySvgToClipboard'
import styled from 'styled-components'
import { Trash, RotateCcw, RotateCw, Settings } from 'react-feather'
import { Trash, RotateCcw, RotateCw, Settings, Clipboard } from 'react-feather'

const ToolbarContainer = styled.div`
position: absolute;
Expand All @@ -16,12 +18,14 @@ const ToolbarContainer = styled.div`
background-color: var(--color-scrim);
backdrop-filter: blur(30px);
user-select: none;
overflow: visible;
`

const ButtonGroup = styled.div`
padding: 0 4px;
display: flex;
align-items: center;
overflow: inherit;
`

const IconButton = styled.button`
Expand All @@ -46,6 +50,8 @@ const IconButton = styled.button`
`

export default function Toolbar() {
const clipboardMessage = useSelector(state => state.data.clipboardMessage)

return (
<ToolbarContainer onPointerDown={e => e.stopPropagation()}>
<ButtonGroup>
Expand All @@ -63,6 +69,20 @@ export default function Toolbar() {
| <a href="https://twitter.com/steveruizok">@steveruizok</a>
</div>
<ButtonGroup>
<Alert
animationLength={150}
visibilityDuration={1200}
alertText={clipboardMessage}
onFinish={() => state.send('SET_CLIPBOARD_MESSAGE', null)}
>
<IconButton
onClick={async () => {
state.send('SET_CLIPBOARD_MESSAGE', await copySvgToClipboard())
}}
>
<Clipboard />
</IconButton>
</Alert>
<IconButton onClick={() => state.send('TOGGLED_CONTROLS')}>
<Settings />
</IconButton>
Expand Down
2 changes: 1 addition & 1 deletion example/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default function Home() {
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<svg ref={ref} viewBox={'0 0 800 600'}>
<svg ref={ref} viewBox={'0 0 800 600'} id="drawable-svg">
{marks.map((mark, i) => (
<path
key={i}
Expand Down
4 changes: 3 additions & 1 deletion example/state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createState, createSelectorHook } from '@state-designer/react'
import { getPointer } from './hooks/useEvents'
import { Mark, CompleteMark } from './types'
import { Mark, CompleteMark, ClipboardMessage } from './types'
import pathAlgorithm, { StrokeOptions } from 'perfect-freehand'

const defaultOptions: StrokeOptions = {
Expand Down Expand Up @@ -29,6 +29,7 @@ const state = createState({
redos: [] as { clear?: boolean; marks: CompleteMark[] }[],
marks: [] as CompleteMark[],
currentMark: null as Mark | null,
clipboardMessage: null as ClipboardMessage | null,
},
on: {
RESET_OPTIONS: [d => (d.alg = { ...defaultOptions }), 'updatePaths'],
Expand All @@ -51,6 +52,7 @@ const state = createState({
UNDO: ['undoMark'],
REDO: ['redoMark'],
TOGGLED_DARK_MODE: ['toggleDarkMode', 'setDarkMode'],
SET_CLIPBOARD_MESSAGE: (d, p) => (d.clipboardMessage = p),
},
states: {
pointer: {
Expand Down
4 changes: 4 additions & 0 deletions example/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ html,
--color-border: rgba(144, 144, 144, 0.4);
--color-hover: rgba(144, 144, 144, 0.1);
--color-scrim: rgba(255, 255, 255, 0.9);
--color-alert-background: #1d1d1d;
--color-alert-text: #ffffff;
}

.dark {
--color-background: #1d1d1d;
--color-text: #cfcfcf;
--color-scrim: rgba(20, 0, 0, 0.3);
--color-alert-background: #ffffff;
--color-alert-text: #1d1d1d;
}

button {
Expand Down
5 changes: 5 additions & 0 deletions example/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,8 @@ export interface Pointer extends Point {
p: number
type: 'pen' | 'mouse' | 'touch'
}

export interface ClipboardMessage {
error: boolean
message: string
}
54 changes: 54 additions & 0 deletions example/utils/copySvgToClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
export default async function copySvgToClipboard() {
let clipboardMessage = null

const element = document.getElementById('drawable-svg') as any

if (element) {
// Get the SVG's bounding box
var bbox = element.getBBox()
let tViewBox = element.getAttribute('viewBox')
var viewBox = [
bbox.x - 16,
bbox.y - 16,
bbox.width + 32,
bbox.height + 32,
].join(' ')
let tW = element.getAttribute('width')
let tH = element.getAttribute('height')

// Resize the element to the bounding box
element.setAttribute('viewBox', viewBox)
element.setAttribute('width', bbox.width)
element.setAttribute('height', bbox.height)

// Take a snapshot of the element
const s = new XMLSerializer()
const svgString = s.serializeToString(element)

// Reset the element to its original viewBox / size
element.setAttribute('viewBox', tViewBox)
element.setAttribute('width', tW)
element.setAttribute('height', tH)

await navigator.clipboard.writeText(svgString).then(
() => {
clipboardMessage = {
error: false,
message: `Copied SVG`,
}
},
() => {
clipboardMessage = {
error: true,
message: `Unable to copy svg`,
}
}
)
} else {
clipboardMessage = {
error: true,
message: `Couldn't find svg`,
}
}
return clipboardMessage
}