rs.scripts.diagram-viewer.0.9.2.source-code.menu.renderer.ts Maven / Gradle / Ivy
The newest version!
// SPDX-License-Identifier: Apache-2.0
// Copyright 2019 XLRIT (https://www.xlrit.com/)
import _ from "lodash"
import $ from "jquery"
import * as util from './util'
interface TIndexItem {
processName: string
processKey: string
diagrams: Array
}
interface TDiagram {
diagramType: string
relPath: string
}
function getPrevNext(arr: Array, elem: T): [T, T] {
const i = arr.indexOf(elem)
const prev = arr[(arr.length + i - 1) % arr.length]
const next = arr[(i + 1) % arr.length]
return [prev, next]
}
function createMenuTitle(item: TIndexItem): string {
return item.processKey == '__GLOBAL__' ? 'Project diagrams' : item.processKey
}
function createPageTitle(item: TIndexItem): string {
return item.processKey == '__GLOBAL__' ? 'Project diagrams' : `${item.processName} (${item.processKey})`;
}
const KEYCODE_PREV = 75 // K
const KEYCODE_NEXT = 74 // J
export default class MenuRenderer {
readonly menuEl: JQuery
constructor(menuEl: JQuery) {
this.menuEl = menuEl
// store the scroll position when leaving the page
$(window).on("unload", () => {
localStorage.setItem('menu-scrollTop', '' + menuEl.scrollTop())
})
}
render(itemsArray: Array) {
const itemsMap = _.keyBy(itemsArray, 'processKey')
// determine the chosen item, from the url-param or local storage
const url = new URL(window.location.href)
let chosen = url.searchParams.get('p') || localStorage.getItem('menu-currentProcess')
if (chosen) {
localStorage.setItem('menu-currentProcess', chosen)
}
else {
chosen = localStorage.getItem('menu-currentProcess')
}
// determine the current, previous and next items
const current = chosen && itemsMap[chosen] ? itemsMap[chosen] : _(itemsMap).find()!
// render menu items
itemsArray.forEach(item => {
const title = createMenuTitle(item)
this.addMenuItem('?p=' + item.processKey, title, item == current)
})
// navigate to previous and next items using K and J
const [prev, next] = getPrevNext(itemsArray, current)
$(document).keyup(e => {
switch (e.keyCode) {
case KEYCODE_PREV: document.location.assign('?p=' + prev.processKey); break;
case KEYCODE_NEXT: document.location.assign('?p=' + next.processKey); break;
}
})
// restore scroll position
const scrollTop = parseInt(localStorage.getItem('menu-scrollTop') || '')
if (!Number.isNaN(scrollTop)) this.menuEl.scrollTop(scrollTop)
// show current item
$("#processName").text(createPageTitle(current))
current.diagrams.forEach(diagram => {
util.loadJsonp(diagram.relPath)
})
}
addMenuItem(link: string, label: string, current: boolean) {
const li = $('').appendTo(this.menuEl)
const anchor = $('').appendTo(li)
anchor.attr('href', link).text(label)
if (current) anchor.addClass("current")
}
}