85 lines
2.4 KiB
JavaScript

import TracksTable from "./tracks_table.mjs"
import IntegrityManager from "./integrity_manager.mjs"
export default class Editor {
constructor() {
const params = new URLSearchParams(window.location.search)
this.filename = params.get("f")
window.addEventListener("keydown", e => {
if (e.key === "s" && e.ctrlKey) {
e.preventDefault()
this.save()
}
})
this.tables = {
audio: new TracksTable(this, "audio", "audio-tracks", "audio_tracks"),
subtitle: new TracksTable(this, "subtitle", "subtitle-tracks", "subtitle_tracks")
}
this.data = {}
this.dirty = false
this.integrity_mgr = new IntegrityManager(this)
this.setup()
}
setup() {
document.getElementById("filename").innerText = this.filename
this.fetchData()
}
fetchData() {
fetch(`/api/file/${this.filename}`).then(res => {
if (res.ok) {
return res.json()
}
return null
}).then(res => {
if (res !== null) {
this.data = res
this.displayData()
}
})
}
displayData() {
document.getElementById("title").value = this.data.title
this.tables.audio.loadTracks(this.data.audio_tracks)
this.tables.subtitle.loadTracks(this.data.subtitle_tracks)
this.integrity_mgr.checkIntegrity()
}
save() {
fetch(`/api/file/${this.filename}`, {
method: "POST",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
}).then(res => {
if (res.ok) {
this.dirty = false
document.getElementById("unsaved").classList.remove("show")
} else {
alert(`Error ${res.status}: ${res.statusText}`)
}
})
}
setDirty() {
this.dirty = true
document.getElementById("unsaved").classList.add("show")
}
editTrack(listKey, trackIdx, key, value) {
const keyParts = key.split("/")
let obj = this.data[listKey][trackIdx]
for (const part of keyParts.slice(0, -1)) {
obj = obj[part]
}
obj[keyParts[keyParts.length - 1]] = value
this.setDirty()
}
}