|
import { CustomPIXIComponent } from 'react-pixi-fiber' |
|
import * as PIXI from 'pixi.js' |
|
|
|
const TYPE = 'Button' |
|
export const behavior = { |
|
customDisplayObject: props => new PIXI.Graphics(), |
|
customApplyProps: (instance, oldProps, newProps) => { |
|
const { |
|
fill, |
|
width, |
|
height, |
|
scale, |
|
onChange, |
|
currentPosition, |
|
stepWidth, |
|
moveToX, |
|
btnWidth, |
|
} = newProps |
|
|
|
const onDragStart = event => { |
|
instance.data = event.data |
|
instance.dragging = true |
|
} |
|
|
|
const onDragEnd = event => { |
|
delete instance.data |
|
instance.dragging = false |
|
} |
|
|
|
const onDragMove = event => { |
|
const min = 0 |
|
// parent._width is the width of the background, and width is the width of this button |
|
const max = instance.parent._width - width |
|
if (instance.dragging) { |
|
const newPosition = instance.data.getLocalPosition(instance.parent) |
|
instance.x = newPosition.x |
|
if (instance.x > max) instance.x = max |
|
if (instance.x < min) instance.x = min |
|
onChange({ x: instance.x }) |
|
} |
|
} |
|
|
|
instance.clear() |
|
instance.beginFill(fill) |
|
instance.drawRect(0, 0, width, height) |
|
instance.endFill() |
|
instance.interactive = true |
|
instance.buttonMode = true |
|
instance.on('pointerdown', onDragStart) |
|
instance.on('pointerup', onDragEnd) |
|
instance.on('pointerupoutside', onDragEnd) |
|
instance.on('pointermove', onDragMove) |
|
|
|
if (oldProps.moveToX && oldProps.moveToX !== moveToX) { |
|
instance.x = 0 |
|
instance.x = moveToX |
|
// Callback |
|
onChange({ x: instance.x }) |
|
} |
|
|
|
if (!oldProps.currentPosition) { |
|
// Only when mounting the component |
|
instance.x = currentPosition * stepWidth |
|
} |
|
|
|
if (oldProps.scale && oldProps.scale !== scale) { |
|
instance.x = 0 |
|
instance.x = currentPosition * stepWidth |
|
} |
|
}, |
|
} |
|
export default CustomPIXIComponent(behavior, TYPE) |