diff --git a/resources/js/components/commit-composer.tsx b/resources/js/components/commit-composer.tsx
index 1208f3ddcc..55a32965cf 100644
--- a/resources/js/components/commit-composer.tsx
+++ b/resources/js/components/commit-composer.tsx
@@ -20,6 +20,7 @@ import {
PreviewToggle,
useComposerPreview,
} from '@/components/composer-preview';
+import { DictationButton } from '@/components/dictation-button';
import { EmojiPickerButton } from '@/components/emoji-picker';
import { GraphRail, RailAvatar } from '@/components/graph-rail';
import InputError from '@/components/input-error';
@@ -521,6 +522,13 @@ function CommitComposerBody({
+ void;
+ textareaRef: RefObject;
+ maxLength: number;
+ disabled: boolean;
+}) {
+ const dictation = useDictation({
+ body,
+ updateBody,
+ textareaRef,
+ maxLength,
+ });
+ const { isListening, stop, abort } = dictation;
+
+ useEffect(() => {
+ if (disabled && isListening) {
+ abort();
+ }
+ }, [disabled, isListening, abort]);
+
+ if (!dictation.isSupported) {
+ return null;
+ }
+
+ return (
+
+
+
+ );
+}
diff --git a/resources/js/hooks/use-dictation.ts b/resources/js/hooks/use-dictation.ts
new file mode 100644
index 0000000000..4609cd94db
--- /dev/null
+++ b/resources/js/hooks/use-dictation.ts
@@ -0,0 +1,183 @@
+import type { RefObject } from 'react';
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
+import { toast } from 'sonner';
+import { dictatedText } from '@/lib/dictation';
+import { insertAtSelection } from '@/lib/text-selection';
+
+type SpeechRecognitionResultList = ArrayLike<
+ ArrayLike<{ transcript: string }> & { isFinal: boolean }
+>;
+
+/**
+ * The part of the Web Speech API's SpeechRecognition used here, which TypeScript's DOM types don't include.
+ */
+type Recognition = {
+ lang: string;
+ continuous: boolean;
+ interimResults: boolean;
+ onresult:
+ | ((event: {
+ resultIndex: number;
+ results: SpeechRecognitionResultList;
+ }) => void)
+ | null;
+ onerror: ((event: { error: string }) => void) | null;
+ onend: (() => void) | null;
+ start: () => void;
+ stop: () => void;
+ abort: () => void;
+};
+
+type RecognitionConstructor = new () => Recognition;
+
+function recognitionConstructor(): RecognitionConstructor | null {
+ if (typeof window === 'undefined') {
+ return null;
+ }
+
+ const speech = window as unknown as {
+ SpeechRecognition?: RecognitionConstructor;
+ webkitSpeechRecognition?: RecognitionConstructor;
+ };
+
+ return speech.SpeechRecognition ?? speech.webkitSpeechRecognition ?? null;
+}
+
+const subscribe = () => () => {};
+
+/**
+ * Dictation into the composer's textarea with the browser's own speech recognition (Chrome, Edge and Safari have it,
+ * Firefox doesn't). Each finished phrase is inserted where the caret is, as typing would, up to `maxLength`.
+ */
+export function useDictation({
+ body,
+ updateBody,
+ textareaRef,
+ maxLength,
+}: {
+ body: string;
+ updateBody: (body: string) => void;
+ textareaRef: RefObject;
+ maxLength: number;
+}): {
+ isSupported: boolean;
+ isListening: boolean;
+ start: () => void;
+ stop: () => void;
+ abort: () => void;
+} {
+ // Unknown while rendering on the server, so the button only appears once the page runs in the browser.
+ const isSupported = useSyncExternalStore(
+ subscribe,
+ () => recognitionConstructor() !== null,
+ () => false,
+ );
+ const [isListening, setIsListening] = useState(false);
+ const recognition = useRef(null);
+ const latest = useRef({ body, updateBody, maxLength });
+ const caret = useRef(null);
+
+ useLayoutEffect(() => {
+ latest.current = { body, updateBody, maxLength };
+
+ const element = textareaRef.current;
+
+ if (caret.current === null || element === null) {
+ return;
+ }
+
+ element.focus();
+ element.setSelectionRange(caret.current, caret.current);
+ caret.current = null;
+ }, [body, updateBody, maxLength, textareaRef]);
+
+ useEffect(() => () => recognition.current?.abort(), []);
+
+ // Phrases can arrive before React has written the previous one, so each insertion moves the body and caret on
+ // right away for the next, instead of waiting for the render.
+ const insert = (transcript: string) => {
+ const { body, updateBody, maxLength } = latest.current;
+ const selection =
+ caret.current === null
+ ? textareaRef.current
+ : {
+ selectionStart: caret.current,
+ selectionEnd: caret.current,
+ };
+ const text = dictatedText(
+ body.slice(0, selection?.selectionStart ?? body.length),
+ transcript,
+ body.slice(selection?.selectionEnd ?? body.length),
+ );
+ const inserted =
+ text === ''
+ ? null
+ : insertAtSelection(body, selection, text, maxLength);
+
+ if (inserted !== null) {
+ caret.current = inserted.caret;
+ latest.current = { ...latest.current, body: inserted.value };
+ updateBody(inserted.value);
+ }
+ };
+
+ const start = () => {
+ const Constructor = recognitionConstructor();
+
+ if (Constructor === null || recognition.current !== null) {
+ return;
+ }
+
+ const listener = new Constructor();
+ listener.lang = document.documentElement.lang || navigator.language;
+ listener.continuous = true;
+ listener.interimResults = false;
+ listener.onresult = (event) => {
+ for (
+ let index = event.resultIndex;
+ index < event.results.length;
+ index++
+ ) {
+ const result = event.results[index];
+
+ if (result.isFinal) {
+ insert(result[0].transcript);
+ }
+ }
+ };
+ listener.onerror = (event) => {
+ if (
+ event.error === 'not-allowed' ||
+ event.error === 'service-not-allowed'
+ ) {
+ toast.error('Allow the microphone to dictate your commit.');
+ } else if (
+ event.error !== 'no-speech' &&
+ event.error !== 'aborted'
+ ) {
+ toast.error('Dictation stopped. Try again.');
+ }
+ };
+ listener.onend = () => {
+ recognition.current = null;
+ setIsListening(false);
+ };
+
+ recognition.current = listener;
+ listener.start();
+ setIsListening(true);
+ };
+
+ // Keeps what was already heard, for a stop the user asked for.
+ const stop = () => recognition.current?.stop();
+ // Drops what wasn't written yet, for when the commit is sent and the composer is about to be cleared.
+ const abort = () => recognition.current?.abort();
+
+ return { isSupported, isListening, start, stop, abort };
+}
diff --git a/resources/js/lib/dictation.ts b/resources/js/lib/dictation.ts
new file mode 100644
index 0000000000..b9201d0174
--- /dev/null
+++ b/resources/js/lib/dictation.ts
@@ -0,0 +1,20 @@
+/**
+ * The text to insert for what was said, given the text before and after the caret: the transcript trimmed, with a space
+ * on either side where it would otherwise stick to a word. Empty when nothing was said.
+ */
+export function dictatedText(
+ before: string,
+ transcript: string,
+ after = '',
+): string {
+ const text = transcript.trim();
+
+ if (text === '') {
+ return '';
+ }
+
+ const space = (side: string) =>
+ side === '' || /\s/u.test(side) ? '' : ' ';
+
+ return space(before.slice(-1)) + text + space(after.slice(0, 1));
+}
diff --git a/resources/js/pages/privacy/show.tsx b/resources/js/pages/privacy/show.tsx
index f16d29a6f9..4585628057 100644
--- a/resources/js/pages/privacy/show.tsx
+++ b/resources/js/pages/privacy/show.tsx
@@ -251,6 +251,13 @@ export default function Show() {
selects which translation to display. Private messages
are not translated.
+
+ Dictating a commit uses your browser's own speech
+ recognition: we never receive your voice, only the text
+ it writes into the composer. Depending on your browser,
+ the recording may be sent to its maker, such as Google
+ or Apple, to be transcribed, under their privacy policy.
+
diff --git a/tests/Unit/Dictation.test.ts b/tests/Unit/Dictation.test.ts
new file mode 100644
index 0000000000..9791bc1b5c
--- /dev/null
+++ b/tests/Unit/Dictation.test.ts
@@ -0,0 +1,17 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { dictatedText } from '../../resources/js/lib/dictation.ts';
+
+void test('dictated text is trimmed and starts a new word after the caret', () => {
+ assert.equal(dictatedText('', ' shipped it '), 'shipped it');
+ assert.equal(dictatedText('Finally', 'shipped it'), ' shipped it');
+ assert.equal(dictatedText('Finally ', 'shipped it'), 'shipped it');
+ assert.equal(dictatedText('Finally\n', 'shipped it'), 'shipped it');
+ assert.equal(dictatedText('Finally', ' '), '');
+});
+
+void test('dictated text before a word is kept apart from it', () => {
+ assert.equal(dictatedText('', 'Finally', 'shipped it'), 'Finally ');
+ assert.equal(dictatedText('We ', 'finally', ' shipped'), 'finally');
+ assert.equal(dictatedText('We', 'finally', 'shipped'), ' finally ');
+});
diff --git a/tests/Unit/DictationInsertion.test.tsx b/tests/Unit/DictationInsertion.test.tsx
new file mode 100644
index 0000000000..f247a34bee
--- /dev/null
+++ b/tests/Unit/DictationInsertion.test.tsx
@@ -0,0 +1,187 @@
+///
+import assert from 'node:assert/strict';
+import * as React from 'react';
+import { afterAll, beforeEach, test, vi } from 'vite-plus/test';
+
+let layoutEffect: () => void = () => {};
+const setIsListening = vi.fn();
+
+// Renders the hook once: effects run when the test says React has written the new body.
+vi.doMock('react', () => ({
+ ...React,
+ useLayoutEffect: (effect: () => void) => {
+ layoutEffect = effect;
+ },
+ useEffect: () => {},
+ useRef: (initial: unknown) => ({ current: initial }),
+ useState: (initial: unknown) => [initial, setIsListening],
+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) =>
+ snapshot(),
+}));
+
+const toastError = vi.fn();
+vi.doMock('sonner', () => ({ toast: { error: toastError } }));
+
+type Listener = {
+ lang: string;
+ continuous: boolean;
+ start: () => void;
+ abort: () => void;
+ onresult: (event: {
+ resultIndex: number;
+ results: ({ transcript: string }[] & { isFinal: boolean })[];
+ }) => void;
+ onerror: (event: { error: string }) => void;
+ onend: () => void;
+};
+
+let listener: Listener;
+
+vi.stubGlobal('window', {
+ webkitSpeechRecognition: class {
+ start = vi.fn();
+ stop = vi.fn();
+ abort = vi.fn();
+
+ constructor() {
+ listener = this as unknown as Listener;
+ }
+ },
+});
+vi.stubGlobal('document', { documentElement: { lang: 'fr' } });
+
+afterAll(() => {
+ vi.doUnmock('react');
+ vi.doUnmock('sonner');
+ vi.unstubAllGlobals();
+});
+
+const { useDictation } = await import('../../resources/js/hooks/use-dictation');
+
+function said(transcript: string, isFinal = true) {
+ return Object.assign([{ transcript }], { isFinal });
+}
+
+function textareaAt(selectionStart: number, selectionEnd = selectionStart) {
+ const focus = vi.fn();
+ const setSelectionRange = vi.fn();
+ const textarea = {
+ selectionStart,
+ selectionEnd,
+ focus,
+ setSelectionRange,
+ } as unknown as HTMLTextAreaElement;
+
+ return { textarea, focus, setSelectionRange };
+}
+
+const updateBody = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+test('listens in the page language and inserts each finished phrase at the caret', () => {
+ const { textarea, focus, setSelectionRange } = textareaAt(7);
+ const dictation = useDictation({
+ body: 'Shipped today',
+ updateBody,
+ textareaRef: { current: textarea },
+ maxLength: 280,
+ });
+
+ assert.equal(dictation.isSupported, true);
+ dictation.start();
+ assert.equal(listener.lang, 'fr');
+ assert.equal(listener.continuous, true);
+ assert.deepEqual(setIsListening.mock.calls, [[true]]);
+
+ listener.onresult({
+ resultIndex: 0,
+ results: [said('the dark mode', false), said(' the dark mode ')],
+ });
+ layoutEffect();
+
+ assert.deepEqual(updateBody.mock.calls, [['Shipped the dark mode today']]);
+ assert.equal(focus.mock.calls.length, 1);
+ assert.deepEqual(setSelectionRange.mock.calls, [[21, 21]]);
+});
+
+test('keeps every phrase heard before React writes the body, in the order they were said', () => {
+ const { textarea, setSelectionRange } = textareaAt(7);
+ const dictation = useDictation({
+ body: 'Shipped today',
+ updateBody,
+ textareaRef: { current: textarea },
+ maxLength: 280,
+ });
+
+ dictation.start();
+ listener.onresult({
+ resultIndex: 0,
+ results: [said('the dark mode'), said('for everyone')],
+ });
+ listener.onresult({
+ resultIndex: 2,
+ results: [said('x'), said('x'), said('at last')],
+ });
+ layoutEffect();
+
+ assert.deepEqual(updateBody.mock.calls.at(-1), [
+ 'Shipped the dark mode for everyone at last today',
+ ]);
+ assert.deepEqual(setSelectionRange.mock.calls, [[42, 42]]);
+});
+
+test('aborts without writing what was still being heard, for when the commit is sent', () => {
+ const dictation = useDictation({
+ body: '',
+ updateBody,
+ textareaRef: { current: null },
+ maxLength: 280,
+ });
+
+ dictation.start();
+ dictation.abort();
+
+ assert.equal(
+ (listener.abort as ReturnType).mock.calls.length,
+ 1,
+ );
+});
+
+test('ignores silence and phrases that would overflow the commit', () => {
+ const dictation = useDictation({
+ body: 'abc',
+ updateBody,
+ textareaRef: { current: textareaAt(3).textarea },
+ maxLength: 5,
+ });
+
+ dictation.start();
+ listener.onresult({
+ resultIndex: 0,
+ results: [said(' '), said('too long')],
+ });
+
+ assert.equal(updateBody.mock.calls.length, 0);
+});
+
+test('says when the microphone is blocked, but not when nothing was said', () => {
+ const dictation = useDictation({
+ body: '',
+ updateBody,
+ textareaRef: { current: null },
+ maxLength: 280,
+ });
+
+ dictation.start();
+ listener.onerror({ error: 'no-speech' });
+ listener.onerror({ error: 'not-allowed' });
+ listener.onend();
+
+ assert.deepEqual(toastError.mock.calls, [
+ ['Allow the microphone to dictate your commit.'],
+ ]);
+ assert.deepEqual(setIsListening.mock.calls, [[true], [false]]);
+});