ArgumentForm.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <template>
  2. <section id="argument-popup">
  3. <div class="section-header">
  4. <h2>
  5. <span class="section-title-with-icon">
  6. Start action:
  7. <router-link
  8. :to="`/action/${bindingId}`"
  9. class="action-details-title-link"
  10. :title="'Action ID: ' + bindingId"
  11. >
  12. <ActionIconGlyph
  13. v-if="icon"
  14. class="action-title-icon"
  15. :glyph="icon"
  16. />
  17. {{ title }}
  18. </router-link>
  19. </span>
  20. </h2>
  21. </div>
  22. <div class="section-content padding">
  23. <form @submit="handleSubmit">
  24. <template v-if="actionArguments.length > 0">
  25. <template
  26. v-for="arg in actionArguments"
  27. :key="arg.name"
  28. >
  29. <label
  30. v-if="arg.type !== 'checklist'"
  31. :for="argumentFieldId(arg.name)"
  32. >
  33. {{ formatLabel(arg.title) }}
  34. </label>
  35. <div
  36. v-else
  37. class="argument-label"
  38. >
  39. {{ formatLabel(arg.title) }}
  40. </div>
  41. <datalist
  42. v-if="(arg.suggestions && Object.keys(arg.suggestions).length > 0) || getBrowserSuggestions(arg).length > 0"
  43. :id="argumentFieldChoicesId(arg.name)"
  44. >
  45. <option
  46. v-for="(suggestion, key) in arg.suggestions"
  47. :key="key"
  48. :value="key"
  49. >
  50. {{ suggestion }}
  51. </option>
  52. <option
  53. v-for="(suggestion, index) in getBrowserSuggestions(arg)"
  54. :key="`browser-${index}`"
  55. :value="suggestion"
  56. >
  57. {{ suggestion }}
  58. </option>
  59. </datalist>
  60. <ChoiceCombobox
  61. v-if="getInputComponent(arg) === 'select'"
  62. :id="argumentFieldId(arg.name)"
  63. :name="arg.name"
  64. :choices="arg.choices"
  65. :model-value="getArgumentValue(arg)"
  66. :required="arg.required"
  67. @update:model-value="handleChoiceUpdate(arg, $event)"
  68. />
  69. <ChoiceChecklist
  70. v-else-if="arg.type === 'checklist'"
  71. :name="arg.name"
  72. :label="arg.title"
  73. :choices="arg.choices"
  74. :model-value="getArgumentValue(arg)"
  75. :required="arg.required"
  76. @update:model-value="handleChoiceUpdate(arg, $event)"
  77. />
  78. <component
  79. :is="getInputComponent(arg)"
  80. v-else
  81. :id="argumentFieldId(arg.name)"
  82. :name="arg.name"
  83. :value="(arg.type === 'checkbox' || arg.type === 'confirmation') ? undefined : getArgumentValue(arg)"
  84. :checked="(arg.type === 'checkbox' || arg.type === 'confirmation') ? getArgumentValue(arg) : undefined"
  85. :list="(arg.suggestions || getBrowserSuggestions(arg).length > 0) ? argumentFieldChoicesId(arg.name) : undefined"
  86. :type="getInputComponent(arg) !== 'select' ? argumentInputType(arg) : undefined"
  87. :rows="arg.type === 'raw_string_multiline' ? 5 : undefined"
  88. :step="arg.type === 'datetime' ? 1 : undefined"
  89. :pattern="getPattern(arg)"
  90. @input="handleInput(arg, $event)"
  91. @change="handleChange(arg, $event)"
  92. />
  93. <!-- eslint-disable vue/no-v-html -- intentional: argument description is documented as raw HTML -->
  94. <span
  95. class="argument-description"
  96. v-html="arg.description"
  97. />
  98. <!-- eslint-enable vue/no-v-html -->
  99. </template>
  100. </template>
  101. <template v-if="justificationRequired">
  102. <label for="justification">Justification:</label>
  103. <input
  104. id="justification"
  105. name="justification"
  106. type="text"
  107. :value="justificationValue"
  108. required
  109. @input="handleJustificationInput"
  110. >
  111. </template>
  112. <div v-if="actionArguments.length === 0 && !justificationRequired">
  113. <p>No arguments required</p>
  114. </div>
  115. <div class="buttons">
  116. <button
  117. name="start"
  118. type="submit"
  119. :disabled="!formReady || (hasConfirmation && !confirmationChecked)"
  120. >
  121. Start
  122. </button>
  123. <button
  124. name="cancel"
  125. type="button"
  126. @click="handleCancel"
  127. >
  128. Cancel
  129. </button>
  130. </div>
  131. </form>
  132. </div>
  133. </section>
  134. </template>
  135. <script setup>
  136. import { ref, computed, onMounted, onBeforeUnmount, onUnmounted, nextTick } from 'vue'
  137. import { useRouter } from 'vue-router'
  138. import { requestReconnectNow } from '../../../js/websocket.js'
  139. import ChoiceCombobox from '../components/ChoiceCombobox.vue'
  140. import ChoiceChecklist from '../components/ChoiceChecklist.vue'
  141. import ActionIconGlyph from '../components/ActionIconGlyph.vue'
  142. import {
  143. actionJustificationTemplate,
  144. actionRequiresJustification,
  145. applyArgumentTemplate
  146. } from '../utils/justificationTemplate.js'
  147. import {
  148. argumentFieldChoicesId,
  149. argumentFieldId,
  150. argumentFieldValidationElementId
  151. } from '../utils/argumentFieldIds.js'
  152. import { argumentInputType } from '../utils/argumentInputType.js'
  153. import { getInitialArgumentValue, readPrefilledArgumentsFromNavigation } from '../utils/prefilledArguments.js'
  154. const router = useRouter()
  155. // Reactive data
  156. const dialog = ref(null)
  157. const title = ref('')
  158. const icon = ref('')
  159. // const arguments = ref([])
  160. const argValues = ref({})
  161. const confirmationChecked = ref(false)
  162. const hasConfirmation = ref(false)
  163. const formErrors = ref({})
  164. const actionArguments = ref([])
  165. const popupOnStart = ref('')
  166. const formReady = ref(false)
  167. const justificationConfig = ref('')
  168. const justificationValue = ref('')
  169. const justificationEditedManually = ref(false)
  170. const justificationRequired = computed(() => actionRequiresJustification(justificationConfig.value))
  171. const justificationTemplate = computed(() => actionJustificationTemplate(justificationConfig.value))
  172. let isComponentMounted = true
  173. // Computed properties
  174. const props = defineProps({
  175. bindingId: {
  176. type: String,
  177. required: true
  178. }
  179. })
  180. // Methods
  181. async function setup () {
  182. formReady.value = false
  183. document.body.removeAttribute('loaded-argument-form')
  184. try {
  185. const ret = await window.client.getActionBinding({
  186. bindingId: props.bindingId
  187. })
  188. const action = ret.action
  189. title.value = action.title
  190. icon.value = action.icon
  191. popupOnStart.value = action.popupOnStart || ''
  192. actionArguments.value = action.arguments || []
  193. justificationConfig.value = action.justification || ''
  194. justificationValue.value = ''
  195. justificationEditedManually.value = false
  196. argValues.value = {}
  197. formErrors.value = {}
  198. confirmationChecked.value = false
  199. hasConfirmation.value = false
  200. const prefilledArguments = readPrefilledArgumentsFromNavigation()
  201. // Initialize values from navigation state, query params, or defaults
  202. actionArguments.value.forEach(arg => {
  203. if (arg.type === 'confirmation') {
  204. hasConfirmation.value = true
  205. const paramValue = getInitialArgumentValue(arg.name, prefilledArguments)
  206. let checkedValue = false
  207. if (paramValue !== null) {
  208. checkedValue = paramValue === '1' || paramValue === 'true' || paramValue === true
  209. } else if (arg.defaultValue !== undefined && arg.defaultValue !== '') {
  210. checkedValue = arg.defaultValue === '1' || arg.defaultValue === 'true' || arg.defaultValue === true
  211. }
  212. argValues.value[arg.name] = checkedValue
  213. confirmationChecked.value = checkedValue
  214. } else {
  215. const paramValue = getInitialArgumentValue(arg.name, prefilledArguments)
  216. if (arg.type === 'checkbox') {
  217. // For checkboxes, handle boolean default values properly
  218. if (paramValue !== null) {
  219. argValues.value[arg.name] = paramValue === '1' || paramValue === 'true' || paramValue === true
  220. } else if (arg.defaultValue !== undefined && arg.defaultValue !== '') {
  221. argValues.value[arg.name] = arg.defaultValue === '1' || arg.defaultValue === 'true' || arg.defaultValue === true
  222. } else {
  223. argValues.value[arg.name] = false
  224. }
  225. } else {
  226. argValues.value[arg.name] = paramValue !== null ? paramValue : arg.defaultValue || ''
  227. }
  228. }
  229. })
  230. // Run initial validation on all fields after DOM is updated
  231. await nextTick()
  232. for (const arg of actionArguments.value) {
  233. if (arg.type && !arg.type.startsWith('regex:') && arg.type !== 'select' && arg.type !== '' && arg.type !== 'confirmation' && arg.type !== 'checkbox') {
  234. await validateArgument(arg, argValues.value[arg.name] || '')
  235. }
  236. }
  237. if (isComponentMounted) {
  238. formReady.value = true
  239. document.body.setAttribute('loaded-argument-form', props.bindingId)
  240. }
  241. updateJustificationFromTemplate()
  242. } catch (err) {
  243. console.error('Failed to load argument form:', err)
  244. }
  245. }
  246. function formatLabel (title) {
  247. const lastChar = title.charAt(title.length - 1)
  248. if (lastChar === '?' || lastChar === '.' || lastChar === ':') {
  249. return title
  250. }
  251. return title + ':'
  252. }
  253. function getInputComponent (arg) {
  254. if (arg.type === 'html') {
  255. return 'div'
  256. } else if (arg.type === 'raw_string_multiline') {
  257. return 'textarea'
  258. } else if (arg.choices && arg.choices.length > 0 && (arg.type === 'select' || arg.type === '')) {
  259. return 'select'
  260. } else {
  261. return 'input'
  262. }
  263. }
  264. function getPattern (arg) {
  265. if (arg.type && arg.type.startsWith('regex:')) {
  266. return arg.type.replace('regex:', '')
  267. }
  268. return undefined
  269. }
  270. function getArgumentValue (arg) {
  271. if (arg.type === 'checkbox' || arg.type === 'confirmation') {
  272. return argValues.value[arg.name] === '1' || argValues.value[arg.name] === true || argValues.value[arg.name] === 'true'
  273. }
  274. return argValues.value[arg.name] || ''
  275. }
  276. function handleJustificationInput (event) {
  277. justificationValue.value = event.target.value
  278. justificationEditedManually.value = true
  279. event.target.setCustomValidity('')
  280. }
  281. function handleInput (arg, event) {
  282. const value = event.target.type === 'checkbox' ? event.target.checked : event.target.value
  283. argValues.value[arg.name] = value
  284. event.target.setCustomValidity('')
  285. updateUrlWithArg(arg.name, value)
  286. updateJustificationFromTemplate()
  287. }
  288. function handleChange (arg, event) {
  289. if (arg.type === 'confirmation') {
  290. confirmationChecked.value = event.target.checked
  291. return
  292. }
  293. // Validate the input
  294. validateArgument(arg, event.target.value)
  295. }
  296. function getValidationElement (arg) {
  297. return document.getElementById(argumentFieldValidationElementId(arg))
  298. }
  299. function handleChoiceUpdate (arg, value) {
  300. argValues.value[arg.name] = value
  301. updateUrlWithArg(arg.name, value)
  302. validateArgument(arg, value)
  303. updateJustificationFromTemplate()
  304. }
  305. async function validateArgument (arg, value) {
  306. if (!arg.type || arg.type.startsWith('regex:')) {
  307. return
  308. }
  309. // Skip validation for datetime - backend will handle mangling values without seconds
  310. if (arg.type === 'datetime') {
  311. const inputElement = getValidationElement(arg)
  312. if (inputElement) {
  313. inputElement.setCustomValidity('')
  314. }
  315. delete formErrors.value[arg.name]
  316. return
  317. }
  318. // Skip validation for checkbox and confirmation - they're always valid
  319. if (arg.type === 'checkbox' || arg.type === 'confirmation') {
  320. const inputElement = getValidationElement(arg)
  321. if (inputElement) {
  322. inputElement.setCustomValidity('')
  323. }
  324. delete formErrors.value[arg.name]
  325. return
  326. }
  327. try {
  328. const validateArgumentTypeArgs = {
  329. value,
  330. type: arg.type,
  331. bindingId: props.bindingId,
  332. argumentName: arg.name
  333. }
  334. const validation = await window.client.validateArgumentType(validateArgumentTypeArgs)
  335. const inputElement = getValidationElement(arg)
  336. if (validation.valid) {
  337. delete formErrors.value[arg.name]
  338. // Clear custom validity message
  339. if (inputElement) {
  340. inputElement.setCustomValidity('')
  341. }
  342. } else {
  343. formErrors.value[arg.name] = validation.description
  344. // Set custom validity message
  345. if (inputElement) {
  346. inputElement.setCustomValidity(validation.description)
  347. }
  348. }
  349. } catch (err) {
  350. console.warn('Validation failed:', err)
  351. const inputElement = getValidationElement(arg)
  352. if (inputElement) {
  353. inputElement.setCustomValidity('')
  354. }
  355. }
  356. }
  357. function updateUrlWithArg (name, value) {
  358. if (name && value !== undefined) {
  359. const url = new URL(window.location.href)
  360. // Don't add passwords to URL
  361. const arg = actionArguments.value.find(a => a.name === name)
  362. if (arg && arg.type === 'password') {
  363. return
  364. }
  365. url.searchParams.set(name, value)
  366. window.history.replaceState({}, '', url.toString())
  367. }
  368. }
  369. function shouldSendArgument (arg) {
  370. if (!arg.name) {
  371. return false
  372. }
  373. return arg.type !== 'html'
  374. }
  375. function formatArgumentValueForApi (arg, rawValue) {
  376. if (arg.type === 'checkbox' || arg.type === 'confirmation') {
  377. return rawValue === '1' || rawValue === true || rawValue === 'true' ? '1' : '0'
  378. }
  379. if (rawValue === true) {
  380. return '1'
  381. }
  382. if (rawValue === false) {
  383. return '0'
  384. }
  385. return rawValue ?? ''
  386. }
  387. function getSelectedArgumentEntries () {
  388. const entries = []
  389. for (const arg of actionArguments.value) {
  390. if (!shouldSendArgument(arg)) {
  391. continue
  392. }
  393. entries.push({
  394. name: arg.name,
  395. value: formatArgumentValueForApi(arg, argValues.value[arg.name])
  396. })
  397. }
  398. return entries
  399. }
  400. function getArgumentValues () {
  401. return getSelectedArgumentEntries().map(({ name, value }) => ({ name, value }))
  402. }
  403. function getArgumentMapForTemplate () {
  404. return Object.fromEntries(
  405. getSelectedArgumentEntries().map(({ name, value }) => [name, value])
  406. )
  407. }
  408. function updateJustificationFromTemplate () {
  409. if (!justificationTemplate.value || justificationEditedManually.value) {
  410. return
  411. }
  412. justificationValue.value = applyArgumentTemplate(justificationTemplate.value, getArgumentMapForTemplate())
  413. }
  414. function getUniqueId () {
  415. if (window.isSecureContext) {
  416. return window.crypto.randomUUID()
  417. } else {
  418. return Date.now().toString()
  419. }
  420. }
  421. function getBrowserSuggestions (arg) {
  422. if (!arg.suggestionsBrowserKey) {
  423. return []
  424. }
  425. try {
  426. const stored = localStorage.getItem(`olivetin-suggestions-${arg.suggestionsBrowserKey}`)
  427. if (stored) {
  428. const suggestions = JSON.parse(stored)
  429. return Array.isArray(suggestions) ? suggestions : []
  430. }
  431. } catch (err) {
  432. console.warn('Failed to load browser suggestions:', err)
  433. }
  434. return []
  435. }
  436. function saveBrowserSuggestions () {
  437. for (const arg of actionArguments.value) {
  438. if (arg.suggestionsBrowserKey) {
  439. const value = argValues.value[arg.name]
  440. // Only save non-empty values for non-checkbox/confirmation/password types
  441. if (value && value !== '' && arg.type !== 'checkbox' && arg.type !== 'confirmation' && arg.type !== 'checklist' && arg.type !== 'password') {
  442. try {
  443. const key = `olivetin-suggestions-${arg.suggestionsBrowserKey}`
  444. const stored = localStorage.getItem(key)
  445. let suggestions = []
  446. if (stored) {
  447. suggestions = JSON.parse(stored)
  448. if (!Array.isArray(suggestions)) {
  449. suggestions = []
  450. }
  451. }
  452. // Add value if not already present
  453. if (!suggestions.includes(value)) {
  454. suggestions.unshift(value) // Add to beginning
  455. // Keep only the most recent 50 suggestions
  456. if (suggestions.length > 50) {
  457. suggestions = suggestions.slice(0, 50)
  458. }
  459. localStorage.setItem(key, JSON.stringify(suggestions))
  460. }
  461. } catch (err) {
  462. console.warn('Failed to save browser suggestions:', err)
  463. }
  464. }
  465. }
  466. }
  467. }
  468. async function startAction (actionArgs) {
  469. const startActionArgs = {
  470. bindingId: props.bindingId,
  471. arguments: actionArgs,
  472. uniqueTrackingId: getUniqueId()
  473. }
  474. if (justificationRequired.value) {
  475. startActionArgs.justification = justificationValue.value
  476. }
  477. try {
  478. requestReconnectNow()
  479. const response = await window.client.startAction(startActionArgs)
  480. console.log('Action started successfully with tracking ID:', response.executionTrackingId)
  481. return response
  482. } catch (err) {
  483. console.error('Failed to start action:', err)
  484. throw err
  485. }
  486. }
  487. async function handleSubmit (event) {
  488. event.preventDefault()
  489. if (!formReady.value) {
  490. return
  491. }
  492. if (popupOnStart.value === 'history') {
  493. router.push(`/action/${props.bindingId}`)
  494. return
  495. }
  496. // Set custom validity for required fields
  497. if (justificationRequired.value && (!justificationValue.value || justificationValue.value.trim() === '')) {
  498. const inputElement = document.getElementById('justification')
  499. if (inputElement) {
  500. inputElement.setCustomValidity('This field is required')
  501. }
  502. }
  503. for (const arg of actionArguments.value) {
  504. const value = argValues.value[arg.name]
  505. const inputElement = getValidationElement(arg)
  506. if (arg.required && (!value || value === '')) {
  507. formErrors.value[arg.name] = 'This field is required'
  508. // Set custom validity for required field validation
  509. if (inputElement) {
  510. inputElement.setCustomValidity('This field is required')
  511. }
  512. }
  513. }
  514. const form = event.target
  515. if (!form.checkValidity()) {
  516. console.log('argument form has elements that failed validation')
  517. return
  518. }
  519. if (Object.keys(formErrors.value).length > 0) {
  520. console.log('argument form has validation errors')
  521. return
  522. }
  523. const argvs = getArgumentValues()
  524. console.log('argument form has elements that passed validation')
  525. // Save values to localStorage for arguments with suggestionsBrowserKey
  526. saveBrowserSuggestions()
  527. try {
  528. const response = await startAction(argvs)
  529. if (popupOnStart.value && popupOnStart.value.includes('execution-dialog')) {
  530. router.push(`/logs/${response.executionTrackingId}`)
  531. } else {
  532. router.back()
  533. }
  534. } catch (err) {
  535. console.error('Failed to start action:', err)
  536. }
  537. }
  538. function handleCancel () {
  539. router.back()
  540. clearBookmark()
  541. }
  542. function clearBookmark () {
  543. window.history.replaceState({
  544. path: window.location.pathname
  545. }, '', window.location.pathname)
  546. }
  547. function show () {
  548. if (dialog.value) {
  549. dialog.value.showModal()
  550. }
  551. }
  552. function close () {
  553. if (dialog.value) {
  554. dialog.value.close()
  555. }
  556. }
  557. // Expose methods for parent components
  558. defineExpose({
  559. show,
  560. close
  561. })
  562. // Lifecycle
  563. onMounted(() => {
  564. setup()
  565. })
  566. onBeforeUnmount(() => {
  567. isComponentMounted = false
  568. })
  569. onUnmounted(() => {
  570. document.body.removeAttribute('loaded-argument-form')
  571. })
  572. </script>
  573. <style scoped>
  574. .section-title-with-icon {
  575. display: inline-flex;
  576. align-items: center;
  577. gap: 0.5rem;
  578. }
  579. .action-title-icon {
  580. font-size: 1.5rem;
  581. }
  582. .action-details-title-link {
  583. display: inline-flex;
  584. align-items: center;
  585. gap: 0.5rem;
  586. color: inherit;
  587. text-decoration: none;
  588. }
  589. .action-details-title-link:hover {
  590. text-decoration: underline;
  591. }
  592. form {
  593. grid-template-columns: minmax(0, max-content) minmax(0, auto) minmax(0, auto);
  594. }
  595. @media (max-width: 600px) {
  596. form {
  597. grid-template-columns: minmax(0, 1fr);
  598. }
  599. form input:not([type="checkbox"]):not([type="radio"]),
  600. form textarea,
  601. form select {
  602. width: 100%;
  603. max-width: 100%;
  604. box-sizing: border-box;
  605. }
  606. }
  607. .argument-description {
  608. font-size: 0.875rem;
  609. color: #666;
  610. margin-top: 0.25rem;
  611. }
  612. .buttons {
  613. display: flex;
  614. gap: 0.5rem;
  615. justify-content: flex-end;
  616. padding-top: 1rem;
  617. border-top: 1px solid #eee;
  618. }
  619. /* Checkbox specific styling */
  620. .argument-group input[type="checkbox"] {
  621. width: auto;
  622. margin-right: 0.5rem;
  623. }
  624. .argument-group input[type="checkbox"]+label {
  625. display: inline;
  626. font-weight: normal;
  627. }
  628. </style>