marshaller.js 18 KB

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