« get me outta code hell

mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--backend.js26
-rw-r--r--ui.js12
2 files changed, 27 insertions, 11 deletions
diff --git a/backend.js b/backend.js
index 23a9309..b8071d1 100644
--- a/backend.js
+++ b/backend.js
@@ -9,6 +9,7 @@ const { getPlayer } = require('./players')
 const RecordStore = require('./record-store')
 
 const {
+  getTimeStringsFromSec,
   shuffleArray,
   throttlePromise
 } = require('./general-util')
@@ -518,6 +519,31 @@ class Backend extends EventEmitter {
     }
   }
 
+  getDuration(item) {
+    let noticedMissingMetadata = false
+
+    const durationFn = (acc, track) => {
+      const metadata = this.getMetadataFor(track)
+      if (!metadata) noticedMissingMetadata = true
+      return acc + (metadata && metadata.duration) || 0
+    }
+
+    let items
+    if (isGroup(item)) {
+      items = flattenGrouplike(item).items
+    } else {
+      items = [item]
+    }
+
+    const seconds = items.reduce(durationFn, 0)
+
+    let { duration: string } = getTimeStringsFromSec(0, seconds)
+    const approxSymbol = noticedMissingMetadata ? '+' : ''
+    string += approxSymbol
+
+    return {seconds, string, noticedMissingMetadata, approxSymbol}
+  }
+
   async download(item) {
     if (isGroup(item)) {
       // TODO: Download all children (recursively), show a confirmation prompt
diff --git a/ui.js b/ui.js
index bdb5711..fa29fd6 100644
--- a/ui.js
+++ b/ui.js
@@ -1013,14 +1013,6 @@ class AppElement extends FocusElement {
     const { playingTrack } = this.backend
     const { items } = this.backend.queueGrouplike
 
-    let noticedMissingMetadata = false
-
-    const durationFn = (acc, track) => {
-      const metadata = this.backend.getMetadataFor(track)
-      if (!metadata) noticedMissingMetadata = true
-      return acc + (metadata && metadata.duration) || 0
-    }
-
     let trackRemainSec = 0
 
     if (playingTrack) {
@@ -1045,8 +1037,7 @@ class AppElement extends FocusElement {
       }
     }
 
-    const aheadRemainSec = items.slice(index).reduce(durationFn, 0)
-
+    const { seconds: aheadRemainSec, approxSymbol } = this.backend.getDuration({items: items.slice(index)})
     const totalRemainSec = trackRemainSec + aheadRemainSec
 
     const { duration } = getTimeStringsFromSec(0, totalRemainSec)
@@ -1055,7 +1046,6 @@ class AppElement extends FocusElement {
       ? `(${this.playSymbol} ${index} / ${items.length})`
       : `(${items.length})`)
 
-    const approxSymbol = noticedMissingMetadata ? '+' : ''
     this.queueTimeLabel.text = `(${duration + approxSymbol})`
 
     this.queueLengthLabel.centerInParent()