Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export function SearchInput({
isSearching={isPending}
maxLength={2048}
onChange={handleQueryChange}
placeholder="Search, or paste a link"
placeholder="Search or paste a link"
value={query}
/>
</div>
Expand Down
4 changes: 3 additions & 1 deletion apps/radio/src/components/radio/node/node-inspector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,9 @@ describe("NodeInspector", () => {
fireEvent.click(view.getByRole("button", { name: "Close settings" }));
};
checkSettings("Empty Station", () =>
expect(view.getByPlaceholderText("Search or paste a stream")).toBeTruthy()
expect(
view.getByPlaceholderText("Search stations or paste a link")
).toBeTruthy()
);
checkSettings("Empty Track", () =>
expect(view.getByRole("combobox", { name: "Platform" })).toBeTruthy()
Expand Down
1 change: 0 additions & 1 deletion apps/radio/src/components/radio/node/station-content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ function EmptyStation({
onSelectDiscovered={onSelectDiscovered}
onSelectLocal={onSelectLocal}
onSubmitUrl={onSubmitUrl}
placeholder="Search or paste a stream"
radios={radios}
/>
</EmptySourceFrame>
Expand Down
2 changes: 1 addition & 1 deletion apps/radio/src/components/radio/radio-search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ export function RadioSearchBar({
onSubmitUrl,
className,
dropdownClassName,
placeholder = "Search stations…",
placeholder = "Search stations or paste a link",
}: RadioSearchBarProps) {
const [query, setQuery] = useState("");
const [isOpen, setIsOpen] = useState(false);
Expand Down
200 changes: 200 additions & 0 deletions apps/radio/src/components/radio/single/single-player.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// @ts-expect-error jsdom types are not installed in this workspace.
import { JSDOM } from "jsdom";
import type { Radio } from "@/lib/audio";
import { browserTestGlobals } from "@/test-utils/browser-globals";

if (process.env.RADIO_SINGLE_LINK_REGRESSION === "1") {
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
pretendToBeVisual: true,
url: "https://radio.test",
});
for (const key of [
"document",
"Element",
"HTMLElement",
"HTMLInputElement",
"HTMLFormElement",
"CustomEvent",
"DocumentFragment",
"MutationObserver",
"Node",
"NodeFilter",
"navigator",
"window",
"getComputedStyle",
]) {
Object.defineProperty(globalThis, key, {
configurable: true,
value: dom.window[key],
writable: true,
});
}
Object.assign(globalThis, browserTestGlobals(dom.window), {
IS_REACT_ACT_ENVIRONMENT: true,
ResizeObserver: class {
disconnect() {
// JSDOM does not perform layout.
}
observe() {
// JSDOM does not perform layout.
}
unobserve() {
// JSDOM does not perform layout.
}
},
});
Object.assign(CSS, { supports: () => false });
const noop = () => undefined;
const playRadio = mock(async (_radio: Radio) => undefined);
mock.module("@/lib/hooks/use-single-session", () => ({
useSingleSession: () => ({
currentRadio: null,
playRadio,
selectRadio: noop,
setVolume: noop,
toggleMute: noop,
togglePlayPause: noop,
volume: 1,
}),
}));
mock.module("@/lib/hooks/use-media-session", () => ({
useMediaSession: noop,
}));
mock.module("@/lib/hooks/use-radio-metadata", () => ({
useRadioMetadata: () => ({ metadata: null }),
}));
mock.module("@/components/settings/radio-dialog", () => ({
prefetchStationDialogOnIntent: noop,
RadioDialog: () => null,
}));
const { act, cleanup, fireEvent, render, waitFor } = await import(
"@testing-library/react"
);
const { radiosCollection } = await import("@/lib/collections/radios");
const { getSessionRadios, isSessionRadio, sessionRadiosCollection } =
await import("@/lib/collections/session-radios");
const { stationIntake } = await import(
"@/lib/stations/external-station-workflow"
);
const { SinglePlayer } = await import("./single-player");
beforeEach(async () => {
await sessionRadiosCollection.stateWhenReady();
playRadio.mockClear();
});
afterEach(() => {
cleanup();
mock.restore();
for (const id of sessionRadiosCollection.state.keys()) {
sessionRadiosCollection.delete(id);
}
});
function renderPlayer() {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const view = render(
<QueryClientProvider client={client}>
<SinglePlayer radios={[]} />
</QueryClientProvider>
);
const search = view.getByRole("combobox", {
name: "Search stations",
}) as HTMLInputElement;
const type = (value: string) => {
fireEvent.focusIn(search);
fireEvent.change(search, { target: { value } });
};
return { search, type, view };
}

test.each(["https://stream.example/live", "https://stream.example/live.mp3"])(
"Single plays %s as a temporary station without saving it",
async (url) => {
const savedIds = [...radiosCollection.state.keys()];
const { search, type, view } = renderPlayer();
expect(search.placeholder).toBe("Search stations or paste a link");
type(` ${url} `);
fireEvent.keyDown(search, { key: "Enter" });
await waitFor(() => expect(playRadio).toHaveBeenCalledTimes(1));
const [station] = getSessionRadios();
expect(station).toMatchObject({
id: "stream.example",
name: "stream.example",
streamUrl: url,
});
expect(playRadio).toHaveBeenCalledWith(station);
expect(isSessionRadio(station)).toBe(true);
expect([...radiosCollection.state.keys()]).toEqual(savedIds);
await waitFor(() => expect(search.value).toBe(""));
fireEvent.click(
view.getByRole("button", { name: "Options for stream.example" })
);
expect(view.getByRole("menuitem", { name: "Save" })).toBeTruthy();
fireEvent.click(view.getByRole("menuitem", { name: "Remove" }));
await waitFor(() => expect(getSessionRadios()).toEqual([]));
}
);

test.each([
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"https://youtu.be/dQw4w9WgXcQ",
"https://soundcloud.com/artist/track",
"https://artist.bandcamp.com/track/song",
])("Single explains where platform links play: %s", async (url) => {
const createSession = spyOn(stationIntake, "createSession");
const { search, type, view } = renderPlayer();
type(url);
fireEvent.keyDown(search, { key: "Enter" });
await waitFor(() =>
expect(view.getByRole("alert").textContent).toBe(
"Platform links play in Node or DJ"
)
);
expect(createSession).not.toHaveBeenCalled();
expect(playRadio).not.toHaveBeenCalled();
expect(search.value).toBe(url);
type("another search");
expect(view.queryByRole("alert")).toBeNull();
});

test("changing the query cancels a stream before it is registered or played", async () => {
const { createSession } = stationIntake;
const pending = Promise.withResolvers<void>();
spyOn(stationIntake, "createSession").mockImplementation(
async (candidate, options) => {
await pending.promise;
return createSession(candidate, options);
}
);
const { search, type } = renderPlayer();
type("https://stream.example/live");
fireEvent.keyDown(search, { key: "Enter" });
type("changed");
await act(async () => {
pending.resolve();
await pending.promise;
});
expect(playRadio).not.toHaveBeenCalled();
expect(getSessionRadios()).toEqual([]);
expect(search.value).toBe("changed");
});
} else {
test("Single pasted-link regressions (isolated playback mocks)", async () => {
const child = Bun.spawn([process.execPath, "test", import.meta.path], {
env: { ...process.env, RADIO_SINGLE_LINK_REGRESSION: "1" },
stderr: "pipe",
stdout: "pipe",
timeout: 20_000,
});
const [stderr, exitCode] = await Promise.all([
new Response(child.stderr).text(),
child.exited,
]);
expect({ errors: exitCode ? stderr : "", exitCode }).toEqual({
errors: "",
exitCode: 0,
});
}, 25_000);
}
20 changes: 20 additions & 0 deletions apps/radio/src/components/radio/single/single-player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { LazyBoundary, lazyWithRetry } from "@/components/lazy-recovery";
import type { Radio } from "@/lib/audio";
import { isMediaVolumeLocked } from "@/lib/audio/playback/media-element-volume-control";
import { shouldUseNativeSinglePlayback } from "@/lib/collections/settings";
import { detectPlatformFromUrl } from "@/lib/external-url/detect";
import { useDiscoveredStationActions } from "@/lib/hooks/use-discovered-station-actions";
import { useMediaSession } from "@/lib/hooks/use-media-session";
import { useRadioMetadata } from "@/lib/hooks/use-radio-metadata";
Expand All @@ -22,6 +23,7 @@ import {
} from "@/lib/hooks/use-session-radios";
import { useAudioSettings } from "@/lib/hooks/use-settings";
import { useSingleSession } from "@/lib/hooks/use-single-session";
import { loadStreamStation } from "@/lib/stations/stream-station-loader";
import {
prefetchStationDialogOnIntent,
RadioDialog,
Expand Down Expand Up @@ -92,6 +94,23 @@ export function SinglePlayer({ radios }: SinglePlayerProps) {
const { saveDiscoveredStation, selectDiscoveredStation } =
useDiscoveredStationActions(playRadio);

const handleSubmitUrl = async (url: string, signal: AbortSignal) => {
const platform = detectPlatformFromUrl(url);
if (platform && platform !== "static-audio") {
return "Platform links play in Node or DJ";
}
const isCurrent = () => !signal.aborted;
const loaded = await loadStreamStation(url, { isCurrent });
if (!isCurrent()) {
return null;
}
if ("error" in loaded) {
return loaded.error;
}
await playRadio(loaded.radio);
return null;
};

const [dialogOpen, setDialogOpen] = useState(false);
const [dialogMode, setDialogMode] = useState<"create" | "edit">("create");
const [selectedRadio, setSelectedRadio] = useState<Radio | undefined>();
Expand Down Expand Up @@ -220,6 +239,7 @@ export function SinglePlayer({ radios }: SinglePlayerProps) {
onSaveDiscovered={saveDiscoveredStation}
onSelectDiscovered={selectDiscoveredStation}
onSelectLocal={playRadio}
onSubmitUrl={handleSubmitUrl}
radios={radios ?? []}
/>
}
Expand Down
6 changes: 5 additions & 1 deletion apps/radio/src/lib/collections/session-radios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ export function isSessionRadio(radio: Radio): boolean {
return false;
}
const id = String(radio.id);
return id.startsWith("rb_") || id.startsWith("rg_");
return (
id.startsWith("rb_") ||
id.startsWith("rg_") ||
sessionRadiosCollection.state.has(id)
);
}

function getOrderedSessionRadioRecords(): SessionRadioRecord[] {
Expand Down
36 changes: 2 additions & 34 deletions apps/radio/src/lib/node-source-loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import {
stationIntake,
} from "@/lib/stations/external-station-workflow";

export { loadStreamStation } from "@/lib/stations/stream-station-loader";

export type SourceLoad = { radio: Radio } | { error: string };

export type NodeSourceLoaderDependencies = {
Expand Down Expand Up @@ -138,40 +140,6 @@ export async function loadLocalFile(
}
}

function streamName(url: string): string {
try {
return new URL(url).hostname || url;
} catch {
return url;
}
}

/**
* A radio stream URL pasted into a Station, made a session station as a
* URL added in Settings would be, under its host's name.
*/
export async function loadStreamStation(
url: string,
{
createSession = stationIntake.createSession,
isCurrent,
}: NodeSourceLoaderDependencies = {}
): Promise<SourceLoad> {
const result = await createSession(
{
fields: { name: streamName(url), streamUrl: url },
origin: "manual",
},
{ isCurrent }
);
if (!result.ok) {
return { error: result.error.message };
}
const { radio } = result.data;
// The session record is keyed by name when the radio has no id.
return { radio: { ...radio, id: radio.id ?? radio.name } };
}

export async function loadLocalFiles(
files: readonly File[],
{ loadFile = extractFileMetadata }: NodeSourceLoaderDependencies = {}
Expand Down
36 changes: 36 additions & 0 deletions apps/radio/src/lib/stations/stream-station-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { Radio } from "@/lib/audio";
import { stationIntake } from "./external-station-workflow";

function streamName(url: string): string {
try {
return new URL(url).hostname || url;
} catch {
return url;
}
}

/** A pasted stream becomes a temporary station named after its host. */
export async function loadStreamStation(
url: string,
{
createSession = stationIntake.createSession,
isCurrent,
}: {
createSession?: typeof stationIntake.createSession;
isCurrent?: () => boolean;
} = {}
): Promise<{ radio: Radio } | { error: string }> {
const result = await createSession(
{
fields: { name: streamName(url), streamUrl: url },
origin: "manual",
},
{ isCurrent }
);
if (!result.ok) {
return { error: result.error.message };
}
const { radio } = result.data;
// The session record is keyed by name when the radio has no id.
return { radio: { ...radio, id: radio.id ?? radio.name } };
}
Loading