Compare commits

...
Author SHA1 Message Date
rootandClaude Opus 5.5 5c87b19085 Soften app icon glow (build 66)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:48:41 -08:00
rootandClaude Opus 5.5 ac363ea0f7 Cover cropper with zoom and output size for both playlist types, lyrics Vocals/Softness turn karaoke on (build 65)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:44:16 -08:00
rootandClaude Opus 5.5 b10528d69c Playlist pages: header rides up into the empty nav bar, bar title hidden (build 64)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:39:43 -08:00
rootandClaude Opus 5.5 42f5eddb36 Stem playlists: sorting, rename/cover/mix/copy to Plex in long-press menu (build 63)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:34:51 -08:00
rootandClaude Opus 5.5 7f4a07d846 Playlist delete in long-press menu, empty playlists, Edit Songs moved to ••• (build 62)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:31:55 -08:00
rootandClaude Opus 5.5 29cc9a03d4 Random Album Radio: every new song adds another album, continuous queue (build 61)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:35:06 -08:00
rootandClaude Opus 5.5 592f623bc2 Plex/Jellyfin playlists: rename and custom cover from the long-press menu (build 60)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:10:23 -08:00
rootandClaude Opus 5.5 3ec9b043e3 Now Playing close drag: hold 120 Hz while dragging (build 59)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:04:11 -08:00
rootandClaude Opus 5.5 cd5a083523 iOS: Now Playing close drag tracks the finger 1:1 (global space) and only re-renders the offset (DropState/DropOffset); build 58
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:59:04 -08:00
rootandClaude Opus 5.5 6606e4d437 iOS: folded, drag down on the album art closes Now Playing (art panel only, not over stem dials); build 57
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:55:28 -08:00
rootandClaude Opus 5.5 d6ba09f14b iOS: folded resume slides Now Playing up (animated) instead of presenting it in the background; build 56
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:50:18 -08:00
rootandClaude Opus 5.5 5959c8a347 iOS: folded Duo opens Now Playing (no animation) when leaving while playing, so it returns on it; build 55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:41:37 -08:00
rootandClaude Opus 5.5 1604a6b3e3 iOS: Duo orientation strict (folded portrait, unfolded landscape, never free), lock changes only after hinge reading holds 450 ms, orient log; build 54
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:38:58 -08:00
rootandClaude Opus 5.5 7dddc25656 iOS: folded Duo keeps portrait lock in background (no landscape flash on reopen while playing); build 53
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:33:39 -08:00
rootandClaude Opus 5.5 452ed6f362 Web: bigger drawer tab titles, equal-width tabs, one drawer width
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:25:59 -08:00
rootandClaude Opus 5.5 536de29e4d Web: keep real playlist art in downloads, hide quota on HTTPS
The group art fetch now falls back to the raw composite when the Plex
transcode fails, and the Downloads card uses any stored group art.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:32:38 -08:00
rootandClaude Opus 5.5 0ef4c650d1 Web: Plex playlist editing, offline art, glass search, NO STEMS tag, artist header fix
- Edit/Rename/Delete on Plex playlists, drag-to-reorder edit mode with the iOS
  remove-then-move-after commit, Remove from playlist, Add to Plex playlists
- Downloads store art blobs with each song and group so it shows offline
- Search box gets a tinted glass blur
- NO STEMS tag restyled and aligned in rows and cards
- Albums header on the artist page no longer overlaps the play button

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:29:03 -08:00
rootandClaude Opus 5.5 3ecfdaa73b web: iOS-style Downloads sections, accent fill on the volume slider
Downloads now groups into Playlists, Albums and Artists card grids plus
Other Songs, with Play/Shuffle up top and a right-click menu per card
(play, queue, remove download). The volume track fills with the accent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:11:41 -08:00
rootandClaude Opus 5.5 d30479c6f7 web: S opens universal search, sort menu, iOS-style appearance, centered play icon
- Sidebar search box replaced by a blurred overlay (S or /, Shift+S shuffles): songs,
  artists, albums, Plex and stem playlists across every enabled server, arrow keys + Enter
- Sort select + flip chip replaced by one button with a checked menu (fields, directions)
- Themes are now Black/Dark/White with the iOS accent colors; old presets migrate
- Play triangle recentered, per-button nudges removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:03:51 -08:00
root 11dffdf9e6 iOS source.json for ios-v0.10.1 2026-11-20 12:25:59 -08:00
rootandClaude Opus 5.5 a8742e7e3d Folded art-left: art's left edge matches the controls' padding
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:25:54 -08:00
root ce6bce4018 iOS source.json for ios-v0.10.1 2026-11-20 12:19:26 -08:00
rootandClaude Opus 5.5 4860db6f6c Duo wide Now Playing: art matches the controls' height
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:19:12 -08:00
root 4c1956d569 iOS source.json for ios-v0.10.1 2026-11-20 10:42:45 -08:00
rootandClaude Opus 5.5 ed0fd1d184 iOS: bigger art in wide panes, Duo Split View player sits lower; build 50
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:39:40 -08:00
root 55f8574eaa iOS source.json for ios-v0.10.1 2026-11-20 10:33:03 -08:00
rootandClaude Opus 5.5 07b5636bac iOS: full-screen Now Playing watches the hinge so unfolding goes landscape; build 49
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:30:00 -08:00
root 88d3aa48e7 iOS source.json for ios-v0.10.1 2026-11-20 10:23:12 -08:00
rootandClaude Opus 5.5 d6da47db9d iOS: only the on-screen Duo pane reports split/unfolded; build 48
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:20:09 -08:00
root 4dfcfbf434 iOS source.json for ios-v0.10.1 2026-11-20 10:17:11 -08:00
rootandClaude Opus 5.5 56c92e8b93 iOS: free orientation in background, re-lock after resume settles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:14:59 -08:00
root 639b5368ff iOS source.json for ios-v0.10.1 2026-11-20 10:10:17 -08:00
rootandClaude Opus 5.5 cfaedd06cf iOS 0.10.1 (build 47)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:08:08 -08:00
28 changed files with 1005 additions and 227 deletions

No files matched your search

