ActionButton.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <template>
  2. <div :id="`actionButton-${bindingId}`" role="none" class="action-button">
  3. <button :id="`actionButtonInner-${bindingId}`" :title="title" :disabled="!canExec || isDisabled"
  4. :class="combinedClasses" @click="handleClick">
  5. <div v-if="showNavigateOnStartIcons" class="navigate-on-start-container">
  6. <div v-if="navigateOnStart == 'pop'" class="navigate-on-start" title="Opens a popup dialog on start">
  7. <HugeiconsIcon :icon="ComputerTerminal01Icon" />
  8. </div>
  9. <div v-if="navigateOnStart == 'arg'" class="navigate-on-start" title="Opens an argument form on start">
  10. <HugeiconsIcon :icon="TypeCursorIcon" />
  11. </div>
  12. <div v-if="navigateOnStart == 'hist'" class="navigate-on-start" title="Opens action execution history on start">
  13. <HugeiconsIcon :icon="WorkHistoryIcon" />
  14. </div>
  15. <div v-if="navigateOnStart == ''" class="navigate-on-start" title="Run in the background">
  16. <HugeiconsIcon :icon="WorkoutRunIcon" />
  17. </div>
  18. </div>
  19. <span class="icon" v-html="unicodeIcon"></span>
  20. <span class="title" aria-live="polite">{{ displayTitle }}
  21. </span>
  22. <span v-if="rateLimitMessage" class="rate-limit-message">{{ rateLimitMessage }}</span>
  23. </button>
  24. </div>
  25. </template>
  26. <script setup>
  27. import { buttonResults } from './stores/buttonResults'
  28. import { rateLimits } from './stores/rateLimits'
  29. import { useRouter } from 'vue-router'
  30. import { HugeiconsIcon } from '@hugeicons/vue'
  31. import { WorkoutRunIcon, TypeCursorIcon, ComputerTerminal01Icon, WorkHistoryIcon } from '@hugeicons/core-free-icons'
  32. import { ref, watch, onMounted, onUnmounted, inject, computed } from 'vue'
  33. const router = useRouter()
  34. const navigateOnStart = ref('')
  35. const props = defineProps({
  36. actionData: {
  37. type: Object,
  38. required: true
  39. },
  40. cssClass: {
  41. type: String,
  42. required: false,
  43. default: ''
  44. }
  45. })
  46. const bindingId = ref('')
  47. const title = ref('')
  48. const canExec = ref(true)
  49. const popupOnStart = ref('')
  50. // Display properties
  51. const unicodeIcon = ref('&#x1f4a9;')
  52. const displayTitle = ref('')
  53. // State
  54. const isDisabled = ref(false)
  55. const showArgumentForm = ref(false)
  56. // Rate limiting
  57. const rateLimitExpires = ref(0)
  58. const isRateLimited = ref(false)
  59. const rateLimitMessage = ref('')
  60. let rateLimitInterval = null
  61. // Animation classes
  62. const buttonClasses = ref([])
  63. // Show navigate on start icons - defaults to true if not set
  64. const showNavigateOnStartIcons = computed(() => {
  65. return window.initResponse?.showNavigateOnStartIcons ?? true
  66. })
  67. // Combined classes including custom cssClass
  68. const combinedClasses = computed(() => {
  69. const classes = [...buttonClasses.value]
  70. if (props.cssClass) {
  71. classes.push(props.cssClass)
  72. }
  73. return classes
  74. })
  75. // Timestamps
  76. const updateIterationTimestamp = ref(0)
  77. function getUnicodeIcon(icon) {
  78. if (icon === '') {
  79. console.log('icon not found ', icon)
  80. return '&#x1f4a9;'
  81. } else {
  82. return unescape(icon)
  83. }
  84. }
  85. function constructFromJson(json) {
  86. updateIterationTimestamp.value = 0
  87. updateFromJson(json)
  88. bindingId.value = json.bindingId
  89. title.value = json.title
  90. canExec.value = json.canExec
  91. popupOnStart.value = json.popupOnStart
  92. if (popupOnStart.value.includes('execution-dialog')) {
  93. navigateOnStart.value = 'pop'
  94. } else if (popupOnStart.value === 'history') {
  95. navigateOnStart.value = 'hist'
  96. } else if (props.actionData.arguments.length > 0) {
  97. navigateOnStart.value = 'arg'
  98. }
  99. isDisabled.value = !json.canExec
  100. displayTitle.value = title.value
  101. unicodeIcon.value = getUnicodeIcon(json.icon)
  102. // Initialize rate limit from action data (parse datetime string)
  103. if (json.datetimeRateLimitExpires) {
  104. const date = new Date(json.datetimeRateLimitExpires.replace(' ', 'T'))
  105. rateLimitExpires.value = date.getTime() / 1000
  106. } else {
  107. rateLimitExpires.value = 0
  108. }
  109. // Also initialize the store so the watch picks it up
  110. if (bindingId.value) {
  111. rateLimits[bindingId.value] = rateLimitExpires.value
  112. }
  113. updateRateLimitStatus()
  114. }
  115. function updateFromJson(json) {
  116. // Fields that should not be updated
  117. // title - as the callback URL relies on it
  118. unicodeIcon.value = getUnicodeIcon(json.icon)
  119. // Update rate limiting if changed (parse datetime string)
  120. if (json.datetimeRateLimitExpires) {
  121. const date = new Date(json.datetimeRateLimitExpires.replace(' ', 'T'))
  122. rateLimitExpires.value = date.getTime() / 1000
  123. updateRateLimitStatus()
  124. } else if (json.datetimeRateLimitExpires === '') {
  125. // Explicitly clear if empty string
  126. rateLimitExpires.value = 0
  127. updateRateLimitStatus()
  128. }
  129. }
  130. function updateRateLimitStatus() {
  131. if (rateLimitExpires.value === 0) {
  132. isRateLimited.value = false
  133. rateLimitMessage.value = ''
  134. if (rateLimitInterval) {
  135. clearInterval(rateLimitInterval)
  136. rateLimitInterval = null
  137. }
  138. return
  139. }
  140. const now = Math.floor(Date.now() / 1000)
  141. const expires = rateLimitExpires.value
  142. if (now >= expires) {
  143. // Rate limit has expired
  144. isRateLimited.value = false
  145. rateLimitMessage.value = ''
  146. rateLimitExpires.value = 0
  147. if (rateLimitInterval) {
  148. clearInterval(rateLimitInterval)
  149. rateLimitInterval = null
  150. }
  151. } else {
  152. // Still rate limited
  153. isRateLimited.value = true
  154. const secondsRemaining = expires - now
  155. rateLimitMessage.value = `Rate limited, available in ${secondsRemaining} second${secondsRemaining !== 1 ? 's' : ''}`
  156. // Set up interval to update every second
  157. if (!rateLimitInterval) {
  158. rateLimitInterval = setInterval(() => {
  159. updateRateLimitStatus()
  160. }, 1000)
  161. }
  162. }
  163. }
  164. async function handleClick() {
  165. if (props.actionData.arguments && props.actionData.arguments.length > 0) {
  166. router.push(`/actionBinding/${props.actionData.bindingId}/argumentForm`)
  167. } else {
  168. await startAction()
  169. }
  170. }
  171. function getUniqueId() {
  172. if (window.isSecureContext) {
  173. return window.crypto.randomUUID()
  174. } else {
  175. return Date.now().toString()
  176. }
  177. }
  178. async function startAction(actionArgs) {
  179. buttonClasses.value = [] // Removes old animation classes
  180. if (actionArgs === undefined) {
  181. actionArgs = []
  182. }
  183. // UUIDs are create client side, so that we can setup a "execution-button"
  184. // to track the execution before we send the request to the server.
  185. const startActionArgs = {
  186. bindingId: props.actionData.bindingId,
  187. arguments: actionArgs,
  188. uniqueTrackingId: getUniqueId()
  189. }
  190. console.log('Watching buttonResults for', startActionArgs.uniqueTrackingId)
  191. watch(
  192. () => buttonResults[startActionArgs.uniqueTrackingId],
  193. (newResult, oldResult) => {
  194. onLogEntryChanged(newResult)
  195. }
  196. )
  197. try {
  198. await window.client.startAction(startActionArgs)
  199. } catch (err) {
  200. console.error('Failed to start action:', err)
  201. }
  202. }
  203. function onLogEntryChanged(logEntry) {
  204. if (logEntry.executionFinished) {
  205. onExecutionFinished(logEntry)
  206. } else {
  207. onExecutionStarted(logEntry)
  208. }
  209. }
  210. function onExecutionStarted(logEntry) {
  211. if (popupOnStart.value && popupOnStart.value.includes('execution-dialog')) {
  212. router.push(`/logs/${logEntry.executionTrackingId}`)
  213. } else if (popupOnStart.value === 'history') {
  214. router.push(`/action/${bindingId.value}`)
  215. }
  216. isDisabled.value = true
  217. }
  218. function onExecutionFinished(logEntry) {
  219. if (logEntry.timedOut) {
  220. renderExecutionResult('action-timeout', 'Timed out')
  221. } else if (logEntry.blocked) {
  222. renderExecutionResult('action-blocked', 'Blocked!')
  223. } else if (logEntry.exitCode !== 0) {
  224. renderExecutionResult('action-nonzero-exit', 'Exit code ' + logEntry.exitCode)
  225. } else {
  226. const ellapsed = Math.ceil(new Date(logEntry.datetimeFinished) - new Date(logEntry.datetimeStarted)) / 1000
  227. renderExecutionResult('action-success', 'Success!')
  228. }
  229. }
  230. function renderExecutionResult(resultCssClass, temporaryStatusMessage) {
  231. updateDom(resultCssClass, '[' + temporaryStatusMessage + ']')
  232. onExecStatusChanged()
  233. }
  234. function updateDom(resultCssClass, newTitle) {
  235. if (resultCssClass == null) {
  236. buttonClasses.value = []
  237. } else {
  238. buttonClasses.value = [resultCssClass]
  239. }
  240. displayTitle.value = newTitle
  241. }
  242. function onExecStatusChanged() {
  243. isDisabled.value = false
  244. setTimeout(() => {
  245. updateDom(null, title.value)
  246. }, 2000)
  247. }
  248. onMounted(() => {
  249. constructFromJson(props.actionData)
  250. // Watch the central rate limit store for updates to this button's bindingId
  251. // Watch the entire rateLimits object to ensure reactivity with dynamic keys
  252. watch(
  253. rateLimits,
  254. () => {
  255. const id = bindingId.value
  256. if (id && rateLimits[id] !== undefined) {
  257. const newExpires = rateLimits[id]
  258. if (newExpires !== rateLimitExpires.value) {
  259. rateLimitExpires.value = newExpires
  260. updateRateLimitStatus()
  261. }
  262. }
  263. },
  264. { deep: true }
  265. )
  266. })
  267. onUnmounted(() => {
  268. if (rateLimitInterval) {
  269. clearInterval(rateLimitInterval)
  270. rateLimitInterval = null
  271. }
  272. })
  273. watch(
  274. () => props.actionData,
  275. (newData) => {
  276. updateFromJson(newData)
  277. },
  278. { deep: true }
  279. )
  280. </script>
  281. <style>
  282. @layer components {
  283. .action-button {
  284. display: flex;
  285. flex-direction: column;
  286. flex-grow: 1;
  287. }
  288. .action-button button {
  289. display: flex;
  290. flex-direction: column;
  291. flex-grow: 1;
  292. justify-content: center;
  293. padding: 0.5em;
  294. border: 1px solid #ccc;
  295. border-radius: 4px;
  296. background: #fff;
  297. cursor: pointer;
  298. transition: all 0.2s ease;
  299. box-shadow: 0 0 .6em #aaa;
  300. font-size: .85em;
  301. border-radius: .7em;
  302. }
  303. .action-button button:hover:not(:disabled) {
  304. background: #f5f5f5;
  305. border-color: #999;
  306. }
  307. .action-button button:disabled {
  308. opacity: 0.6;
  309. cursor: not-allowed;
  310. }
  311. .action-button button .icon {
  312. font-size: 3em;
  313. flex-grow: 1;
  314. align-content: center;
  315. }
  316. .action-button button .title {
  317. font-weight: 500;
  318. padding: 0.2em;
  319. }
  320. .action-button button .rate-limit-message {
  321. font-size: 0.75em;
  322. color: #856404;
  323. padding: 0.2em;
  324. font-weight: normal;
  325. }
  326. /* Animation classes */
  327. .action-button button.action-timeout {
  328. background: #fff3cd;
  329. border-color: #ffeaa7;
  330. color: #856404;
  331. }
  332. .action-button button.action-blocked {
  333. background: #f8d7da !important;
  334. border-color: #f5c6cb;
  335. color: #721c24;
  336. }
  337. .action-button button.action-nonzero-exit {
  338. background: #f8d7da !important;
  339. border-color: #f5c6cb;
  340. color: #721c24;
  341. }
  342. .action-button button.action-success {
  343. background: #d4edda !important;
  344. border-color: #c3e6cb;
  345. color: #155724;
  346. }
  347. .action-button-footer {
  348. margin-top: 0.5em;
  349. }
  350. .navigate-on-start-container {
  351. position: relative;
  352. margin-left: auto;
  353. height: 0;
  354. right: 0;
  355. top: 0;
  356. }
  357. @media (prefers-color-scheme: dark) {
  358. .action-button button {
  359. background: #111;
  360. border-color: #000;
  361. box-shadow: 0 0 6px #000;
  362. color: #fff;
  363. }
  364. .action-button button:hover:not(:disabled) {
  365. background: #222;
  366. border-color: #000;
  367. box-shadow: 0 0 6px #444;
  368. color: #fff;
  369. }
  370. }
  371. }
  372. </style>