marshaller.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. import './ActionButton.js' // To define action-button
  2. import { ExecutionDialog } from './ExecutionDialog.js'
  3. import { ActionStatusDisplay } from './ActionStatusDisplay.js'
  4. function createElement (tag, attributes) {
  5. const el = document.createElement(tag)
  6. if (attributes !== null) {
  7. if (attributes.classNames !== undefined) {
  8. el.classList.add(...attributes.classNames)
  9. }
  10. if (attributes.innerText !== undefined) {
  11. el.innerText = attributes.innerText
  12. }
  13. }
  14. return el
  15. }
  16. function createTag (val) {
  17. const domTag = createElement('span', {
  18. innerText: val,
  19. classNames: ['tag']
  20. })
  21. return domTag
  22. }
  23. function createAnnotation (key, val) {
  24. const domAnnotation = createElement('span', {
  25. classNames: ['annotation']
  26. })
  27. domAnnotation.appendChild(createElement('span', {
  28. innerText: key,
  29. classNames: ['annotation-key']
  30. }))
  31. domAnnotation.appendChild(createElement('span', {
  32. innerText: val,
  33. classNames: ['annotation-value']
  34. }))
  35. return domAnnotation
  36. }
  37. /**
  38. * This is a weird function that just sets some globals.
  39. */
  40. export function initMarshaller () {
  41. window.showSection = showSection
  42. window.showSectionView = showSectionView
  43. window.executionDialog = new ExecutionDialog()
  44. window.logEntries = new Map()
  45. window.registeredPaths = new Map()
  46. window.breadcrumbNavigation = []
  47. window.currentPath = ''
  48. window.addEventListener('EventExecutionStarted', onExecutionStarted)
  49. window.addEventListener('EventExecutionFinished', onExecutionFinished)
  50. window.addEventListener('EventOutputChunk', onOutputChunk)
  51. }
  52. export function marshalDashboardComponentsJsonToHtml (json) {
  53. marshalActionsJsonToHtml(json)
  54. marshalDashboardStructureToHtml(json)
  55. document.getElementById('username').innerText = json.authenticatedUser
  56. if (window.settings.AuthLocalLogin || window.settings.AuthOAuth2Providers !== null) {
  57. if (json.authenticatedUser === 'guest') {
  58. document.getElementById('link-login').hidden = false
  59. document.getElementById('link-logout').hidden = true
  60. } else {
  61. document.getElementById('link-login').hidden = true
  62. if (json.authenticatedUserProvider === 'local' || json.authenticatedUserProvider === 'oauth2') {
  63. document.getElementById('link-logout').hidden = false
  64. }
  65. }
  66. document.getElementById('username').setAttribute('title', json.authenticatedUserProvider)
  67. }
  68. document.body.setAttribute('initial-marshal-complete', 'true')
  69. }
  70. function marshalActionsJsonToHtml (json) {
  71. const currentIterationTimestamp = Date.now()
  72. window.actionButtons = {}
  73. for (const jsonButton of json.actions) {
  74. let htmlButton = window.actionButtons[jsonButton.id]
  75. if (typeof htmlButton === 'undefined') {
  76. htmlButton = document.createElement('action-button')
  77. htmlButton.constructFromJson(jsonButton)
  78. window.actionButtons[jsonButton.title] = htmlButton
  79. }
  80. htmlButton.updateFromJson(jsonButton)
  81. htmlButton.updateIterationTimestamp = currentIterationTimestamp
  82. }
  83. // Remove existing, but stale buttons (that were not updated in this round)
  84. for (const existingButton of document.querySelectorAll('action-button')) {
  85. if (existingButton.updateIterationTimestamp !== currentIterationTimestamp) {
  86. existingButton.remove()
  87. }
  88. }
  89. }
  90. function onOutputChunk (evt) {
  91. const chunk = evt.payload
  92. if (chunk.executionTrackingId === window.executionDialog.executionTrackingId) {
  93. window.terminal.write(chunk.output)
  94. window.executionDialog.showOutput()
  95. }
  96. }
  97. function onExecutionStarted (evt) {
  98. const logEntry = evt.payload.logEntry
  99. marshalLogsJsonToHtml({
  100. logs: [logEntry]
  101. })
  102. }
  103. function onExecutionFinished (evt) {
  104. const logEntry = evt.payload.logEntry
  105. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  106. const actionButton = window.actionButtons[logEntry.actionTitle]
  107. if (actionButton === undefined) {
  108. return
  109. }
  110. switch (actionButton.popupOnStart) {
  111. case 'execution-button':
  112. if (document.querySelector('execution-button#execution-' + logEntry.executionTrackingId) !== null) { // If the button was created in our instance
  113. document.querySelector('execution-button#execution-' + logEntry.executionTrackingId).onExecutionFinished(logEntry)
  114. }
  115. break
  116. case 'execution-dialog-stdout-only':
  117. case 'execution-dialog':
  118. actionButton.onExecutionFinished(logEntry)
  119. // We don't need to fetch the logEntry for the dialog because we already
  120. // have it, so we open the dialog and it will get updated below.
  121. window.executionDialog.show()
  122. window.executionDialog.executionTrackingId = logEntry.uuid
  123. break
  124. default:
  125. actionButton.onExecutionFinished(logEntry)
  126. break
  127. }
  128. marshalLogsJsonToHtml({
  129. logs: [logEntry]
  130. })
  131. // If the current execution dialog is open, update that too
  132. if (window.executionDialog.dlg.open && window.executionDialog.executionUuid === logEntry.uuid) {
  133. window.executionDialog.renderExecutionResult({
  134. logEntry: logEntry
  135. })
  136. }
  137. }
  138. function convertPathToBreadcrumb (path) {
  139. const parts = path.split('/')
  140. const result = []
  141. for (let i = 0; i < parts.length; i++) {
  142. if (parts[i] === '') {
  143. continue
  144. }
  145. result.push(parts.slice(0, i + 1).join('/'))
  146. }
  147. return result
  148. }
  149. function showExecutionResult (pathName) {
  150. const executionTrackingId = pathName.split('/')[2]
  151. window.executionDialog.fetchExecutionResult(executionTrackingId)
  152. window.executionDialog.show()
  153. }
  154. function showSection (pathName) {
  155. if (pathName.startsWith('/logs/')) {
  156. showExecutionResult(pathName)
  157. pushNewNavigationPath(pathName)
  158. return
  159. }
  160. const path = window.registeredPaths.get(pathName)
  161. if (path === undefined) {
  162. console.warn('Section not found by path: ' + pathName)
  163. showSection('/')
  164. return
  165. }
  166. window.convertPathToBreadcrumb = convertPathToBreadcrumb
  167. window.currentPath = pathName
  168. window.breadcrumbNavigation = convertPathToBreadcrumb(pathName)
  169. for (const section of document.querySelectorAll('section')) {
  170. if (section.title === path.section) {
  171. section.style.display = 'block'
  172. } else {
  173. section.style.display = 'none'
  174. }
  175. }
  176. pushNewNavigationPath(pathName)
  177. setSectionNavigationVisible(false)
  178. showSectionView(path.view)
  179. }
  180. function pushNewNavigationPath (pathName) {
  181. window.history.pushState({
  182. path: pathName
  183. }, null, pathName)
  184. }
  185. function setSectionNavigationVisible (visible) {
  186. const nav = document.querySelector('nav')
  187. const btn = document.getElementById('sidebar-toggler-button')
  188. nav.removeAttribute('hidden')
  189. if (document.body.classList.contains('has-sidebar')) {
  190. if (visible) {
  191. btn.setAttribute('aria-pressed', false)
  192. btn.setAttribute('aria-label', 'Open sidebar navigation')
  193. btn.innerHTML = '&laquo;'
  194. nav.classList.add('shown')
  195. } else {
  196. btn.setAttribute('aria-pressed', true)
  197. btn.setAttribute('aria-label', 'Close sidebar navigation')
  198. btn.innerHTML = '&#9776;'
  199. nav.classList.remove('shown')
  200. }
  201. } else {
  202. btn.disabled = true
  203. }
  204. }
  205. export function setupSectionNavigation (style) {
  206. const nav = document.querySelector('nav')
  207. const btn = document.getElementById('sidebar-toggler-button')
  208. if (style === 'sidebar') {
  209. nav.classList.add('sidebar')
  210. document.body.classList.add('has-sidebar')
  211. btn.onclick = () => {
  212. if (nav.classList.contains('shown')) {
  213. setSectionNavigationVisible(false)
  214. } else {
  215. setSectionNavigationVisible(true)
  216. }
  217. }
  218. } else {
  219. nav.classList.add('topbar')
  220. document.body.classList.add('has-topbar')
  221. }
  222. registerSection('/', 'Actions', null, document.getElementById('showActions'))
  223. registerSection('/diagnostics', 'Diagnostics', null, document.getElementById('showDiagnostics'))
  224. registerSection('/logs', 'Logs', null, document.getElementById('showLogs'))
  225. registerSection('/login', 'Login', null, null)
  226. }
  227. function registerSection (path, section, view, linkElement) {
  228. window.registeredPaths.set(path, {
  229. section: section,
  230. view: view
  231. })
  232. if (linkElement != null) {
  233. addLinkToSection(path, linkElement)
  234. }
  235. }
  236. function addLinkToSection (pathName, element) {
  237. const path = window.registeredPaths.get(pathName)
  238. element.href = 'javascript:void(0)'
  239. element.title = path.section
  240. element.onclick = () => {
  241. showSection(pathName)
  242. }
  243. }
  244. export function refreshDiagnostics () {
  245. document.getElementById('diagnostics-sshfoundkey').innerHTML = window.settings.SshFoundKey
  246. document.getElementById('diagnostics-sshfoundconfig').innerHTML = window.settings.SshFoundConfig
  247. }
  248. function getSystemTitle (title) {
  249. return title.replaceAll(' ', '')
  250. }
  251. function marshalSingleDashboard (dashboard, nav) {
  252. const oldsection = document.querySelector('section[title="' + getSystemTitle(dashboard.title) + '"]')
  253. if (oldsection != null) {
  254. oldsection.remove()
  255. }
  256. const section = document.createElement('section')
  257. section.setAttribute('system-title', getSystemTitle(dashboard.title))
  258. section.title = section.getAttribute('system-title')
  259. const def = createFieldset('default', section)
  260. section.appendChild(def)
  261. document.getElementsByTagName('main')[0].appendChild(section)
  262. marshalContainerContents(dashboard, section, def, dashboard.title)
  263. const oldLi = nav.querySelector('li[title="' + dashboard.title + '"]')
  264. if (oldLi != null) {
  265. oldLi.remove()
  266. }
  267. const navigationA = document.createElement('a')
  268. navigationA.title = dashboard.title
  269. navigationA.innerText = dashboard.title
  270. registerSection('/' + getSystemTitle(section.title), section.title, null, navigationA)
  271. const navigationLi = document.createElement('li')
  272. navigationLi.appendChild(navigationA)
  273. navigationLi.title = dashboard.title
  274. document.getElementById('navigation-links').appendChild(navigationLi)
  275. }
  276. function marshalDashboardStructureToHtml (json) {
  277. const nav = document.getElementById('navigation-links')
  278. for (const dashboard of json.dashboards) {
  279. marshalSingleDashboard(dashboard, nav)
  280. }
  281. const rootGroup = document.querySelector('#root-group')
  282. for (const btn of Object.values(window.actionButtons)) {
  283. if (btn.parentElement === null) {
  284. rootGroup.appendChild(btn)
  285. }
  286. }
  287. if (window.currentPath !== '') {
  288. showSection(window.currentPath)
  289. } else if (window.location.pathname !== '/' && document.body.getAttribute('initial-marshal-complete') === null) {
  290. showSection(window.location.pathname)
  291. } else {
  292. if (rootGroup.querySelectorAll('action-button').length === 0 && json.dashboards.length > 0) {
  293. nav.querySelector('li[title="Actions"]').style.display = 'none'
  294. showSection('/' + getSystemTitle(json.dashboards[0].title))
  295. } else {
  296. showSection('/')
  297. }
  298. }
  299. }
  300. function marshalLink (item, fieldset) {
  301. let btn = window.actionButtons[item.title]
  302. if (typeof btn === 'undefined') {
  303. btn = document.createElement('button')
  304. btn.innerText = 'Action not found: ' + item.title
  305. btn.classList.add('error')
  306. }
  307. if (item.cssClass !== '') {
  308. btn.classList.add(item.cssClass)
  309. }
  310. fieldset.appendChild(btn)
  311. }
  312. function marshalMreOutput (dashboardComponent, fieldset) {
  313. const pre = document.createElement('pre')
  314. pre.classList.add('mre-output')
  315. pre.innerHTML = 'Waiting...'
  316. const executionStatus = {
  317. actionId: dashboardComponent.title
  318. }
  319. window.fetch(window.restBaseUrl + 'ExecutionStatus', {
  320. method: 'POST',
  321. headers: {
  322. 'Content-Type': 'application/json'
  323. },
  324. body: JSON.stringify(executionStatus)
  325. }).then((res) => {
  326. if (res.ok) {
  327. return res.json()
  328. } else {
  329. pre.innerHTML = 'error'
  330. throw new Error(res.statusText)
  331. }
  332. }).then((json) => {
  333. updateMre(pre, json.logEntry)
  334. })
  335. const updateMre = (pre, json) => {
  336. pre.innerHTML = json.output
  337. }
  338. window.addEventListener('ExecutionFinished', (e) => {
  339. // The dashboard component "title" field is used for lots of things
  340. // and in this context for MreOutput it's just to refer an an actionId.
  341. //
  342. // So this is not a typo.
  343. if (e.payload.actionId === dashboardComponent.title) {
  344. updateMre(pre, e.payload)
  345. }
  346. })
  347. fieldset.appendChild(pre)
  348. }
  349. function marshalContainerContents (json, section, fieldset, parentDashboard) {
  350. for (const item of json.contents) {
  351. switch (item.type) {
  352. case 'fieldset':
  353. marshalFieldset(item, section, parentDashboard)
  354. break
  355. case 'directory': {
  356. const directoryPath = marshalDirectory(item, section)
  357. marshalDirectoryButton(item, fieldset, directoryPath)
  358. }
  359. break
  360. case 'display':
  361. marshalDisplay(item, fieldset)
  362. break
  363. case 'stdout-most-recent-execution':
  364. marshalMreOutput(item, fieldset)
  365. break
  366. case 'link':
  367. marshalLink(item, fieldset)
  368. break
  369. default:
  370. }
  371. }
  372. }
  373. function createFieldset (title, parentDashboard) {
  374. const legend = document.createElement('legend')
  375. legend.innerText = title
  376. const fs = document.createElement('fieldset')
  377. fs.title = title
  378. fs.appendChild(legend)
  379. if (typeof parentDashboard === 'undefined') {
  380. fs.setAttribute('parent-dashboard', '')
  381. } else {
  382. fs.setAttribute('parent-dashboard', parentDashboard)
  383. }
  384. return fs
  385. }
  386. function marshalFieldset (item, section, parentDashboard) {
  387. const fs = createFieldset(item.title, parentDashboard)
  388. marshalContainerContents(item, section, fs, parentDashboard)
  389. section.appendChild(fs)
  390. }
  391. function showSectionView (selected) {
  392. if (selected === '') {
  393. selected = null
  394. }
  395. for (const fieldset of document.querySelectorAll('fieldset')) {
  396. if (selected === null) {
  397. if ((fieldset.id === 'root-group' || fieldset.getAttribute('parent-dashboard') !== '') && fieldset.children.length > 1) {
  398. fieldset.style.display = 'grid'
  399. } else {
  400. fieldset.style.display = 'none'
  401. }
  402. } else {
  403. if (fieldset.title === selected) {
  404. fieldset.style.display = 'grid'
  405. } else {
  406. fieldset.style.display = 'none'
  407. }
  408. }
  409. }
  410. const current = window.registeredPaths.get(window.currentPath)
  411. for (const navLink of document.querySelector('nav').querySelectorAll('a')) {
  412. if (navLink.title === current.section) {
  413. navLink.classList.add('selected')
  414. } else {
  415. navLink.classList.remove('selected')
  416. }
  417. }
  418. rebuildH1BreadcrumbNavigation(selected)
  419. pushNewNavigationPath(window.currentPath)
  420. }
  421. function rebuildH1BreadcrumbNavigation () {
  422. const title = document.querySelector('h1')
  423. title.innerHTML = ''
  424. const rootLink = document.createElement('a')
  425. rootLink.innerText = window.pageTitle
  426. rootLink.href = 'javascript:void(0)'
  427. rootLink.onclick = () => {
  428. showSection('/')
  429. }
  430. title.appendChild(rootLink)
  431. for (const pathName of window.breadcrumbNavigation) {
  432. const sep = document.createElement('span')
  433. sep.innerHTML = ' &raquo; '
  434. title.append(sep)
  435. const path = window.registeredPaths.get(pathName)
  436. title.appendChild(createNavigationBreadcrumbDisplay(path))
  437. }
  438. document.title = title.innerText
  439. }
  440. function createNavigationBreadcrumbDisplay (path) {
  441. const a = document.createElement('a')
  442. a.href = 'javascript:void(0)'
  443. if (path.view === null) {
  444. a.title = path.section
  445. a.innerText = path.section
  446. } else {
  447. a.innerText = path.view
  448. a.title = path.view
  449. }
  450. a.onclick = () => {
  451. showSectionView(path.view)
  452. }
  453. return a
  454. }
  455. function marshalDisplay (item, fieldset) {
  456. const display = document.createElement('div')
  457. display.innerHTML = item.title
  458. display.classList.add('display')
  459. if (item.cssClass !== '') {
  460. display.classList.add(item.cssClass)
  461. }
  462. fieldset.appendChild(display)
  463. }
  464. function marshalDirectoryButton (item, fieldset, path) {
  465. const directoryButton = document.createElement('button')
  466. directoryButton.innerHTML = '<span class = "icon">' + item.icon + '</span> ' + item.title
  467. directoryButton.onclick = () => {
  468. showSection(path)
  469. }
  470. fieldset.appendChild(directoryButton)
  471. }
  472. function marshalDirectory (item, section) {
  473. const fs = createFieldset(item.title)
  474. fs.style.display = 'none'
  475. const directoryBackButton = document.createElement('button')
  476. directoryBackButton.innerHTML = window.settings.DefaultIconForBack
  477. directoryBackButton.title = 'Go back one directory'
  478. directoryBackButton.onclick = () => {
  479. showSection('/' + section.title)
  480. }
  481. fs.appendChild(directoryBackButton)
  482. marshalContainerContents(item, section, fs)
  483. section.appendChild(fs)
  484. const path = '/' + section.title + '/' + getSystemTitle(item.title)
  485. registerSection(path, section.title, item.title, null)
  486. return path
  487. }
  488. export function marshalLogsJsonToHtml (json) {
  489. for (const logEntry of json.logs) {
  490. let row = document.getElementById('log-' + logEntry.executionTrackingId)
  491. if (row == null) {
  492. const tpl = document.getElementById('tplLogRow')
  493. row = tpl.content.querySelector('tr').cloneNode(true)
  494. row.id = 'log-' + logEntry.executionTrackingId
  495. row.querySelector('.content').onclick = () => {
  496. window.executionDialog.reset()
  497. window.executionDialog.show()
  498. window.executionDialog.renderExecutionResult({
  499. logEntry: window.logEntries.get(logEntry.executionTrackingId)
  500. })
  501. pushNewNavigationPath('/logs/' + logEntry.executionTrackingId)
  502. }
  503. row.exitCodeDisplay = new ActionStatusDisplay(row.querySelector('.exit-code'))
  504. logEntry.dom = row
  505. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  506. document.querySelector('#logTableBody').prepend(row)
  507. }
  508. row.querySelector('.timestamp').innerText = logEntry.datetimeStarted
  509. row.querySelector('.content').innerText = logEntry.actionTitle
  510. row.querySelector('.icon').innerHTML = logEntry.actionIcon
  511. row.setAttribute('title', logEntry.actionTitle)
  512. row.exitCodeDisplay.update(logEntry)
  513. row.querySelector('.tags').innerHTML = ''
  514. for (const tag of logEntry.tags) {
  515. row.querySelector('.tags').append(createTag(tag))
  516. }
  517. row.querySelector('.tags').append(createAnnotation('user', logEntry.user))
  518. }
  519. }
  520. window.addEventListener('popstate', (e) => {
  521. e.preventDefault()
  522. if (e.state != null && typeof e.state.path !== 'undefined') {
  523. showSection(e.state.path)
  524. }
  525. })
  526. export function refreshServerConnectionLabel () {
  527. if (window.restAvailable) {
  528. document.querySelector('#serverConnectionRest').classList.remove('error')
  529. } else {
  530. document.querySelector('#serverConnectionRest').classList.add('error')
  531. }
  532. if (window.websocketAvailable) {
  533. document.querySelector('#serverConnectionWebSocket').classList.remove('error')
  534. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket'
  535. } else {
  536. document.querySelector('#serverConnectionWebSocket').classList.add('error')
  537. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket Error'
  538. }
  539. }