ActionButton.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. class ActionButton extends window.HTMLButtonElement {
  2. constructFromJson (json) {
  3. this.title = json.title
  4. this.states = []
  5. this.stateLabels = []
  6. this.currentState = 0
  7. this.isWaiting = false
  8. this.actionCallUrl = window.restBaseUrl + 'StartAction?actionName=' + this.title
  9. if (json.icon == "") {
  10. this.unicodeIcon = '&#x1f4a9'
  11. } else {
  12. this.unicodeIcon = unescape(json.icon)
  13. }
  14. this.onclick = () => { this.startAction() }
  15. this.constructTemplate()
  16. this.updateHtml()
  17. }
  18. startAction () {
  19. this.disabled = true
  20. this.isWaiting = true
  21. this.updateHtml()
  22. this.classList = [] // Removes old animation classes
  23. window.fetch(this.actionCallUrl).then(res => {
  24. if (!res.ok) {
  25. return res.json()
  26. }
  27. }).then(json => {
  28. if (json.timedOut) {
  29. this.onActionResult('actionTimedOut')
  30. } else if (json.exitCode != 0) {
  31. this.onActionResult('actionNonZeroExit')
  32. } else {
  33. this.onActionResult('actionSuccess')
  34. }
  35. }).catch(err => {
  36. this.onActionError(err)
  37. })
  38. }
  39. onActionResult (cssClass) {
  40. this.disabled = false
  41. this.isWaiting = false
  42. this.updateHtml()
  43. this.classList.add(cssClass)
  44. }
  45. onActionError (err) {
  46. console.log('callback error', err)
  47. this.disabled = false
  48. this.isWaiting = false
  49. this.updateHtml()
  50. this.classList.add('actionFailed')
  51. }
  52. constructTemplate () {
  53. const tpl = document.getElementById('tplActionButton')
  54. const content = tpl.content.cloneNode(true)
  55. /*
  56. * FIXME: Should probably be using a shadowdom here, but seem to
  57. * get an error when combined with custom elements.
  58. */
  59. this.appendChild(content)
  60. this.domTitle = this.querySelector('.title')
  61. this.domIcon = this.querySelector('.icon')
  62. }
  63. updateHtml () {
  64. if (this.isWaiting) {
  65. this.domTitle.innerText = 'Waiting...'
  66. } else {
  67. this.domTitle.innerText = this.title
  68. }
  69. this.domIcon.innerHTML = this.unicodeIcon
  70. }
  71. getCurrentStateLabel (useLabels = true) {
  72. if (useLabels) {
  73. return this.stateLabels[this.currentState]
  74. } else {
  75. return this.states[this.currentState]
  76. }
  77. }
  78. getNextStateLabel () {
  79. return this.stateLabels[this.currentState + 1]
  80. }
  81. }
  82. window.customElements.define('action-button', ActionButton, { extends: 'button' })