ActionButton.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <template>
  2. <div
  3. :id="`actionButton-${bindingId}`"
  4. role="none"
  5. class="action-button"
  6. @contextmenu.prevent="openActionDetails"
  7. >
  8. <span
  9. v-if="showExecutionIndicator"
  10. class="execution-indicator"
  11. :class="executionIndicatorClass"
  12. :title="executionIndicatorTitle"
  13. aria-hidden="true"
  14. />
  15. <button
  16. :id="`actionButtonInner-${bindingId}`"
  17. :title="title"
  18. :disabled="!canExec || isDisabled"
  19. :class="combinedClasses"
  20. @click="handleClick"
  21. >
  22. <div
  23. v-if="showNavigateOnStartIcons"
  24. class="navigate-on-start-container"
  25. >
  26. <div
  27. v-if="navigateOnStart == 'pop'"
  28. class="navigate-on-start"
  29. title="Opens a popup dialog on start"
  30. >
  31. <HugeiconsIcon :icon="ComputerTerminal01Icon" />
  32. </div>
  33. <div
  34. v-if="navigateOnStart == 'arg'"
  35. class="navigate-on-start"
  36. title="Opens an argument form on start"
  37. >
  38. <HugeiconsIcon :icon="TypeCursorIcon" />
  39. </div>
  40. <div
  41. v-if="navigateOnStart == 'hist'"
  42. class="navigate-on-start"
  43. title="Opens action execution history on start"
  44. >
  45. <HugeiconsIcon :icon="WorkHistoryIcon" />
  46. </div>
  47. <div
  48. v-if="navigateOnStart == ''"
  49. class="navigate-on-start"
  50. title="Run in the background"
  51. >
  52. <HugeiconsIcon :icon="WorkoutRunIcon" />
  53. </div>
  54. </div>
  55. <ActionIconGlyph
  56. class="icon"
  57. :glyph="actionGlyph"
  58. />
  59. <span
  60. class="title"
  61. aria-live="polite"
  62. >{{ displayTitle }}
  63. </span>
  64. <span
  65. v-if="rateLimitMessage"
  66. class="rate-limit-message"
  67. >{{ rateLimitMessage }}</span>
  68. </button>
  69. </div>
  70. </template>
  71. <script setup>
  72. import { buttonResults } from './stores/buttonResults'
  73. import { rateLimits } from './stores/rateLimits'
  74. import {
  75. bindingExecutionState,
  76. pendingBindingFlash,
  77. consumePendingBindingFlash,
  78. setBindingExecutionState
  79. } from './stores/bindingExecutionState'
  80. import { connectionState } from './stores/connectionState'
  81. import { requestReconnectNow, applyExecutionLogEntry } from '../../js/websocket.js'
  82. import { useRouter } from 'vue-router'
  83. import { needsArgumentForm } from './utils/needsArgumentForm.js'
  84. import { shouldSuppressPopupOnStartNavigation } from './utils/popupOnStartNavigation.js'
  85. import { HugeiconsIcon } from '@hugeicons/vue'
  86. import { WorkoutRunIcon, TypeCursorIcon, ComputerTerminal01Icon, WorkHistoryIcon } from '@hugeicons/core-free-icons'
  87. import ActionIconGlyph from './components/ActionIconGlyph.vue'
  88. import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
  89. const router = useRouter()
  90. const navigateOnStart = ref('')
  91. const props = defineProps({
  92. actionData: {
  93. type: Object,
  94. required: true
  95. },
  96. cssClass: {
  97. type: String,
  98. required: false,
  99. default: ''
  100. },
  101. prefilledArguments: {
  102. type: Object,
  103. required: false,
  104. default: () => ({})
  105. }
  106. })
  107. const bindingId = ref('')
  108. const title = ref('')
  109. const canExec = ref(true)
  110. const popupOnStart = ref('')
  111. // Display properties
  112. const displayTitle = ref('')
  113. // State
  114. const isDisabled = ref(false)
  115. // Rate limiting
  116. const rateLimitExpires = ref(0)
  117. const isRateLimited = ref(false)
  118. const rateLimitMessage = ref('')
  119. const rateLimitInterval = ref(null)
  120. const isComponentMounted = ref(true)
  121. // Animation classes
  122. const buttonClasses = ref([])
  123. const flashedTrackingIds = new Set()
  124. // Show navigate on start icons - defaults to true if not set
  125. const showNavigateOnStartIcons = computed(() => {
  126. return window.initResponse?.showNavigateOnStartIcons ?? true
  127. })
  128. const actionGlyph = computed(() => props.actionData?.icon ?? '')
  129. const glyph = ref('')
  130. // Combined classes including custom cssClass
  131. const combinedClasses = computed(() => {
  132. const classes = [...buttonClasses.value]
  133. if (props.cssClass) {
  134. classes.push(props.cssClass)
  135. }
  136. return classes
  137. })
  138. const hasRunningInstance = computed(() => {
  139. const id = bindingId.value
  140. return !!(id && bindingExecutionState[id]?.hasRunning)
  141. })
  142. const hasQueuedInstance = computed(() => {
  143. const id = bindingId.value
  144. return !!(id && bindingExecutionState[id]?.hasQueued)
  145. })
  146. const showExecutionIndicator = computed(() => {
  147. return hasRunningInstance.value || hasQueuedInstance.value
  148. })
  149. const executionIndicatorClass = computed(() => {
  150. if (hasRunningInstance.value) {
  151. return 'execution-indicator-running'
  152. }
  153. if (hasQueuedInstance.value) {
  154. return 'execution-indicator-queued'
  155. }
  156. return ''
  157. })
  158. const executionIndicatorTitle = computed(() => {
  159. if (hasRunningInstance.value) {
  160. return 'Running'
  161. }
  162. if (hasQueuedInstance.value) {
  163. return 'Queued'
  164. }
  165. return ''
  166. })
  167. function consumeAndFlashPendingResult () {
  168. const id = bindingId.value
  169. if (!id) {
  170. return
  171. }
  172. const pending = consumePendingBindingFlash(id)
  173. if (pending) {
  174. onExecutionFinished(pending)
  175. }
  176. }
  177. // Timestamps
  178. const updateIterationTimestamp = ref(0)
  179. function isBindingBusy () {
  180. const id = bindingId.value
  181. if (!id) {
  182. return false
  183. }
  184. const state = bindingExecutionState[id]
  185. return !!(state?.hasRunning || state?.hasQueued)
  186. }
  187. function applyCanExecFromServer (json) {
  188. if (json?.canExec === undefined) {
  189. return
  190. }
  191. canExec.value = json.canExec
  192. if (!isBindingBusy()) {
  193. isDisabled.value = !json.canExec
  194. }
  195. }
  196. async function refreshCanExecFromServer () {
  197. const id = bindingId.value
  198. if (!id || !window.client) {
  199. return
  200. }
  201. try {
  202. const response = await window.client.getActionBinding({ bindingId: id })
  203. if (response?.action) {
  204. applyCanExecFromServer(response.action)
  205. updateFromJson(response.action)
  206. }
  207. } catch (err) {
  208. console.error('Failed to refresh action exec permission:', err)
  209. }
  210. }
  211. function onEntityOrConfigChanged () {
  212. refreshCanExecFromServer()
  213. }
  214. function constructFromJson (json) {
  215. updateIterationTimestamp.value = 0
  216. updateFromJson(json)
  217. bindingId.value = json.bindingId
  218. title.value = json.title
  219. popupOnStart.value = json.popupOnStart
  220. if (popupOnStart.value.includes('execution-dialog')) {
  221. navigateOnStart.value = 'pop'
  222. } else if (popupOnStart.value === 'history') {
  223. navigateOnStart.value = 'hist'
  224. } else if (needsArgumentForm(props.actionData)) {
  225. navigateOnStart.value = 'arg'
  226. }
  227. applyCanExecFromServer(json)
  228. displayTitle.value = title.value
  229. glyph.value = json.icon ?? ''
  230. // Initialize rate limit from action data (parse datetime string)
  231. if (json.datetimeRateLimitExpires) {
  232. const date = new Date(json.datetimeRateLimitExpires.replace(' ', 'T'))
  233. rateLimitExpires.value = date.getTime() / 1000
  234. } else {
  235. rateLimitExpires.value = 0
  236. }
  237. // Also initialize the store so the watch picks it up
  238. if (bindingId.value) {
  239. rateLimits[bindingId.value] = rateLimitExpires.value
  240. setBindingExecutionState(
  241. bindingId.value,
  242. !!json.hasRunningInstance,
  243. !!json.hasQueuedInstance
  244. )
  245. }
  246. updateRateLimitStatus()
  247. }
  248. function updateFromJson (json) {
  249. // Fields that should not be updated
  250. // title - as the callback URL relies on it
  251. applyCanExecFromServer(json)
  252. // Update rate limiting if changed (parse datetime string)
  253. if (json.datetimeRateLimitExpires) {
  254. const date = new Date(json.datetimeRateLimitExpires.replace(' ', 'T'))
  255. rateLimitExpires.value = date.getTime() / 1000
  256. if (bindingId.value) {
  257. rateLimits[bindingId.value] = rateLimitExpires.value
  258. }
  259. updateRateLimitStatus()
  260. } else if (json.datetimeRateLimitExpires === '') {
  261. // Explicitly clear if empty string
  262. rateLimitExpires.value = 0
  263. if (bindingId.value) {
  264. rateLimits[bindingId.value] = 0
  265. }
  266. updateRateLimitStatus()
  267. }
  268. }
  269. function updateRateLimitStatus () {
  270. if (rateLimitExpires.value === 0) {
  271. isRateLimited.value = false
  272. rateLimitMessage.value = ''
  273. if (rateLimitInterval.value) {
  274. clearInterval(rateLimitInterval.value)
  275. rateLimitInterval.value = null
  276. }
  277. return
  278. }
  279. const now = Math.floor(Date.now() / 1000)
  280. const expires = rateLimitExpires.value
  281. if (now >= expires) {
  282. // Rate limit has expired
  283. isRateLimited.value = false
  284. rateLimitMessage.value = ''
  285. rateLimitExpires.value = 0
  286. if (rateLimitInterval.value) {
  287. clearInterval(rateLimitInterval.value)
  288. rateLimitInterval.value = null
  289. }
  290. } else {
  291. // Still rate limited
  292. isRateLimited.value = true
  293. const secondsRemaining = expires - now
  294. rateLimitMessage.value = `Rate limited, available in ${secondsRemaining} second${secondsRemaining !== 1 ? 's' : ''}`
  295. // Set up interval to update every second
  296. if (!rateLimitInterval.value) {
  297. rateLimitInterval.value = setInterval(() => {
  298. updateRateLimitStatus()
  299. }, 1000)
  300. }
  301. }
  302. }
  303. function openActionDetails () {
  304. const id = props.actionData?.bindingId
  305. if (!id) {
  306. return
  307. }
  308. router.push(`/action/${id}`)
  309. }
  310. async function handleClick () {
  311. if (popupOnStart.value === 'history') {
  312. openActionDetails()
  313. return
  314. }
  315. if (needsArgumentForm(props.actionData)) {
  316. const bindingId = props.actionData.bindingId
  317. const prefilled = props.prefilledArguments || {}
  318. if (Object.keys(prefilled).length > 0) {
  319. router.push({
  320. path: `/actionBinding/${bindingId}/argumentForm`,
  321. state: { prefilledArguments: prefilled }
  322. })
  323. } else {
  324. router.push(`/actionBinding/${bindingId}/argumentForm`)
  325. }
  326. } else {
  327. await startAction()
  328. }
  329. }
  330. function getUniqueId () {
  331. if (window.isSecureContext) {
  332. return window.crypto.randomUUID()
  333. } else {
  334. return Date.now().toString()
  335. }
  336. }
  337. async function pollExecutionUntilDone (trackingId) {
  338. const pollIntervalMs = 500
  339. const pollTimeoutMs = 10 * 60 * 1000
  340. const deadline = Date.now() + pollTimeoutMs
  341. while (Date.now() < deadline && isComponentMounted.value) {
  342. try {
  343. const result = await window.client.executionStatus({ executionTrackingId: trackingId })
  344. if (!isComponentMounted.value) {
  345. return
  346. }
  347. if (result.logEntry) {
  348. applyExecutionLogEntry(result.logEntry)
  349. if (result.logEntry.executionFinished) {
  350. return
  351. }
  352. }
  353. } catch (err) {
  354. console.error('Failed to poll execution status:', err)
  355. }
  356. if (!isComponentMounted.value) {
  357. return
  358. }
  359. await new Promise(resolve => setTimeout(resolve, pollIntervalMs))
  360. }
  361. }
  362. let stopButtonResultWatch = null
  363. function stopWatchingButtonResult () {
  364. if (stopButtonResultWatch) {
  365. stopButtonResultWatch()
  366. stopButtonResultWatch = null
  367. }
  368. }
  369. async function startAction (actionArgs) {
  370. buttonClasses.value = [] // Removes old animation classes
  371. if (actionArgs === undefined) {
  372. actionArgs = []
  373. }
  374. // UUIDs are create client side, so that we can setup a "execution-button"
  375. // to track the execution before we send the request to the server.
  376. const startActionArgs = {
  377. bindingId: props.actionData.bindingId,
  378. arguments: actionArgs,
  379. uniqueTrackingId: getUniqueId()
  380. }
  381. console.log('Watching buttonResults for', startActionArgs.uniqueTrackingId)
  382. stopWatchingButtonResult()
  383. stopButtonResultWatch = watch(
  384. () => buttonResults[startActionArgs.uniqueTrackingId],
  385. (newResult, oldResult) => {
  386. onLogEntryChanged(newResult)
  387. }
  388. )
  389. requestReconnectNow()
  390. try {
  391. const response = await window.client.startAction(startActionArgs)
  392. const trackingId = response.executionTrackingId || startActionArgs.uniqueTrackingId
  393. if (popupOnStart.value && popupOnStart.value.includes('execution-dialog')) {
  394. router.push(`/logs/${trackingId}`)
  395. }
  396. if (!connectionState.connected) {
  397. await pollExecutionUntilDone(trackingId)
  398. }
  399. } catch (err) {
  400. stopWatchingButtonResult()
  401. console.error('Failed to start action:', err)
  402. }
  403. }
  404. function onLogEntryChanged (logEntry) {
  405. if (!logEntry) {
  406. return
  407. }
  408. if (logEntry.executionFinished) {
  409. stopWatchingButtonResult()
  410. onExecutionFinished(logEntry)
  411. } else if (logEntry.queued && !logEntry.executionStarted) {
  412. onExecutionQueued(logEntry)
  413. } else {
  414. onExecutionStarted(logEntry)
  415. }
  416. }
  417. function onExecutionQueued (_logEntry) {
  418. isDisabled.value = true
  419. updateDom('action-queued', '[Queued]')
  420. }
  421. function onExecutionStarted (logEntry) {
  422. if (
  423. popupOnStart.value &&
  424. popupOnStart.value.includes('execution-dialog') &&
  425. !shouldSuppressPopupOnStartNavigation(router)
  426. ) {
  427. router.push(`/logs/${logEntry.executionTrackingId}`)
  428. }
  429. isDisabled.value = true
  430. updateDom(null, title.value)
  431. }
  432. function onExecutionFinished (logEntry) {
  433. const trackingId = logEntry.executionTrackingId
  434. if (trackingId) {
  435. if (flashedTrackingIds.has(trackingId)) {
  436. return
  437. }
  438. flashedTrackingIds.add(trackingId)
  439. }
  440. // Local no-arg watches and the binding-scoped pending flash can both
  441. // observe the same finished execution; consume so only one path flashes.
  442. if (bindingId.value) {
  443. consumePendingBindingFlash(bindingId.value)
  444. }
  445. if (logEntry.timedOut) {
  446. renderExecutionResult('action-timeout', 'Timed out')
  447. } else if (logEntry.blocked) {
  448. renderExecutionResult('action-blocked', 'Blocked!')
  449. } else if (logEntry.exitCode !== 0) {
  450. renderExecutionResult('action-nonzero-exit', 'Exit code ' + logEntry.exitCode)
  451. } else {
  452. renderExecutionResult('action-success', 'Success!')
  453. }
  454. }
  455. function renderExecutionResult (resultCssClass, temporaryStatusMessage) {
  456. updateDom(resultCssClass, '[' + temporaryStatusMessage + ']')
  457. onExecStatusChanged()
  458. }
  459. function updateDom (resultCssClass, newTitle) {
  460. if (resultCssClass == null) {
  461. buttonClasses.value = []
  462. } else {
  463. buttonClasses.value = [resultCssClass]
  464. }
  465. displayTitle.value = newTitle
  466. }
  467. function onExecStatusChanged () {
  468. isDisabled.value = false
  469. setTimeout(() => {
  470. updateDom(null, title.value)
  471. }, 2000)
  472. }
  473. onMounted(() => {
  474. constructFromJson(props.actionData)
  475. window.addEventListener('EventEntityChanged', onEntityOrConfigChanged)
  476. window.addEventListener('EventConfigChanged', onEntityOrConfigChanged)
  477. // Watch the central rate limit store for updates to this button's bindingId
  478. // Watch the entire rateLimits object to ensure reactivity with dynamic keys
  479. watch(
  480. rateLimits,
  481. () => {
  482. const id = bindingId.value
  483. if (id && rateLimits[id] !== undefined) {
  484. const newExpires = rateLimits[id]
  485. if (newExpires !== rateLimitExpires.value) {
  486. rateLimitExpires.value = newExpires
  487. updateRateLimitStatus()
  488. }
  489. }
  490. },
  491. { deep: true }
  492. )
  493. // Binding-scoped flash survives argument-form navigation/remount (#920).
  494. watch(
  495. () => pendingBindingFlash[bindingId.value],
  496. (pending) => {
  497. if (pending) {
  498. consumeAndFlashPendingResult()
  499. }
  500. },
  501. { immediate: true }
  502. )
  503. })
  504. onUnmounted(() => {
  505. isComponentMounted.value = false
  506. window.removeEventListener('EventEntityChanged', onEntityOrConfigChanged)
  507. window.removeEventListener('EventConfigChanged', onEntityOrConfigChanged)
  508. if (rateLimitInterval.value) {
  509. clearInterval(rateLimitInterval.value)
  510. rateLimitInterval.value = null
  511. }
  512. })
  513. watch(
  514. () => props.actionData,
  515. (newData) => {
  516. updateFromJson(newData)
  517. if (newData?.icon !== undefined) {
  518. glyph.value = newData.icon ?? ''
  519. }
  520. },
  521. { deep: true }
  522. )
  523. defineExpose({
  524. glyph
  525. })
  526. </script>
  527. <style>
  528. @layer components {
  529. .action-button {
  530. display: flex;
  531. flex-direction: column;
  532. flex-grow: 1;
  533. position: relative;
  534. }
  535. .execution-indicator {
  536. position: absolute;
  537. top: 0.45em;
  538. left: 0.45em;
  539. width: 0.65em;
  540. height: 0.65em;
  541. border-radius: 50%;
  542. z-index: 1;
  543. pointer-events: none;
  544. }
  545. .execution-indicator-running {
  546. background: #28a745;
  547. }
  548. .execution-indicator-queued {
  549. background: #0d6efd;
  550. }
  551. .action-button button {
  552. display: flex;
  553. flex-direction: column;
  554. flex-grow: 1;
  555. justify-content: center;
  556. padding: 0.5em;
  557. border: 1px solid #ccc;
  558. border-radius: 4px;
  559. background: #fff;
  560. cursor: pointer;
  561. transition: all 0.2s ease;
  562. box-shadow: 0 0 .6em #aaa;
  563. font-size: .85em;
  564. border-radius: .7em;
  565. }
  566. .action-button button:hover:not(:disabled) {
  567. background: #f5f5f5;
  568. border-color: #999;
  569. }
  570. .action-button button:disabled {
  571. opacity: 0.6;
  572. cursor: not-allowed;
  573. }
  574. .action-button button .icon {
  575. font-size: 3em;
  576. flex-grow: 1;
  577. align-content: center;
  578. }
  579. .action-button button .title {
  580. font-weight: 500;
  581. padding: 0.2em;
  582. }
  583. .action-button button .rate-limit-message {
  584. font-size: 0.75em;
  585. color: #856404;
  586. padding: 0.2em;
  587. font-weight: normal;
  588. }
  589. /* Animation classes */
  590. .action-button button.action-timeout {
  591. background: #fff3cd;
  592. border-color: #ffeaa7;
  593. color: #856404;
  594. }
  595. .action-button button.action-blocked {
  596. background: #f8d7da !important;
  597. border-color: #f5c6cb;
  598. color: #721c24;
  599. }
  600. .action-button button.action-queued {
  601. background: #e7f1ff !important;
  602. border-color: #9ec5fe;
  603. color: #084298;
  604. }
  605. .action-button button.action-nonzero-exit {
  606. background: #f8d7da !important;
  607. border-color: #f5c6cb;
  608. color: #721c24;
  609. }
  610. .action-button button.action-success {
  611. background: #d4edda !important;
  612. border-color: #c3e6cb;
  613. color: #155724;
  614. }
  615. .action-button-footer {
  616. margin-top: 0.5em;
  617. }
  618. .navigate-on-start-container {
  619. position: relative;
  620. margin-left: auto;
  621. height: 0;
  622. right: 0;
  623. top: 0;
  624. }
  625. @media (prefers-color-scheme: dark) {
  626. .action-button button {
  627. background: #111;
  628. border-color: #000;
  629. box-shadow: 0 0 6px #000;
  630. color: #fff;
  631. }
  632. .action-button button:hover:not(:disabled) {
  633. background: #222;
  634. border-color: #000;
  635. box-shadow: 0 0 6px #444;
  636. color: #fff;
  637. }
  638. }
  639. }
  640. </style>