iwmlib/lib/pixi/buttongroup.js

691 lines
26 KiB
JavaScript

/* globals ThrowPropsPlugin, Strong */
import Theme from './theme.js'
import Button from './button.js'
import Events from '../events.js'
/**
* Class that represents a PixiJS ButtonGroup.
*
* @example
* // Create the button group
* const buttonGroup = new ButtonGroup({
* buttons: [
* {label: 'Button 1', action: event => console.log(event)},
* {label: 'Button 2', action: event => console.log(event)},
* {label: 'Button 3', action: event => console.log(event)}
* ],
* minWidth: 100
* })
*
* // Add the button group to a DisplayObject
* app.scene.addChild(buttonGroup)
*
* @class
* @extends PIXI.Graphics
* @see {@link http://pixijs.download/dev/docs/PIXI.Graphics.html|PIXI.Graphics}
* @see {@link https://www.iwm-tuebingen.de/iwmbrowser/lib/pixi/buttongroup.html|DocTest}
*/
export default class ButtonGroup extends PIXI.Container {
/**
* Creates an instance of a ButtonGroup.
*
* @constructor
* @param {object} [opts] - An options object to specify to style and behaviour of the button group.
* @param {number} [opts.id=auto generated] - The id of the button group.
* @param {number} [opts.x=0] - The x position of the button group. Can be also set after creation with buttonGroup.x = 0.
* @param {number} [opts.y=0] - The y position of the button group. Can be also set after creation with buttonGroup.y = 0.
* @param {object[]} [opts.buttons=[]] - An array of the buttons of the button group. One item of the array (one object)
* can have exactly the same properties as an Button object when instantiating a Button. If a property of the button group
* conflicts with a property of a button object, the value from the button object will be used.
* @param {string|Theme=} [opts.theme=dark] - The theme to use for this button group. Possible values are dark, light, red
* or a Theme object.
* @param {number} [opts.minWidth=44] - Button: The minimum width of one button.
* @param {number} [opts.minHeight=44] - Button: The minimum height of one button.
* @param {number} [opts.maxWidth] - The maximum width of the button group. If the buttons are wider than the maximum width, the buttons get stacked. Note: The buttons can only be stacked if margin is not zero. Note 2: Load the Greensock ThrowPropsPlugin for smoother animations.
* @param {number} [opts.maxHeight] - The maximum height of the button group. If the buttons are higher than the maximum height, the buttons get stacked. Note: The buttons can only be stacked if margin is not zero. Note 2: Load the Greensock ThrowPropsPlugin for smoother animations.
* @param {number} [opts.stackPadding=10] - The padding for stacked buttons.
* @param {PIXI.Application} [opts.app=window.app] - The PixiJS Application. Must be set if you want to use the mousewheel to scroll your button group. Only used when the buttons are stacked (with maxWidth or maxHeight).
* @param {number} [opts.padding=Theme.padding] - Button: The inner spacing (distance from icon and/or label) the the border.
* @param {number} [opts.margin=Theme.margin] - The outer spacing (distance from one button to the previous/next button).
* @param {string} [opts.iconPosition=left] - Button: The position of the icon in relation to the label. Can be left or right.
* @param {number} [opts.iconColor=Theme.iconColor] - Button: The color of the icon (set by the tint property) as a hex value.
* @param {number} [opts.iconColorActive=Theme.iconColorActive] - Button: The color of the icon when activated.
* @param {number} [opts.fill=Theme.fill] - Button: The color of the button background as a hex value.
* @param {number} [opts.fillAlpha=Theme.fillAlpha] - Button: The alpha value of the background.
* @param {number} [opts.fillActive=Theme.fillActive] - Button: The color of the button background when activated.
* @param {number} [opts.fillActiveAlpha=Theme.fillActiveAlpha] - Button: The alpha value of the background when activated.
* @param {number} [opts.stroke=Theme.stroke] - Button: The color of the border as a hex value.
* @param {number} [opts.strokeWidth=Theme.strokeWidth] - Button: The width of the border in pixel.
* @param {number} [opts.strokeAlpha=Theme.strokeAlpha] - Button: The alpha value of the border.
* @param {number} [opts.strokeActive=Theme.strokeActive] - Button: The color of the border when activated.
* @param {number} [opts.strokeActiveWidth=Theme.strokeActiveWidth] - Button: The width of the border in pixel when activated.
* @param {number} [opts.strokeActiveAlpha=Theme.strokeActiveAlpha] - Button: The alpha value of the border when activated.
* @param {object} [opts.textStyle=Theme.textStyle] - Button: A textstyle object for the styling of the label. See PIXI.TextStyle
* for possible options.
* @param {number} [opts.textStyleActive=Theme.textStyleActive] - Button: A textstyle object for the styling of the label when the
* button is activated. See PIXI.TextStyle for possible options.
* @param {string} [opts.style=default] - A shortcut for styling options. Possible values are default, link.
* @param {number} [opts.radius=Theme.radius] - Button: The radius of the four corners of the button (which is a rounded rectangle).
* @param {boolean} [opts.disabled=false] - Is the button group disabled? When disabled, the button group has a lower alpha value
* and cannot be clicked (interactive of every button is set to false).
* @param {string} [opts.type=default] - The type of the button group. Can be default, checkbox or radio. When the type is
* checkbox, the active state is toggled for each button automatically. When the type is radio, only one button can
* be activated at the same time.
* @param {string} [opts.orientation=horizontal] - The orientation of the button group. Can be horizontal or vertical.
* @param {string} [opts.align=center] - Button: The horizontal position of the label and the icon. Possible values are
* left, center and right. Only affects the style when the minWidth is bigger than the width of the icon and label.
* @param {string} [opts.verticalAlign=middle] - Button: The vertical position of the label and the icon. Possible values are
* top, middle and bottom. Only affects the style when the minHeight is bigger than the height of the icon and label.
* @param {boolean} [opts.visible=true] - Is the button group initially visible (property visible)?
*/
constructor(opts = {}) {
super()
const theme = Theme.fromString(opts.theme)
this.theme = theme
this.opts = Object.assign(
{},
{
id: PIXI.utils.uid(),
x: 0,
y: 0,
buttons: [],
minWidth: 44,
minHeight: 44,
maxWidth: null,
maxHeight: null,
stackPadding: 10,
app: window.app,
padding: theme.padding,
margin: theme.margin,
iconPosition: 'left', // left, right
iconColor: theme.iconColor,
iconColorActive: theme.iconColorActive,
fill: theme.fill,
fillAlpha: theme.fillAlpha,
fillActive: theme.fillActive,
fillActiveAlpha: theme.fillActiveAlpha,
stroke: theme.stroke,
strokeWidth: theme.strokeWidth,
strokeAlpha: theme.strokeAlpha,
strokeActive: theme.strokeActive,
strokeActiveWidth: theme.strokeActiveWidth,
strokeActiveAlpha: theme.strokeActiveAlpha,
textStyle: theme.textStyle,
textStyleActive: theme.textStyleActive,
style: 'default',
radius: theme.radius,
disabled: null,
type: 'default', // default, checkbox, radio
orientation: 'horizontal',
align: 'center', // left, center, right
verticalAlign: 'middle', // top, middle, bottom
visible: true
},
opts
)
this.buttons = []
this._disabled = null
this.__dragging = false
this.visible = this.opts.visible
// setup
//-----------------
this.setup()
// layout
//-----------------
this.layout()
}
/**
* Creates children and instantiates everything.
*
* @private
* @return {ButtonGroup} A reference to the button group for chaining.
*/
setup() {
// inner container
//--------------------
const container = new PIXI.Graphics()
this.addChild(container)
this.container = container
// Buttons
//-----------------
let position = 0
let index = 0
for (let it of this.opts.buttons) {
delete it.x
delete it.y
if (this.opts.orientation === 'horizontal') {
it.x = position
} else {
it.y = position
}
it.theme = it.theme || this.opts.theme
it.minWidth = it.minWidth || this.opts.minWidth
it.minHeight = it.minHeight || this.opts.minHeight
it.padding = it.padding || this.opts.padding
it.iconPosition = it.iconPosition || this.opts.iconPosition
it.iconColor = it.iconColor || this.opts.iconColor
it.iconColorActive = it.iconColorActive || this.opts.iconColorActive
it.fill = it.fill || this.opts.fill
it.fillAlpha = it.fillAlpha || this.opts.fillAlpha
it.fillActive = it.fillActive || this.opts.fillActive
it.fillActiveAlpha = it.fillActiveAlpha || this.opts.fillActiveAlpha
it.stroke = it.stroke || this.opts.stroke
it.strokeWidth = it.strokeWidth != null ? it.strokeWidth : this.opts.strokeWidth
it.strokeAlpha = it.strokeAlpha != null ? it.strokeAlpha : this.opts.strokeAlpha
it.strokeActive = it.strokeActive || this.opts.strokeActive
it.strokeActiveWidth = it.strokeActiveWidth != null ? it.strokeActiveWidth : this.opts.strokeActiveWidth
it.strokeActiveAlpha = it.strokeActiveAlpha != null ? it.strokeActiveAlpha : this.opts.strokeActiveAlpha
it.textStyle = it.textStyle || this.opts.textStyle
it.textStyleActive = it.textStyleActive || this.opts.textStyleActive
it.style = it.style || this.opts.style
it.radius = it.radius != null ? it.radius : this.opts.radius
if (!it.type) {
switch (this.opts.type) {
case 'checkbox':
it.type = this.opts.type
break
default:
it.type = 'default'
break
}
}
//it.type = it.type || this.opts.type || 'default'
it.align = it.align || this.opts.align
it.verticalAlign = it.verticalAlign || this.opts.verticalAlign
it.afterAction = (event, button) => {
if (this.opts.type === 'radio' && button.opts.type === 'default') {
this.buttons.forEach(it => {
if (it.opts.type === 'default') {
it.active = false
}
})
if (button.opts.type === 'default') {
button.active = true
}
}
}
if (it.tooltip) {
if (typeof it.tooltip === 'string') {
it.tooltip = { content: it.tooltip, container: this }
} else {
it.tooltip = Object.assign({}, { container: this }, it.tooltip)
}
}
let button = new Button(it)
this.container.addChild(button)
this.buttons.push(button)
button.__originalPosition = {
x: button.x,
y: button.y
}
position += (this.opts.orientation === 'horizontal' ? button.width : button.height) + this.opts.margin
button.__initIndex = index
index++
}
if (this.opts.orientation === 'vertical') {
const maxWidth = this.getMaxButtonWidth()
this.buttons.forEach(it => {
it.opts.minWidth = maxWidth
it.layout()
})
}
// disabled
//-----------------
if (this.opts.disabled != null) {
this.disabled = this.opts.disabled
}
// interaction
//--------------------
if (this.opts.margin > 0 && (this.opts.maxWidth || this.opts.maxHeight)) {
this.interactive = true
this.on('pointerdown', this.onStart.bind(this))
this.on('pointermove', this.onMove.bind(this))
this.on('pointerup', this.onEnd.bind(this))
this.on('pointercancel', this.onEnd.bind(this))
this.on('pointerout', this.onEnd.bind(this))
this.on('pointerupoutside', this.onEnd.bind(this))
this.on('scroll', this.onScroll.bind(this))
// mousewheel
//--------------------
if (this.opts.app) {
const app = this.opts.app
app.view.addEventListener('mousewheel', event => {
const bounds = this.getBounds()
const x = event.clientX - app.view.getBoundingClientRect().left
const y = event.clientY - app.view.getBoundingClientRect().top
if (bounds.contains(x, y)) {
event.preventDefault()
this.emit('scroll', event)
}
})
}
const background = new PIXI.Graphics()
background.beginFill(0x000000, 0)
background.drawRect(0, 0, this.width, this.height)
background.endFill()
this.addChildAt(background, 0)
this.__initWidth = this.container.width
}
return this
}
/**
* Should be called to refresh the layout of the button group. Can be used after resizing.
*
* @return {ButtonGroup} A reference to the button group for chaining.
*/
layout() {
// set position
//-----------------
this.position.set(this.opts.x, this.opts.y)
// draw
//-----------------
this.draw()
// stack
//-----------------
if (this.opts.margin > 0 && (this.opts.maxWidth || this.opts.maxHeight)) {
this.stack()
}
return this
}
/**
* Draws the canvas.
*
* @private
* @return {ButtonGroup} A reference to the button group for chaining.
*/
draw() {
if (this.opts.margin === 0) {
this.buttons.forEach(it => it.hide())
this.container.clear()
this.container.lineStyle(this.opts.strokeWidth, this.opts.stroke, this.opts.strokeAlpha)
this.container.beginFill(this.opts.fill, this.opts.fillAlpha)
this.container.drawRoundedRect(0, 0, this.width, this.height, this.opts.radius)
// Draw borders
this.container.lineStyle(this.opts.strokeWidth, this.opts.stroke, this.opts.strokeAlpha / 2)
this.buttons.forEach((it, i) => {
if (i > 0) {
this.container.moveTo(it.x, it.y)
if (this.opts.orientation === 'horizontal') {
this.container.lineTo(it.x, it.height)
} else {
this.container.lineTo(it.width, it.y)
}
}
})
this.container.endFill()
}
return this
}
/**
* Gets or sets the disabled state. When disabled, no button of the button group can be clicked.
*
* @member {boolean}
*/
get disabled() {
return this._disabled
}
set disabled(value) {
this._disabled = value
this.buttons.forEach(it => (it.disabled = value))
}
/**
* Gets or sets the maximum width of the button group for stacking. Usefull when you want to resize the available space.
*
* @member {number}
*/
get maxWidth() {
return this.opts.maxWidth
}
set maxWidth(value) {
this.opts.maxWidth = value
this.layout()
}
/**
* Gets or sets the maximum height of the button group for stacking. Usefull when you want to resize the available space.
*
* @member {number}
*/
get maxHeight() {
return this.opts.maxHeight
}
set maxHeight(value) {
this.opts.maxHeight = value
this.layout()
}
/**
* Searches all buttons of the button group and returns the maximum width of one button.
*
* @private
* @return {number} The maximum with of a button of the button group.
*/
getMaxButtonWidth() {
let widths = this.buttons.map(it => it.width)
return Math.max(...widths)
}
/**
* Shows the button group (sets his alpha value to 1).
*
* @return {ButtonGroup} A reference to the button group for chaining.
*/
show() {
this.alpha = 1
return this
}
/**
* Hides the button group (sets his alpha value to 0).
*
* @return {ButtonGroup} A reference to the button group for chaining.
*/
hide() {
this.alpha = 0
return this
}
/**
*
* @private
* @param {*} event
*/
onStart(event) {
this.__dragging = true
this.capture(event)
this.__delta = {
x: this.container.position.x - event.data.global.x,
y: this.container.position.y - event.data.global.y
}
TweenLite.killTweensOf(this.container.position, { x: true, y: true })
if (typeof ThrowPropsPlugin != 'undefined') {
ThrowPropsPlugin.track(this.container.position, 'x,y')
}
}
/**
*
* @private
* @param {*} event
*/
onMove(event) {
if (this.__dragging) {
this.capture(event)
if (this.opts.orientation === 'horizontal') {
this.container.position.x = event.data.global.x + this.__delta.x
} else {
this.container.position.y = event.data.global.y + this.__delta.y
}
this.stack()
}
}
/**
*
* @private
* @param {*} event
*/
onEnd(event) {
if (this.__dragging) {
this.__dragging = false
this.capture(event)
const throwProps = { x: { velocity: 'auto' }, y: { velocity: 'auto' } }
if (this.opts.orientation === 'horizontal') {
const distanceToLeft = this.container.x
const distanceToRight = this.opts.maxWidth - this.container.x - this.__initWidth
if (distanceToLeft > 0 && distanceToLeft > distanceToRight) {
throwProps.x.end = 0
} else if (distanceToRight > 0 && distanceToRight > distanceToLeft) {
throwProps.x.end = this.opts.maxWidth - this.__initWidth
}
} else {
const distanceToTop = this.container.y
const distanceToBottom = this.opts.maxHeight - this.container.y - this.container.height
if (distanceToTop > 0 && distanceToTop > distanceToBottom) {
throwProps.y.end = 0
} else if (distanceToBottom > 0 && distanceToBottom > distanceToTop) {
throwProps.y.end = this.opts.maxHeight - this.container.height
}
}
if (typeof ThrowPropsPlugin != 'undefined') {
ThrowPropsPlugin.to(
this.container.position,
{
throwProps,
ease: Strong.easeOut,
onUpdate: () => this.stack(),
onComplete: () => ThrowPropsPlugin.untrack(this.container.position)
},
0.8,
0.4
)
} else {
if (this.opts.orientation === 'horizontal' && throwProps.x.end != null) {
TweenMax.to(this.container.position, 0.3, { x: throwProps.x.end, onUpdate: this.stack.bind(this) })
} else if (this.opts.orientation === 'vertical' && throwProps.y.end != null) {
TweenMax.to(this.container.position, 0.3, { y: throwProps.y.end, onUpdate: this.stack.bind(this) })
}
}
}
}
/**
*
* @private
* @param {*} event
*/
onScroll(event) {
this.capture(event)
if (this.opts.orientation === 'horizontal') {
this.container.position.x -= event.deltaX
if (this.container.position.x > 0) {
this.container.position.x = 0
} else if (this.container.position.x + this.__initWidth < this.opts.maxWidth) {
this.container.position.x = this.opts.maxWidth - this.__initWidth
}
} else {
this.container.position.y -= event.deltaY
if (this.container.position.y > 0) {
this.container.position.y = 0
} else if (this.container.position.y + this.container.height < this.opts.maxHeight) {
this.container.position.y = this.opts.maxHeight - this.container.height
}
}
this.stack()
}
/**
* Captures an event to inform InteractionMapper about processed events.
*
* @param {event|PIXI.InteractionEvent} event - The PIXI event to capture.
*/
capture(event) {
const originalEvent = event.data && event.data.originalEvent ? event.data.originalEvent : event
Events.capturedBy(originalEvent, this)
}
/**
*
*/
stack() {
if (this.opts.maxWidth) {
this._stackHorizontal()
} else if (this.opts.maxHeight) {
this._stackVertical()
}
}
/**
*
*/
_stackHorizontal() {
const sorted = []
let reverseCounter = this.buttons.length - 1
this.buttons.forEach((it, index) => {
const leftCorner = it.__originalPosition.x + this.container.x
const rightCorner = it.__originalPosition.x + it.button.width
const paddingLeft = index * this.opts.stackPadding
const paddingRight = reverseCounter * this.opts.stackPadding
if (leftCorner < paddingLeft) {
// left border
it.x = -this.container.x + paddingLeft
} else if (rightCorner > -this.container.x + this.opts.maxWidth - paddingRight) {
// right border
it.x = -this.container.x + this.opts.maxWidth - it.button.width - paddingRight
} else {
it.x = it.__originalPosition.x
}
reverseCounter--
sorted.push(it)
})
const min = Math.min(...sorted.map(it => it.x))
const max = Math.max(...sorted.map(it => it.x + it.button.width))
const center = (min + max) / 2
// z-index
sorted
.sort((a, b) => {
const centerA = a.x + a.button.width / 2
const centerB = b.x + b.button.width / 2
if (centerA < center && centerB < center) {
if (a.x < b.x) {
return -1
} else if (b.x < a.x) {
return 1
}
} else if (centerA > center && centerB > center) {
if (a.x + a.button.width > b.x + b.button.width) {
return -1
} else if (b.x + b.button.width < a.x + a.button.x) {
return 1
}
}
return 0
})
.forEach(it => it.parent.addChild(it))
}
/**
*
*/
_stackVertical() {
const sorted = []
let reverseCounter = this.buttons.length - 1
this.buttons.forEach((it, index) => {
const topCorner = it.__originalPosition.y + this.container.y
const bottomCorner = it.__originalPosition.y + it.button.height
const paddingTop = index * this.opts.stackPadding
const paddingBottom = reverseCounter * this.opts.stackPadding
if (topCorner < paddingTop) {
// top border
it.y = -this.container.y + paddingTop
} else if (bottomCorner > -this.container.y + this.opts.maxHeight - paddingBottom) {
// bottom border
it.y = -this.container.y + this.opts.maxHeight - it.button.height - paddingBottom
} else {
it.y = it.__originalPosition.y
}
reverseCounter--
sorted.push(it)
})
const min = Math.min(...sorted.map(it => it.y))
const max = Math.max(...sorted.map(it => it.y + it.button.height))
const center = (min + max) / 2
// z-index
sorted
.sort((a, b) => {
const centerA = a.y + a.button.height / 2
const centerB = b.y + b.button.height / 2
if (centerA < center && centerB < center) {
if (a.y < b.y) {
return -1
} else if (b.y < a.y) {
return 1
}
} else if (centerA > center && centerB > center) {
if (a.y + a.button.height > b.y + b.button.height) {
return -1
} else if (b.y + b.button.height < a.y + a.button.y) {
return 1
}
}
return 0
})
.forEach(it => it.parent.addChild(it))
}
}