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 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
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +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.


See this [example `<GraphEvent/>` component](./example/src/components/GraphEvent.tsx).

### `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`.
See this [example `<GraphEventTooltip/>` component](./example/src/components/GraphEventTooltip.tsx).
### `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.

Example:
```jsx
<LineGraph
points={priceHistory}
color="#4484B2"
animated={true}
enablePanGesture={true}
events={transactionEvents}
EventComponent={DefaultEventComponent}
/>
```
> Events related props require `animated` and `enablePanGesture` to be `true`.

<img src="./img/events.gif" align="right" height="250" />

## Sponsor

Expand Down
74 changes: 74 additions & 0 deletions example/src/components/GraphEvent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import React, { useEffect } from 'react'
import {
runOnJS,
useDerivedValue,
useSharedValue,
withSpring,
withTiming,
} from 'react-native-reanimated'

import {
Circle,
Group,
TwoPointConicalGradient,
vec,
} from '@shopify/react-native-skia'
import { EventComponentProps } from '../../../src/LineGraphProps'

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

export function GraphEvent({
isGraphActive,
fingerX,
eventX,
eventY,
color,
index,
onEventHover,
}: EventComponentProps) {
const isEventActive = useDerivedValue(() => {
// If the finger is on X position of the event.
if (
isGraphActive.value &&
Math.abs(fingerX.value - eventX) < ACTIVE_EVENT_SIZE
) {
if (onEventHover) runOnJS(onEventHover)(index, true)

return true
}

if (onEventHover) runOnJS(onEventHover)(index, false)
return false
})

const dotRadius = useDerivedValue(() =>
withSpring(isEventActive.value ? ACTIVE_EVENT_SIZE : EVENT_SIZE)
)
const gradientEndRadius = useDerivedValue(() =>
withSpring(dotRadius.value / 2)
)
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}>
<TwoPointConicalGradient
start={vec(eventX, eventY)}
startR={0}
end={vec(eventX, eventY)}
endR={gradientEndRadius}
colors={['white', color]}
/>
</Circle>
</Group>
)
}
68 changes: 68 additions & 0 deletions example/src/components/GraphEventTooltip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import React from 'react'
import Animated, { FadeIn, FadeOut } from 'react-native-reanimated'
import { Dimensions, Platform, StyleSheet, Text, View } from 'react-native'
import { EventTooltipComponentProps } from '../../../src/LineGraphProps'

export type TransactionEventTooltipProps = EventTooltipComponentProps<{}>

const SCREEN_WIDTH = Dimensions.get('screen').width
const ANIMATION_DURATION = 200
const TOOLTIP_LEFT_OFFSET = 25
const TOOLTIP_RIGHT_OFFSET = 145

export const GraphEventTooltip = ({
eventX,
eventY,
}: TransactionEventTooltipProps) => {
const tooltipPositionStyle = {
left:
eventX > SCREEN_WIDTH / 2
? eventX - TOOLTIP_RIGHT_OFFSET
: eventX + TOOLTIP_LEFT_OFFSET,
top: eventY,
}
return (
<Animated.View
style={[styles.tooltip, tooltipPositionStyle]}
entering={FadeIn.duration(ANIMATION_DURATION)}
exiting={FadeOut.duration(ANIMATION_DURATION)}
>
<View style={styles.content}>
<Text style={styles.textNote}>
Here you can display {'\n'}
any information you {'\n'}
want about the event.
</Text>
</View>
</Animated.View>
)
}

const styles = StyleSheet.create({
tooltip: {
position: 'absolute',
backgroundColor: 'white',
paddingHorizontal: 10,

borderRadius: 20,
// add shadow based on platform
...Platform.select({
ios: {
shadowColor: 'black',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.5,
shadowRadius: 3,
},
android: {
elevation: 3,
},
}),
},
content: {
paddingVertical: 12,
},
textNote: {
color: 'gray',
fontSize: 10,
},
})
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
30 changes: 27 additions & 3 deletions example/src/screens/GraphPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@ import { LineGraph } from 'react-native-graph'
import StaticSafeAreaInsets from 'react-native-static-safe-area-insets'
import type { GraphRange } from '../../../src/LineGraphProps'
import { SelectionDot } from '../components/CustomSelectionDot'
import { GraphEvent } from '../components/GraphEvent'
import { GraphEventTooltip } from '../components/GraphEventTooltip'
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 +35,17 @@ export function GraphPage() {
const [enableRange, setEnableRange] = useState(false)
const [enableIndicator, setEnableIndicator] = useState(false)
const [indicatorPulsating, setIndicatorPulsating] = useState(false)
const [enableEvents, setEnableEvents] = useState(false)
const [enableEventTooltip, setEnableEventTooltip] = 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 +111,9 @@ export function GraphPage() {
enableIndicator={enableIndicator}
horizontalPadding={enableIndicator ? 15 : 0}
indicatorPulsating={indicatorPulsating}
events={enableEvents ? events : []}
EventComponent={enableEvents ? GraphEvent : null}
EventTooltipComponent={enableEventTooltip ? GraphEventTooltip : null}
/>

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

<View style={styles.spacer} />
Expand Down
Binary file added img/events.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading