marshaller.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. const shouldHideActions = rootGroup.querySelectorAll('action-button').length === 0 && json.dashboards.length > 0
  288. if (shouldHideActions) {
  289. nav.querySelector('li[title="Actions"]').style.display = 'none'
  290. }
  291. if (window.currentPath !== '') {
  292. showSection(window.currentPath)
  293. } else if (window.location.pathname !== '/' && document.body.getAttribute('initial-marshal-complete') === null) {
  294. showSection(window.location.pathname)
  295. } else {
  296. if (shouldHideActions) {
  297. showSection('/' + getSystemTitle(json.dashboards[0].title))
  298. } else {
  299. showSection('/')
  300. }
  301. }
  302. }
  303. function marshalLink (item, fieldset) {
  304. let btn = window.actionButtons[item.title]
  305. if (typeof btn === 'undefined') {
  306. btn = document.createElement('button')
  307. btn.innerText = 'Action not found: ' + item.title
  308. btn.classList.add('error')
  309. }
  310. if (item.cssClass !== '') {
  311. btn.classList.add(item.cssClass)
  312. }
  313. fieldset.appendChild(btn)
  314. }
  315. function marshalMreOutput (dashboardComponent, fieldset) {
  316. const pre = document.createElement('pre')
  317. pre.classList.add('mre-output')
  318. pre.innerHTML = 'Waiting...'
  319. const executionStatus = {
  320. actionId: dashboardComponent.title
  321. }
  322. window.fetch(window.restBaseUrl + 'ExecutionStatus', {
  323. method: 'POST',
  324. headers: {
  325. 'Content-Type': 'application/json'
  326. },
  327. body: JSON.stringify(executionStatus)
  328. }).then((res) => {
  329. if (res.ok) {
  330. return res.json()
  331. } else {
  332. pre.innerHTML = 'error'
  333. throw new Error(res.statusText)
  334. }
  335. }).then((json) => {
  336. updateMre(pre, json.logEntry)
  337. })
  338. const updateMre = (pre, json) => {
  339. pre.innerHTML = json.output
  340. }
  341. window.addEventListener('ExecutionFinished', (e) => {
  342. // The dashboard component "title" field is used for lots of things
  343. // and in this context for MreOutput it's just to refer an an actionId.
  344. //
  345. // So this is not a typo.
  346. if (e.payload.actionId === dashboardComponent.title) {
  347. updateMre(pre, e.payload)
  348. }
  349. })
  350. fieldset.appendChild(pre)
  351. }
  352. function marshalContainerContents (json, section, fieldset, parentDashboard) {
  353. for (const item of json.contents) {
  354. switch (item.type) {
  355. case 'fieldset':
  356. marshalFieldset(item, section, parentDashboard)
  357. break
  358. case 'directory': {
  359. const directoryPath = marshalDirectory(item, section)
  360. marshalDirectoryButton(item, fieldset, directoryPath)
  361. }
  362. break
  363. case 'display':
  364. marshalDisplay(item, fieldset)
  365. break
  366. case 'stdout-most-recent-execution':
  367. marshalMreOutput(item, fieldset)
  368. break
  369. case 'link':
  370. marshalLink(item, fieldset)
  371. break
  372. default:
  373. }
  374. }
  375. }
  376. function createFieldset (title, parentDashboard) {
  377. const legend = document.createElement('legend')
  378. legend.innerText = title
  379. const fs = document.createElement('fieldset')
  380. fs.title = title
  381. fs.appendChild(legend)
  382. if (typeof parentDashboard === 'undefined') {
  383. fs.setAttribute('parent-dashboard', '')
  384. } else {
  385. fs.setAttribute('parent-dashboard', parentDashboard)
  386. }
  387. return fs
  388. }
  389. function marshalFieldset (item, section, parentDashboard) {
  390. const fs = createFieldset(item.title, parentDashboard)
  391. marshalContainerContents(item, section, fs, parentDashboard)
  392. section.appendChild(fs)
  393. }
  394. function showSectionView (selected) {
  395. if (selected === '') {
  396. selected = null
  397. }
  398. for (const fieldset of document.querySelectorAll('fieldset')) {
  399. if (selected === null) {
  400. if ((fieldset.id === 'root-group' || fieldset.getAttribute('parent-dashboard') !== '') && fieldset.children.length > 1) {
  401. fieldset.style.display = 'grid'
  402. } else {
  403. fieldset.style.display = 'none'
  404. }
  405. } else {
  406. if (fieldset.title === selected) {
  407. fieldset.style.display = 'grid'
  408. } else {
  409. fieldset.style.display = 'none'
  410. }
  411. }
  412. }
  413. const current = window.registeredPaths.get(window.currentPath)
  414. for (const navLink of document.querySelector('nav').querySelectorAll('a')) {
  415. if (navLink.title === current.section) {
  416. navLink.classList.add('selected')
  417. } else {
  418. navLink.classList.remove('selected')
  419. }
  420. }
  421. rebuildH1BreadcrumbNavigation(selected)
  422. pushNewNavigationPath(window.currentPath)
  423. }
  424. function rebuildH1BreadcrumbNavigation () {
  425. const title = document.querySelector('h1')
  426. title.innerHTML = ''
  427. const rootLink = document.createElement('a')
  428. rootLink.innerText = window.pageTitle
  429. rootLink.href = 'javascript:void(0)'
  430. rootLink.onclick = () => {
  431. showSection('/')
  432. }
  433. title.appendChild(rootLink)
  434. for (const pathName of window.breadcrumbNavigation) {
  435. const sep = document.createElement('span')
  436. sep.innerHTML = ' &raquo; '
  437. title.append(sep)
  438. const path = window.registeredPaths.get(pathName)
  439. title.appendChild(createNavigationBreadcrumbDisplay(path))
  440. }
  441. document.title = title.innerText
  442. }
  443. function createNavigationBreadcrumbDisplay (path) {
  444. const a = document.createElement('a')
  445. a.href = 'javascript:void(0)'
  446. if (path.view === null) {
  447. a.title = path.section
  448. a.innerText = path.section
  449. } else {
  450. a.innerText = path.view
  451. a.title = path.view
  452. }
  453. a.onclick = () => {
  454. showSectionView(path.view)
  455. }
  456. return a
  457. }
  458. function marshalDisplay (item, fieldset) {
  459. const display = document.createElement('div')
  460. display.innerHTML = item.title
  461. display.classList.add('display')
  462. if (item.cssClass !== '') {
  463. display.classList.add(item.cssClass)
  464. }
  465. fieldset.appendChild(display)
  466. }
  467. function marshalDirectoryButton (item, fieldset, path) {
  468. const directoryButton = document.createElement('button')
  469. directoryButton.innerHTML = '<span class = "icon">' + item.icon + '</span> ' + item.title
  470. directoryButton.onclick = () => {
  471. showSection(path)
  472. }
  473. fieldset.appendChild(directoryButton)
  474. }
  475. function marshalDirectory (item, section) {
  476. const fs = createFieldset(item.title)
  477. fs.style.display = 'none'
  478. const directoryBackButton = document.createElement('button')
  479. directoryBackButton.innerHTML = window.settings.DefaultIconForBack
  480. directoryBackButton.title = 'Go back one directory'
  481. directoryBackButton.onclick = () => {
  482. showSection('/' + section.title)
  483. }
  484. fs.appendChild(directoryBackButton)
  485. marshalContainerContents(item, section, fs)
  486. section.appendChild(fs)
  487. const path = '/' + section.title + '/' + getSystemTitle(item.title)
  488. registerSection(path, section.title, item.title, null)
  489. return path
  490. }
  491. export function marshalLogsJsonToHtml (json) {
  492. for (const logEntry of json.logs) {
  493. let row = document.getElementById('log-' + logEntry.executionTrackingId)
  494. if (row == null) {
  495. const tpl = document.getElementById('tplLogRow')
  496. row = tpl.content.querySelector('tr').cloneNode(true)
  497. row.id = 'log-' + logEntry.executionTrackingId
  498. row.querySelector('.content').onclick = () => {
  499. window.executionDialog.reset()
  500. window.executionDialog.show()
  501. window.executionDialog.renderExecutionResult({
  502. logEntry: window.logEntries.get(logEntry.executionTrackingId)
  503. })
  504. pushNewNavigationPath('/logs/' + logEntry.executionTrackingId)
  505. }
  506. row.exitCodeDisplay = new ActionStatusDisplay(row.querySelector('.exit-code'))
  507. logEntry.dom = row
  508. window.logEntries.set(logEntry.executionTrackingId, logEntry)
  509. document.querySelector('#logTableBody').prepend(row)
  510. }
  511. row.querySelector('.timestamp').innerText = logEntry.datetimeStarted
  512. row.querySelector('.content').innerText = logEntry.actionTitle
  513. row.querySelector('.icon').innerHTML = logEntry.actionIcon
  514. row.setAttribute('title', logEntry.actionTitle)
  515. row.exitCodeDisplay.update(logEntry)
  516. row.querySelector('.tags').innerHTML = ''
  517. for (const tag of logEntry.tags) {
  518. row.querySelector('.tags').append(createTag(tag))
  519. }
  520. row.querySelector('.tags').append(createAnnotation('user', logEntry.user))
  521. }
  522. }
  523. window.addEventListener('popstate', (e) => {
  524. e.preventDefault()
  525. if (e.state != null && typeof e.state.path !== 'undefined') {
  526. showSection(e.state.path)
  527. }
  528. })
  529. export function refreshServerConnectionLabel () {
  530. if (window.restAvailable) {
  531. document.querySelector('#serverConnectionRest').classList.remove('error')
  532. } else {
  533. document.querySelector('#serverConnectionRest').classList.add('error')
  534. }
  535. if (window.websocketAvailable) {
  536. document.querySelector('#serverConnectionWebSocket').classList.remove('error')
  537. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket'
  538. } else {
  539. document.querySelector('#serverConnectionWebSocket').classList.add('error')
  540. document.querySelector('#serverConnectionWebSocket').innerText = 'WebSocket Error'
  541. }
  542. }