+30 -10
View File
@@ -219,11 +219,19 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
@ObservationIgnored private var stationGen = 0
@ObservationIgnored private var stationBusy = false
private static let radioAlbumsAhead = 8
private static let radioAlbumsLow = 3
/// Each new song adds an album, up to this many ahead (keeps the queue from growing without end).
private static let radioAlbumsMax = 40
/// Album radio: the song the last top-up saw, and songs started since that haven't added their album yet.
@ObservationIgnored private var radioSeenUid: Int64?
@ObservationIgnored private var radioOwed = 0
private static let radioSongsBatch = 100
private static let radioSongsLow = 25
private func setStation(_ s: Station?) { station = s; stationGen += 1; stationBusy = false }
private func setStation(_ s: Station?) {
station = s; stationGen += 1; stationBusy = false
radioSeenUid = queue.indices.contains(index) ? queue[index].uid : nil
radioOwed = 0
}
private func albumDeck() async throws -> [String] {
var deck = (try? await plex.albums().map(\.ratingKey)) ?? []
@@ -268,18 +276,28 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
let gen = stationGen
switch st {
case .albums(let saved):
// Every song that starts (the next track, a skip, a jump to another album) owes one more album,
// so the queue always runs on past what's playing.
let uid = queue[index].uid
if uid != radioSeenUid { radioSeenUid = uid; radioOwed += 1 }
let ahead = Set(queue[index...].map { $0.track.albumKey ?? $0.track.album }).count
guard ahead <= Self.radioAlbumsLow else { return }
let want = min(max(Self.radioAlbumsAhead + 1 - ahead, radioOwed), Self.radioAlbumsMax - ahead)
guard want > 0 else { radioOwed = 0; return }
stationBusy = true
let owed = radioOwed
Task { @MainActor in
defer { if gen == stationGen { stationBusy = false } }
var got = false
// Checks again once the albums are in, unless nothing came back (server down: don't spin).
defer { if gen == stationGen { stationBusy = false; if got { topUpStation() } } }
var deck = saved
if deck.isEmpty { deck = (try? await albumDeck()) ?? [] }
let take = Array(deck.prefix(Self.radioAlbumsAhead + 1 - ahead))
if deck.count < want { deck += (try? await albumDeck()) ?? [] }
let take = Array(deck.prefix(want))
deck.removeFirst(take.count)
let tracks = await albumTracks(take)
guard gen == stationGen else { return }
station = .albums(deck)
radioOwed = max(radioOwed - owed, 0)
got = !tracks.isEmpty
addToQueue(tracks)
}
case .songs:
@@ -563,14 +581,16 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
var karaokeVocals: KaraokeVocals { KaraokeVocals(rawValue: settings.karaokeVocals) ?? .Off }
func setKaraokeVocals(_ v: KaraokeVocals) {
/// [engage] (from the lyrics panel) turns karaoke on, so the choice is heard even if lyrics were opened without it.
func setKaraokeVocals(_ v: KaraokeVocals, engage: Bool = false) {
settings.karaokeVocals = v.rawValue
if karaoke { applyMix(karaokeMix) }
if karaoke { applyMix(karaokeMix) } else if engage { setKaraoke(true) }
}
func setKaraokeSoftDb(_ db: Int) {
func setKaraokeSoftDb(_ db: Int, engage: Bool = false) {
settings.karaokeSoftDb = db
if karaoke && karaokeVocals == .Soft { applyMix(karaokeMix) }
guard karaokeVocals == .Soft else { return }
if karaoke { applyMix(karaokeMix) } else if engage { setKaraoke(true) }
}
/// Turning it off puts back the song's saved mix, or the one from before, unless the mix was changed meanwhile.
+10 -4
View File
@@ -88,15 +88,21 @@ final class StemPlaylists {
/// Saves [data] (any image format Photos hands over) as the list's cover, scaled to 1200 px.
/// Each pick gets a new file name so cached art doesn't show the old one.
@discardableResult
func setPhotoArt(_ id: String, _ data: Data) -> Bool {
guard let img = UIImage(data: data) else { return false }
let side: CGFloat = 1200
/// A picked photo as a JPEG no bigger than 2000 px a side. The cropper's JPEGs pass through as they are.
static func coverJpeg(_ data: Data) -> Data? {
guard let img = UIImage(data: data) else { return nil }
let side: CGFloat = 2000
if data.starts(with: [0xFF, 0xD8]), max(img.size.width, img.size.height) <= side { return data }
let scale = min(1, side / max(img.size.width, img.size.height, 1))
let size = CGSize(width: (img.size.width * scale).rounded(), height: (img.size.height * scale).rounded())
let fmt = UIGraphicsImageRendererFormat.default(); fmt.scale = 1
let jpeg = UIGraphicsImageRenderer(size: size, format: fmt).jpegData(withCompressionQuality: 0.85) { _ in
return UIGraphicsImageRenderer(size: size, format: fmt).jpegData(withCompressionQuality: 0.85) { _ in
img.draw(in: CGRect(origin: .zero, size: size))
}
}
func setPhotoArt(_ id: String, _ data: Data) -> Bool {
guard let jpeg = Self.coverJpeg(data) else { return false }
let name = "\(id)-\(UUID().uuidString.prefix(8).lowercased()).jpg"
do {
try FileManager.default.createDirectory(at: Self.artDir, withIntermediateDirectories: true)
+14 -3
View File
@@ -80,7 +80,8 @@ struct JItem: Decodable {
func toArtist() -> Artist { Artist(ratingKey: id, title: name, sortTitle: sortName ?? name, thumb: thumb) }
func toPlaylist() -> Playlist {
Playlist(ratingKey: id, title: name, thumb: thumb, trackCount: childCount ?? 0, durationMs: durationMs)
// "id|tag": a new cover changes the tag, so the art cache doesn't keep the old one.
Playlist(ratingKey: id, title: name, thumb: primaryTag.map { "\(id)|\($0)" } ?? thumb, trackCount: childCount ?? 0, durationMs: durationMs)
}
}
@@ -414,6 +415,15 @@ final class JellyfinClient: MediaSource, @unchecked Sendable {
try await send("DELETE", "/Items/\(key)")
}
/// Jellyfin wants the image base64 encoded in the body.
func setPlaylistArt(_ key: String, jpeg: Data) async throws {
guard server.signedIn else { throw NotSignedIn() }
var req = request(try url("/Items/\(key)/Images/Primary"), method: "POST")
req.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
req.httpBody = jpeg.base64EncodedData()
_ = try await http.data(req)
}
// ---- playback reporting ----------------------------------------------------------------
func scrobble(_ trackKey: String) async {
@@ -431,8 +441,9 @@ final class JellyfinClient: MediaSource, @unchecked Sendable {
// ---- URLs ---------------------------------------------------------------------------
func artUrl(_ thumb: String?, px: Int) -> URL? {
guard let thumb, !thumb.isEmpty, server.signedIn, let u = URL(string: base + "/Items/\(thumb)/Images/Primary") else { return nil }
return u.with([("fillWidth", px), ("fillHeight", px), ("quality", 90), ("api_key", server.token)])
let parts = thumb?.split(separator: "|", maxSplits: 1).map(String.init) ?? []
guard let id = parts.first, !id.isEmpty, server.signedIn, let u = URL(string: base + "/Items/\(id)/Images/Primary") else { return nil }
return u.with([("fillWidth", px), ("fillHeight", px), ("quality", 90), ("tag", parts.count > 1 ? parts[1] : nil), ("api_key", server.token)])
}
/// The original file, untouched, like Plex's part URL.
+2
View File
@@ -55,6 +55,8 @@ protocol MediaSource: AnyObject, Sendable {
func removeFromPlaylist(_ key: String, playlistItemId: Int64) async throws
func movePlaylistItem(_ key: String, playlistItemId: Int64, afterItemId: Int64?) async throws
func renamePlaylist(_ key: String, title: String) async throws
/// Uploads [jpeg] as the playlist's cover.
func setPlaylistArt(_ key: String, jpeg: Data) async throws
func deletePlaylist(_ key: String) async throws
func scrobble(_ trackKey: String) async
func timeline(_ track: Track, state: String, positionMs: Int64) async
+17
View File
@@ -201,6 +201,16 @@ final class PlexClient: @unchecked Sendable {
}
/// Made on the server of the first song; songs from other servers are left out.
/// Servers a new playlist can live on, as (id, name).
var playlistServers: [(String, String)] { sources.map { ($0.server.id, $0.server.name) } }
/// An empty playlist on one server (the only one when [serverId] is nil).
func createEmptyPlaylist(_ title: String, serverId: String?) async throws -> Playlist? {
let list = sources
guard let s = list.first(where: { $0.server.id == serverId }) ?? list.first else { throw NotSignedIn() }
return try await s.createPlaylist(title, trackKeys: [])?.tagged(s.server.id)
}
func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? {
guard let first = trackKeys.first else { return nil }
let (s, _) = try routed(first)
@@ -235,6 +245,13 @@ final class PlexClient: @unchecked Sendable {
try await s.deletePlaylist(k)
}
/// Uploads the cover, then returns the playlist's new thumb.
func setPlaylistArt(_ key: String, jpeg: Data) async throws -> String? {
let (s, k) = try routed(key)
try await s.setPlaylistArt(k, jpeg: jpeg)
return try await s.playlists(sort: "titleSort").first { $0.ratingKey == k }?.thumb.tagged(s.server.id)
}
// ---- playback reporting ---------------------------------------------------------
func scrobble(_ trackKey: String) async {
+12 -1
View File
@@ -266,7 +266,9 @@ final class PlexServer: MediaSource, @unchecked Sendable {
}
func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? {
let uri = try await libraryUri(trackKeys)
// No songs: a bare library uri makes an empty playlist (newer Plex servers allow it).
if trackKeys.isEmpty, machine.isEmpty { machine = try await machineId() }
let uri = trackKeys.isEmpty ? "server://\(machine)/com.plexapp.plugins.library" : try await libraryUri(trackKeys)
return try await send("POST", "/playlists", [("type", "audio"), ("title", title), ("smart", 0), ("uri", uri)])
.metadata.first?.toPlaylist()
}
@@ -293,6 +295,15 @@ final class PlexServer: MediaSource, @unchecked Sendable {
try await send("DELETE", "/playlists/\(key)")
}
/// Plex takes the image as the raw body and selects it as the poster.
func setPlaylistArt(_ key: String, jpeg: Data) async throws {
guard signedIn else { throw NotSignedIn() }
var req = request(try url("/library/metadata/\(key)/posters"), method: "POST")
req.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
req.httpBody = jpeg
_ = try await http.data(req)
}
// ---- playback reporting ---------------------------------------------------------
func scrobble(_ trackKey: String) async {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 228 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 192 KiB

+3
View File
@@ -315,11 +315,14 @@ struct HingeEdge: ViewModifier {
struct Page<Content: View>: View {
let title: String
var large = true
/// Moves the content up into an empty nav bar.
var pullUp: CGFloat = 0
@ViewBuilder let content: () -> Content
@Environment(\.palette) private var p
var body: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) { content() }
.padding(.top, -pullUp)
.padding(.bottom, 24)
}
.modifier(HingeEdge())
@@ -0,0 +1,149 @@
import SwiftUI
import UIKit
/// Square crop for a playlist cover: pinch or slide to zoom, drag to place, pick the saved size.
struct CoverCropper: View {
let image: UIImage
let done: (Data?) -> Void
@State private var zoom: CGFloat = 1
@State private var offset: CGSize = .zero
@State private var dragStart: CGSize?
@State private var zoomStart: CGFloat?
@State private var side: CGFloat = 1
@State private var saving = false
@AppStorage("coverCropSize") private var outSize = 1200
private static let sizes = [(600, "Small"), (1200, "Medium"), (2000, "Large")]
private let maxZoom: CGFloat = 6
var body: some View {
NavigationStack {
VStack(spacing: 0) {
GeometryReader { geo in
let s = max(1, min(geo.size.width, geo.size.height) - 32)
ZStack {
Color.black
Image(uiImage: image)
.resizable()
.frame(width: shown(s).width, height: shown(s).height)
.offset(offset)
CropMask(side: s).allowsHitTesting(false)
}
.frame(width: geo.size.width, height: geo.size.height)
.contentShape(Rectangle())
.gesture(drag(s).simultaneously(with: pinch(s)))
.onAppear { side = s }
.onChange(of: s) { _, v in side = v; clamp(v) }
}
.clipped()
controls
}
.background(Color.black)
.navigationTitle("Crop Cover")
.navigationBarTitleDisplayMode(.inline)
.toolbarColorScheme(.dark, for: .navigationBar)
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
ToolbarItem(placement: .confirmationAction) {
if saving { ProgressView() } else { Button("Apply") { apply() }.bold() }
}
}
}
.preferredColorScheme(.dark)
}
private var controls: some View {
VStack(spacing: 14) {
HStack(spacing: 12) {
Image(systemName: "minus.magnifyingglass").foregroundStyle(.secondary)
Slider(value: Binding(get: { zoom }, set: { zoom = $0; clamp(side) }), in: 1...maxZoom)
Image(systemName: "plus.magnifyingglass").foregroundStyle(.secondary)
}
Picker("Size", selection: $outSize) {
ForEach(Self.sizes, id: \.0) { Text($0.1).tag($0.0) }
}
.pickerStyle(.segmented)
Text("\(outSize) × \(outSize) px").font(.caption).monospacedDigit().foregroundStyle(.secondary)
Button("Reset") { withAnimation(.snappy(duration: 0.2)) { zoom = 1; offset = .zero } }
.font(.subheadline)
}
.padding(.horizontal, 24).padding(.top, 12).padding(.bottom, 20)
}
/// The image's on-screen size: filling the square at zoom 1.
private func shown(_ s: CGFloat) -> CGSize {
let w = max(image.size.width, 1), h = max(image.size.height, 1)
let k = s / min(w, h) * zoom
return CGSize(width: w * k, height: h * k)
}
/// Keeps the square covered by the image.
private func clamp(_ s: CGFloat) {
let d = shown(s)
let mx = max(0, (d.width - s) / 2), my = max(0, (d.height - s) / 2)
offset = CGSize(width: min(max(offset.width, -mx), mx), height: min(max(offset.height, -my), my))
}
private func drag(_ s: CGFloat) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { v in
let start = dragStart ?? offset
if dragStart == nil { dragStart = start }
offset = CGSize(width: start.width + v.translation.width, height: start.height + v.translation.height)
clamp(s)
}
.onEnded { _ in dragStart = nil }
}
private func pinch(_ s: CGFloat) -> some Gesture {
MagnifyGesture()
.onChanged { v in
let start = zoomStart ?? zoom
if zoomStart == nil { zoomStart = start }
zoom = min(max(start * v.magnification, 1), maxZoom)
clamp(s)
}
.onEnded { _ in zoomStart = nil }
}
private func apply() {
let s = side
let d = shown(s)
let k = d.width / max(image.size.width, 1) // screen points per image point
// The square's top-left and side, in image points.
let x0 = (d.width / 2 - s / 2 - offset.width) / k
let y0 = (d.height / 2 - s / 2 - offset.height) / k
let crop = CGRect(x: x0, y: y0, width: s / k, height: s / k)
let img = image
let out = CGFloat(outSize)
saving = true
Task {
let data = await Task.detached(priority: .userInitiated) { CoverCropper.render(img, crop, out) }.value
saving = false
done(data)
}
}
nonisolated static func render(_ img: UIImage, _ crop: CGRect, _ out: CGFloat) -> Data? {
let f = out / max(crop.width, 1)
let fmt = UIGraphicsImageRendererFormat.default(); fmt.scale = 1; fmt.opaque = true
return UIGraphicsImageRenderer(size: CGSize(width: out, height: out), format: fmt).jpegData(withCompressionQuality: 0.85) { _ in
img.draw(in: CGRect(x: -crop.minX * f, y: -crop.minY * f, width: img.size.width * f, height: img.size.height * f))
}
}
}
/// Dims everything outside the centered square and outlines it.
private struct CropMask: View {
let side: CGFloat
var body: some View {
GeometryReader { geo in
let r = CGRect(x: (geo.size.width - side) / 2, y: (geo.size.height - side) / 2, width: side, height: side)
Path { p in p.addRect(CGRect(origin: .zero, size: geo.size)); p.addRect(r) }
.fill(Color.black.opacity(0.55), style: FillStyle(eoFill: true))
Rectangle().stroke(Color.white.opacity(0.9), lineWidth: 1)
.frame(width: side, height: side).position(x: r.midX, y: r.midY)
}
}
}
+101 -17
View File
@@ -54,14 +54,68 @@ struct MediaMenu {
playlistKey: nil, extra: [], confirmDownload: true, stemmed: stemmed(cov))
}
func playlist(_ pl: Playlist, extra: [SheetAction] = []) -> [SheetAction] {
/// [changed] hears the playlist after a rename or a new cover, so an open page can follow; [deleted] after a delete.
func playlist(_ pl: Playlist, extra: [SheetAction] = [], changed: ((Playlist) -> Void)? = nil, deleted: (() -> Void)? = nil) -> [SheetAction] {
let plex = g.plex
let copy = SheetAction("Copy to Stem Playlist…", icon: "doc.on.doc") { copyToStems(pl) }
let gr = DownloadGroup(kind: .playlist, key: pl.ratingKey, title: pl.title, subtitle: "Playlist", thumb: pl.thumb)
return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey, extra: [copy] + extra,
return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey,
extra: [copy] + (pl.smart ? [] : playlistEdits(pl, changed)) + extra + [delete(pl, deleted)],
confirmDownload: pl.trackCount > 50)
}
/// Rename and Change Cover, saved on the playlist's own server (Plex or Jellyfin).
private func playlistEdits(_ pl: Playlist, _ changed: ((Playlist) -> Void)?) -> [SheetAction] {
let plex = g.plex
let overlays = overlays
let ui = ui
let rename = SheetAction("Rename…", icon: "pencil") {
overlays.prompt("Rename Playlist", nil, initial: pl.title, "Save") { name in
Task {
do {
try await plex.renamePlaylist(pl.ratingKey, title: name)
var p = pl; p.title = name
ui.playlistEdits += 1
changed?(p)
} catch { overlays.hud("Couldn't rename: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
let cover = SheetAction("Change Cover…", icon: "photo") {
overlays.pickPhoto { data in
guard let jpeg = StemPlaylists.coverJpeg(data) else { overlays.hud("Couldn't use that photo", "exclamationmark.triangle"); return }
Task {
do {
let thumb = try await plex.setPlaylistArt(pl.ratingKey, jpeg: jpeg)
var p = pl; p.thumb = thumb ?? pl.thumb
ui.playlistEdits += 1
changed?(p)
overlays.hud("Cover updated")
} catch { overlays.hud("Couldn't upload: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
return [rename, cover]
}
private func delete(_ pl: Playlist, _ deleted: (() -> Void)?) -> SheetAction {
let plex = g.plex
let overlays = overlays
let ui = ui
return SheetAction("Delete Playlist…", icon: "trash", destructive: true) {
overlays.confirm("Delete “\(pl.title)”?", "This removes it from the server for every app.", "Delete") {
Task {
do {
try await plex.deletePlaylist(pl.ratingKey)
ui.playlistEdits += 1
overlays.hud("Deleted “\(pl.title)”", "trash")
deleted?()
} catch { overlays.hud("Couldn't delete: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
}
func stemPlaylist(_ pl: StemPlaylist, extra: [SheetAction] = [], onPage: Bool = false) -> [SheetAction] {
var a = [
SheetAction("Play Next", icon: "text.line.first.and.arrowtriangle.forward") {
@@ -75,23 +129,30 @@ struct MediaMenu {
{ pl.tracks }, confirm: false)
if pl.items.isEmpty { a = [] }
let lists = g.stemPlaylists
a.append(SheetAction("Rename…", icon: "pencil") {
overlays.prompt("Rename Stem Playlist", nil, initial: pl.title, "Save") { lists.rename(pl.id, $0) }
})
a.append(SheetAction("Change Cover…", icon: "photo") {
var seen = Set<String>()
var acts: [SheetAction] = [
SheetAction("Choose from Photos…", icon: "photo.on.rectangle") {
overlays.pickPhoto { data in
if !lists.setPhotoArt(pl.id, data) { overlays.hud("Couldn't use that photo", "exclamationmark.triangle") }
}
},
SheetAction("Automatic", icon: "wand.and.stars") { lists.setArt(pl.id, nil) },
]
for t in pl.tracks {
guard let th = t.thumb, seen.insert(th).inserted, seen.count <= 20 else { continue }
acts.append(SheetAction(t.album, icon: th == pl.artThumb ? "checkmark" : "photo") { lists.setArt(pl.id, th) })
}
overlays.actions("Choose a Cover", acts)
})
if !pl.items.isEmpty {
a.append(SheetAction("Change Cover…", icon: "photo") {
var seen = Set<String>()
var acts: [SheetAction] = [
SheetAction("Choose from Photos…", icon: "photo.on.rectangle") {
overlays.pickPhoto { data in
if !lists.setPhotoArt(pl.id, data) { overlays.hud("Couldn't use that photo", "exclamationmark.triangle") }
}
},
SheetAction("Automatic", icon: "wand.and.stars") { lists.setArt(pl.id, nil) },
]
for t in pl.tracks {
guard let th = t.thumb, seen.insert(th).inserted, seen.count <= 20 else { continue }
acts.append(SheetAction(t.album, icon: th == pl.artThumb ? "checkmark" : "photo") { lists.setArt(pl.id, th) })
}
overlays.actions("Choose a Cover", acts)
a.append(SheetAction("Set Mix for All Songs…", icon: "slider.horizontal.3") {
chooseMix(pl.tracks) { m in lists.setItems(pl.id, pl.items.map { var it = $0; it.mix = MixPresets.normalized(m); return it }) }
})
a.append(SheetAction("Copy to Plex Playlist…", icon: "doc.on.doc") { newPlaylist(pl.tracks) { ui.playlistEdits += 1 } })
}
a.append(SheetAction("Delete Stem Playlist", icon: "trash", destructive: true) {
overlays.confirm("Delete “\(pl.title)”?", "Stem playlists are only on this device.", "Delete") { lists.delete(pl.id); if onPage { ui.pop() } }
@@ -260,6 +321,29 @@ struct MediaMenu {
}
}
/// Empty playlist; asks which server first when more than one is signed in.
func newEmptyPlaylist(onCreated: @escaping () -> Void = {}) {
let plex = g.plex
let servers = plex.playlistServers
let make: (String?) -> Void = { id in
overlays.prompt("New Playlist", "Add songs later with “Add to Playlist”.", "Create", placeholder: "Playlist name") { name in
Task {
do {
_ = try await plex.createEmptyPlaylist(name, serverId: id)
overlays.hud("Created “\(name)”")
ui.playlistEdits += 1
onCreated()
} catch {
overlays.hud("Couldn't create: \(error.localizedDescription)", "exclamationmark.triangle")
}
}
}
}
if servers.count > 1 {
overlays.actions("Which Server?", servers.map { s in SheetAction(s.1.isEmpty ? "Server" : s.1) { make(s.0) } })
} else { make(servers.first?.0) }
}
func newPlaylist(_ tracks: [Track], onCreated: @escaping () -> Void = {}) {
let plex = g.plex
overlays.prompt("New Playlist", "Name it; you can add more songs later.", "Create", placeholder: "Playlist name") { name in
+21 -3
View File
@@ -33,6 +33,9 @@ final class Overlays {
/// Set while the Photos picker is up; gets the picked image's data.
var photoPick: ((Data) -> Void)?
var photoShown = false
/// A picked cover waiting in the cropper.
var crop: Crop?
struct Crop: Identifiable { let id = UUID(); var image: UIImage; var run: (Data) -> Void }
/// 1 while the Now Playing sheet is up, so its host shows overlays instead of the root's.
var level = 0
@@ -95,7 +98,7 @@ struct OverlayHost: ViewModifier {
private var mine: Bool { overlays.level == level }
func body(content: Content) -> some View {
content
content.modifier(CropHost(overlays: overlays, mine: mine))
.overlay {
if mine, let h = overlays.hud {
HudView(hud: h).transition(.opacity.combined(with: .scale(scale: 0.9))).allowsHitTesting(false)
@@ -132,8 +135,9 @@ struct OverlayHost: ViewModifier {
photo = nil
overlays.photoPick = nil
Task { @MainActor in
if let data = try? await item.loadTransferable(type: Data.self) { run(data) }
else { overlays.hud("Couldn't load that photo", "exclamationmark.triangle") }
if let data = try? await item.loadTransferable(type: Data.self), let img = UIImage(data: data) {
overlays.crop = Overlays.Crop(image: img, run: run)
} else { overlays.hud("Couldn't load that photo", "exclamationmark.triangle") }
}
}
.sheet(item: Binding(get: { mine ? overlays.addToPlaylist : nil }, set: { overlays.addToPlaylist = $0 })) { r in
@@ -146,6 +150,20 @@ struct OverlayHost: ViewModifier {
}
}
/// The cover cropper, split out to keep OverlayHost's chain small enough to type-check.
private struct CropHost: ViewModifier {
let overlays: Overlays
let mine: Bool
func body(content: Content) -> some View {
content.fullScreenCover(item: Binding(get: { mine ? overlays.crop : nil }, set: { overlays.crop = $0 })) { c in
CoverCropper(image: c.image) { data in
overlays.crop = nil
if let data { c.run(data) }
}
}
}
}
private struct HudView: View {
let hud: Overlays.Hud
var body: some View {
+42 -8
View File
@@ -74,6 +74,8 @@ final class Ui {
/// Split only: which of the deck's pages is showing.
var deckPage: DeckPage = .Stems
let overlays: Overlays
/// Bumped when a playlist is renamed or gets a new cover, so the lists reload.
var playlistEdits = 0
init(overlays: Overlays) { self.overlays = overlays }
@@ -126,6 +128,7 @@ final class Ui {
private var duo = UserDefaults.standard.bool(forKey: "duoSeen")
/// Folded iPhone Duo: the outer display, kept upright.
var folded: Bool { duo && !split && !unfolded }
var isDuo: Bool { duo }
/// Called with the window's side insets. Upright, only the folded Duo has a trailing one.
func sawInsets(trailing: CGFloat, upright: Bool) {
@@ -136,29 +139,60 @@ final class Ui {
lockOrientation()
}
/// Split (unfolded) goes landscape at once. Portrait waits a moment and checks again, so a
/// frame without a hinge reading mid-rotation can't throw an unfolded phone back upright.
/// Back in the foreground: the phone may have been folded or unfolded meanwhile.
func resumed() { lockOrientation() }
/// The Duo is never free to turn: folded is portrait only, unfolded is landscape only.
/// Hinge readings flicker while the window settles (coming back from the background, mid
/// fold), so the lock only changes once a reading has held for a moment. Other iPhones turn freely.
private var lockGen = 0
func resumed() {
lockOrientation()
if away { showPlayingFolded() }
away = false
}
/// Leaves the lock as it is: freeing it let iOS turn the window while audio kept the app alive.
func backgrounded() { away = true }
private var away = false
/// Folded with something playing, the app comes back on Now Playing.
private func showPlayingFolded() {
guard folded, !nowPlayingOpen, AppGraph.shared.playback.current != nil else { return }
// Back from the background folded with something playing: Now Playing slides up as if
// swiped open, once the app's own opening animation has landed.
Task { @MainActor in
try? await Task.sleep(for: .milliseconds(180))
guard self.folded, !self.nowPlayingOpen, AppGraph.shared.playback.current != nil else { return }
self.nowPlayingOpen = true
}
}
private func lockOrientation() {
if split || unfolded { Orientation.lock(.landscape); return }
guard folded else { Orientation.lock(.allButUpsideDown); return }
guard duo || split || unfolded else { Orientation.lock(.allButUpsideDown); return }
let want: UIInterfaceOrientationMask = (split || unfolded) ? .landscape : .portrait
lockGen += 1
let gen = lockGen
Task { @MainActor in
try? await Task.sleep(for: .milliseconds(400))
if self.folded { Orientation.lock(.portrait) }
try? await Task.sleep(for: .milliseconds(450))
guard gen == self.lockGen else { return }
let now: UIInterfaceOrientationMask = (self.split || self.unfolded) ? .landscape : .portrait
guard now == want else { return }
Log.shared.info("orient", "lock \(want == .landscape ? "landscape" : "portrait") split=\(self.split) unfolded=\(self.unfolded)")
Orientation.lock(want)
}
}
func setUnfolded(_ on: Bool) {
guard on != unfolded else { return }
unfolded = on
Log.shared.info("orient", "unfolded \(on)")
lockOrientation()
}
func setSplit(_ on: Bool) {
guard on != split else { return }
split = on
Log.shared.info("orient", "split \(on)")
lockOrientation()
if on {
nowPlayingOpen = false
+22 -5
View File
@@ -19,9 +19,21 @@ struct RootView: View {
.onGeometryChange(for: CGFloat.self) { $0.safeAreaInsets.trailing } action: { ui.sawInsets(trailing: $0, upright: vSize == .regular) }
.background(p.bg.ignoresSafeArea())
.onChange(of: ui.tabs) { _, _ in ui.ensureValidTab() }
.onChange(of: phase) { _, ph in if ph == .active { ui.resumed() } }
.onChange(of: phase) { _, ph in
if ph == .active { ui.resumed() } else if ph == .background { ui.backgrounded() }
}
.fullScreenCover(isPresented: Binding(get: { ui.nowPlayingOpen }, set: { ui.nowPlayingOpen = $0 })) {
NowPlayingScreen()
// The panes underneath stop reporting while this covers them, so watch for the
// hinge here too: unfolding hands over to the split (docked) layout.
.background(GeometryReader { geo in
let c = DuoPane<EmptyView>.cut(geo)
Color.clear.onChange(of: c == nil ? 0 : c!.vertical ? 2 : 1, initial: true) { _, k in
guard k > 0 else { return }
ui.setUnfolded(true)
ui.setSplit(k == 2)
}
})
.overlayHost(ui.overlays, level: 1)
.environment(ui)
.environment(\.palette, p)
@@ -198,6 +210,7 @@ private struct DuoPane<Content: View>: View {
@Environment(Ui.self) private var ui
@AppStorage("duoSwap") private var swap = false
@Environment(\.palette) private var p
@State private var shown = false
private var g: AppGraph { .shared }
var body: some View {
@@ -229,15 +242,19 @@ private struct DuoPane<Content: View>: View {
// The hinge gap shows whatever is behind; paint it so the two sides read as one.
.background(p.bg.ignoresSafeArea())
.animation(.spring(duration: 0.4, bounce: 0.1), value: flip)
.onChange(of: hinge != nil, initial: true) { _, on in ui.setUnfolded(on) }
.onChange(of: cut != nil, initial: true) { _, on in ui.setSplit(on) }
// Every tab has its own pane and TabView keeps hidden ones alive, so only the one on
// screen reports; a hidden one's stale size used to turn split off under the visible one.
.onChange(of: hinge != nil) { _, on in if shown { ui.setUnfolded(on) } }
.onChange(of: cut != nil) { _, on in if shown { ui.setSplit(on) } }
.onAppear { shown = true; ui.setUnfolded(hinge != nil); ui.setSplit(cut != nil) }
.onDisappear { shown = false }
}
}
/// Where the hinge cuts the view: sizes of the two sides and the gap between them.
private struct Cut { var vertical: Bool; var first: CGFloat; var gap: CGFloat; var second: CGFloat }
fileprivate struct Cut { var vertical: Bool; var first: CGFloat; var gap: CGFloat; var second: CGFloat }
private static func cut(_ geo: GeometryProxy) -> Cut? {
fileprivate static func cut(_ geo: GeometryProxy) -> Cut? {
let size = geo.size
var c: Cut?
// The hinge reports inactive while the phone lies flat, so ask for inactive regions too.
+82 -19
View File
@@ -3,6 +3,44 @@ import UIKit
enum NpPanel { case Art, Mixer, Queue, Lyrics }
/// The close drag's offset. Only DropOffset reads it, so dragging re-renders just the offset.
@Observable final class DropState { var y: CGFloat = 0 }
/// ProMotion only runs as fast as someone asks. A plain drag asks nothing, and the 30 fps meters and
/// bars then set the pace, so the close drag crawled. This display link asks for 120 Hz while held.
@MainActor final class FrameBoost: NSObject {
static let shared = FrameBoost()
private var link: CADisplayLink?
private var stopGen = 0
func start() {
stopGen += 1
guard link == nil else { return }
let l = CADisplayLink(target: self, selector: #selector(tick))
l.preferredFrameRateRange = CAFrameRateRange(minimum: 80, maximum: 120, preferred: 120)
l.add(to: .main, forMode: .common)
link = l
}
/// Keeps the boost through the spring back or the cover's slide down.
func stop(after: Double = 0.6) {
stopGen += 1
let gen = stopGen
DispatchQueue.main.asyncAfter(deadline: .now() + after) { [weak self] in
guard let self, gen == self.stopGen else { return }
self.link?.invalidate()
self.link = nil
}
}
@objc private func tick() {}
}
private struct DropOffset: ViewModifier {
let state: DropState
func body(content: Content) -> some View { content.offset(y: state.y) }
}
func deviceIcon(_ d: OutputDevice) -> (String, UInt32) {
switch d.kind {
case .Speaker: ("iphone", 0x8E8E93)
@@ -62,15 +100,22 @@ struct NowPlayingScreen: View {
@Environment(\.palette) private var base
@Environment(\.dismiss) private var dismiss
@State private var panel = NpPanel.Art
/// How far the screen is being dragged down to close it.
@State private var drop: CGFloat = 0
/// How far the screen is being dragged down to close it. Kept out of the view's own state so a
/// drag only moves the screen (DropOffset) instead of rebuilding all of Now Playing each frame.
@State private var drop = DropState()
/// Docked beside the hinge the pane is narrow, so the controls pack tighter. Full screen
/// (folded or any other iPhone) uses the roomy layout across the whole window.
private var tight: Bool { docked }
/// Full screen on the Duo (folded, or a Split View half), the controls run down into the home indicator strip.
private var runsLow: Bool { !docked && (folded || ui.isDuo) }
/// Size of the art panel in the stacked layout, so the controls can match the art's width.
@State private var artBox: CGSize = .zero
/// Height of the wide layout's controls column, so the Duo art can match it.
@State private var ctlH: CGFloat = 0
/// The screen's height, for the strip at the top that a drag down closes from.
@State private var screenH: CGFloat = 0
/// Where the art sits on screen: folded, a drag down that starts on it closes Now Playing.
@State private var artFrame: CGRect = .zero
@Environment(\.verticalSizeClass) private var vSize
/// Folded iPhone Duo: the outer display keeps a status column down the right edge.
@State private var folded = false
@@ -91,13 +136,18 @@ struct NowPlayingScreen: View {
if wide {
// The column never drops below what the transport row needs, so the buttons
// can't spill onto the art or under the Duo rail.
let col = tight ? min(max(geo.size.width * 0.46, 300), 420) : min(geo.size.width * 0.48, 440)
let col = tight ? min(max(geo.size.width * 0.46, 300), 420) : min(max(geo.size.width * 0.42, 300), 440)
HStack(spacing: 0) {
// On the Duo the art matches the controls' height, so it lines up with the title
// and the button row instead of floating in the middle of a tall pane.
let match = ui.isDuo && !docked && panel == .Art && ctlH > 0
panelView(track, header: false)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(maxWidth: .infinity, maxHeight: match ? min(ctlH, geo.size.height) : .infinity)
.frame(maxHeight: .infinity)
.transition(.opacity.combined(with: .scale(scale: 0.96)))
controls(track, wide: true, width: col)
.frame(width: col)
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { ctlH = $0 }
.frame(maxHeight: .infinity)
}
} else {
@@ -126,12 +176,12 @@ struct NowPlayingScreen: View {
// Folded, the bottom inset is empty space too: run the controls down into it, and the art grows into the room.
// The room under the controls has to be inside this view: padding outside it would keep
// the view off the bottom edge, and then it can't run into the home indicator strip.
.padding(.bottom, folded && !docked ? 6 : 0)
.ignoresSafeArea(.container, edges: !docked && vSize == .regular ? (folded ? [.trailing, .bottom] : .trailing) : [])
.padding(.bottom, runsLow ? 6 : 0)
.ignoresSafeArea(.container, edges: !docked && vSize == .regular ? (runsLow ? [.trailing, .bottom] : .trailing) : [])
// Measured outside the line above, so it still sees the status column.
.onGeometryChange(for: Bool.self) { $0.safeAreaInsets.trailing > 20 } action: { folded = $0 && vSize == .regular }
.padding(.top, docked ? 4 : tight ? 14 : 20)
.padding(.bottom, folded && !docked ? 0 : tight ? 4 : 8)
.padding(.bottom, runsLow ? 0 : tight ? 4 : 8)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(c.bg.ignoresSafeArea())
.overlay(alignment: .top) {
@@ -142,7 +192,7 @@ struct NowPlayingScreen: View {
.gesture(screenDrag(header: true)) }
}
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { screenH = $0 }
.offset(y: drop)
.modifier(DropOffset(state: drop))
// Drag down from the top strip (or the song header) to close, so it never fights the
// stem faders. Swipe up anywhere on the art for the queue.
.simultaneousGesture(screenDrag(), including: panel == .Art ? .all : .subviews)
@@ -156,8 +206,9 @@ struct NowPlayingScreen: View {
@ViewBuilder
private func panelView(_ track: Track, header: Bool) -> some View {
switch panel {
case .Art: ArtPanel(thumb: track.thumb, playing: g.playback.playWhenReady, inset: header || !tight ? artInset : 12,
leading: folded && !docked && !ui.split && g.settings.foldedArtLeft).contentShape(Rectangle())
case .Art: ArtPanel(thumb: track.thumb, playing: g.playback.playWhenReady, inset: header ? artInset : 12,
leading: folded && !docked && !ui.split && g.settings.foldedArtLeft, edge: hPad).contentShape(Rectangle())
.onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { if drop.y == 0 { artFrame = $0 } }
case .Mixer: VStack(spacing: 0) { if header { mini(track) }; MixerPanel(spread: folded) }
case .Queue: VStack(spacing: 0) { if header { mini(track) }; QueuePanel(close: { show(.Queue) }) }
case .Lyrics: VStack(spacing: 0) { if header { mini(track) }; LyricsPanel(track: track) }
@@ -190,7 +241,7 @@ struct NowPlayingScreen: View {
Spacer(minLength: 8)
EllipsisButton(items: ui.menu.track(track))
}
.padding(.top, snug && !docked ? 20 : tight ? 8 : 14)
.padding(.top, snug && !docked ? 20 : tight ? 8 : ui.isDuo && !wide ? 30 : 14)
.transition(.opacity.combined(with: .move(edge: .top)))
}
ProgressVolumeBar(played: g.settings.albumTheme ? c.accent : c.label, unplayed: c.label3, centerLabel: badge(track))
@@ -278,19 +329,28 @@ struct NowPlayingScreen: View {
}
/// Drag down to close: from the grabber or song header, or anywhere in the top tenth of the screen.
/// Folded, also from the art (only while it shows, so never over the stem dials).
private func fromTop(_ v: DragGesture.Value, header: Bool) -> Bool {
header || v.startLocation.y < max(screenH * 0.1, 56)
|| (folded && !docked && panel == .Art && artFrame.contains(v.startLocation))
}
private func screenDrag(header: Bool = false) -> some Gesture {
DragGesture(minimumDistance: 20)
DragGesture(minimumDistance: 20, coordinateSpace: .global)
.onChanged { v in
let dy = v.translation.height
let top = header || v.startLocation.y < max(screenH * 0.1, 56)
drop = !docked && top && dy > 0 && dy > abs(v.translation.width) ? dy : 0
let top = fromTop(v, header: header)
let y = !docked && top && dy > 0 && dy > abs(v.translation.width) ? dy : 0
if y > 0 { FrameBoost.shared.start() }
if y != drop.y { drop.y = y }
}
.onEnded { v in
FrameBoost.shared.stop()
let dy = v.translation.height
let vertical = abs(dy) > abs(v.translation.width)
let top = header || v.startLocation.y < max(screenH * 0.1, 56)
let top = fromTop(v, header: header)
if !docked && top && vertical && (dy > 120 || v.predictedEndTranslation.height > 300) { dismiss(); return }
withAnimation(.spring(duration: 0.3, bounce: 0.1)) { drop = 0 }
withAnimation(.spring(duration: 0.3, bounce: 0.1)) { drop.y = 0 }
// Never from the stems: a slightly upward fader drag or scroll there kept opening the queue.
if !docked && vertical && dy < -50 && panel != .Mixer && g.settings.swipeUpQueue {
withAnimation(.spring(duration: 0.38, bounce: 0.12)) { panel = .Queue }
@@ -451,6 +511,8 @@ private struct ArtPanel: View {
var inset: CGFloat = 28
/// Settings > Appearance, folded Duo only: art against the left edge.
var leading = false
/// The controls' side padding, which the art's left edge matches when `leading`.
var edge: CGFloat = 28
var body: some View {
GeometryReader { geo in
let side = max(min(geo.size.width, geo.size.height), 1)
@@ -460,7 +522,8 @@ private struct ArtPanel: View {
.animation(.spring(response: 0.45, dampingFraction: 0.62), value: playing)
.frame(width: geo.size.width, height: geo.size.height, alignment: leading ? .leading : .center)
}
.padding(.horizontal, inset).padding(.vertical, 8)
// Against the left edge, the art starts where the controls below it do.
.padding(.leading, leading ? edge : inset).padding(.trailing, inset).padding(.vertical, 8)
}
}
@@ -1273,7 +1336,7 @@ private struct LyricsPanel: View {
if g.playback.source == .Stems && g.playback.stemNames.contains("vocals") {
HStack(spacing: 12) {
Text("Vocals").font(.subheadline.weight(.semibold)).foregroundStyle(p.label2)
Picker("Vocals", selection: Binding(get: { g.playback.karaokeVocals }, set: { g.playback.setKaraokeVocals($0) })) {
Picker("Vocals", selection: Binding(get: { g.playback.karaokeVocals }, set: { g.playback.setKaraokeVocals($0, engage: true) })) {
ForEach(KaraokeVocals.allCases, id: \.self) { Text(String(describing: $0)).tag($0) }
}
.pickerStyle(.segmented)
@@ -1283,7 +1346,7 @@ private struct LyricsPanel: View {
let db = g.settings.karaokeSoftDb
HStack(spacing: 12) {
Text("Softness").font(.subheadline.weight(.semibold)).foregroundStyle(p.label2)
Slider(value: Binding(get: { Double(db) }, set: { g.playback.setKaraokeSoftDb(Int($0.rounded())) }), in: -30...(-3), step: 1)
Slider(value: Binding(get: { Double(db) }, set: { g.playback.setKaraokeSoftDb(Int($0.rounded()), engage: true) }), in: -30...(-3), step: 1)
Text("\(db) dB").font(.caption).monospacedDigit().foregroundStyle(p.label2).frame(width: 46, alignment: .trailing)
}
.padding(.horizontal, 28).padding(.top, 8)
+59 -45
View File
@@ -10,6 +10,8 @@ struct PlaylistsScreen: View {
@State private var reload = 0
@AppStorage("playlistKind") private var kind = PlaylistKind.Plex
private let sort = SortState("playlists", PLAYLIST_SORTS)
private let stemSort = SortState("stemPlaylists", STEM_PLAYLIST_SORTS)
@State private var shuffleSeed = 0
private var g: AppGraph { .shared }
var body: some View {
@@ -31,7 +33,7 @@ struct PlaylistsScreen: View {
}
}
} else {
let stems = g.stemPlaylists.lists
let stems = g.stemPlaylists.lists.sorted(stemSort, seed: shuffleSeed)
if stems.isEmpty {
EmptyState(icon: "slider.horizontal.3", title: "No Stem Playlists",
message: "Each song plays with its own mix, like an instrumental or a cappella. Hold any song and choose “Add to Stem Playlist”, or copy a Plex playlist with +.")
@@ -42,30 +44,29 @@ struct PlaylistsScreen: View {
}
}
.toolbar {
if kind == .Plex { ToolbarItem(placement: .topBarTrailing) { SortMenu(sort: sort) } }
ToolbarItem(placement: .topBarTrailing) { SortMenu(sort: kind == .Plex ? sort : stemSort) }
ToolbarItem(placement: .topBarTrailing) {
Button { kind == .Plex ? newPlaylist() : newStemPlaylist() } label: { Image(systemName: "plus") }
}
}
.task(id: "\(g.settings.libraryKey)|\(sort.token)|\(reload)") {
.onChange(of: stemSort.token) { shuffleSeed += 1 }
.task(id: "\(g.settings.libraryKey)|\(sort.token)|\(reload)|\(ui.playlistEdits)") {
// /playlists may not take sort=random, so Random shuffles here.
let random = sort.option.random
await LoadState.load($lists) { try await random ? g.plex.playlists().shuffled() : g.plex.playlists(sort: sort.param) }
}
}
/// Plex can't hold an empty playlist, so new ones start from songs you have.
private func newPlaylist() {
let queue = g.playback.queue
var acts: [SheetAction] = []
var acts: [SheetAction] = [SheetAction("Empty Playlist…", icon: "plus") { ui.menu.newEmptyPlaylist { reload += 1 } }]
if !queue.isEmpty {
acts.append(SheetAction("New Playlist from Queue (\(queue.count))") { ui.menu.newPlaylist(queue.map(\.track)) { reload += 1 } })
}
if let now = g.playback.current?.track {
acts.append(SheetAction("New Playlist with “\(now.title)”") { ui.menu.newPlaylist([now]) { reload += 1 } })
}
if acts.isEmpty { ui.overlays.hud("Play something first, or use “Add to Playlist” on any song.", "info.circle") }
else { ui.overlays.actions("New Playlist", acts) }
ui.overlays.actions("New Playlist", acts)
}
private func newStemPlaylist() {
@@ -142,7 +143,7 @@ struct StemPlaylistScreen: View {
.navigationTitle(pl.title)
.navigationBarTitleDisplayMode(.inline)
} else {
Page(title: pl.title, large: false) {
Page(title: pl.title, large: false, pullUp: BAR_PULL) {
header(pl)
if pl.items.isEmpty {
EmptyState(icon: "slider.horizontal.3", title: "No Songs",
@@ -159,12 +160,11 @@ struct StemPlaylistScreen: View {
}
.toolbar {
ToolbarItemGroup(placement: .topBarTrailing) {
if !editing { MoreMenu(items: moreItems(pl)) }
if editing { Button("Done") { g.stemPlaylists.setItems(pl.id, items); editing = false }.bold() }
else if !pl.items.isEmpty { Button("Edit") { items = pl.items; editing = true } }
else { MoreMenu(items: moreItems(pl)) }
}
}
.modifier(SplitHidesTitle())
.modifier(SplitHidesTitle(bare: !editing))
}
private func header(_ pl: StemPlaylist) -> some View {
@@ -179,18 +179,40 @@ struct StemPlaylistScreen: View {
}
}
.frame(maxWidth: .infinity)
.padding(.top, 8).padding(.bottom, 16)
.padding(.bottom, 16)
}
private func moreItems(_ pl: StemPlaylist) -> [SheetAction] {
let lists = g.stemPlaylists
let rename = SheetAction("Rename…", icon: "pencil") {
ui.overlays.prompt("Rename Stem Playlist", nil, initial: pl.title, "Save") { lists.rename(pl.id, $0) }
let edit = pl.items.isEmpty ? [] : [SheetAction("Edit Songs", icon: "list.bullet") { items = pl.items; editing = true }]
return ui.menu.stemPlaylist(pl, extra: edit, onPage: true)
}
}
/// Stem playlists live on the device, so they sort here.
let STEM_PLAYLIST_SORTS = [
SortOption(title: "Title", key: "title", up: "A to Z", down: "Z to A"),
SortOption(title: "Date Added", key: "created", desc: true, up: "Oldest First", down: "Newest First"),
SortOption(title: "Last Updated", key: "updated", desc: true, up: "Oldest First", down: "Newest First"),
SortOption(title: "Songs", key: "count", desc: true, up: "Fewest First", down: "Most First"),
SortOption(title: "Duration", key: "duration", desc: true, up: "Shortest First", down: "Longest First"),
SortOption(title: "Random", key: "random", up: "Shuffled", down: "Shuffled"),
]
extension [StemPlaylist] {
func sorted(_ sort: SortState, seed: Int) -> [StemPlaylist] {
let o = sort.option
if o.random {
return map { ($0, ($0.id + "\(seed)").hashValue) }.sorted { $0.1 < $1.1 }.map(\.0)
}
let mixAll = SheetAction("Set Mix for All Songs…", icon: "slider.horizontal.3") {
ui.menu.chooseMix(pl.tracks) { m in lists.setItems(pl.id, pl.items.map { var it = $0; it.mix = MixPresets.normalized(m); return it }) }
let asc: [StemPlaylist]
switch o.key {
case "created": asc = sorted { $0.created < $1.created }
case "updated": asc = sorted { $0.updated < $1.updated }
case "count": asc = sorted { $0.items.count < $1.items.count }
case "duration": asc = sorted { $0.durationMs < $1.durationMs }
default: asc = sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
}
return ui.menu.stemPlaylist(pl, extra: pl.items.isEmpty ? [rename] : [rename, mixAll], onPage: true)
return sort.descending ? asc.reversed() : asc
}
}
@@ -221,6 +243,7 @@ struct PlaylistScreen: View {
@State private var tracks: LoadState<[Track]> = .loading
@State private var reload = 0
@State private var title: String
@State private var thumb: String?
@State private var editing = false
@State private var items: [Track] = []
@State private var removed: [Track] = []
@@ -230,6 +253,7 @@ struct PlaylistScreen: View {
init(playlist: Playlist) {
self.playlist = playlist
_title = State(initialValue: playlist.title)
_thumb = State(initialValue: playlist.thumb)
}
var body: some View {
@@ -255,7 +279,7 @@ struct PlaylistScreen: View {
.navigationTitle(title)
.navigationBarTitleDisplayMode(.inline)
} else {
Page(title: title, large: false) {
Page(title: title, large: false, pullUp: BAR_PULL) {
header(list)
Loaded(state: tracks, retry: { reload += 1 }) { list in
ForEach(Array(list.enumerated()), id: \.element.id) { i, t in
@@ -268,15 +292,12 @@ struct PlaylistScreen: View {
}
.toolbar {
ToolbarItemGroup(placement: .topBarTrailing) {
if !editing { MoreMenu(items: moreItems(list)) }
if !playlist.smart && !list.isEmpty {
if saving { ProgressView() }
else if editing { Button("Done") { commit(list) }.bold() }
else { Button("Edit") { items = list; removed = []; editing = true } }
}
if saving { ProgressView() }
else if editing { Button("Done") { commit(list) }.bold() }
else { MoreMenu(items: moreItems(list)) }
}
}
.modifier(SplitHidesTitle())
.modifier(SplitHidesTitle(bare: !editing))
.task(id: reload) {
await LoadState.load($tracks) { try await g.plex.playlistTracks(playlist.ratingKey) }
}
@@ -284,7 +305,7 @@ struct PlaylistScreen: View {
private func header(_ list: [Track]) -> some View {
VStack(spacing: 0) {
Artwork(thumb: playlist.thumb, size: 230, corner: 10, placeholder: "music.note.list")
Artwork(thumb: thumb, size: 230, corner: 10, placeholder: "music.note.list")
Text(title).font(.title2.bold()).foregroundStyle(p.label).multilineTextAlignment(.center).lineLimit(2)
.padding(.horizontal, 32).padding(.top, 14)
if !list.isEmpty {
@@ -295,7 +316,7 @@ struct PlaylistScreen: View {
}
}
.frame(maxWidth: .infinity)
.padding(.top, 8).padding(.bottom, 16)
.padding(.bottom, 16)
}
private func removeAction(_ t: Track) -> [SheetAction] {
@@ -309,25 +330,13 @@ struct PlaylistScreen: View {
}
private func moreItems(_ list: [Track]) -> [SheetAction] {
var extra: [SheetAction] = []
let plex = g.plex
let key = playlist.ratingKey
if !playlist.smart {
extra.append(SheetAction("Rename…", icon: "pencil") {
ui.overlays.prompt("Rename Playlist", nil, initial: title, "Save") { name in
Task { if (try? await plex.renamePlaylist(key, title: name)) != nil { title = name } }
}
})
}
extra.append(SheetAction("Delete Playlist", icon: "trash", destructive: true) {
ui.overlays.confirm("Delete “\(title)”?", "This removes it from Plex for every app.", "Delete") {
Task { if (try? await plex.deletePlaylist(key)) != nil { ui.pop() } }
}
})
let extra = playlist.smart || list.isEmpty ? [] :
[SheetAction("Edit Songs", icon: "list.bullet") { items = list; removed = []; editing = true }]
var pl = playlist
pl.title = title
pl.thumb = thumb
pl.trackCount = list.count
return ui.menu.playlist(pl, extra: extra)
return ui.menu.playlist(pl, extra: extra, changed: { title = $0.title; thumb = $0.thumb }, deleted: { ui.pop() })
}
/// Sends removals, then replays the new order as "move after" calls against a simulated server list.
@@ -417,11 +426,16 @@ struct SearchScreen: View {
}
/// Split at the Duo's hinge the pane's own header already names the playlist, so the bar drops the title.
/// How far a playlist page's header rides up into the empty nav bar, between back and •••.
private let BAR_PULL: CGFloat = 40
/// Hides the bar title in split view, and while [bare] (the header already shows it).
private struct SplitHidesTitle: ViewModifier {
var bare = false
@Environment(Ui.self) private var ui
func body(content: Content) -> some View {
content.toolbar {
if ui.split { ToolbarItem(placement: .principal) { Color.clear.frame(width: 1, height: 1) } }
if ui.split || bare { ToolbarItem(placement: .principal) { Color.clear.frame(width: 1, height: 1) } }
}
}
}
+3 -3
View File
@@ -7,9 +7,9 @@ settings:
base:
SWIFT_VERSION: "5.0"
# iOS needs a plain number for the bundle version; the label is what the app and releases show.
MARKETING_VERSION: "0.10.0"
VERSION_LABEL: "0.10.0"
CURRENT_PROJECT_VERSION: "47"
MARKETING_VERSION: "0.10.1"
VERSION_LABEL: "0.10.1"
CURRENT_PROJECT_VERSION: "66"
# Dev builds override these (build-ipa.sh dev) so they install next to the release app.
APP_ID: org.cdnutter.stemify
APP_NAME: Stemify
+3 -3
View File
@@ -47,7 +47,7 @@ def svg(mode="color", sash=False):
'<stop offset="1" stop-color="#05040A"/></radialGradient>'
'<rect width="1024" height="1024" fill="url(#bg)"/>')
# soft colored light pooling behind the bars
aura = ('<g filter="url(#aura)" opacity="0.55">'
aura = ('<g filter="url(#aura)" opacity="0.35">'
f'<circle cx="330" cy="420" r="190" fill="{hx(STEMS[0])}"/>'
f'<circle cx="690" cy="400" r="200" fill="{hx(STEMS[4])}"/>'
f'<circle cx="520" cy="660" r="210" fill="{hx(STEMS[2])}"/>'
@@ -76,11 +76,11 @@ def svg(mode="color", sash=False):
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>{"".join(defs)}
<filter id="aura" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="110"/></filter>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="26"/></filter>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="18"/></filter>
<filter id="drop" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="10"/></filter>
</defs>
{bg}{aura}
<g filter="url(#glow)" opacity="{0.25 if tint else 0.7}">{"".join(glow)}</g>
<g filter="url(#glow)" opacity="{0.15 if tint else 0.35}">{"".join(glow)}</g>
<g filter="url(#drop)" opacity="0.5" transform="translate(0,14)">{"".join(g.replace('fill="#', 'fill="#000" data-c="') for g in glow)}</g>
<g>{"".join(bars)}</g>
<g>{"".join(shine)}</g>
+10
View File
@@ -15,6 +15,16 @@
"tintColor": "#FA2D48",
"category": "entertainment",
"versions": [
{
"version": "0.10.1",
"marketingVersion": "0.10.1",
"buildVersion": "52",
"date": "2026-11-20T12:25:58-08:00",
"localizedDescription": "Folded art-left: art's left edge matches the controls' padding",
"downloadURL": "https://git.iamchrisama.com/cdnutter/stemify/releases/download/ios-v0.10.1/stemify-0.10.1.ipa",
"size": 3142623,
"minOSVersion": "17.0"
},
{
"version": "0.10.0",
"marketingVersion": "0.10.0",
+280 -70
View File
@@ -3,7 +3,7 @@
import { $, $$, esc, fmtTime, fmtBytes, plural, on, emit, toast, ICON, store, uuid } from "./util.js";
import { S, save, songMixes, saveSongMix, forgetSongMix, playlists, savePlaylists, newPlaylist, addToPlaylist, Offline } from "./store.js";
import { px, img, rawImg, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything } from "./plex.js";
import { px, img, rawImg, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything, pxSend, plexUri } from "./plex.js";
import { Stems, Live, stemNow, stemTrack, stemBase, api } from "./stems.js";
import { E, Q, setting, stemGain, presets, allPresets, presetLabel, applyPreset, currentPreset, nextPreset, savePreset, deletePreset, movePreset, restorePresets, deleteAllCustom, toggleLock,
mixChanged, setKaraoke, setKaraokeMode, sameMix, setSpeed, saveQueue, saveOffline, Radio } from "./player.js";
@@ -14,16 +14,18 @@ const view = $("#view");
// ---- appearance -------------------------------------------------------------------------------
// Same palettes as the iOS app: three appearances and the system accent colors (light / dark variants).
const THEMES = {
graphite: { bg: "#181819", panel: "#101010", raised: "#262628", line: "#2b2b2e", text: "#e7e7e7", muted: "#a8a8a8", accent: "#3a81ed" },
amber: { bg: "#0d0e12", panel: "#15171d", raised: "#1d2028", line: "#262a33", text: "#eceef3", muted: "#8a8f9c", accent: "#f2b544" },
ocean: { bg: "#0a1018", panel: "#101a26", raised: "#172434", line: "#1f2f42", text: "#e6eef7", muted: "#8698ad", accent: "#4cc2ff" },
rose: { bg: "#120c10", panel: "#1b1218", raised: "#251922", line: "#33222e", text: "#f5e9f0", muted: "#a48b99", accent: "#ff6f9f" },
forest: { bg: "#0b110d", panel: "#111a14", raised: "#18241c", line: "#223127", text: "#e8f2ea", muted: "#88a08e", accent: "#62d38a" },
mono: { bg: "#0e0e0e", panel: "#161616", raised: "#202020", line: "#2c2c2c", text: "#f0f0f0", muted: "#8c8c8c", accent: "#f0f0f0" },
oled: { bg: "#000000", panel: "#000000", raised: "#141414", line: "#1e1e1e", text: "#f2f2f2", muted: "#8a8a8a", accent: "#f2b544" },
light: { bg: "#f6f6f3", panel: "#ffffff", raised: "#ebeae5", line: "#dddbd4", text: "#18181b", muted: "#6b6b73", accent: "#c27a06", light: true },
black: { label: "Black", bg: "#000000", panel: "#000000", raised: "#1c1c1e", line: "#2c2c2e", text: "#ffffff", muted: "#8d8d93", fill: "#3a3a3c" },
dark: { label: "Dark", bg: "#1c1c1e", panel: "#161618", raised: "#2c2c2e", line: "#3d3d40", text: "#ffffff", muted: "#98989d", fill: "#48484a" },
white: { label: "White", bg: "#ffffff", panel: "#f2f2f7", raised: "#efeff0", line: "#d8d8dc", text: "#000000", muted: "#8a8a8e", fill: "#e3e3e8", light: true },
};
const ACCENTS = {
music: ["Music", "#fa2d48", "#fc3c44"], pink: ["Pink", "#ff2d55", "#ff375f"], orange: ["Orange", "#ff9500", "#ff9f0a"],
yellow: ["Yellow", "#ffcc00", "#ffd60a"], green: ["Green", "#34c759", "#30d158"], teal: ["Teal", "#30b0c7", "#40c8e0"],
blue: ["Blue", "#007aff", "#0a84ff"], indigo: ["Indigo", "#5856d6", "#5e5ce6"], purple: ["Purple", "#af52de", "#bf5af2"],
};
const accentOf = (base, key = S.accent) => (ACCENTS[key] || ACCENTS.music)[base.light ? 1 : 2];
const inkFor = hex => {
const n = parseInt(hex.slice(1), 16), l = (0.299 * (n >> 16) + 0.587 * (n >> 8 & 255) + 0.114 * (n & 255)) / 255;
return l > 0.6 ? "#141414" : "#ffffff";
@@ -76,7 +78,7 @@ const ArtTheme = {
},
};
function applyTheme() {
const base = THEMES[S.theme] || THEMES.graphite, t = ArtTheme.hsv ? artPalette(ArtTheme.hsv, base) : base, a = ArtTheme.hsv ? t.accent : S.accent || t.accent;
const base = THEMES[S.theme] || THEMES.dark, t = ArtTheme.hsv ? artPalette(ArtTheme.hsv, base) : base, a = ArtTheme.hsv ? t.accent : accentOf(base);
$("#theme").textContent = `:root{--bg:${t.bg};--panel:${t.panel};--raised:${t.raised};--line:${t.line};--text:${t.text};--muted:${t.muted};` +
`--accent:${a};--accent-ink:${inkFor(a)};--glass:${t.panel}ee;--hover:${t.text}0d;--shadow:${t.light ? "#0003" : "#0009"};` +
`--wave:${t.text}44;--wave-ghost:${t.text}14;color-scheme:${t.light ? "light" : "dark"}}`;
@@ -517,7 +519,7 @@ $("#b-mixer").innerHTML = ICON.mixer;
$("#b-lyrics").innerHTML = ICON.lyrics;
$("#b-queue").innerHTML = ICON.queue;
$("#speed").innerHTML = SPEEDS.map(v => `<option value="${v}">${v}×</option>`).join("");
$("#volume").value = S.volume;
$("#volume").value = S.volume; $("#volume").style.setProperty("--v", S.volume * 100 + "%");
const togglePlay = () => { if (Radio.station) return Radio.toggle(); if (!Q.cur()) return; E.playing ? E.pause() : E.play(); saveQueue(); };
$("#b-play").onclick = togglePlay;
@@ -537,7 +539,7 @@ $("#b-mixer").onclick = () => toggleDrawer("mixer");
$("#b-lyrics").onclick = () => toggleDrawer("lyrics");
$("#b-queue").onclick = () => toggleDrawer("queue");
$("#speed").onchange = ev => setSpeed(+ev.target.value);
$("#volume").oninput = ev => { S.volume = +ev.target.value; E.applyGains(); save(); };
$("#volume").oninput = ev => { S.volume = +ev.target.value; ev.target.style.setProperty("--v", S.volume * 100 + "%"); E.applyGains(); save(); };
function applyBar() {
$("#speed").style.display = S.bar.speed ? "" : "none";
for (const k of ["mixer", "lyrics", "queue"]) $(`#b-${k}`).style.display = S.bar[k] ? "" : "none";
@@ -558,13 +560,14 @@ if ("mediaSession" in navigator) {
}
document.addEventListener("keydown", ev => {
if (ev.key === "Escape") return Menu.close();
if (ev.key === "Escape") { Finder.close(); return Menu.close(); }
if (ev.target.closest("input, select, textarea") || ev.metaKey || ev.ctrlKey || ev.altKey) return;
const k = ev.key.toLowerCase();
if (k === "/" || (k === "s" && !ev.shiftKey)) { ev.preventDefault(); return Finder.open(); }
if (k === " ") { ev.preventDefault(); togglePlay(); }
else if (k === "arrowright") E.seek(Math.min(E.duration(), E.position() + (ev.shiftKey ? 30 : 5)));
else if (k === "arrowleft") E.seek(Math.max(0, E.position() - (ev.shiftKey ? 30 : 5)));
else if (k === "s") Q.toggleShuffle();
else if (k === "s") Q.toggleShuffle(); // Shift+S
else if (k === "r") Q.cycleRepeat();
else if (k === "m") toggleDrawer("mixer");
else if (k === "l") toggleDrawer("lyrics");
@@ -646,7 +649,7 @@ const Menu = {
items = items.filter(Boolean);
const m = document.createElement("div");
m.id = "menu";
m.innerHTML = items.map((it, i) => it === "-" ? "<hr>" : `<button data-mi="${i}" ${it.run ? "" : "disabled"}>${esc(it.label)}</button>`).join("");
m.innerHTML = items.map((it, i) => it === "-" ? "<hr>" : it.head ? `<h5>${esc(it.head)}</h5>` : `<button data-mi="${i}" ${it.run ? "" : "disabled"} ${"check" in it ? `class="chk ${it.check ? "on" : ""}"` : ""}>${"check" in it ? ICON.check : ""}${esc(it.label)}</button>`).join("");
document.body.append(m);
const r = m.getBoundingClientRect();
m.style.left = Math.max(8, Math.min(x, innerWidth - r.width - 8)) + "px";
@@ -654,12 +657,105 @@ const Menu = {
m.onclick = ev => { const b = ev.target.closest("[data-mi]"); if (b) { const it = items[+b.dataset.mi]; this.close(); it.run(); } };
this.el = m;
},
close() { this.el?.remove(); this.el = null; },
close() { this.el?.remove(); this.el = this.from = null; },
};
addEventListener("pointerdown", ev => { if (Menu.el && !Menu.el.contains(ev.target)) Menu.close(); }, true);
addEventListener("pointerdown", ev => { if (Menu.el && !Menu.el.contains(ev.target) && !Menu.from?.contains(ev.target)) Menu.close(); }, true);
addEventListener("blur", () => Menu.close());
view.addEventListener("scroll", () => Menu.close(), { passive: true });
// ---- universal search (S) -----------------------------------------------------------------------
// One box over every enabled server: songs, artists, albums and playlists, plus stem playlists.
// Arrow keys move, Enter opens (or plays a song), Esc closes.
const Finder = {
el: null, items: [], at: 0, n: 0, timer: 0, pls: null, plsAt: 0,
build() {
const f = document.createElement("div");
f.id = "finder"; f.hidden = true;
f.innerHTML = `<div class="fbox" role="dialog" aria-label="Search"><label class="fin">${ICON.search}<input type="text" placeholder="Search songs, artists, albums, playlists" autocomplete="off" spellcheck="false"><kbd>esc</kbd></label><div class="fres" role="listbox"></div></div>`;
document.body.append(f);
const inp = f.querySelector("input"), res = f.querySelector(".fres");
f.addEventListener("pointerdown", ev => { if (ev.target === f) this.close(); });
inp.addEventListener("input", () => { clearTimeout(this.timer); this.timer = setTimeout(() => this.run(inp.value.trim()), 180); });
inp.addEventListener("keydown", ev => {
if (ev.key === "ArrowDown" || ev.key === "ArrowUp") { ev.preventDefault(); this.move(ev.key === "ArrowDown" ? 1 : -1); }
else if (ev.key === "Enter") { ev.preventDefault(); this.pick(this.at, ev.shiftKey); }
else if (ev.key === "Escape") { ev.preventDefault(); this.close(); }
});
res.addEventListener("pointermove", ev => { const r = ev.target.closest("[data-fi]"); if (r && +r.dataset.fi !== this.at) this.move(+r.dataset.fi - this.at); });
res.addEventListener("click", ev => { const r = ev.target.closest("[data-fi]"); if (r) this.pick(+r.dataset.fi, ev.shiftKey); });
this.el = f; this.inp = inp; this.res = res;
},
open() {
if (!this.el) this.build();
Menu.close();
this.el.hidden = false;
document.body.classList.add("finding");
this.inp.select(); this.inp.focus();
if (!this.inp.value) this.hint();
},
close() { if (!this.el || this.el.hidden) return; this.el.hidden = true; document.body.classList.remove("finding"); this.inp.blur(); },
hint() { this.items = []; this.res.innerHTML = `<p class="fmsg">Type to search every server. <kbd>↑</kbd><kbd>↓</kbd> to move, <kbd>↵</kbd> to open, <kbd>⇧↵</kbd> to queue a song.</p>`; },
// Plex playlists aren't in hub search results per section, so keep a short-lived list of them.
async plexPlaylists() {
if (!this.pls || Date.now() - this.plsAt > 120000) {
this.plsAt = Date.now();
this.pls = everything(liveServers().map(srv => ({ srv })), "/playlists", { playlistType: "audio" }).catch(() => []);
}
return this.pls;
},
async run(q) {
const n = ++this.n;
if (!q) return this.hint();
this.res.classList.add("busy");
const lq = q.toLowerCase(), has = s => (s || "").toLowerCase().includes(lq);
const [hubs, pls] = await Promise.all([
Promise.all(sources().map(s => px(s.srv, "/hubs/search", { query: q, limit: 8, sectionId: s.sec })
.then(mc => (mc.Hub || []).flatMap(h => (h.Metadata || []).map(m => (m._srv = s.srv.id, m._type = h.type, m)))).catch(() => []))).then(a => a.flat()),
this.plexPlaylists(),
]);
if (n !== this.n) return;
this.res.classList.remove("busy");
const of = t => hubs.filter(m => m._type === t), dedupe = (a, k) => [...new Map(a.map(x => [k(x), x])).values()];
const songs = dedupe(of("track").map(m => track(m._srv, m)), t => t.id).slice(0, 8);
const groups = [
["Songs", songs.map(t => ({ kind: "song", t: t.title, s: [t.artist, t.album].filter(Boolean).join(" · "), art: artOf(t, 96), track: t }))],
["Artists", dedupe(of("artist"), m => m._srv + m.ratingKey).slice(0, 5).map(m => ({ kind: "artist", t: m.title, s: "Artist", art: img(m._srv, m.thumb, 96), round: true, href: `#/artist/${m._srv}:${m.ratingKey}` }))],
["Albums", dedupe(of("album"), m => m._srv + m.ratingKey).slice(0, 6).map(m => ({ kind: "album", t: m.title, s: [m.parentTitle, m.year].filter(Boolean).join(" · "), art: img(m._srv, m.thumb, 96), href: `#/album/${m._srv}:${m.ratingKey}` }))],
["Playlists", [
...playlists.filter(p => has(p.title)).map(p => ({ kind: "playlist", t: p.title, s: `Stem playlist · ${plural(p.items.length, "track")}`, art: artOf(p.items[0]?.track, 96), href: `#/stemplaylist/${p.id}` })),
...pls.filter(p => has(p.title)).map(p => ({ kind: "playlist", t: p.title, s: `Playlist · ${plural(p.leafCount || 0, "track")}`, art: img(p._srv, p.thumb || p.composite, 96), href: `#/playlist/${p._srv}:${p.ratingKey}` })),
].slice(0, 6)],
].filter(g => g[1].length);
this.items = groups.flatMap(g => g[1]);
this.items.push({ kind: "all", t: `See all results for “${q}”`, href: "#/search/" + encodeURIComponent(q) });
let i = 0;
const row = it => `<div class="frow ${it.kind === "all" ? "fall" : ""}" role="option" data-fi="${i++}">${it.kind === "all" ? `<span class="fic">${ICON.search}</span>`
: `<span class="fart ${it.round ? "round" : ""}">${it.art ? `<img src="${esc(it.art)}" alt="" loading="lazy" decoding="async" ${FB}>` : ""}</span>`}
<span class="ftx"><b>${esc(it.t)}</b>${it.s ? `<small>${esc(it.s)}</small>` : ""}</span>${it.kind === "song" ? `<span class="fkey">Play</span>` : it.kind === "all" ? "" : `<span class="fkey">Open</span>`}</div>`;
this.res.innerHTML = (groups.length ? "" : `<p class="fmsg">No matches.</p>`) +
groups.map(([h, its]) => `<div class="fgrp"><h4>${h}</h4>${its.map(row).join("")}</div>`).join("") + row(this.items.at(-1));
this.at = 0; this.move(0);
},
move(d) {
if (!this.items.length) return;
this.at = (this.at + d + this.items.length) % this.items.length;
this.res.querySelector(".frow.on")?.classList.remove("on");
const r = this.res.querySelector(`[data-fi="${this.at}"]`);
r?.classList.add("on");
if (d) r?.scrollIntoView({ block: "nearest" });
},
pick(i, queue) {
const it = this.items[i];
if (!it) return;
this.close();
if (it.track) return queue ? Q.add([it.track], false) : Q.playList([it.track], 0, false);
location.hash = it.href;
},
};
$("#b-search").innerHTML = ICON.search;
$("#b-search").onclick = () => Finder.open();
const download = (tracks, group = null) => saveOffline(tracks, m => m && toast(m, 120000), group);
function stemItem(tracks) {
const need = tracks.filter(t => !Stems.find(t));
@@ -672,12 +768,28 @@ function stemItem(tracks) {
}
return { label: tracks.length === 1 ? "Stem Now" : `Stem Now (${need.length})`, run: () => stemNow(tracks) };
}
function pickPlaylist(x, y, tracks, mix = null) {
// Stem playlists live in the browser. Plex playlists take the songs from their own server.
async function pickPlaylist(x, y, tracks, mix = null) {
const add = p => { addToPlaylist(p, tracks, mix); toast(`Added to “${p.title}”${mix ? " with this mix" : ""}`); };
const srv = tracks.find(t => t.srv && t.key)?.srv, pts = tracks.filter(t => t.srv === srv && t.key);
const pls = srv && server(srv) && !mix ? ((await px(srv, "/playlists", { playlistType: "audio" }).catch(() => ({}))).Metadata || []).filter(p => !p.smart) : [];
const toPlex = async (key, title) => {
try {
const uri = await plexUri(srv, pts.map(t => t.key));
if (key) await pxSend(srv, "PUT", `/playlists/${key}/items`, { uri });
else await pxSend(srv, "POST", "/playlists", { type: "audio", title, smart: 0, uri });
Finder.pls = null;
toast(`Added to “${title}”`);
if (location.hash === `#/playlist/${srv}:${key}`) route();
} catch (e) { toast(e.message); }
};
Menu.open(x, y, [
{ head: "Stem playlists" },
{ label: "New stem playlist…", run: () => { const n = prompt("Stem playlist name"); if (n?.trim()) add(newPlaylist(n.trim())); } },
playlists.length && "-",
...playlists.map(p => ({ label: p.title, run: () => add(p) })),
...(srv && server(srv) && !mix ? ["-", { head: `Plex playlists · ${server(srv).name}` },
{ label: "New Plex playlist…", run: () => { const n = prompt("Plex playlist name"); if (n?.trim()) toPlex(null, n.trim()); } },
...pls.map(p => ({ label: p.title, run: () => toPlex(p.ratingKey, p.title) }))] : []),
]);
}
function trackMenu(x, y, listId, i) {
@@ -688,7 +800,7 @@ function trackMenu(x, y, listId, i) {
{ label: "Add to queue", run: () => Q.add([listItems[listId]?.[i] || t]) },
"-",
stemItem([t]),
{ label: "Add to stem playlist…", run: () => pickPlaylist(x, y, [t]) },
{ label: "Add to playlist…", run: () => pickPlaylist(x, y, [t]) },
Offline.has(t.id) ? { label: "Remove download", run: () => Offline.remove(t.id).then(() => emit("offline")) }
: { label: "Download for offline", run: () => download([t]) },
(t.albumKey || t.artistKey) && "-",
@@ -698,9 +810,15 @@ function trackMenu(x, y, listId, i) {
pl && Q.cur()?.id === t.id && E.entry && { label: "Use the current mix here", run: () => { pl.items[i].mix = JSON.parse(JSON.stringify(S.mix)); savePlaylists(); route(); } },
pl && pl.items[i].mix && { label: "Clear this item's mix", run: () => { pl.items[i].mix = null; savePlaylists(); route(); } },
pl && { label: "Remove from playlist", run: () => { pl.items.splice(i, 1); pl.updated = Date.now(); savePlaylists(); route(); } },
listId === "playlist" && curPx?.editable && t.pid != null && "-",
listId === "playlist" && curPx?.editable && t.pid != null && { label: "Remove from playlist", run: async () => {
try { await pxSend(curPx.srv, "DELETE", `/playlists/${curPx.key}/items/${t.pid}`); Finder.pls = null; route(); } catch (e) { toast(e.message); }
} },
]);
}
async function leaves(srv, key) { return ((await px(srv, `/library/metadata/${key}/allLeaves`)).Metadata || []).map(m => track(srv, m)); }
// The image's current src plus its fallback (Plex playlist composites often fail to transcode).
const artUrls = im => im ? [im.src, im.getAttribute("data-fb")].filter(u => u && !u.startsWith("data:")) : [];
function listMenu(x, y, get, group = null) {
const run = fn => async () => { try { fn(visible(await get())); } catch (e) { toast(e.message); } };
Menu.open(x, y, [
@@ -710,13 +828,14 @@ function listMenu(x, y, get, group = null) {
{ label: "Add to queue", run: run(ts => Q.add(ts)) },
"-",
{ label: "Stem Now", run: run(ts => stemNow(ts)) },
{ label: "Add to stem playlist…", run: run(ts => pickPlaylist(x, y, ts)) },
{ label: "Add to playlist…", run: run(ts => pickPlaylist(x, y, ts)) },
{ label: "Download for offline", run: run(ts => download(ts, group)) },
]);
}
// ---- views --------------------------------------------------------------------------------------
let curPx = null, pxEdit = null;
let lists = {}, listItems = {}, seq = 0, kick = null, genreCache = null;
const visible = tracks => S.stemFilter ? tracks.filter(t => !!Stems.find(t.t || t) === (S.stemFilter === "stems")) : tracks;
function playFrom(listId, i) {
@@ -727,15 +846,16 @@ function playFrom(listId, i) {
// A broken image tries its fallback (data-fb) once, then shows the placeholder.
const FB = `onerror="if(this.dataset.fb){this.src=this.dataset.fb;this.dataset.fb=''}else{this.onerror=null;this.src='data:image/gif;base64,R0lGODlhAQABAAAAACw='}"`;
function card({ href, img: src, fb, t, s = "", round, kind, srv, key }) {
function card({ href, img: src, fb, t, s = "", round, kind, srv, key, dl }) {
const nk = kind === "album" || kind === "artist" ? nameKey(t) : "";
const hide = nk && !stemSets()[kind].has(nk);
return `<a class="card ${round ? "round" : ""} ${hide ? "nostem" : ""}" href="${href}" ${kind ? `data-kind="${kind}" data-srv="${esc(srv)}" data-key="${esc(key)}"` : ""} ${nk ? `data-nk="${esc(nk)}"` : ""}>
<div class="art">${src ? `<img loading="lazy" decoding="async" src="${esc(src)}" ${fb ? `data-fb="${esc(fb)}"` : ""} ${FB} alt="">` : `<div class="ph"></div>`}${kind ? `<button class="cplay" data-cardplay title="Play">${ICON.play}</button>` : ""}</div><div class="t">${esc(t)}</div><div class="s">${esc(s)}</div></a>`;
return `<a class="card ${round ? "round" : ""} ${hide ? "nostem" : ""}" href="${href}" ${kind ? `data-kind="${kind}" data-srv="${esc(srv)}" data-key="${esc(key)}"` : ""} ${dl != null ? `data-dl="${dl}"` : ""} ${nk ? `data-nk="${esc(nk)}"` : ""}>
<div class="art">${src ? `<img loading="lazy" decoding="async" src="${esc(src)}" ${fb ? `data-fb="${esc(fb)}"` : ""} ${FB} alt="">` : `<div class="ph"></div>`}${kind || dl != null ? `<button class="cplay" data-cardplay title="Play">${ICON.play}</button>` : ""}</div><div class="t">${esc(t)}</div><div class="s">${esc(s)}</div></a>`;
}
// Tracks behind a card, for its play button and right-click menu.
async function cardTracks(c) {
const { kind, srv, key } = c.dataset;
const { kind, srv, key, dl } = c.dataset;
if (dl != null) return lists["dl:" + dl] || [];
if (kind === "playlist") return ((await px(srv, `/playlists/${key}/items`)).Metadata || []).map(m => track(srv, m));
return leaves(srv, key);
}
@@ -764,9 +884,20 @@ const stemsChip = () => `<div class="seg stemfilter">${[["stems", "Stems Only"],
`<button class="${S.stemFilter === v ? "on" : ""}" data-stemfilter="${v}">${l}</button>`).join("")}</div>`;
function sortControl(screen) {
const st = sortState(screen);
return `<div class="sort"><select data-sort="${screen}" title="Sort">${st.opts.map((o, i) => `<option value="${i}" ${i === st.i ? "selected" : ""}>${o[0]}</option>`).join("")}</select>
${st.random ? `<button class="chip" data-reshuffle title="Shuffle again">${ICON.shuffle}</button>`
: `<button class="chip" data-sortdir="${screen}" title="Flip order">${st.desc ? st.o[4] : st.o[3]}</button>`}</div>`;
return `<button class="sortbtn" data-sortmenu="${screen}" title="Sort" aria-haspopup="menu">${ICON.sort}<span>${st.o[0]}</span>` +
`${st.random ? "" : `<small>${st.desc ? st.o[4] : st.o[3]}</small>`}<i class="caret"></i></button>`;
}
// The sort menu: fields with a check on the current one, then the two directions (or reshuffle).
function sortMenu(btn) {
const screen = btn.dataset.sortmenu, st = sortState(screen), r = btn.getBoundingClientRect(), go = f => () => { f(); route(); };
Menu.open(r.left, r.bottom + 6, [
{ head: "Sort by" },
...st.opts.map((o, i) => ({ label: o[0], check: i === st.i, run: go(() => i !== st.i && pickSort(screen, i)) })),
"-",
...(st.random ? [{ label: "Shuffle again", run: () => route() }]
: [{ label: st.o[3], check: !st.desc, run: go(() => pickSort(screen, st.i, false)) }, { label: st.o[4], check: st.desc, run: go(() => pickSort(screen, st.i, true)) }]),
]);
Menu.el.classList.add("sortmenu"); Menu.from = btn;
}
const bar = (title, { sort, filter = true, extra = "" } = {}) =>
`<div class="bar"><h1>${esc(title)}</h1><span class="sub" id="count"></span><span class="grow"></span>${extra}${filter ? stemsChip() : ""}${sort ? sortControl(sort) : ""}</div>`;
@@ -825,21 +956,32 @@ async function genres() {
}
const hue = s => [...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 360, 7);
// Downloads by the album or playlist they came from, newest first. Single songs go under Songs.
// Downloads the way iOS shows them: Playlists, Albums and Artists as card grids, then loose songs.
let dlUrls = [];
const DL_KINDS = [["Playlists", h => !/^#\/(album|artist)\//.test(h)], ["Albums", h => h.startsWith("#/album/")], ["Artists", h => h.startsWith("#/artist/")]];
function dlGroups(recs) {
const by = new Map();
const by = new Map(), loose = [];
for (const r of recs) {
const k = r.group?.href || "";
const k = r.group?.href;
if (!k) { loose.push(r); continue; }
if (!by.has(k)) by.set(k, { g: r.group, recs: [] });
by.get(k).recs.push(r);
}
const gs = [...by.values()].sort((a, b) => !a.g - !b.g);
return gs.map(({ g, recs }, n) => {
if (g) recs.sort((a, b) => a.saved - b.saved);
return `<section class="dlgroup"><div class="bar sm"><h2>${g ? `<a href="${esc(g.href)}">${esc(g.title)}</a>` : "Songs"}</h2>
<span class="sub">${plural(recs.length, "track")}, ${fmtBytes(recs.reduce((a, r) => a + r.size, 0))}</span><span class="grow"></span>
<button class="chip" data-dlgroup="${n}">Remove</button></div>${trackTable("dl:" + n, recs.map(r => r.track))}</section>`;
}).join("");
const gs = [...by.values()];
gs.forEach((x, n) => { x.n = n; x.recs.sort((a, b) => a.saved - b.saved); lists["dl:" + n] = x.recs.map(r => r.track); });
dlUrls.forEach(u => URL.revokeObjectURL(u)); dlUrls = [];
const blobUrl = b => b instanceof Blob ? (dlUrls.push(URL.createObjectURL(b)), dlUrls.at(-1)) : "";
const tile = ({ g, recs, n }) => {
const t = recs[0].track, h = g.href, songs = plural(recs.length, "song");
const art = blobUrl(g.art) || blobUrl(recs.find(r => r.group?.art instanceof Blob)?.group.art) || blobUrl(recs.find(r => r.art)?.art) || artOf(recs.find(r => r.track.thumb)?.track, 300);
const s = h.startsWith("#/album/") ? t.artist || "" : h.startsWith("#/artist/") ? songs : `Playlist · ${songs}`;
return card({ href: esc(h), img: art, t: g.title, s, round: h.startsWith("#/artist/"), dl: n });
};
return DL_KINDS.map(([title, test]) => {
const list = gs.filter(x => test(x.g.href));
return list.length ? `<section class="dlgroup"><div class="bar sm"><h2>${title}</h2></div><div class="grid">${list.map(tile).join("")}</div></section>` : "";
}).join("") + (loose.length ? `<section class="dlgroup"><div class="bar sm"><h2>Other Songs</h2><span class="grow"></span>
<button class="chip" data-dlgroup="loose">Remove</button></div>${trackTable("dl:loose", loose.map(r => r.track))}</section>` : "");
}
// Albums whose original release date falls today (or within three days) in an earlier year.
@@ -992,9 +1134,11 @@ const routes = {
const [srv, key] = splitKey(arg);
const [info, items] = await Promise.all([px(srv, `/playlists/${key}`), px(srv, `/playlists/${key}/items`)]);
if (my !== seq) return;
const p = info.Metadata?.[0] || {}, tracks = sortTracks((items.Metadata || []).map(m => track(srv, m)), sortState("playlist"));
view.innerHTML = hero(img(srv, p.thumb || p.composite, 420), "Playlist", p.title, plural(tracks.length, "track"), "playlist", false, p.composite && rawImg(srv, p.composite, 420))
+ `<div class="bar sm"><span class="grow"></span>${stemsChip()}${sortControl("playlist")}</div>` + trackTable("playlist", tracks);
const p = info.Metadata?.[0] || {}, raw = (items.Metadata || []).map(m => track(srv, m)), tracks = sortTracks(raw, sortState("playlist"));
curPx = { srv, key, title: p.title, editable: !p.smart, raw };
const id = esc(arg), tools = p.smart ? " · Smart playlist" : ` · <button class="link" data-pxedit="${id}">Edit</button> · <button class="link" data-pxrename="${id}">Rename</button> · <button class="link" data-pxdelete="${id}">Delete</button>`;
view.innerHTML = hero(img(srv, p.thumb || p.composite, 420), "Playlist", p.title, plural(tracks.length, "track") + tools, "playlist", false, p.composite && rawImg(srv, p.composite, 420))
+ `<div id="pxbody"><div class="bar sm"><span class="grow"></span>${stemsChip()}${sortControl("playlist")}</div>${trackTable("playlist", tracks)}</div>`;
},
async stemplaylist(my, id) {
const p = playlists.find(x => x.id === id);
@@ -1025,10 +1169,11 @@ const routes = {
if (my !== seq) return;
const total = recs.reduce((a, r) => a + r.size, 0);
const est = await navigator.storage?.estimate?.().catch(() => null);
lists["dl:all"] = recs.map(r => r.track);
view.innerHTML = bar("Downloads", { filter: false, extra: recs.length ? `<button class="chip" data-dlclear>Remove all</button>` : "" })
+ `<p class="note">${plural(recs.length, "track")}, ${fmtBytes(total)} stored in this browser${est?.quota ? ` (${fmtBytes(est.usage)} of ${fmtBytes(est.quota)} used)` : ""}.
+ `<p class="note">${plural(recs.length, "song")} · ${fmtBytes(total)} stored in this browser${est?.quota && !isSecureContext ? ` (${fmtBytes(est.usage)} of ${fmtBytes(est.quota)} used)` : ""}.
Downloads play without the network. ${isSecureContext ? "" : "This page isn't on HTTPS, so the browser may clear them when space runs low."}</p>`
+ (recs.length ? dlGroups(recs) : `<p class="empty-msg">Nothing downloaded.</p>`);
+ (recs.length ? actions("dl:all") + dlGroups(recs) : `<p class="empty-msg">Nothing downloaded. Right-click any playlist, album or artist and choose Download for offline.</p>`);
count(recs.length, "track");
},
async stems(my) {
@@ -1050,6 +1195,7 @@ const routes = {
async function route() {
const my = ++seq;
pxEdit = null; curPx = null;
const [, name = "home", ...rest] = (location.hash || "#/home").split("/");
const arg = decodeURIComponent(rest.join("/"));
$$("#nav a").forEach(a => a.classList.toggle("on", a.dataset.nav === name || (a.dataset.nav === "genres" && name === "genre") || (a.dataset.nav === "playlists" && /playlist$/.test(name))));
@@ -1062,11 +1208,6 @@ async function route() {
if (my === seq) marks();
}
addEventListener("hashchange", route);
$("#search").onsubmit = ev => {
ev.preventDefault();
const q = ev.target.q.value.trim();
if (q) location.hash = "#/search/" + encodeURIComponent(q);
};
view.addEventListener("click", async ev => {
const el = ev.target.closest("button, tr[data-list]");
@@ -1078,8 +1219,7 @@ view.addEventListener("click", async ev => {
return ts.length ? Q.playList(ts, 0, false) : toast("Nothing to play");
}
if (ds.stemfilter) { S.stemFilter = S.stemFilter === ds.stemfilter ? "" : ds.stemfilter; save(); applyStemFilter(); return; }
if ("sortdir" in ds) { pickSort(ds.sortdir, sortState(ds.sortdir).i); return route(); }
if ("reshuffle" in ds) return route();
if (ds.sortmenu) return Menu.el ? Menu.close() : sortMenu(el);
if ("add" in ds && row) return Q.add([listItems[row.dataset.list]?.[+row.dataset.i] || lists[row.dataset.list][+row.dataset.i]], ev.shiftKey);
if ("menu" in ds && row) { const r = el.getBoundingClientRect(); return trackMenu(r.left, r.bottom, row.dataset.list, +row.dataset.i); }
if (el === row) return playFrom(row.dataset.list, +row.dataset.i);
@@ -1089,7 +1229,7 @@ view.addEventListener("click", async ev => {
if (!tracks.length) return toast(!all.length ? "Still loading…" : S.stemFilter === "nostems" ? "All of these have stems" : "None of these have stems yet");
return Q.playList(tracks, ds.mode === "shuffle" ? -1 : 0, ds.mode === "shuffle");
}
if (ds.listmenu) { const r = el.getBoundingClientRect(); return listMenu(r.left, r.bottom, async () => listItems[ds.listmenu] || lists[ds.listmenu] || [], { title: $(".hero h1", view)?.textContent || "", href: location.hash }); }
if (ds.listmenu) { const r = el.getBoundingClientRect(); return listMenu(r.left, r.bottom, async () => listItems[ds.listmenu] || lists[ds.listmenu] || [], { title: $(".hero h1", view)?.textContent || "", href: location.hash, art: artUrls($(".hero img.art", view)) }); }
if (ds.station) {
try {
let ts;
@@ -1116,11 +1256,7 @@ view.addEventListener("click", async ev => {
S.stations = S.stations.filter(x => x.id !== ds.rddelete); save();
return route();
}
if (ds.dlgroup) {
const ts = lists["dl:" + ds.dlgroup] || [];
if (confirm(`Remove ${plural(ts.length, "download")}?`)) { for (const t of ts) await Offline.remove(t.id); emit("offline"); route(); }
return;
}
if (ds.dlgroup) return removeDl(ds.dlgroup, "these songs");
if ("shuffleall" in ds) {
const ts = (await new Pager(sources(), secPath, { type: 10, sort: "random" }, 200).next(200)).map(m => track(m._srv, m));
return Q.playList(visible(ts), -1, true);
@@ -1131,19 +1267,92 @@ view.addEventListener("click", async ev => {
const ts = (await Promise.all(albums.map(m => leaves(m._srv, m.ratingKey)))).flat();
return Q.playList(visible(ts), -1, true);
}
if (ds.pxrename && curPx) {
const n = prompt("Rename playlist", curPx.title);
if (n?.trim() && n.trim() !== curPx.title) try { await pxSend(curPx.srv, "PUT", `/playlists/${curPx.key}`, { title: n.trim() }); Finder.pls = null; route(); } catch (e) { toast(e.message); }
return;
}
if (ds.pxdelete && curPx) {
if (confirm(`Delete “${curPx.title}” from Plex? This can't be undone.`)) try { await pxSend(curPx.srv, "DELETE", `/playlists/${curPx.key}`); Finder.pls = null; location.hash = "#/playlists"; } catch (e) { toast(e.message); }
return;
}
if (ds.pxedit && curPx) { pxEdit = { orig: curPx.raw, cur: [...curPx.raw] }; drawPxEdit(); return; }
if ("pxcancel" in ds) { pxEdit = null; route(); return; }
if (ds.pxrm != null && pxEdit) { pxEdit.cur.splice(+ds.pxrm, 1); drawPxEdit(); return; }
if ("pxdone" in ds && pxEdit) { el.disabled = true; await commitPxEdit(); return; }
if ("newpl" in ds) { const n = prompt("Stem playlist name"); if (n?.trim()) { newPlaylist(n.trim()); route(); } return; }
if (ds.plrename) { const p = playlists.find(x => x.id === ds.plrename), n = prompt("Rename", p.title); if (n?.trim()) { p.title = n.trim(); savePlaylists(); route(); } return; }
if (ds.pldelete) { if (confirm("Delete this stem playlist?")) { playlists.splice(playlists.findIndex(x => x.id === ds.pldelete), 1); savePlaylists(); location.hash = "#/playlists"; } return; }
if ("dlclear" in ds) { if (confirm("Remove every download?")) { for (const id of [...Offline.ids]) await Offline.remove(id); emit("offline"); route(); } }
});
view.addEventListener("change", ev => {
const s = ev.target.dataset.sort;
if (s) { pickSort(s, +ev.target.value); route(); }
// ---- Plex playlist edit mode (iOS PlaylistScreens): drag to reorder, remove, then Done ----------
function drawPxEdit() {
const body = $("#pxbody", view);
if (!body || !pxEdit) return;
body.innerHTML = `<div class="bar sm"><span class="note">Drag to reorder</span><span class="grow"></span><button class="chip" data-pxcancel>Cancel</button><button class="chip on" data-pxdone>Done</button></div>
<div class="pxedit">${pxEdit.cur.map((t, i) => `<div class="pxrow" data-i="${i}"><span class="grip" title="Drag">${ICON.queue}</span><img src="${esc(artOf(t, 96))}" alt="" ${FB}><div class="pxt"><b>${esc(t.title)}</b><small>${esc(t.artist)}</small></div><button class="ib bad" data-pxrm="${i}" title="Remove">${ICON.x}</button></div>`).join("") || `<p class="empty-msg">Nothing left. Done will empty the playlist.</p>`}</div>`;
}
// Pointer drag on the grip, so it works with touch too. Only transforms move during the drag.
view.addEventListener("pointerdown", e => {
const g = e.target.closest(".pxrow .grip");
if (!g || !pxEdit) return;
e.preventDefault();
const row = g.parentElement, wrap = row.parentElement, rows = [...wrap.children], from = +row.dataset.i;
const h = row.getBoundingClientRect().height + parseFloat(getComputedStyle(wrap).rowGap || 0), y0 = e.clientY;
let to = from;
row.classList.add("drag"); g.setPointerCapture(e.pointerId);
const move = ev => {
const dy = ev.clientY - y0;
to = Math.max(0, Math.min(rows.length - 1, from + Math.round(dy / h)));
row.style.transform = `translateY(${dy}px)`;
rows.forEach((r, i) => { if (r !== row) r.style.transform = i > from && i <= to ? `translateY(${-h}px)` : i < from && i >= to ? `translateY(${h}px)` : ""; });
};
const up = () => {
g.removeEventListener("pointermove", move); g.removeEventListener("pointerup", up); g.removeEventListener("pointercancel", up);
if (to !== from) pxEdit.cur.splice(to, 0, ...pxEdit.cur.splice(from, 1));
drawPxEdit();
};
g.addEventListener("pointermove", move); g.addEventListener("pointerup", up); g.addEventListener("pointercancel", up);
});
// Removals first, then replay the new order as move-after calls against a simulated list.
async function commitPxEdit() {
const { srv, key } = curPx, keep = new Set(pxEdit.cur.map(t => t.pid));
try {
for (const t of pxEdit.orig) if (!keep.has(t.pid)) await pxSend(srv, "DELETE", `/playlists/${key}/items/${t.pid}`);
const sim = pxEdit.orig.filter(t => keep.has(t.pid)).map(t => t.pid);
for (let i = 0; i < pxEdit.cur.length; i++) {
const pid = pxEdit.cur[i].pid;
if (sim[i] === pid) continue;
const after = i ? pxEdit.cur[i - 1].pid : null;
await pxSend(srv, "PUT", `/playlists/${key}/items/${pid}/move`, { after });
sim.splice(sim.indexOf(pid), 1); sim.splice(i, 0, pid);
}
toast("Playlist saved");
} catch (e) { toast(e.message); }
pxEdit = null; Finder.pls = null; route();
}
async function removeDl(n, what) {
const ts = lists["dl:" + n] || [];
if (!confirm(`Remove ${what} (${plural(ts.length, "download")})? They will no longer play offline.`)) return;
for (const t of ts) await Offline.remove(t.id);
emit("offline"); route();
}
function dlMenu(x, y, n, title) {
const ts = () => lists["dl:" + n] || [];
Menu.open(x, y, [
{ label: "Play", run: () => Q.playList(ts(), 0, false) },
{ label: "Shuffle", run: () => Q.playList(ts(), -1, true) },
{ label: "Play next", run: () => Q.add(ts(), true) },
{ label: "Add to queue", run: () => Q.add(ts()) },
"-",
{ label: "Remove download", run: () => removeDl(n, `“${title}”`) },
]);
}
view.addEventListener("contextmenu", ev => {
const row = ev.target.closest("tr[data-list]"), c = ev.target.closest(".card[data-kind]");
if (row) { ev.preventDefault(); trackMenu(ev.clientX, ev.clientY, row.dataset.list, +row.dataset.i); }
else if (c) { ev.preventDefault(); listMenu(ev.clientX, ev.clientY, () => cardTracks(c), { title: $(".t", c).textContent, href: c.getAttribute("href") }); }
const row = ev.target.closest("tr[data-list]"), c = ev.target.closest(".card[data-kind]"), d = ev.target.closest(".card[data-dl]");
if (d) { ev.preventDefault(); dlMenu(ev.clientX, ev.clientY, d.dataset.dl, $(".t", d).textContent); }
else if (row) { ev.preventDefault(); trackMenu(ev.clientX, ev.clientY, row.dataset.list, +row.dataset.i); }
else if (c) { ev.preventDefault(); listMenu(ev.clientX, ev.clientY, () => cardTracks(c), { title: $(".t", c).textContent, href: c.getAttribute("href"), art: artUrls($("img", c)) }); }
});
// ---- settings -----------------------------------------------------------------------------------
@@ -1187,11 +1396,11 @@ function serverHtml(srv) {
: `<small>No music libraries</small>`}</div></div>`;
}
const KEYS = [["Space", "Play / pause"], ["← →", "Seek 5 s"], ["⇧ ← →", "Seek 30 s"], ["S", "Shuffle"], ["R", "Repeat"], ["[ ]", "Speed"],
const KEYS = [["Space", "Play / pause"], ["← →", "Seek 5 s"], ["⇧ ← →", "Seek 30 s"], ["S", "Search"], ["⇧ S", "Shuffle"], ["R", "Repeat"], ["[ ]", "Speed"],
["M", "Mixer"], ["L", "Lyrics"], ["Q", "Queue"], ["K", "Karaoke"], ["P", "Next preset"]];
function renderSettings() {
const theme = THEMES[S.theme] || THEMES.graphite, nMix = Object.keys(songMixes).length;
const nMix = Object.keys(songMixes).length;
view.innerHTML = `<div class="settings"><nav class="toc">${SECTIONS.map(([id, l]) => `<a href="#/settings" data-jump="${id}">${l}</a>`).join("")}</nav><div class="panes">
<h1>Settings</h1>
<section id="set-plex"><h2>Plex</h2>
@@ -1222,8 +1431,10 @@ function renderSettings() {
</section>
<section id="set-look"><h2>Appearance</h2>
<div class="sg"><div class="sr col"><div class="sl"><span>Theme</span></div>
<div class="themes">${Object.entries(THEMES).map(([k, t]) => `<button class="swatch ${S.theme === k ? "on" : ""}" data-theme="${k}" style="background:${t.bg};color:${t.text};border-color:${t.line}"><i style="background:${t.accent}"></i>${k[0].toUpperCase() + k.slice(1)}</button>`).join("")}</div></div>
${srow("Accent", `${S.accent ? `<button class="btn small" id="accentreset">Reset</button>` : ""}<input type="color" id="accent" value="${S.accent || theme.accent}">`)}
<div class="themes">${Object.entries(THEMES).map(([k, t]) => `<button class="tcard ${S.theme === k ? "on" : ""}" data-theme="${k}">
<span class="tmock" style="background:${t.bg};border-color:${t.line}"><i style="background:${t.text}"></i>${"<b></b>".repeat(3).replaceAll("<b>", `<b style="background:${t.raised === t.bg ? t.panel : t.raised}">`)}<u style="background:${accentOf(t)}"></u></span>${t.label}</button>`).join("")}</div></div>
<div class="sr col"><div class="sl"><span>Accent</span><small>${(ACCENTS[S.accent] || ACCENTS.music)[0]}</small></div>
<div class="accents">${Object.entries(ACCENTS).map(([k, [l]]) => `<button class="dot ${(ACCENTS[S.accent] ? S.accent : "music") === k ? "on" : ""}" data-accent="${k}" title="${l}" aria-label="${l}" style="--c:${accentOf(THEMES[S.theme] || THEMES.dark, k)}"></button>`).join("")}</div></div>
${stog("Match album art", sw(`id="arttheme"`, S.artTheme))}
${stog("Call the vocals-only preset “Acapella”", sw(`id="acapella"`, S.acapella))}</div>
<h3 class="sgh">Player bar</h3>
@@ -1293,8 +1504,6 @@ function renderSettings() {
$("#kmode").onchange = ev => setKaraokeMode(ev.target.value);
$("#kdb").oninput = ev => { $("#kdbv").textContent = ev.target.value + " dB"; };
$("#kdb").onchange = ev => setKaraokeMode(S.karaokeMode, +ev.target.value);
$("#accent").oninput = ev => { S.accent = ev.target.value; applyTheme(); save(); };
if ($("#accentreset")) $("#accentreset").onclick = () => { S.accent = ""; applyTheme(); save(); again(); };
let cssTimer;
$("#css").oninput = ev => { clearTimeout(cssTimer); cssTimer = setTimeout(() => { S.css = ev.target.value; applyTheme(); save(); }, 250); };
if ($("#persist")) $("#persist").onclick = async () => toast(await navigator.storage.persist() ? "Downloads will be kept" : "The browser said no");
@@ -1315,11 +1524,12 @@ function renderSettings() {
};
const sv = $(".settings");
sv.addEventListener("click", async ev => {
const b = ev.target.closest("[data-jump], [data-theme], [data-refsrv], [data-rmsrv], [data-plock], [data-pmove], [data-pdel], [data-padd], [data-prestore], [data-pclear]");
const b = ev.target.closest("[data-jump], [data-theme], [data-accent], [data-refsrv], [data-rmsrv], [data-plock], [data-pmove], [data-pdel], [data-padd], [data-prestore], [data-pclear]");
if (!b) return;
const ds = b.dataset;
if (ds.jump) { ev.preventDefault(); $("#set-" + ds.jump).scrollIntoView({ behavior: "smooth", block: "start" }); }
else if (ds.theme) { S.theme = ds.theme; S.accent = ""; applyTheme(); save(); again(); }
else if (ds.theme) { S.theme = ds.theme; applyTheme(); save(); again(); }
else if (ds.accent) { S.accent = ds.accent; applyTheme(); save(); again(); }
else if (ds.refsrv) { try { await refreshServer(server(ds.refsrv)); toast("Refreshed"); } catch (e) { toast(e.message); } plexChanged(); again(); }
else if (ds.rmsrv && confirm("Remove this server?")) { S.servers = S.servers.filter(s => s.id !== ds.rmsrv); plexChanged(); again(); }
else if (ds.plock) toggleLock(ds.plock, mixNames());
+2 -3
View File
@@ -12,8 +12,7 @@
<body>
<div id="app">
<aside id="nav">
<div class="brand">stemify</div>
<form id="search"><input type="search" name="q" placeholder="Search" autocomplete="off"></form>
<div class="navtop"><div class="brand">stemify</div><button id="b-search" title="Search (S)" aria-label="Search"></button></div>
<a href="#/home" data-nav="home"><svg viewBox="0 0 24 24"><path d="M12 3l9 7.5V21h-6.5v-6h-5v6H3V10.5L12 3zm0 2.6L5 11.4V19h2.5v-6h9v6H19v-7.6l-7-5.8z"/></svg>Home</a>
<a href="#/albums" data-nav="albums"><svg viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20zm0 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16zm0 5a3 3 0 1 1 0 6 3 3 0 0 1 0-6zm0 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/></svg>Albums</a>
<a href="#/artists" data-nav="artists"><svg viewBox="0 0 24 24"><path d="M12 3a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9zm0 2a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zm0 8c4.4 0 8 2.2 8 5v3H4v-3c0-2.8 3.6-5 8-5zm0 2c-3.4 0-6 1.6-6 3v1h12v-1c0-1.4-2.6-3-6-3z"/></svg>Artists</a>
@@ -38,7 +37,7 @@
</div>
<div class="center">
<div class="transport">
<button id="b-shuffle" class="side" title="Shuffle (S)"></button>
<button id="b-shuffle" class="side" title="Shuffle (Shift+S)"></button>
<button id="b-prev" title="Previous"></button>
<button id="b-play" class="play" title="Play (Space)"></button>
<button id="b-next" title="Next (hold to skip the album)"></button>
+10 -2
View File
@@ -5,7 +5,7 @@
import { S, save, songMixes, Offline } from "./store.js";
import { Stems, api } from "./stems.js";
import { partUrl } from "./plex.js";
import { partUrl, img } from "./plex.js";
import { emit, load, store, shuffled, toast, clone } from "./util.js";
// ---- mix -------------------------------------------------------------------------------------
@@ -547,8 +547,15 @@ export const Radio = {
// ---- offline ----------------------------------------------------------------------------------
// group: the album or playlist these came from, {title, href}, so Downloads can list them that way.
// Art is stored as Blobs with the songs so Downloads shows it with no network.
const artBlob = url => url && !url.startsWith("data:") ? fetch(url).then(r => r.ok ? r.blob() : null).catch(() => null) : null;
export async function saveOffline(tracks, onStatus, group = null) {
let n = 0;
if (group?.art && !(group.art instanceof Blob)) {
let blob = null;
for (const u of [group.art].flat()) if ((blob = await artBlob(u))) break;
group = { ...group, art: blob };
}
for (const t of tracks) {
if (Offline.has(t.id)) continue;
onStatus?.(`Downloading ${++n} of ${tracks.length}: ${t.title}`);
@@ -566,7 +573,8 @@ export async function saveOffline(tracks, onStatus, group = null) {
blobs = { file: await r.blob() };
}
const size = Object.values(blobs).reduce((a, b) => a + b.size, 0);
await Offline.put({ id: t.id, track: t, entry, fmt: entry ? S.fmt : "original", size, peaks: peaks?.stems || null, blobs, group, saved: Date.now() });
const art = await artBlob(t.srv && t.thumb ? img(t.srv, t.thumb, 300) : "");
await Offline.put({ id: t.id, track: t, entry, art, fmt: entry ? S.fmt : "original", size, peaks: peaks?.stems || null, blobs, group, saved: Date.now() });
} catch (e) { toast(`Couldn't download “${t.title}”: ${e.message}`); }
}
emit("offline");
+19 -1
View File
@@ -23,6 +23,24 @@ export async function px(srv, path, params = {}) {
return (await r.json()).MediaContainer || {};
}
// Writes (playlist edits). Plex answers some of these with an empty body.
export async function pxSend(srv, method, path, params = {}) {
if (typeof srv === "string") srv = server(srv);
if (!srv) throw new Error("That Plex server isn't set up any more");
const u = new URL(srv.url + path, location.href);
for (const [k, v] of Object.entries(params)) if (v != null) u.searchParams.set(k, v);
const r = await fetch(u, { method, headers: headers(srv.token), signal: AbortSignal.timeout(15000) });
if (!r.ok) throw new Error(`Plex ${r.status} from ${srv.name}`);
const txt = await r.text();
try { return JSON.parse(txt).MediaContainer || {}; } catch { return {}; }
}
// The library uri Plex playlists take for a set of items, like iOS PlexServer.itemsURI.
export async function plexUri(srv, keys) {
if (typeof srv === "string") srv = server(srv);
if (!srv.mid) srv.mid = (await px(srv, "/identity")).machineIdentifier;
return `server://${srv.mid}/com.plexapp.plugins.library/library/metadata/${keys.join(",")}`;
}
export function img(srvId, thumb, size = 300) {
const s = server(srvId);
if (!thumb || !s) return "";
@@ -49,7 +67,7 @@ export function track(srvId, m) {
title: m.title, artist: m.originalTitle || m.grandparentTitle || "", album: m.parentTitle || "",
albumKey: m.parentRatingKey, artistKey: m.grandparentRatingKey,
thumb: m.thumb || m.parentThumb || m.grandparentThumb, duration: m.duration || part?.duration || 0,
part: part?.key, file: part?.file, index: m.index,
part: part?.key, file: part?.file, index: m.index, pid: m.playlistItemID,
meta: { titleSort: m.titleSort, addedAt: m.addedAt, lastViewedAt: m.lastViewedAt, viewCount: m.viewCount, userRating: m.userRating },
};
}
+15 -1
View File
@@ -24,11 +24,25 @@ export const S = Object.assign({
acapella: false, // spell "A Cappella" as "Acapella"
bar: { speed: true, mixer: true, lyrics: true, queue: true }, // player bar buttons
stations: [], // web radio: [{id, name, url}]
theme: "graphite", accent: "", css: "", sideArt: false, artTheme: false,
theme: "dark", accent: "music", css: "", sideArt: false, artTheme: false,
}, load(KEY) || {});
if (!S.clientId) S.clientId = uuid();
if (!S.ui2) { if (S.theme === "amber" && !S.accent) S.theme = "graphite"; S.ui2 = true; }
// Before the iOS-style appearance: eight preset themes and a free accent color.
if (!["black", "dark", "white"].includes(S.theme)) {
const old = S.theme, hues = { music: 353, pink: 349, orange: 35, yellow: 48, green: 135, teal: 189, blue: 211, indigo: 241, purple: 280 };
S.theme = old === "oled" ? "black" : old === "light" ? "white" : "dark";
let h = { graphite: 216, amber: 39, ocean: 201, rose: 340, forest: 142, mono: 211, oled: 39, light: 37 }[old] ?? 211;
const m = /^#([0-9a-f]{6})$/i.exec(S.accent || "");
if (m) {
const n = parseInt(m[1], 16), r = (n >> 16) / 255, g = (n >> 8 & 255) / 255, b = (n & 255) / 255, mx = Math.max(r, g, b), c = mx - Math.min(r, g, b);
if (c > 0.05) h = 60 * (mx === r ? ((g - b) / c + 6) % 6 : mx === g ? (b - r) / c + 2 : (r - g) / c + 4);
}
const d = x => Math.min(Math.abs(x - h), 360 - Math.abs(x - h));
S.accent = Object.keys(hues).sort((a, b) => d(hues[a]) - d(hues[b]))[0];
}
if (!S.accent || S.accent[0] === "#") S.accent = "music";
if (S.fmt.startsWith("opus") && !new Audio().canPlayType('audio/ogg; codecs="opus"')) S.fmt = "flac";
// Before multiple servers there was one S.plex and one S.section.
+96 -28
View File
@@ -41,8 +41,11 @@ svg { width: 1em; height: 1em; fill: currentColor; display: block; }
#nav a svg { width: 18px; height: 18px; flex: none; }
#nav a:hover { color: var(--text); background: var(--hover); }
#nav a.on { background: var(--raised); color: var(--text); }
#search input { width: 100%; margin: 10px 0; padding: 7px 10px; background: var(--raised); border: 1px solid transparent; border-radius: 4px; outline: none; }
#search input:focus { border-color: var(--accent); }
.navtop { display: flex; align-items: center; justify-content: space-between; padding-bottom: 8px; }
.navtop .brand { padding-bottom: 0; }
#b-search { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; color: var(--muted); flex: none; }
#b-search:hover { color: var(--text); background: var(--hover); }
#b-search svg { width: 18px; height: 18px; fill: currentColor; }
.settings-link { margin-top: 2px; }
#sideart { display: none; position: sticky; bottom: 0; z-index: 2; margin-top: auto; padding: 10px 0 12px; background: var(--panel); }
#sideart::before { content: ""; position: absolute; left: -10px; right: -10px; bottom: 100%; height: 28px; pointer-events: none; background: linear-gradient(to top, var(--panel), transparent); }
@@ -75,7 +78,7 @@ select, textarea, input[type=text], input[type=url], input[type=password] { back
.card.round img, .card.round .ph { border-radius: 50%; }
.cplay { position: absolute; right: 8px; bottom: 8px; width: 42px; height: 42px; border-radius: 50%; background: var(--accent); color: var(--accent-ink);
display: grid; place-items: center; font-size: 17px; box-shadow: 0 6px 16px #0008; opacity: 0; transform: translateY(6px); transition: opacity .15s, transform .15s; }
.cplay svg { margin-left: 2px; }
.card:hover .cplay, .cplay:focus-visible { opacity: 1; transform: none; }
.cplay:hover { transform: scale(1.06) !important; }
.card .t { margin-top: 10px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@@ -96,7 +99,7 @@ select, textarea, input[type=text], input[type=url], input[type=password] { back
.actions { display: flex; gap: 14px; align-items: center; margin: 4px 0 6px; padding: 14px 0; }
.bigplay { width: 52px; height: 52px; border-radius: 50%; background: var(--accent); color: var(--accent-ink); display: grid; place-items: center; font-size: 22px;
box-shadow: 0 6px 18px #0006; transition: transform .1s, filter .15s; }
.bigplay svg { margin-left: 3px; }
.bigplay:hover { transform: scale(1.05); filter: brightness(1.1); }
.ibtn { color: var(--muted); font-size: 22px; width: 38px; height: 38px; border-radius: 50%; display: grid; place-items: center; }
.ibtn:hover { color: var(--text); }
@@ -124,9 +127,9 @@ select, textarea, input[type=text], input[type=url], input[type=password] { back
.tracks .acts button { opacity: 0; color: var(--muted); font-size: 18px; width: 26px; height: 26px; border-radius: 6px; display: inline-grid; place-items: center; vertical-align: middle; }
.tracks tr:hover .acts button { opacity: 1; }
.tracks .acts button:hover { color: var(--text); background: var(--raised); }
.tag { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .05em; color: var(--muted); border: 1px solid currentColor; border-radius: 4px; padding: 0 4px; margin-left: 8px; vertical-align: 1px; }
.tag.nostems { color: var(--muted); opacity: .8; }
body.stems-ready .card.nostem .t::after { content: "NO STEMS"; font-size: 9px; font-weight: 700; letter-spacing: .05em; color: var(--muted); border: 1px solid currentColor; border-radius: 4px; padding: 0 4px; margin-left: 6px; vertical-align: 1px; }
.tag { display: inline-flex; align-items: center; height: 15px; font-size: 9px; line-height: 1; font-weight: 700; letter-spacing: .06em; color: var(--muted); border: 1px solid color-mix(in srgb, currentColor 55%, transparent); border-radius: 4px; padding: 0 4px; margin-left: 8px; vertical-align: 2px; white-space: nowrap; }
.tag.nostems { color: var(--muted); }
body.stems-ready .card.nostem .s::before { content: "NO STEMS"; display: inline-flex; align-items: center; height: 14px; font-size: 8.5px; line-height: 1; font-weight: 700; letter-spacing: .06em; color: var(--muted); border: 1px solid color-mix(in srgb, currentColor 55%, transparent); border-radius: 4px; padding: 0 4px; margin-right: 6px; vertical-align: 1px; }
.tag.queued { color: var(--muted); }
.tag.stemming { color: var(--accent); animation: pulse 1.4s ease-in-out infinite; }
.tag.failed { color: #e5534b; }
@@ -138,9 +141,12 @@ body.stems-ready .card.nostem .t::after { content: "NO STEMS"; font-size: 9px; f
.bar.sm { margin: 28px 0 12px; }
.bar.sm h2 { margin: 0; }
.grow { flex: 1; }
.sort { display: flex; gap: 6px; align-items: center; }
.sort select { padding: 5px 8px; font-size: 13px; }
.sort .chip svg { display: inline-block; vertical-align: -2px; }
.sortbtn { display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 10px 0 9px; border-radius: 8px; border: 1px solid var(--line);
font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; transition: background .12s, border-color .12s; }
.sortbtn:hover { background: var(--hover); border-color: color-mix(in srgb, var(--line) 50%, var(--muted)); }
.sortbtn svg { width: 15px; height: 15px; fill: var(--muted); flex: none; }
.sortbtn small { color: var(--muted); font-size: 12px; font-weight: 500; }
.sortbtn .caret { width: 6px; height: 6px; margin: -3px 1px 0 1px; border: solid var(--muted); border-width: 0 1.5px 1.5px 0; transform: rotate(45deg); }
.chip { display: inline-flex; gap: 6px; align-items: center; }
.link { color: var(--accent); cursor: pointer; }
.btn.small { padding: 5px 12px; font-size: 13px; }
@@ -170,6 +176,48 @@ body.no-stems .tracks:not(:has(tbody tr.nostem)) ~ .only-nostems { display: bloc
#menu button { display: block; width: 100%; text-align: left; padding: 7px 10px; border-radius: 6px; }
#menu button:not(:disabled):hover { background: var(--accent); color: var(--accent-ink); }
#menu hr { border: 0; border-top: 1px solid var(--line); margin: 4px 2px; }
#menu h5 { margin: 4px 10px 4px; font-size: 11px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); }
#menu button.chk { display: flex; align-items: center; gap: 8px; padding-left: 8px; }
#menu button.chk svg { width: 15px; height: 15px; fill: currentColor; flex: none; visibility: hidden; }
#menu button.chk.on { font-weight: 600; }
#menu button.chk.on svg { visibility: visible; }
#menu.sortmenu { min-width: 190px; }
#finder { position: fixed; inset: 0; z-index: 60; display: flex; justify-content: center; align-items: flex-start; padding: 12vh 16px 16px;
background: color-mix(in srgb, var(--bg) 35%, transparent); animation: ffade .14s ease-out; }
#finder[hidden] { display: none; }
@keyframes ffade { from { opacity: 0; } }
.fbox { width: min(640px, 100%); max-height: 72vh; display: flex; flex-direction: column;
background: color-mix(in srgb, var(--accent) 12%, color-mix(in srgb, var(--raised) 58%, transparent));
-webkit-backdrop-filter: blur(28px) saturate(1.8); backdrop-filter: blur(28px) saturate(1.8);
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent); box-shadow: inset 0 1px 0 color-mix(in srgb, #fff 14%, transparent), 0 24px 60px var(--shadow);
border-radius: 16px; overflow: hidden; animation: fpop .16s cubic-bezier(.2, .9, .3, 1.2); }
@keyframes fpop { from { transform: translateY(-8px) scale(.98); } }
.fin { display: flex; align-items: center; gap: 10px; padding: 0 14px; height: 54px; border-bottom: 1px solid color-mix(in srgb, var(--accent) 22%, transparent); background: color-mix(in srgb, var(--accent) 8%, transparent); flex: none; }
.fin svg { fill: var(--accent) !important; }
.fin svg { width: 20px; height: 20px; fill: var(--muted); flex: none; }
.fin input { flex: 1; min-width: 0; background: none; border: 0; outline: none; font-size: 17px; padding: 0; }
.fres { overflow-y: auto; padding: 6px; overscroll-behavior: contain; }
.fres.busy { opacity: .6; }
.fgrp h4 { margin: 8px 10px 4px; font-size: 11px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); }
.frow { display: flex; align-items: center; gap: 12px; padding: 6px 10px; border-radius: 8px; cursor: pointer; }
.frow.on { background: var(--accent); color: var(--accent-ink); }
.frow.on small, .frow.on .fkey { color: inherit; opacity: .8; }
.fart { width: 38px; height: 38px; border-radius: 5px; overflow: hidden; background: var(--line); flex: none; }
.fart.round { border-radius: 50%; }
.fart img { width: 100%; height: 100%; object-fit: cover; display: block; }
.fic { width: 38px; height: 38px; display: grid; place-items: center; flex: none; }
.fic svg { width: 18px; height: 18px; fill: currentColor; }
.ftx { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
.ftx b, .ftx small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ftx b { font-weight: 600; font-size: 14px; }
.ftx small { color: var(--muted); font-size: 12px; }
.fkey { font-size: 12px; color: var(--muted); visibility: hidden; }
.frow.on .fkey { visibility: visible; }
.fall { margin-top: 4px; }
.fmsg { margin: 14px 12px; color: var(--muted); font-size: 13px; }
.fmsg kbd { margin: 0 2px; }
body.finding { overflow: hidden; }
#toast { position: fixed; left: 50%; bottom: calc(var(--player-h) + 18px); transform: translate(-50%, 10px); z-index: 60; max-width: min(520px, calc(100% - 32px));
background: var(--text); color: var(--bg); padding: 9px 16px; border-radius: 999px; font-weight: 500; font-size: 13px; opacity: 0; pointer-events: none; transition: opacity .2s, transform .2s; }
@@ -246,13 +294,20 @@ kbd { display: inline-grid; place-items: center; min-width: 22px; height: 22px;
.keys { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
.keys > div { display: flex; align-items: center; gap: 4px; min-height: 42px; padding: 8px 16px; font-size: 13px; border-top: 1px solid var(--line); margin-top: -1px; }
.keys > div > span { flex: 1; color: var(--muted); }
.themes { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 8px; }
.swatch { border: 1px solid; border-radius: 8px; padding: 10px 12px; text-align: left; font-weight: 600; font-size: 13px; display: flex; gap: 8px; align-items: center; transition: transform .12s; }
.swatch:hover { transform: translateY(-1px); }
.swatch i { width: 12px; height: 12px; border-radius: 50%; flex: none; }
.swatch.on { outline: 2px solid var(--accent); outline-offset: 2px; }
input[type=color] { width: 32px; height: 32px; padding: 0; border: 1px solid var(--line); border-radius: 50%; background: none; cursor: pointer; overflow: hidden; }
input[type=color]::-webkit-color-swatch-wrapper { padding: 0; }
.themes { display: flex; gap: 14px; flex-wrap: wrap; }
.tcard { display: flex; flex-direction: column; align-items: center; gap: 8px; font-size: 13px; font-weight: 500; color: var(--muted); }
.tcard.on { color: var(--text); font-weight: 600; }
.tmock { width: 92px; height: 64px; border-radius: 10px; border: 1px solid; padding: 9px 10px; display: flex; flex-direction: column; gap: 5px;
box-shadow: 0 0 0 0 var(--accent); transition: box-shadow .14s; }
.tcard:hover .tmock { box-shadow: 0 0 0 2px var(--line); }
.tcard.on .tmock { box-shadow: 0 0 0 3px var(--accent); }
.tmock i { width: 40%; height: 5px; border-radius: 3px; opacity: .9; }
.tmock b { height: 6px; border-radius: 3px; }
.tmock u { width: 30%; height: 6px; border-radius: 3px; margin-top: auto; }
.accents { display: flex; gap: 12px; flex-wrap: wrap; padding: 2px; }
.dot { width: 28px; height: 28px; border-radius: 50%; background: var(--c); box-shadow: 0 0 0 0 var(--text); transition: box-shadow .12s, transform .12s; }
.dot:hover { transform: scale(1.08); }
.dot.on { box-shadow: 0 0 0 2px var(--panel), 0 0 0 4px var(--text); }
input[type=color]::-webkit-color-swatch { border: 0; border-radius: 50%; }
input[type=color]::-moz-color-swatch { border: 0; border-radius: 50%; }
.note { color: var(--muted); font-size: 13px; }
@@ -261,11 +316,11 @@ input[type=color]::-moz-color-swatch { border: 0; border-radius: 50%; }
#drawer h2 { margin: 0 0 14px; }
#drawer { display: flex; flex-direction: column; padding-top: 12px; }
#drawer[hidden] { display: none; }
#drawer.mixing { width: 340px; }
#drawer { width: 340px; }
.tabs { display: flex; gap: 4px; margin-bottom: 16px; position: sticky; top: -12px; background: var(--panel); padding: 6px 0; z-index: 1; }
.tabs button { padding: 6px 12px; border-radius: 8px; color: var(--muted); font-weight: 600; }
.tabs button { flex: 1 1 0; padding: 8px 0; border-radius: 9px; color: var(--muted); font-weight: 700; font-size: 16px; text-align: center; }
.tabs button.on { background: var(--raised); color: var(--text); }
.tabs .x { margin-left: auto; font-size: 20px; }
.tabs .x { flex: 0 0 36px; font-size: 22px; padding: 6px 0; }
.kara { display: grid; gap: 10px; margin-bottom: 16px; }
.kara .chip { justify-self: start; }
.seg { display: flex; background: var(--raised); border-radius: 8px; padding: 3px; }
@@ -383,7 +438,7 @@ input[type=range] { accent-color: var(--accent); }
#nav a svg, #sideart, #b-art .exp { display: none !important; }
#nav { overflow-y: hidden; }
#nav a { min-height: 32px; }
#search input { margin: 0; width: 120px; }
.navtop { padding: 0; gap: 4px; }
#live { margin: 0; white-space: nowrap; }
.settings { grid-template-columns: 1fr; gap: 0; }
.toc { display: none; }
@@ -448,12 +503,25 @@ input[type=number]#precachen { width: 64px; background: var(--raised); border: 1
/* toolbar shares its row with the filter/sort bar on wide screens */
@media (min-width: 861px) {
.actions + .bar.sm { margin: -66px 0 12px auto; min-height: 52px; pointer-events: none; }
.actions + .bar.sm > * { pointer-events: auto; }
.actions + .bar.sm:not(:has(h2)) { margin: -66px 0 12px auto; min-height: 52px; pointer-events: none; }
.actions + .bar.sm:not(:has(h2)) > * { pointer-events: auto; }
}
#volume { -webkit-appearance: none; appearance: none; height: 16px; background: none; cursor: pointer; }
#volume::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #3c3f43; }
#volume::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; margin-top: -4px; border-radius: 50%; background: #e7e7e7; border: 0; }
#volume::-moz-range-track { height: 4px; border-radius: 2px; background: #3c3f43; }
#volume::-moz-range-progress { height: 4px; border-radius: 2px; background: #cccccc; }
#volume::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: #e7e7e7; border: 0; }
#volume::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: linear-gradient(90deg, var(--accent) var(--v, 85%), color-mix(in srgb, var(--text) 22%, transparent) var(--v, 85%)); }
#volume::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; margin-top: -4px; border-radius: 50%; background: var(--text); border: 0; }
#volume::-moz-range-track { height: 4px; border-radius: 2px; background: color-mix(in srgb, var(--text) 22%, transparent); }
#volume::-moz-range-progress { height: 4px; border-radius: 2px; background: var(--accent); }
#volume::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: var(--text); border: 0; }
/* Plex playlist edit mode */
.pxedit { display: grid; gap: 4px; }
.pxrow { display: flex; align-items: center; gap: 12px; padding: 6px 10px; border-radius: 10px; background: var(--panel); transition: transform .15s ease; will-change: transform; }
.pxrow.drag { transition: none; position: relative; z-index: 2; box-shadow: var(--shadow); background: var(--raised); }
.pxrow img { width: 40px; height: 40px; border-radius: 6px; object-fit: cover; flex: none; }
.pxrow .pxt { flex: 1; min-width: 0; display: grid; }
.pxrow .pxt b, .pxrow .pxt small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pxrow .pxt b { font-weight: 500; }
.pxrow .pxt small { color: var(--muted); }
.pxrow .grip { cursor: grab; touch-action: none; color: var(--muted); display: grid; place-items: center; padding: 4px; }
.pxrow .grip svg { width: 20px; height: 20px; fill: currentColor; }
.pxrow .ib.bad svg { fill: #ff453a; }
+3 -1
View File
@@ -38,9 +38,11 @@ export const ICON = {
pladd: '<svg viewBox="0 0 24 24"><path d="M3 5h13v2H3zm0 5h13v2H3zm0 5h8v2H3zm15-2h2v3h3v2h-3v3h-2v-3h-3v-2h3z"/></svg>',
up: '<svg viewBox="0 0 24 24"><path d="M12 7.6l7.7 7.7-1.4 1.4-6.3-6.3-6.3 6.3-1.4-1.4z"/></svg>',
down: '<svg viewBox="0 0 24 24"><path d="M12 16.4L4.3 8.7l1.4-1.4 6.3 6.3 6.3-6.3 1.4 1.4z"/></svg>',
search: '<svg viewBox="0 0 24 24"><path d="M10.5 4a6.5 6.5 0 0 1 5.2 10.4l4.4 4.4-1.4 1.4-4.4-4.4A6.5 6.5 0 1 1 10.5 4zm0 2a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9z"/></svg>',
sort: '<svg viewBox="0 0 24 24"><path d="M7 4l4 4H8v12H6V8H3zm10 16l-4-4h3V4h2v12h3z"/></svg>',
x: '<svg viewBox="0 0 24 24"><path d="M6.4 5L12 10.6 17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6 10.6 12 5 6.4z"/></svg>',
lock: '<svg viewBox="0 0 24 24"><path d="M7 10V7a5 5 0 0 1 10 0v3h.5A1.5 1.5 0 0 1 19 11.5v8a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 19.5v-8A1.5 1.5 0 0 1 6.5 10H7zm2 0h6V7a3 3 0 0 0-6 0v3z"/></svg>',
play: '<svg viewBox="0 0 24 24"><path d="M7 4.5v15a1 1 0 0 0 1.5.86l12.5-7.5a1 1 0 0 0 0-1.72L8.5 3.64A1 1 0 0 0 7 4.5z"/></svg>',
play: '<svg viewBox="0 0 24 24"><path d="M5.5 4.5v15a1 1 0 0 0 1.5.86l12.5-7.5a1 1 0 0 0 0-1.72L7 3.64A1 1 0 0 0 5.5 4.5z"/></svg>',
pause: '<svg viewBox="0 0 24 24"><rect x="5.5" y="4" width="4.5" height="16" rx="1.2"/><rect x="14" y="4" width="4.5" height="16" rx="1.2"/></svg>',
prev: '<svg viewBox="0 0 24 24"><rect x="4" y="5" width="2.5" height="14" rx="1"/><path d="M20 5.7v12.6a1 1 0 0 1-1.55.83L9 12.83a1 1 0 0 1 0-1.66l9.45-6.3A1 1 0 0 1 20 5.7z"/></svg>',
next: '<svg viewBox="0 0 24 24"><rect x="17.5" y="5" width="2.5" height="14" rx="1"/><path d="M4 5.7v12.6a1 1 0 0 0 1.55.83L15 12.83a1 1 0 0 0 0-1.66l-9.45-6.3A1 1 0 0 0 4 5.7z"/></svg>',