marshaller.js 17 KB

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