ToolBar.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * ToolBar.js
  3. *
  4. * @author realor
  5. */
  6. import { I18N } from '../i18n/I18N.js'
  7. class ToolBar {
  8. constructor(application, element) {
  9. this.application = application
  10. this.buttons = []
  11. this.buttonsElem = document.createElement('div')
  12. this.buttonsElem.className = 'tool_buttons'
  13. element.appendChild(this.buttonsElem)
  14. const toolListener = event => {
  15. const type = event.type
  16. const tool = event.tool
  17. if (type === 'activated') {
  18. for (let button of this.buttons) {
  19. if (button.tool === tool) {
  20. button.buttonElem.classList.add('selected')
  21. button.buttonElem.scrollIntoView({ block: 'center', inline: 'nearest' })
  22. }
  23. }
  24. } else if (type === 'deactivated') {
  25. for (let button of this.buttons) {
  26. if (button.tool === tool) {
  27. button.buttonElem.classList.remove('selected')
  28. }
  29. }
  30. }
  31. }
  32. application.addEventListener('tool', toolListener)
  33. }
  34. addToolButton(tool, index) {
  35. let button = new ToolButton(this, tool)
  36. let buttonElem = button.buttonElem
  37. const buttonsElem = this.buttonsElem
  38. const children = buttonsElem.children
  39. if (typeof index === 'number' && index < children.length) {
  40. if (index < 0) index = 0
  41. let oldElem = children[index]
  42. buttonsElem.insertBefore(buttonElem, oldElem)
  43. this.buttons.splice(index, 0, button)
  44. } else {
  45. buttonsElem.appendChild(buttonElem)
  46. this.buttons.push(button)
  47. }
  48. }
  49. }
  50. class ToolButton {
  51. constructor(toolBar, tool) {
  52. this.toolBar = toolBar
  53. this.tool = tool
  54. this.buttonElem = document.createElement('button')
  55. let buttonElem = this.buttonElem
  56. I18N.set(buttonElem, 'title', tool.label)
  57. I18N.set(buttonElem, 'alt', tool.label)
  58. buttonElem.className = 'tool_button ' + tool.className
  59. buttonElem.addEventListener(
  60. 'click',
  61. () => {
  62. buttonElem.scrollIntoView({ block: 'center', inline: 'nearest' })
  63. this.toolBar.application.useTool(tool)
  64. },
  65. false
  66. )
  67. }
  68. }
  69. export { ToolBar }