856 lines
20 KiB
TypeScript
Raw Normal View History

2017-07-14 21:50:34 +00:00
import { Application } from "./Application"
import { Diff } from "./Diff"
2017-07-05 19:06:38 +00:00
import { MutationQueue } from "./MutationQueue"
2017-07-12 18:37:34 +00:00
import { StatusMessage } from "./StatusMessage"
2017-07-14 21:50:34 +00:00
import { PushManager } from "./PushManager"
2017-07-19 16:47:17 +00:00
import { TouchController } from "./TouchController"
2018-02-28 15:26:49 +00:00
import { NotificationManager } from "./NotificationManager"
2017-10-01 05:50:53 +00:00
import { Analytics } from "./Analytics"
2017-10-02 00:02:07 +00:00
import { SideBar } from "./SideBar"
2017-10-16 10:56:46 +00:00
import { InfiniteScroller } from "./InfiniteScroller"
2017-10-20 00:43:02 +00:00
import { ServiceWorkerManager } from "./ServiceWorkerManager"
2017-11-22 11:20:57 +00:00
import { displayAiringDate, displayDate, displayTime } from "./DateView"
2017-10-20 00:43:02 +00:00
import { findAll, delay, canUseWebP, swapElements } from "./Utils"
import * as actions from "./Actions"
2017-11-17 11:51:08 +00:00
import { darkTheme } from "./Actions";
2017-06-29 06:32:46 +00:00
2017-06-19 14:49:24 +00:00
export class AnimeNotifier {
app: Application
2017-10-01 05:50:53 +00:00
analytics: Analytics
2017-06-30 15:51:17 +00:00
user: HTMLElement
2017-07-06 20:08:49 +00:00
title: string
2017-07-08 13:40:13 +00:00
webpEnabled: boolean
2017-07-14 02:58:21 +00:00
contentLoadedActions: Promise<any>
2017-07-12 18:37:34 +00:00
statusMessage: StatusMessage
2017-07-05 19:06:38 +00:00
visibilityObserver: IntersectionObserver
2017-07-14 21:50:34 +00:00
pushManager: PushManager
2017-10-20 00:43:02 +00:00
serviceWorkerManager: ServiceWorkerManager
2018-02-28 15:26:49 +00:00
notificationManager: NotificationManager
2017-07-19 16:47:17 +00:00
touchController: TouchController
2017-10-02 00:02:07 +00:00
sideBar: SideBar
2017-10-16 10:56:46 +00:00
infiniteScroller: InfiniteScroller
2017-07-19 04:55:21 +00:00
mainPageLoaded: boolean
2017-10-14 10:45:22 +00:00
isLoading: boolean
2017-07-19 05:39:09 +00:00
lastReloadContentPath: string
2018-03-11 14:43:17 +00:00
currentSoundTrackId: string
2017-07-05 19:06:38 +00:00
2017-10-12 15:52:46 +00:00
elementFound: MutationQueue
elementNotFound: MutationQueue
2017-09-22 04:19:32 +00:00
unmount: MutationQueue
2017-06-19 14:49:24 +00:00
constructor(app: Application) {
this.app = app
2017-06-30 15:51:17 +00:00
this.user = null
2017-07-06 20:08:49 +00:00
this.title = "Anime Notifier"
2017-10-14 10:45:22 +00:00
this.isLoading = true
2017-10-12 15:52:46 +00:00
this.elementFound = new MutationQueue(elem => elem.classList.add("element-found"))
this.elementNotFound = new MutationQueue(elem => elem.classList.add("element-not-found"))
2017-09-22 04:19:32 +00:00
this.unmount = new MutationQueue(elem => elem.classList.remove("mounted"))
2017-07-05 19:06:38 +00:00
2017-07-19 02:18:56 +00:00
// These classes will never be removed on DOM diffs
Diff.persistentClasses.add("mounted")
2017-10-12 15:52:46 +00:00
Diff.persistentClasses.add("element-found")
2017-07-19 02:18:56 +00:00
2017-07-19 07:09:55 +00:00
// Never remove src property on diffs
Diff.persistentAttributes.add("src")
// Is intersection observer supported?
if("IntersectionObserver" in window) {
// Enable lazy load
this.visibilityObserver = new IntersectionObserver(
entries => {
for(let entry of entries) {
2017-11-19 12:51:23 +00:00
if(entry.isIntersecting) {
entry.target["became visible"]()
this.visibilityObserver.unobserve(entry.target)
}
2017-06-24 14:17:38 +00:00
}
},
{}
)
} else {
// Disable lazy load feature
this.visibilityObserver = {
disconnect: () => {},
observe: (elem: HTMLElement) => {
elem["became visible"]()
},
unobserve: (elem: HTMLElement) => {}
} as IntersectionObserver
}
2017-06-19 14:49:24 +00:00
}
2017-06-30 15:51:17 +00:00
init() {
2017-07-21 10:55:36 +00:00
// App init
this.app.init()
// Event listeners
2017-06-30 15:51:17 +00:00
document.addEventListener("readystatechange", this.onReadyStateChange.bind(this))
document.addEventListener("DOMContentLoaded", this.onContentLoaded.bind(this))
document.addEventListener("keydown", this.onKeyDown.bind(this), false)
window.addEventListener("popstate", this.onPopState.bind(this))
2017-07-14 02:58:21 +00:00
// Idle
2017-07-03 15:21:00 +00:00
this.requestIdleCallback(this.onIdle.bind(this))
}
requestIdleCallback(func: Function) {
2017-06-30 15:51:17 +00:00
if("requestIdleCallback" in window) {
2017-07-03 15:21:00 +00:00
window["requestIdleCallback"](func)
2017-06-30 15:51:17 +00:00
} else {
2017-07-03 15:21:00 +00:00
func()
2017-06-30 15:51:17 +00:00
}
}
2017-06-19 15:45:27 +00:00
onReadyStateChange() {
if(document.readyState !== "interactive") {
return
}
this.run()
}
2017-06-19 14:49:24 +00:00
run() {
2017-07-08 13:40:13 +00:00
// Check for WebP support
this.webpEnabled = canUseWebP()
2017-07-03 23:20:27 +00:00
// Initiate the elements we need
2017-06-30 15:51:17 +00:00
this.user = this.app.find("user")
2017-06-19 14:49:24 +00:00
this.app.content = this.app.find("content")
this.app.loading = this.app.find("loading")
2017-07-03 23:20:27 +00:00
2017-11-17 11:51:08 +00:00
// Theme
if(this.user && this.user.dataset.pro === "true" && this.user.dataset.theme !== "light") {
2018-03-13 15:45:40 +00:00
darkTheme(this)
2017-11-17 11:51:08 +00:00
}
2017-07-12 18:37:34 +00:00
// Status message
this.statusMessage = new StatusMessage(
this.app.find("status-message"),
this.app.find("status-message-text")
)
2017-07-14 21:50:34 +00:00
// Push manager
this.pushManager = new PushManager()
2017-07-19 14:56:02 +00:00
2018-02-28 15:26:49 +00:00
// Notification manager
this.notificationManager = new NotificationManager()
2017-10-01 05:50:53 +00:00
// Analytics
this.analytics = new Analytics()
2017-07-19 14:56:02 +00:00
// Sidebar control
2017-10-02 00:02:07 +00:00
this.sideBar = new SideBar(this.app.find("sidebar"))
2017-10-16 10:56:46 +00:00
// Infinite scrolling
2018-03-10 19:17:08 +00:00
this.infiniteScroller = new InfiniteScroller(this.app.content.parentElement, 150)
2017-11-09 16:18:15 +00:00
2017-10-14 10:45:22 +00:00
// Loading
this.loading(false)
2017-06-19 14:49:24 +00:00
}
2017-06-19 15:45:27 +00:00
2017-10-01 05:56:30 +00:00
onContentLoaded() {
2017-06-30 15:51:17 +00:00
// Stop watching all the objects from the previous page.
2017-06-24 14:17:38 +00:00
this.visibilityObserver.disconnect()
2017-11-09 16:18:15 +00:00
2017-07-14 02:58:21 +00:00
this.contentLoadedActions = Promise.all([
2017-09-22 04:19:32 +00:00
Promise.resolve().then(() => this.mountMountables()),
2017-10-12 15:52:46 +00:00
Promise.resolve().then(() => this.lazyLoad()),
2017-07-14 02:58:21 +00:00
Promise.resolve().then(() => this.displayLocalDates()),
Promise.resolve().then(() => this.setSelectBoxValue()),
2018-03-11 14:43:17 +00:00
Promise.resolve().then(() => this.markPlayingSoundTrack()),
2017-07-14 23:32:06 +00:00
Promise.resolve().then(() => this.assignActions()),
2017-07-17 01:14:05 +00:00
Promise.resolve().then(() => this.updatePushUI()),
2017-10-04 11:39:59 +00:00
Promise.resolve().then(() => this.dragAndDrop()),
2017-07-17 01:14:05 +00:00
Promise.resolve().then(() => this.countUp())
2017-07-14 02:58:21 +00:00
])
2017-07-06 20:08:49 +00:00
2017-07-14 23:32:06 +00:00
// Apply page title
2017-07-06 20:08:49 +00:00
let headers = document.getElementsByTagName("h1")
2017-11-07 08:29:34 +00:00
if(this.app.currentPath === "/" || headers.length === 0 || headers[0].innerText === "NOTIFY.MOE") {
2017-07-06 20:08:49 +00:00
if(document.title !== this.title) {
document.title = this.title
}
} else {
document.title = headers[0].innerText
}
2017-06-29 13:55:04 +00:00
}
async onIdle() {
2017-07-19 03:23:06 +00:00
// Service worker
2017-11-07 08:06:04 +00:00
this.serviceWorkerManager = new ServiceWorkerManager(this, "/service-worker")
2017-10-20 00:43:02 +00:00
this.serviceWorkerManager.register()
2017-07-19 03:23:06 +00:00
// Analytics
2017-10-01 05:50:53 +00:00
if(this.user) {
this.analytics.push()
}
2017-07-15 00:01:14 +00:00
2017-07-19 03:23:06 +00:00
// Offline message
2017-07-15 00:01:14 +00:00
if(navigator.onLine === false) {
this.statusMessage.showError("You are viewing an offline version of the site now.")
}
2018-02-28 15:26:49 +00:00
// Notification manager
if(this.user) {
this.notificationManager.update()
}
// Download popular anime titles for the search
// let response = await fetch("/api/popular/anime/titles/500")
// let titles = await response.json()
// let titleList = document.createElement("datalist")
// titleList.id = "popular-anime-titles-list"
// for(let title of titles) {
// let option = document.createElement("option")
// option.value = title
// titleList.appendChild(option)
// }
// document.body.appendChild(titleList)
// let search = this.app.find("search") as HTMLInputElement
// search.setAttribute("list", titleList.id)
2017-07-13 15:56:14 +00:00
}
2017-10-04 11:39:59 +00:00
dragAndDrop() {
for(let element of findAll("inventory-slot")) {
2017-10-05 07:39:37 +00:00
// Skip elements that have their event listeners attached already
if(element["listeners-attached"]) {
continue
}
2017-10-05 07:54:11 +00:00
element.addEventListener("dragstart", e => {
if(!element.draggable) {
return
}
e.dataTransfer.setData("text", element.dataset.index)
}, false)
element.addEventListener("dblclick", e => {
if(!element.draggable) {
return
}
let itemName = element.title
if(element.dataset.consumable !== "true") {
return this.statusMessage.showError(itemName + " is not a consumable item.")
}
2017-11-09 16:18:15 +00:00
2017-10-05 07:54:11 +00:00
let apiEndpoint = this.findAPIEndpoint(element)
2017-11-09 16:18:15 +00:00
2017-10-05 07:54:11 +00:00
this.post(apiEndpoint + "/use/" + element.dataset.index, "")
.then(() => this.reloadContent())
.then(() => this.statusMessage.showInfo(`You used ${itemName}.`))
.catch(err => this.statusMessage.showError(err))
}, false)
2017-10-04 11:39:59 +00:00
element.addEventListener("dragenter", e => {
element.classList.add("drag-enter")
}, false)
element.addEventListener("dragleave", e => {
element.classList.remove("drag-enter")
}, false)
element.addEventListener("dragover", e => {
e.preventDefault()
}, false)
element.addEventListener("drop", e => {
let toElement = e.toElement as HTMLElement
2017-10-05 07:54:11 +00:00
toElement.classList.remove("drag-enter")
2017-10-04 11:39:59 +00:00
e.stopPropagation()
e.preventDefault()
2017-10-05 07:54:11 +00:00
let inventory = e.toElement.parentElement
let fromIndex = e.dataTransfer.getData("text")
if(!fromIndex) {
return
}
let fromElement = inventory.childNodes[fromIndex] as HTMLElement
2017-11-09 16:18:15 +00:00
2017-10-05 07:54:11 +00:00
let toIndex = toElement.dataset.index
2017-10-04 11:39:59 +00:00
if(fromElement === toElement || fromIndex === toIndex) {
return
}
2017-10-05 07:39:37 +00:00
// Swap in database
let apiEndpoint = this.findAPIEndpoint(inventory)
2017-11-09 16:18:15 +00:00
2017-10-05 07:39:37 +00:00
this.post(apiEndpoint + "/swap/" + fromIndex + "/" + toIndex, "")
.catch(err => this.statusMessage.showError(err))
// Swap in UI
2017-10-04 11:39:59 +00:00
swapElements(fromElement, toElement)
2017-11-09 16:18:15 +00:00
2017-10-04 11:39:59 +00:00
fromElement.dataset.index = toIndex
toElement.dataset.index = fromIndex
}, false)
2017-10-05 07:39:37 +00:00
// Prevent re-attaching the same listeners
element["listeners-attached"] = true
2017-10-04 11:39:59 +00:00
}
}
async updatePushUI() {
2017-11-07 08:13:48 +00:00
if(!this.app.currentPath.includes("/settings/notifications")) {
return
}
let enableButton = this.app.find("enable-notifications") as HTMLButtonElement
let disableButton = this.app.find("disable-notifications") as HTMLButtonElement
2017-11-07 08:18:57 +00:00
let testButton = this.app.find("test-notification") as HTMLButtonElement
2017-11-07 08:13:48 +00:00
if(!this.pushManager.pushSupported) {
2017-11-07 08:18:57 +00:00
enableButton.style.display = "none"
2017-11-07 08:13:48 +00:00
disableButton.style.display = "none"
2017-11-07 08:18:57 +00:00
testButton.innerHTML = "Your browser doesn't support push notifications!"
2017-10-04 11:39:59 +00:00
return
}
2017-11-09 16:18:15 +00:00
2017-10-04 11:39:59 +00:00
let subscription = await this.pushManager.subscription()
if(subscription) {
2017-11-07 08:13:48 +00:00
enableButton.style.display = "none"
disableButton.style.display = "flex"
2017-10-04 11:39:59 +00:00
} else {
2017-11-07 08:13:48 +00:00
enableButton.style.display = "flex"
disableButton.style.display = "none"
2017-10-04 11:39:59 +00:00
}
}
2017-07-17 01:14:05 +00:00
countUp() {
2017-11-10 07:41:45 +00:00
if(!this.app.currentPath.includes("/paypal/success")) {
return
}
2017-07-17 01:14:05 +00:00
for(let element of findAll("count-up")) {
let final = parseInt(element.innerText)
let duration = 2000.0
let start = Date.now()
element.innerText = "0"
let callback = () => {
let progress = (Date.now() - start) / duration
if(progress > 1) {
progress = 1
}
element.innerText = String(Math.round(progress * final))
if(progress < 1) {
window.requestAnimationFrame(callback)
}
}
window.requestAnimationFrame(callback)
}
}
2018-03-11 14:43:17 +00:00
markPlayingSoundTrack() {
for(let element of findAll("soundtrack-play-area")) {
if(element.dataset.soundtrackId === this.currentSoundTrackId) {
element.classList.add("playing")
}
}
}
2017-06-29 13:55:04 +00:00
setSelectBoxValue() {
for(let element of document.getElementsByTagName("select")) {
element.value = element.getAttribute("value")
}
2017-06-29 06:32:46 +00:00
}
displayLocalDates() {
const now = new Date()
2017-07-07 15:16:40 +00:00
for(let element of findAll("utc-airing-date")) {
displayAiringDate(element, now)
}
2017-06-29 06:32:46 +00:00
for(let element of findAll("utc-date")) {
2017-07-07 15:16:40 +00:00
displayDate(element, now)
2017-06-29 06:32:46 +00:00
}
2017-11-22 11:20:57 +00:00
for(let element of findAll("utc-date-absolute")) {
displayTime(element, now)
}
2017-06-24 14:17:38 +00:00
}
2017-07-19 06:45:41 +00:00
reloadContent(cached?: boolean) {
2017-07-19 06:49:38 +00:00
// console.log("reload content", "/_" + this.app.currentPath)
2017-07-19 05:39:09 +00:00
2017-07-13 22:11:25 +00:00
let headers = new Headers()
2017-07-19 06:45:41 +00:00
if(!cached) {
headers.append("X-Reload", "true")
} else {
headers.append("X-CacheOnly", "true")
}
2017-07-13 22:11:25 +00:00
2017-07-13 23:07:49 +00:00
let path = this.app.currentPath
2017-07-19 05:39:09 +00:00
this.lastReloadContentPath = path
2017-07-13 23:07:49 +00:00
2017-07-19 04:55:21 +00:00
return fetch("/_" + path, {
2017-07-13 22:11:25 +00:00
credentials: "same-origin",
headers
})
.then(response => {
2017-07-13 23:07:49 +00:00
if(this.app.currentPath !== path) {
return Promise.reject("old request")
}
return Promise.resolve(response)
2017-06-21 16:44:20 +00:00
})
.then(response => response.text())
.then(html => Diff.innerHTML(this.app.content, html))
2017-06-24 00:10:04 +00:00
.then(() => this.app.emit("DOMContentLoaded"))
2017-06-21 16:44:20 +00:00
}
2017-07-13 22:11:25 +00:00
reloadPage() {
2017-07-19 05:39:09 +00:00
console.log("reload page", this.app.currentPath)
2017-07-19 03:23:06 +00:00
let path = this.app.currentPath
2017-07-19 05:39:09 +00:00
this.lastReloadContentPath = path
2017-07-19 03:23:06 +00:00
return fetch(path, {
2017-07-19 04:32:31 +00:00
credentials: "same-origin"
2017-07-19 03:23:06 +00:00
})
.then(response => {
if(this.app.currentPath !== path) {
return Promise.reject("old request")
}
return Promise.resolve(response)
})
.then(response => response.text())
2017-11-10 07:41:45 +00:00
.then(html => Diff.root(document.documentElement, html))
2017-07-19 03:23:06 +00:00
.then(() => this.app.emit("DOMContentLoaded"))
2017-07-19 03:27:37 +00:00
.then(() => this.loading(false)) // Because our loading element gets reset due to full page diff
2017-07-13 22:11:25 +00:00
}
2017-10-14 10:45:22 +00:00
loading(newState: boolean) {
this.isLoading = newState
if(this.isLoading) {
2017-07-19 07:09:55 +00:00
document.documentElement.style.cursor = "progress"
2017-06-20 10:41:26 +00:00
this.app.loading.classList.remove(this.app.fadeOutClass)
} else {
2017-07-19 07:09:55 +00:00
document.documentElement.style.cursor = "auto"
2017-06-20 10:41:26 +00:00
this.app.loading.classList.add(this.app.fadeOutClass)
}
}
2017-11-09 16:18:15 +00:00
2017-06-26 01:57:29 +00:00
assignActions() {
2017-06-21 13:29:06 +00:00
for(let element of findAll("action")) {
2017-07-08 21:27:24 +00:00
let actionTrigger = element.dataset.trigger
2017-06-20 10:41:26 +00:00
let actionName = element.dataset.action
2017-10-05 19:27:49 +00:00
if(!actionTrigger || !actionName) {
continue
}
2017-07-08 21:27:24 +00:00
let oldAction = element["action assigned"]
if(oldAction) {
if(oldAction.trigger === actionTrigger && oldAction.action === actionName) {
continue
}
element.removeEventListener(oldAction.trigger, oldAction.handler)
}
// This prevents default actions on links
if(actionTrigger === "click" && element.tagName === "A") {
element.onclick = null
}
2017-10-05 11:48:16 +00:00
if(!(actionName in actions)) {
this.statusMessage.showError(`Action '${actionName}' has not been defined`)
2017-10-05 19:27:49 +00:00
continue
2017-10-05 11:48:16 +00:00
}
2017-07-08 21:27:24 +00:00
let actionHandler = e => {
2017-06-20 20:54:45 +00:00
actions[actionName](this, element, e)
2017-06-26 01:57:29 +00:00
e.stopPropagation()
e.preventDefault()
2017-07-08 21:27:24 +00:00
}
element.addEventListener(actionTrigger, actionHandler)
2017-06-20 20:54:45 +00:00
2017-06-24 15:38:10 +00:00
// Use "action assigned" flag instead of removing the class.
// This will make sure that DOM diffs which restore the class name
// will not assign the action multiple times to the same element.
2017-07-08 21:27:24 +00:00
element["action assigned"] = {
trigger: actionTrigger,
action: actionName,
handler: actionHandler
}
2017-06-20 10:41:26 +00:00
}
2017-06-19 15:45:27 +00:00
}
2017-10-12 15:52:46 +00:00
lazyLoad() {
2017-06-24 15:38:10 +00:00
for(let element of findAll("lazy")) {
2017-10-12 15:52:46 +00:00
switch(element.tagName) {
case "IMG":
this.lazyLoadImage(element as HTMLImageElement)
break
2017-11-09 16:18:15 +00:00
2017-10-12 15:52:46 +00:00
case "IFRAME":
this.lazyLoadIFrame(element as HTMLIFrameElement)
break
}
2017-06-24 14:17:38 +00:00
}
}
2017-10-12 15:52:46 +00:00
lazyLoadImage(element: HTMLImageElement) {
2017-06-24 14:17:38 +00:00
// Once the image becomes visible, load it
2017-10-12 15:52:46 +00:00
element["became visible"] = () => {
2017-11-09 17:10:10 +00:00
let dataSrc = element.dataset.src
let dotPos = dataSrc.lastIndexOf(".")
let base = dataSrc.substring(0, dotPos)
2017-11-09 17:10:10 +00:00
let extension = ""
2017-07-08 13:40:13 +00:00
// Replace URL with WebP if supported
2018-03-09 15:08:35 +00:00
if(this.webpEnabled && element.dataset.webp === "true") {
let queryPos = dataSrc.lastIndexOf("?")
if(queryPos !== -1) {
extension = ".webp" + dataSrc.substring(queryPos)
} else {
extension = ".webp"
}
2017-07-08 13:40:13 +00:00
} else {
extension = dataSrc.substring(dotPos)
2017-11-09 17:10:10 +00:00
}
// Anime images on Retina displays
2017-11-09 19:45:27 +00:00
if(base.includes("/anime/") && window.devicePixelRatio > 1) {
2017-11-09 17:10:10 +00:00
base += "@2"
2017-07-08 13:40:13 +00:00
}
2017-06-19 15:45:27 +00:00
2017-11-09 17:10:10 +00:00
element.src = base + extension
2017-10-12 15:52:46 +00:00
if(element.naturalWidth === 0) {
element.onload = () => {
this.elementFound.queue(element)
2017-06-19 15:45:27 +00:00
}
2017-10-12 15:52:46 +00:00
element.onerror = () => {
this.elementNotFound.queue(element)
2017-06-19 15:45:27 +00:00
}
} else {
2017-10-12 15:52:46 +00:00
this.elementFound.queue(element)
}
}
this.visibilityObserver.observe(element)
}
lazyLoadIFrame(element: HTMLIFrameElement) {
// Once the iframe becomes visible, load it
element["became visible"] = () => {
// If the source is already set correctly, don't set it again to avoid iframe flickering.
2017-10-16 09:53:47 +00:00
if(element.src !== element.dataset.src && element.src !== (window.location.protocol + element.dataset.src)) {
2017-10-12 15:52:46 +00:00
element.src = element.dataset.src
2017-06-19 15:45:27 +00:00
}
2017-10-12 15:52:46 +00:00
this.elementFound.queue(element)
2017-06-19 15:45:27 +00:00
}
2017-06-24 14:17:38 +00:00
2017-10-12 15:52:46 +00:00
this.visibilityObserver.observe(element)
2017-06-19 15:45:27 +00:00
}
2017-06-20 12:16:23 +00:00
2017-09-22 04:19:32 +00:00
mountMountables() {
this.modifyDelayed("mountable", element => element.classList.add("mounted"))
}
2017-06-26 01:57:29 +00:00
2017-09-22 04:19:32 +00:00
unmountMountables() {
for(let element of findAll("mountable")) {
if(element.classList.contains("never-unmount")) {
continue
}
2017-07-03 15:21:00 +00:00
2017-09-22 04:19:32 +00:00
this.unmount.queue(element)
}
}
2017-06-26 01:57:29 +00:00
2017-09-22 04:19:32 +00:00
modifyDelayed(className: string, func: (element: HTMLElement) => void) {
const maxDelay = 1000
2017-11-03 17:10:31 +00:00
const delay = 18
2017-11-09 16:18:15 +00:00
2017-09-22 04:19:32 +00:00
let time = 0
let start = Date.now()
let maxTime = start + maxDelay
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
let mountableTypes = new Map<string, number>()
let mountableTypeMutations = new Map<string, Array<any>>()
2017-06-20 18:13:04 +00:00
2017-09-22 04:19:32 +00:00
let collection = document.getElementsByClassName(className)
2017-07-19 11:21:01 +00:00
2017-09-22 04:19:32 +00:00
if(collection.length === 0) {
return
}
2017-07-19 11:21:01 +00:00
2017-09-22 04:19:32 +00:00
// let delay = Math.min(maxDelay / collection.length, 20)
2017-07-19 11:21:01 +00:00
2017-09-22 04:19:32 +00:00
for(let i = 0; i < collection.length; i++) {
let element = collection.item(i) as HTMLElement
2018-03-14 19:35:00 +00:00
// Skip already mounted elements.
// This helps a lot when dealing with infinite scrolling
// where the first elements are already mounted.
if(element.classList.contains("mounted")) {
continue
}
2017-09-22 04:19:32 +00:00
let type = element.dataset.mountableType || "general"
2017-07-02 15:51:17 +00:00
2017-09-22 04:19:32 +00:00
if(mountableTypes.has(type)) {
time = mountableTypes.get(type) + delay
mountableTypes.set(type, time)
} else {
time = start
mountableTypes.set(type, time)
mountableTypeMutations.set(type, [])
}
2017-06-20 18:13:04 +00:00
2017-09-22 04:19:32 +00:00
if(time > maxTime) {
time = maxTime
}
2017-07-06 01:24:56 +00:00
2017-09-22 04:19:32 +00:00
mountableTypeMutations.get(type).push({
element,
time
})
}
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
for(let mountableType of mountableTypeMutations.keys()) {
let mutations = mountableTypeMutations.get(mountableType)
let mutationIndex = 0
2017-07-20 12:26:43 +00:00
2017-09-22 04:19:32 +00:00
let updateBatch = () => {
let now = Date.now()
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
for(; mutationIndex < mutations.length; mutationIndex++) {
let mutation = mutations[mutationIndex]
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
if(mutation.time > now) {
break
}
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
func(mutation.element)
}
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
if(mutationIndex < mutations.length) {
window.requestAnimationFrame(updateBatch)
}
}
2017-07-05 13:29:18 +00:00
2017-09-22 04:19:32 +00:00
window.requestAnimationFrame(updateBatch)
}
}
2017-06-20 18:13:04 +00:00
2017-06-27 02:15:52 +00:00
diff(url: string) {
2017-07-13 23:50:10 +00:00
if(url === this.app.currentPath) {
2017-07-06 01:24:56 +00:00
return Promise.reject(null)
2017-07-03 15:21:00 +00:00
}
2017-07-19 04:32:31 +00:00
let path = "/_" + url
let request = fetch(path, {
credentials: "same-origin"
})
2017-11-10 07:41:45 +00:00
.then(response => response.text())
2017-11-09 16:18:15 +00:00
2017-06-26 17:03:48 +00:00
history.pushState(url, null, url)
this.app.currentPath = url
this.app.markActiveLinks()
2017-09-22 04:19:32 +00:00
this.unmountMountables()
this.loading(true)
2017-06-26 17:03:48 +00:00
2017-06-29 14:49:26 +00:00
// Delay by transition-speed
2018-03-06 23:36:04 +00:00
return delay(150).then(() => request)
2017-11-10 07:41:45 +00:00
.then(html => Diff.innerHTML(this.app.content, html))
2017-07-22 13:04:54 +00:00
.then(() => this.app.emit("DOMContentLoaded"))
.then(() => this.loading(false))
.catch(console.error)
2017-06-26 17:03:48 +00:00
}
2017-10-13 11:55:33 +00:00
post(url: string, body: any) {
2017-10-14 10:45:22 +00:00
if(this.isLoading) {
2017-10-15 18:19:45 +00:00
return Promise.resolve(null)
2017-10-14 10:45:22 +00:00
}
2017-07-21 08:10:48 +00:00
if(typeof body !== "string") {
body = JSON.stringify(body)
}
this.loading(true)
2017-06-27 02:15:52 +00:00
return fetch(url, {
method: "POST",
2017-07-21 08:10:48 +00:00
body,
2017-06-27 02:15:52 +00:00
credentials: "same-origin"
})
2017-10-15 18:19:45 +00:00
.then(response => {
2017-07-21 08:10:48 +00:00
this.loading(false)
2017-10-15 18:19:45 +00:00
if(response.status === 200) {
return Promise.resolve(response)
2017-06-27 02:15:52 +00:00
}
2017-10-15 18:19:45 +00:00
return response.text().then(err => {
throw err
})
2017-06-27 02:15:52 +00:00
})
2017-07-21 08:10:48 +00:00
.catch(err => {
this.loading(false)
throw err
})
2017-06-27 02:15:52 +00:00
}
2017-07-06 14:54:10 +00:00
scrollTo(target: HTMLElement) {
const duration = 250.0
const steps = 60
const interval = duration / steps
const fullSin = Math.PI / 2
const contentPadding = 24
2017-11-09 16:18:15 +00:00
2017-07-06 14:54:10 +00:00
let scrollHandle: number
let newScroll = 0
let finalScroll = Math.max(target.offsetTop - contentPadding, 0)
2017-11-10 07:41:45 +00:00
// Calculating scrollTop will force a layout - careful!
let oldScroll = this.app.content.parentElement.scrollTop
2017-07-06 14:54:10 +00:00
let scrollDistance = finalScroll - oldScroll
2017-09-22 15:23:22 +00:00
if(scrollDistance > 0 && scrollDistance < 4) {
return
}
2017-07-06 14:54:10 +00:00
let timeStart = Date.now()
let timeEnd = timeStart + duration
let scroll = () => {
let time = Date.now()
let progress = (time - timeStart) / duration
if(progress > 1.0) {
progress = 1.0
}
newScroll = oldScroll + scrollDistance * Math.sin(progress * fullSin)
this.app.content.parentElement.scrollTop = newScroll
if(time < timeEnd && newScroll != finalScroll) {
window.requestAnimationFrame(scroll)
}
}
window.requestAnimationFrame(scroll)
}
findAPIEndpoint(element: HTMLElement) {
2017-10-05 07:39:37 +00:00
if(element.dataset.api !== undefined) {
return element.dataset.api
}
2017-07-06 14:54:10 +00:00
let apiObject: HTMLElement
let parent = element
while(parent = parent.parentElement) {
if(parent.dataset.api !== undefined) {
apiObject = parent
break
}
}
if(!apiObject) {
throw "API object not found"
}
return apiObject.dataset.api
}
2017-06-21 12:00:52 +00:00
onPopState(e: PopStateEvent) {
if(e.state) {
this.app.load(e.state, {
addToHistory: false
})
} else if(this.app.currentPath !== this.app.originalPath) {
this.app.load(this.app.originalPath, {
addToHistory: false
})
}
}
onKeyDown(e: KeyboardEvent) {
2017-06-30 21:52:42 +00:00
let activeElement = document.activeElement
2017-06-24 14:41:22 +00:00
// Ignore hotkeys on input elements
2017-06-30 21:52:42 +00:00
switch(activeElement.tagName) {
2017-06-24 14:41:22 +00:00
case "INPUT":
case "TEXTAREA":
return
}
2017-10-12 15:52:46 +00:00
// Ignore hotkeys on contentEditable elements
if(activeElement.getAttribute("contenteditable") === "true") {
// Disallow Enter key in contenteditables and make it blur the element instead
if(e.keyCode == 13) {
if("blur" in activeElement) {
activeElement["blur"]()
}
2017-11-09 16:18:15 +00:00
2017-10-12 15:52:46 +00:00
e.preventDefault()
e.stopPropagation()
2017-06-30 21:52:42 +00:00
}
2017-11-09 16:18:15 +00:00
2017-06-30 21:52:42 +00:00
return
}
2018-03-07 13:52:56 +00:00
// "F" = Search
2017-07-04 14:13:20 +00:00
if(e.keyCode == 70 && !e.ctrlKey) {
2017-06-21 12:00:52 +00:00
let search = this.app.find("search") as HTMLInputElement
search.focus()
search.select()
e.preventDefault()
e.stopPropagation()
2017-06-30 21:52:42 +00:00
return
2017-06-21 12:00:52 +00:00
}
2017-10-17 16:16:44 +00:00
2018-03-07 13:52:56 +00:00
// "S" = Toggle sidebar
if(e.keyCode == 83 && !e.ctrlKey) {
this.sideBar.toggle()
e.preventDefault()
e.stopPropagation()
return
}
// "Ctrl" + "," = Settings
2017-10-17 16:16:44 +00:00
if(e.ctrlKey && e.keyCode == 188) {
this.app.load("/settings")
e.preventDefault()
e.stopPropagation()
return
}
2017-06-21 12:00:52 +00:00
}
2017-06-19 14:49:24 +00:00
}