Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alter user feedback when mic access permission denied #3247

Merged
merged 7 commits into from
Jul 25, 2024
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
7 changes: 5 additions & 2 deletions public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,7 @@
"upload": "Upload"
},
"pronunciations": {
"enableMicTooltip": "Enable microphone access to record.",
"recordTooltip": "Press and hold to record.",
"playTooltip": "Click to play.",
"deleteTooltip": "Shift click to delete.",
Expand All @@ -480,8 +481,10 @@
"speakerAdd": "Right click to add a speaker.",
"speakerChange": "Right click to change speaker.",
"speakerSelect": "Select speaker of this audio recording",
"noMicAccess": "Recording error: Could not access a microphone.",
"deleteRecording": "Delete Recording"
"recordingError": "Recording error",
"deleteRecording": "Delete Recording",
"audioStreamError": "Error getting audio stream!",
"noMicAccess": "No microphone access. Audio recording disabled."
},
"statistics": {
"title": "Data Statistics: {{ val }}",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Pronunciations/AudioRecorder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default function AudioRecorder(props: RecorderProps): ReactElement {
}
const file = await recorder.stopRecording();
if (!file) {
toast.error(t("pronunciations.noMicAccess"));
toast.error(t("pronunciations.recordingError"));
return;
}
if (!props.noSpeaker) {
Expand Down
14 changes: 11 additions & 3 deletions src/components/Pronunciations/Recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import RecordRTC from "recordrtc";
import { getFileNameForWord } from "components/Pronunciations/utilities";

export default class Recorder {
private toast: (text: string) => void;
private toast: (textId: string) => void;
private recordRTC?: RecordRTC;
private id?: string;

static blobType: RecordRTC.Options["type"] = "audio";

constructor(toast?: (text: string) => void) {
constructor(toast?: (textId: string) => void) {
this.toast = toast ?? ((text: string) => alert(text));
navigator.mediaDevices
.getUserMedia({ audio: true })
Expand Down Expand Up @@ -63,6 +63,14 @@ export default class Recorder {

private onError(err: Error): void {
console.error(err);
this.toast("Error getting audio stream!");
navigator.permissions
.query({ name: "microphone" as PermissionName })
.then((result) => {
this.toast(
result.state === "granted"
? "pronunciations.audioStreamError"
: "pronunciations.noMicAccess"
);
});
}
}
5 changes: 4 additions & 1 deletion src/components/Pronunciations/RecorderContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { enqueueSnackbar } from "notistack";
import { createContext } from "react";

import Recorder from "components/Pronunciations/Recorder";
import i18n from "i18n";

const RecorderContext = createContext(new Recorder(enqueueSnackbar));
const RecorderContext = createContext(
new Recorder((textId: string) => enqueueSnackbar(i18n.t(textId)))
);

export default RecorderContext;
65 changes: 39 additions & 26 deletions src/components/Pronunciations/RecorderIcon.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FiberManualRecord } from "@mui/icons-material";
import { IconButton, Tooltip } from "@mui/material";
import { ReactElement } from "react";
import { ReactElement, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import {
Expand Down Expand Up @@ -33,8 +33,15 @@ export default function RecorderIcon(props: RecorderIconProps): ReactElement {
const isRecordingThis = isRecording && recordingId === props.id;

const dispatch = useAppDispatch();
const [hasMic, setHasMic] = useState(false);
const { t } = useTranslation();

useEffect(() => {
navigator.permissions
.query({ name: "microphone" as PermissionName })
.then((result) => setHasMic(result.state === "granted"));
}, []);

function toggleIsRecordingToTrue(): void {
if (!isRecording) {
// Only start a recording if there's not another on in progress.
Expand Down Expand Up @@ -75,36 +82,42 @@ export default function RecorderIcon(props: RecorderIconProps): ReactElement {
document.removeEventListener("contextmenu", disableContextMenu, false);
}

const tooltipId = hasMic
? "pronunciations.recordTooltip"
: "pronunciations.enableMicTooltip";

return (
<Tooltip
disableTouchListener // Distracting when already recording with a long-press.
placement="top"
title={t("pronunciations.recordTooltip")}
title={!props.disabled && t(tooltipId)}
>
<IconButton
aria-label="record"
disabled={props.disabled}
id={recordButtonId}
onBlur={toggleIsRecordingToFalse}
onPointerDown={toggleIsRecordingToTrue}
onPointerUp={toggleIsRecordingToFalse}
onTouchEnd={handleTouchEnd}
onTouchStart={handleTouchStart}
size="large"
tabIndex={-1}
>
<FiberManualRecord
id={recordIconId}
sx={{
color: (t) =>
props.disabled
? t.palette.grey[400]
: isRecordingThis
? themeColors.recordActive
: themeColors.recordIdle,
}}
/>
</IconButton>
<span>
<IconButton
aria-label="record"
disabled={props.disabled || !hasMic}
id={recordButtonId}
onBlur={toggleIsRecordingToFalse}
onPointerDown={toggleIsRecordingToTrue}
onPointerUp={toggleIsRecordingToFalse}
onTouchEnd={handleTouchEnd}
onTouchStart={handleTouchStart}
size="large"
tabIndex={-1}
>
<FiberManualRecord
id={recordIconId}
sx={{
color: (t) =>
props.disabled || !hasMic
? t.palette.grey[400]
: isRecordingThis
? themeColors.recordActive
: themeColors.recordIdle,
}}
/>
</IconButton>
</span>
</Tooltip>
);
}
8 changes: 4 additions & 4 deletions src/components/Pronunciations/tests/AudioRecorder.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ function mockRecordingState(wordId: string): Partial<StoreState> {
}

describe("AudioRecorder", () => {
test("default icon style is idle", () => {
act(() => {
test("default icon style is idle", async () => {
await act(async () => {
testRenderer = create(
<ThemeProvider theme={theme}>
<StyledEngineProvider>
Expand All @@ -41,10 +41,10 @@ describe("AudioRecorder", () => {
expect(icon.props.sx.color({})).toEqual(themeColors.recordIdle);
});

test("icon style depends on pronunciations state", () => {
test("icon style depends on pronunciations state", async () => {
const wordId = "1";
const mockStore2 = configureMockStore()(mockRecordingState(wordId));
act(() => {
await act(async () => {
testRenderer = create(
<ThemeProvider theme={theme}>
<StyledEngineProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ let testRenderer: renderer.ReactTestRenderer;
const mockStore = configureMockStore()(defaultState);

describe("PronunciationsFrontend", () => {
it("renders with record button and play buttons", () => {
it("renders with record button and play buttons", async () => {
const audio = ["a.wav", "b.wav"].map((f) => newPronunciation(f));
renderer.act(() => {
await renderer.act(async () => {
testRenderer = renderer.create(
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
Expand Down
9 changes: 8 additions & 1 deletion src/setupTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ global.console.warn = (message) => {
throw message;
};

// Mock all permissions as granted
Object.defineProperty(navigator, "permissions", {
get() {
return { query: () => Promise.resolve({ state: "granted" }) };
},
});

// Mock the audio components
jest
.spyOn(window.HTMLMediaElement.prototype, "pause")
.mockImplementation(() => {});
jest.mock("components/Pronunciations/Recorder");
jest.mock("components/Pronunciations/RecorderContext", () => ({}));

// Mock the router to short circuit a circular dependency
jest.mock("router/browserRouter", () => ({ navigate: jest.fn() }));
Loading