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: graph events #84

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,34 @@ Example:
```

See this [example `<SelectionDot />` component](./example/src/components/CustomSelectionDot.tsx).
### `events`
An array of events to be marked in the graph. The position is calculated based on the `date` property of each event relatively to `points` of the graph.

### `EventComponent`
A component that is used to render an event.
Copy link
Contributor

Choose a reason for hiding this comment

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

Link EventComponent file here as example (same as SelectionDot)

Copy link
Author

Choose a reason for hiding this comment

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

Linked in the fixup 5ff9fd7.


### `EventTooltipComponent`
Copy link
Contributor

Choose a reason for hiding this comment

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

Please create some default component EventTooltip and link it here as example (same asi SelectionDot)

Copy link
Author

Choose a reason for hiding this comment

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

Default component created in the fixup 5ff9fd7.

An additional event component that is rendered if the `SelectionDot` overlaps an `Event`.

### `onEventHover`

This comment was marked as outdated.

Copy link
Author

Choose a reason for hiding this comment

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

The library does not work with any tap gestures so far. The only user interaction so far is created by the pan gesture which is also the gesture that enables the new event functionality of this PR. I would prefer to not add this functionality to not make the PR too big. The onPressEvent could be added to the follow-up PR if needed.

Callback called when an `Event` is hovered on.

> Events related props require `animated` and `enablePanGesture` to be `true`.

Example:

<img src="./img/events.png" align="right" height="200" />
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Can you make default color of event different that line? Maybe some kind of simple fade out gradient of dot or something like that will make it really nice.

Copy link
Author

Choose a reason for hiding this comment

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

The style of the default event component was adjusted to appear more contrasting. 5ff9fd7


```jsx
<LineGraph
points={priceHistory}
color="#4484B2"
animated={true}
enablePanGesture={true}
events={transactionEvents}
EventComponent={DefaultEventComponent}
/>
```
## Sponsor

<img src="./img/pinkpanda.png" align="right" height="50">
Expand Down
26 changes: 24 additions & 2 deletions example/src/data/GraphData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { GraphPoint } from '../../../src/LineGraphProps'
import type { GraphEvent, GraphPoint } from '../../../src/LineGraphProps'
import gaussian from 'gaussian'

function weightedRandom(mean: number, variance: number): number {
Expand All @@ -7,7 +7,7 @@ function weightedRandom(mean: number, variance: number): number {
return distribution.ppf(Math.random())
}

export function generateRandomGraphData(length: number): GraphPoint[] {
export function generateRandomGraphPoints(length: number): GraphPoint[] {
return Array<number>(length)
.fill(0)
.map((_, index) => ({
Expand All @@ -18,6 +18,28 @@ export function generateRandomGraphData(length: number): GraphPoint[] {
}))
}

export function generateRandomGraphEvents(
length: number,
points: GraphPoint[]
): GraphEvent[] {
const firstPointTimestamp = points[0]?.date.getTime()
const lastPointTimestamp = points[points.length - 1]?.date.getTime()

if (!firstPointTimestamp || !lastPointTimestamp) {
return []
}
return Array<number>(length)
.fill(0)
.map((_) => ({
date: new Date( // Get a random date between the two defined timestamps.
Math.floor(
Math.random() * (lastPointTimestamp - firstPointTimestamp + 1)
) + firstPointTimestamp
),
payload: {},
}))
}

export function generateSinusGraphData(length: number): GraphPoint[] {
return Array<number>(length)
.fill(0)
Expand Down
20 changes: 17 additions & 3 deletions example/src/screens/GraphPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import type { GraphRange } from '../../../src/LineGraphProps'
import { SelectionDot } from '../components/CustomSelectionDot'
import { Toggle } from '../components/Toggle'
import {
generateRandomGraphData,
generateRandomGraphEvents,
generateRandomGraphPoints,
generateSinusGraphData,
} from '../data/GraphData'
import { useColors } from '../hooks/useColors'
import { hapticFeedback } from '../utils/HapticFeedback'

const POINT_COUNT = 70
const POINTS = generateRandomGraphData(POINT_COUNT)
const POINTS = generateRandomGraphPoints(POINT_COUNT)
const EVENT_COUNT = 10
const EVENTS = generateRandomGraphEvents(EVENT_COUNT, POINTS)
const COLOR = '#6a7ee7'
const GRADIENT_FILL_COLORS = ['#7476df5D', '#7476df4D', '#7476df00']
const SMALL_POINTS = generateSinusGraphData(9)
Expand All @@ -30,11 +33,16 @@ export function GraphPage() {
const [enableRange, setEnableRange] = useState(false)
const [enableIndicator, setEnableIndicator] = useState(false)
const [indicatorPulsating, setIndicatorPulsating] = useState(false)
const [enableEvents, setEnableEvents] = useState(false)

const [points, setPoints] = useState(POINTS)
const [events, setEvents] = useState(EVENTS)

const refreshData = useCallback(() => {
setPoints(generateRandomGraphData(POINT_COUNT))
const freshPoints = generateRandomGraphPoints(POINT_COUNT)
const freshEvents = generateRandomGraphEvents(EVENT_COUNT, freshPoints)
setPoints(freshPoints)
setEvents(freshEvents)
hapticFeedback('impactLight')
}, [])

Expand Down Expand Up @@ -100,6 +108,7 @@ export function GraphPage() {
enableIndicator={enableIndicator}
horizontalPadding={enableIndicator ? 15 : 0}
indicatorPulsating={indicatorPulsating}
events={enableEvents ? events : []}
/>

<Button title="Refresh" onPress={refreshData} />
Expand Down Expand Up @@ -148,6 +157,11 @@ export function GraphPage() {
isEnabled={indicatorPulsating}
setIsEnabled={setIndicatorPulsating}
/>
<Toggle
title="Enable events:"
isEnabled={enableEvents}
setIsEnabled={setEnableEvents}
/>
</ScrollView>

<View style={styles.spacer} />
Expand Down
Binary file added img/events.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 59 additions & 3 deletions src/AnimatedLineGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ import {
Shadow,
} from '@shopify/react-native-skia'

import type { AnimatedLineGraphProps } from './LineGraphProps'
import type {
AnimatedLineGraphProps,
GraphEventWithCords,
} from './LineGraphProps'
import { SelectionDot as DefaultSelectionDot } from './SelectionDot'
import {
createGraphPath,
Expand All @@ -45,6 +48,8 @@ import { getSixDigitHex } from './utils/getSixDigitHex'
import { usePanGesture } from './hooks/usePanGesture'
import { getYForX } from './GetYForX'
import { hexToRgba } from './utils/hexToRgba'
import { DefaultGraphEvent } from './DefaultGraphEvent'
import { useEventTooltipProps } from './hooks/useEventTooltipProps'

const INDICATOR_RADIUS = 7
const INDICATOR_BORDER_MULTIPLIER = 1.3
Expand All @@ -53,7 +58,7 @@ const INDICATOR_PULSE_BLUR_RADIUS_SMALL =
const INDICATOR_PULSE_BLUR_RADIUS_BIG =
INDICATOR_RADIUS * INDICATOR_BORDER_MULTIPLIER + 20

export function AnimatedLineGraph({
export function AnimatedLineGraph<TEventPayload extends object>({
points: allPoints,
color,
gradientFillColors,
Expand All @@ -74,12 +79,24 @@ export function AnimatedLineGraph({
verticalPadding = lineThickness,
TopAxisLabel,
BottomAxisLabel,
events,
EventComponent = DefaultGraphEvent,
EventTooltipComponent,
onEventHover,
...props
}: AnimatedLineGraphProps): React.ReactElement {
}: AnimatedLineGraphProps<TEventPayload>): React.ReactElement {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const interpolateProgress = useValue(0)

const [eventsWithCords, setEventsWithCords] = useState<
GraphEventWithCords<TEventPayload>[] | null
>(null)
const { eventTooltipProps, handleDisplayEventTooltip } = useEventTooltipProps(
eventsWithCords,
onEventHover
)

const { gesture, isActive, x } = usePanGesture({
enabled: enablePanGesture,
holdDuration: panGestureDelay,
Expand Down Expand Up @@ -252,6 +269,7 @@ export function AnimatedLineGraph({
}

setCommandsChanged(commandsChanged + 1)
setEventsWithCords(null)

runSpring(
interpolateProgress,
Expand All @@ -261,6 +279,19 @@ export function AnimatedLineGraph({
stiffness: 500,
damping: 400,
velocity: 0,
},
() => {
// Calculate graph event coordinates when the interpolation ends.
if (events) {
const extendedEvents: GraphEventWithCords<TEventPayload>[] = []
events.forEach((e) => {
const eventX =
getXInRange(drawingWidth, e.date, pathRange.x) + horizontalPadding
const eventY = getYForX(commands.value, eventX) ?? 0
extendedEvents.push({ ...e, x: eventX, y: eventY })
})
setEventsWithCords(extendedEvents)
}
}
)
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -277,6 +308,7 @@ export function AnimatedLineGraph({
straightLine,
verticalPadding,
width,
events,
])

const gradientColors = useMemo(() => {
Expand Down Expand Up @@ -515,6 +547,25 @@ export function AnimatedLineGraph({
/>
)}

{/* Render Event Component for every event. */}
{EventComponent != null && eventsWithCords && (
<Group>
{eventsWithCords?.map((event, index) => (
<EventComponent
key={event.date.getTime()}
index={index}
isGraphActive={isActive}
fingerX={circleX}
eventX={event.x}
eventY={event.y}
color={color}
onEventHover={handleDisplayEventTooltip}
{...event.payload}
/>
))}
</Group>
)}

{indicatorVisible && (
<Group>
{indicatorPulsating && (
Expand Down Expand Up @@ -555,6 +606,11 @@ export function AnimatedLineGraph({
)}
</Reanimated.View>
</GestureDetector>

{/* Tooltip displayed on hover on EventComponent. */}
{EventTooltipComponent && eventTooltipProps && (
<EventTooltipComponent {...eventTooltipProps} />
)}
</View>
)
}
Expand Down
48 changes: 48 additions & 0 deletions src/DefaultGraphEvent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { useEffect } from 'react'
import {
useDerivedValue,
useSharedValue,
withSpring,
withTiming,
} from 'react-native-reanimated'

import { Circle, Group } from '@shopify/react-native-skia'

import { EventComponentProps } from './LineGraphProps'

const EVENT_SIZE = 6
const ACTIVE_EVENT_SIZE = 8
const ENTERING_ANIMATION_DURATION = 750

export function DefaultGraphEvent({
isGraphActive,
fingerX,
eventX,
eventY,
color,
}: EventComponentProps) {
const isEventActive = useDerivedValue(
() =>
isGraphActive.value &&
Math.abs(fingerX.value - eventX) < ACTIVE_EVENT_SIZE
)

const dotRadius = useDerivedValue(() =>
withSpring(isEventActive.value ? ACTIVE_EVENT_SIZE : EVENT_SIZE)
)

const animatedOpacity = useSharedValue(0)

useEffect(() => {
// Entering opacity animation triggered on the first render.
animatedOpacity.value = withTiming(1, {
duration: ENTERING_ANIMATION_DURATION,
})
}, [animatedOpacity])

return (
<Group opacity={animatedOpacity}>
<Circle cx={eventX} cy={eventY} r={dotRadius} color={color} />
</Group>
)
}
11 changes: 7 additions & 4 deletions src/LineGraph.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react'

import { AnimatedLineGraph } from './AnimatedLineGraph'
import type { LineGraphProps } from './LineGraphProps'
import { StaticLineGraph } from './StaticLineGraph'

function LineGraphImpl(props: LineGraphProps): React.ReactElement {
if (props.animated) return <AnimatedLineGraph {...props} />
else return <StaticLineGraph {...props} />
export function LineGraphImpl<TEventPayload extends object>(
props: LineGraphProps<TEventPayload>
): React.ReactElement {
if (props.animated) return <AnimatedLineGraph<TEventPayload> {...props} />
return <StaticLineGraph {...props} />
}

export const LineGraph = React.memo(LineGraphImpl)
export const LineGraph = React.memo(LineGraphImpl) as typeof LineGraphImpl
Copy link
Member

Choose a reason for hiding this comment

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

Why? This should be typed

Loading