From f46490c12ed99095bcb64777d3fb9ede02dff8c3 Mon Sep 17 00:00:00 2001 From: Noel Chou Date: Fri, 30 Oct 2026 16:28:05 -0400 Subject: [PATCH 01/12] reviewed --- localization/TranscriberAdmin-en-1.2.xliff | 7 - localization/TranscriberAdmin-en.xlf | 6 - .../ProjectResourceConfigure.test.tsx | 1 - web/src/components/GraphicUploader.tsx | 17 +- web/src/components/MediaRecord.test.tsx | 55 --- web/src/components/MediaRecord.tsx | 39 +- web/src/components/MediaUploadContent.tsx | 59 +-- web/src/components/MediaUploadDialog.tsx | 7 - web/src/components/PassageRecordDlg.test.tsx | 117 ----- web/src/components/PassageRecordDlg.tsx | 411 ------------------ web/src/components/UploadType.ts | 2 +- web/src/components/Uploader.test.tsx | 179 -------- web/src/components/Uploader.tsx | 127 +----- web/src/components/useRecordSave.ts | 12 - web/src/store/upload/actions.tsx | 58 +-- 15 files changed, 94 insertions(+), 1003 deletions(-) delete mode 100644 web/src/components/PassageRecordDlg.test.tsx delete mode 100644 web/src/components/PassageRecordDlg.tsx delete mode 100644 web/src/components/Uploader.test.tsx diff --git a/localization/TranscriberAdmin-en-1.2.xliff b/localization/TranscriberAdmin-en-1.2.xliff index 8d1bbea60..e9b325ba1 100644 --- a/localization/TranscriberAdmin-en-1.2.xliff +++ b/localization/TranscriberAdmin-en-1.2.xliff @@ -6730,13 +6730,6 @@ AddResource.tsx - - - Chunk into Resources - - - AddResource.tsx - Record diff --git a/localization/TranscriberAdmin-en.xlf b/localization/TranscriberAdmin-en.xlf index f1396097d..0cdba0e03 100644 --- a/localization/TranscriberAdmin-en.xlf +++ b/localization/TranscriberAdmin-en.xlf @@ -5770,12 +5770,6 @@ - - - Chunk into Resources - - - Record diff --git a/web/src/__tests__/ProjectResourceConfigure.test.tsx b/web/src/__tests__/ProjectResourceConfigure.test.tsx index c90d1deb4..81b94ff33 100644 --- a/web/src/__tests__/ProjectResourceConfigure.test.tsx +++ b/web/src/__tests__/ProjectResourceConfigure.test.tsx @@ -132,7 +132,6 @@ jest.mock('react-redux', () => ({ pasteError: 'Paste Errors {0}, Updated {1}', pasteFormat: 'Paste Format', pasteNoChange: 'Paste No Change', - projectResourceConfigure: 'Project Resource Configure', reference: 'Reference', startStop: 'Start/Stop', suffix: 'Suffix', diff --git a/web/src/components/GraphicUploader.tsx b/web/src/components/GraphicUploader.tsx index f8fd7639f..b153d2c1a 100644 --- a/web/src/components/GraphicUploader.tsx +++ b/web/src/components/GraphicUploader.tsx @@ -1,6 +1,5 @@ import { shallowEqual, useSelector } from 'react-redux'; import { restoreScroll } from '../utils'; -import MediaUploadDialog from './MediaUploadDialog'; import { UploadType } from './UploadType'; import { sharedSelector } from '../selector'; import { ISharedStrings } from '../model'; @@ -15,7 +14,6 @@ import { CompressedImages, useCompression } from '../utils/useCompression'; interface IProps { defaultFilename?: string; dimension: number[]; - isOpen?: boolean; onOpen: (visible: boolean) => void; showMessage: (msg: string | React.JSX.Element) => void; hasRights?: boolean; // required for upload @@ -32,7 +30,6 @@ export function GraphicUploader(props: IProps) { const { defaultFilename, dimension, - isOpen, onOpen, showMessage, cancelled, @@ -59,19 +56,7 @@ export function GraphicUploader(props: IProps) { restoreScroll(); }; - return isOpen ? ( - Boolean(hasRights)} - uploadMethod={uploadMedia} - cancelMethod={uploadCancel} - cancelLabel={ts.close} - metaData={metadata} - onFiles={showFile} - /> - ) : ( + return ( { ); }); - it('keeps a successful stage when the recorder returns to idle', async () => { - let requested = false; - mockSaveRequested = () => requested; - mockSaveCompleted.mockImplementation( - (_toolId: unknown, message?: string) => { - if (!message) requested = false; - } - ); - const onSaveRejected = jest.fn(); - const onStageFile = jest.fn(async () => { - latestWsProps?.onBlobReady?.(undefined); - }); - const { TestUnsavedProvider, unsavedTest } = jest.requireMock( - '../context/UnsavedContext' - ) as { - TestUnsavedProvider: React.ComponentType<{ children: React.ReactNode }>; - unsavedTest: { bump: () => void }; - }; - render( - - - - ); - - await waitFor(() => expect(latestWsProps).toBeDefined()); - act(() => { - latestWsProps?.setBlobReady?.(true); - latestWsProps?.setChanged?.(true); - latestWsProps?.onDuration?.(12); - latestWsProps?.onBlobReady?.( - new Blob([new Uint8Array(1000)], { type: 'audio/wav' }) - ); - }); - await waitFor(() => - expect(document.getElementById('size')?.textContent).toBe('0.11MB') - ); - - onSaveRejected.mockClear(); - mockSaveCompleted.mockClear(); - requested = true; - act(() => unsavedTest.bump()); - - await waitFor(() => expect(onStageFile).toHaveBeenCalled()); - expect(onSaveRejected).not.toHaveBeenCalled(); - expect(mockSaveCompleted).toHaveBeenCalledWith('record-tool'); - expect(mockSaveCompleted).not.toHaveBeenCalledWith( - 'record-tool', - 'Media error' - ); - }); - it('does not upload wav when the size check fails after compression', async () => { mockSaveRequested = () => true; mockConvertToFormat = jest.fn(async () => undefined as unknown as Blob); diff --git a/web/src/components/MediaRecord.tsx b/web/src/components/MediaRecord.tsx index b1191ba5d..1aa096b6e 100644 --- a/web/src/components/MediaRecord.tsx +++ b/web/src/components/MediaRecord.tsx @@ -67,13 +67,6 @@ export interface IProps { * `pendingRestore` can include newly created category ids. */ beforeUpload?: () => Promise; - /** - * When set, `doUpload` hands the finished (already converted) take here and - * returns instead of calling `uploadMedia` — the general-resource flow defers - * the upload until the user has chosen passages/sections (SelectSections). - * When absent, a saved take uploads immediately as usual. - */ - onStageFile?: ((files: File[]) => void | Promise) | undefined; onReady?: (() => void) | undefined; onSaving?: (() => void) | undefined; onRecording?: ((r: boolean) => void) | undefined; @@ -85,6 +78,20 @@ export interface IProps { /** When false, hide the Download item in the recorder's more menu. Default true if omitted. */ allowDownload?: boolean; setCanSave: (canSave: boolean) => void; + /** + * Reports whether a usable take is loaded in the waveform, independent of + * whether it counts as an unsaved change. Unlike `setCanSave`, this stays true + * after a take has been uploaded (the upload clears the dirty flags but leaves + * the take shown). The deferred add-resource wizard uses it to keep its "Next" + * button live when the user steps back to the still-mounted Record step after + * the take already uploaded once. + */ + // TODO cleanup: combine a bunch of these props that describe what stage the recording is in + // into one lifecycle prop that sets the current stage as e.g. Recording, Saving, Loading, Unsaved, etc. Maybe even HasValidTake or HasInvalidTake? + // Also, in particular, make the situation around recording and the recorder more readable. + // At the very least, allowRecord should be renamed to indicate that it controls the total + // presence or absence of the recorder, unlike recordBlocked. + setHasTake?: ((hasTake: boolean) => void) | undefined; /** * Called when a save attempt is rejected — the upload failed or finished * without a mediaId. May fire more than once for a single failed save, so @@ -168,8 +175,8 @@ function MediaRecord(props: IProps) { pendingRestore, uploadType = UploadType.Media, beforeUpload, - onStageFile, setCanSave, + setHasTake, setCanCancel, setStatusText, allowRecord, @@ -516,7 +523,6 @@ function MediaRecord(props: IProps) { onSaving, onReady, onSaveRejected, - onStageFile, onUploaded, upload: { fields: { @@ -616,6 +622,21 @@ function MediaRecord(props: IProps) { if (setCanCancel) setCanCancel(!inFlight); }, [inFlight, setCanCancel]); + // A usable take is loaded in the waveform — the same readiness canSave + // requires, but without the (pendingSave || filechanged) dirty gate. A + // successful upload clears those flags (so canSave drops) yet leaves the take + // shown; this stays true so the deferred wizard's Next button survives a Back + // to the already-uploaded Record step. + const hasTake = + waveformDuration > 0 && + blobReady && + !sizeBlocksSave && + !inFlight && + !recording; + useEffect(() => { + setHasTake?.(hasTake); + }, [hasTake, setHasTake]); + const { isMobile: isMobileView } = useMobile(); const effectiveMobileView = Boolean(forceMobileView) || isMobileView; diff --git a/web/src/components/MediaUploadContent.tsx b/web/src/components/MediaUploadContent.tsx index e9f6aca5b..8c2a472eb 100644 --- a/web/src/components/MediaUploadContent.tsx +++ b/web/src/components/MediaUploadContent.tsx @@ -27,7 +27,7 @@ import { MarkDownType, UriLinkType, } from '../utils/contentType'; -import { UploadType } from './UploadType'; +import { NON_FILE_UPLOAD_TYPES, UploadType } from './UploadType'; import { FileDrop } from 'react-file-drop'; import { Button } from '../control/Button'; @@ -173,7 +173,6 @@ interface IProps { onFiles?: ((files: File[]) => void) | undefined; inValue?: string | undefined; onValue?: ((value: string) => void) | undefined; - onNonAudio?: ((nonAudio: boolean) => void) | undefined; audioOnly?: boolean | undefined; saveButtonText?: string | undefined; validationMessage?: string | undefined; @@ -182,22 +181,23 @@ interface IProps { /** When true, render `DialogContent`/`DialogActions` without the wrapping Box * so they are direct children of a shared Dialog paper (MUI flex handles the * scroll region + pinned actions, matching the record body). - * TODO future work: I would like to see if we can get rid of the wrapper altogether, + * TODO cleanup: I would like to see if we can get rid of the wrapper altogether, * but don't have time to check all the usages now. */ - noWrapper?: boolean | undefined; /** Hide the bottom "Cancel" button (cancel is reached via the dialog's X). */ hideCancel?: boolean | undefined; - /** Pre-select these files when the content mounts, so a returning user (e.g. - * after the Add Resource wizard's Back) sees their previous choice and can - * proceed without re-picking. Seeded once on mount; a fresh open passes an - * empty list, so nothing is seeded there. */ - initialFiles?: File[] | undefined; /** Keep the file selection after a successful submit instead of clearing it. - * Used by the deferred general-resource flow: the file is only *staged* on - * submit (uploaded later), so the parent keeps it selected to restore if the - * user steps back to this dialog. */ + * Used by the deferred general-resource flow, where the body stays mounted + * across the wizard steps: the selection must survive the upload (fired from + * SelectSections) so it's still shown if the user steps back to this body. */ keepFilesAfterSubmit?: boolean | undefined; + /** When set, the primary action button becomes a "proceed" button that calls + * this instead of uploading; the real upload stays reachable through + * `controlsRef.handleAddOrSave`. Used by the add-resource wizard's deferred + * general-resource flow, where Next only advances and the upload fires later + * from SelectSections, driven off the still-mounted selection. */ + onNext?: (() => void) | undefined; + // TODO cleanup: see if we can consolidate onNext, uploadMethod, and keepFilesAfterSubmit. } function MediaUploadContent(props: IProps) { @@ -216,7 +216,6 @@ function MediaUploadContent(props: IProps) { onFiles, inValue, onValue, - onNonAudio, audioOnly, saveButtonText, validationMessage, @@ -224,8 +223,8 @@ function MediaUploadContent(props: IProps) { onSaveDisabled, noWrapper, hideCancel, - initialFiles, keepFilesAfterSubmit, + onNext, } = props; const [name, setName] = useState(''); const [files, setFilesx] = useState([]); @@ -268,7 +267,14 @@ function MediaUploadContent(props: IProps) { // Historical behavior: clear selection after initiating an upload. Skip it // when deferring — the file is only staged (uploaded later), so the parent // keeps it selected to restore if the user steps back to this dialog. - if (!keepFilesAfterSubmit) handleFiles(undefined); + if (!keepFilesAfterSubmit) { + handleFiles(undefined); + } else { + // In the Wizard, we only stage the file and defer uploading but stay mounted for the sake of the back button. + // So clear the progress state, otherwise it would spin forever and keep + // the Next button disabled on return. + setProgress(false); + } } catch { setProgress(false); } @@ -347,8 +353,6 @@ function MediaUploadContent(props: IProps) { ) ); } - const nonAudio = goodFiles.some((f) => !f?.type.includes('audio')); - if (onNonAudio) onNonAudio(nonAudio); goodFiles = checkSizes(goodFiles, typeLimit(uploadType)); setName(fileName(goodFiles)); setFiles(goodFiles); @@ -415,17 +419,6 @@ function MediaUploadContent(props: IProps) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [uploadType, audioOnly]); - // Seed the selection from a previously-chosen file (e.g. after the Add - // Resource wizard's Back). Mount-only: the dialog remounts this content on - // each open and a fresh open passes an empty list, so nothing is seeded there. - useEffect(() => { - if (initialFiles && initialFiles.length > 0) { - setName(fileName(initialFiles)); - setFiles(initialFiles); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - const body = ( <> @@ -441,11 +434,7 @@ function MediaUploadContent(props: IProps) { aiip={false} /> )} - {![ - UploadType.Link, - UploadType.MarkDown, - UploadType.FaithbridgeLink, - ].includes(uploadType) ? ( + {!NON_FILE_UPLOAD_TYPES.includes(uploadType) ? ( {hasRights ? ( } - {!controlsRef && ( + {(!controlsRef || onNext) && ( {!hideCancel && ( - ), -})); -jest.mock('../control/Button', () => ({ - Button: (props: { children?: React.ReactNode }) => ( - - ), -})); -jest.mock('../utils/getRefWidth', () => ({ getRefWidth: () => 600 })); -jest.mock('./MediaUploadContent', () => () => null); -jest.mock('./Busy', () => () => null); -jest.mock('./AlertDialog', () => () => null); -jest.mock('./PassageDetail/Internalization/UploadRecordToggle', () => ({ - __esModule: true, - default: (props: { onMode: (mode: 'upload' | 'record') => void }) => ( - - ), -})); -jest.mock('./MediaRecord', () => ({ - __esModule: true, - default: (props: { allowRecord?: boolean }) => { - capturedAllowRecord = props.allowRecord; - return null; - }, -})); - -const ipRec = (rightsHolder: string) => ({ - type: 'intellectualproperty', - id: `ip-${rightsHolder}`, - attributes: { rightsHolder }, - relationships: { - organization: { data: { type: 'organization', id: 'org1' } }, - }, -}); - -const openRecordTab = (speaker: string) => { - render( - - ); - act(() => { - fireEvent.click(screen.getByTestId('tab-record')); - }); -}; - -describe('PassageRecordDlg speaker rights', () => { - beforeEach(() => { - capturedAllowRecord = undefined; - mockIpRecs = []; - }); - - it('allows recording for a preselected speaker with a rights record', () => { - mockIpRecs = [ipRec('Alice')]; - openRecordTab('Alice'); - expect(capturedAllowRecord).toBe(true); - }); - - it('allows recording for a preselected speaker whose rights were deferred ("Do later")', () => { - // No IP record exists for Bob: ProvideRights' "Do later" doesn't create one. - openRecordTab('Bob'); - expect(capturedAllowRecord).toBe(true); - }); - - it('blocks recording when no speaker is selected', () => { - mockIpRecs = [ipRec('Alice')]; - openRecordTab(''); - expect(capturedAllowRecord).toBe(false); - }); -}); diff --git a/web/src/components/PassageRecordDlg.tsx b/web/src/components/PassageRecordDlg.tsx deleted file mode 100644 index 8d5fc50c2..000000000 --- a/web/src/components/PassageRecordDlg.tsx +++ /dev/null @@ -1,411 +0,0 @@ -import { useCallback, useContext, useEffect, useRef, useState } from 'react'; -import { - Box, - Dialog, - DialogActions, - DialogContent, - DialogTitle, - IconButton, - styled, - Typography, - TypographyProps, -} from '@mui/material'; -import CloseIcon from '@mui/icons-material/Close'; -import MediaUploadContent from './MediaUploadContent'; -import { shallowEqual, useSelector } from 'react-redux'; -import { - IPassageDetailArtifactsStrings, - IPassageRecordStrings, -} from '../model'; -import { passageRecordSelector, resourceSelector } from '../selector'; -import UploadRecordToggle, { - AudioAddMode, -} from './PassageDetail/Internalization/UploadRecordToggle'; -import { UploadType } from './UploadType'; -import { useGlobal } from '../context/useGlobal'; -import { getRefWidth } from '../utils/getRefWidth'; -import { useFetchMediaUrl } from '../crud'; -import MediaRecord from './MediaRecord'; -import { UnsavedContext } from '../context/UnsavedContext'; -import SpeakerName from './SpeakerName'; -import { Button } from '../control'; -import Busy from './Busy'; -import Confirm from './AlertDialog'; - -const audioDlgWidth = 'min(680px, calc(100vw - 32px))'; -const audioDlgHeight = 'min(700px, calc(100dvh - 32px))'; - -const StatusMessage = styled(Typography)(({ theme }) => ({ - marginRight: theme.spacing(2), - alignSelf: 'center', - display: 'block', - gutterBottom: 'true', -})); - -const RecordDialog = styled(Dialog)(({ theme }) => ({ - flexGrow: 1, - '& .MuiDialog-paper': { - width: audioDlgWidth, - maxWidth: audioDlgWidth, - minWidth: 0, - height: audioDlgHeight, - minHeight: audioDlgHeight, - maxHeight: audioDlgHeight, - }, - // Tighten vertical chrome so record mode (speaker + player + metadata) - // fits without scrolling on typical laptop heights. - '& .MuiDialogTitle-root': { - paddingTop: theme.spacing(1.5), - paddingBottom: theme.spacing(0.5), - }, - '& .MuiDialogContent-root': { - paddingTop: theme.spacing(1), - paddingBottom: theme.spacing(1), - }, - '& .MuiDialogActions-root': { - paddingTop: theme.spacing(0.5), - paddingBottom: theme.spacing(1), - }, - '& #uploadCancel, & #uploadSave': { - margin: theme.spacing(1), - }, -})); - -interface IProps { - visible: boolean; - onVisible: (visible: boolean) => void; - onCancel: () => void; - mediaId: string; - artifactId: string | null; - afterUploadCb: (mediaId: string | undefined) => Promise; - passageId: string | undefined; - planId?: string | undefined; - metaData?: React.JSX.Element | undefined; - defaultFilename: string; - ready?: (() => boolean) | undefined; - allowWave?: boolean | undefined; - speaker?: string | undefined; - onSpeaker?: ((speaker: string) => void) | undefined; - team?: string | undefined; - onFiles?: ((files: File[]) => void) | undefined; - uploadType: UploadType; - uploadMethod: - ((files: File[]) => void | boolean | Promise) | undefined; - multiple?: boolean | undefined; - inValue?: string | undefined; - onNonAudio?: ((nonAudio: boolean) => void) | undefined; - audioOnly?: boolean | undefined; - validationMessage?: string | undefined; - pendingRestore?: import('../store/upload/pendingMediaUploads').PendingRestoreInput; - beforeUpload?: (() => Promise) | undefined; - /** - * Forwarded to MediaRecord (the record tab): when set, a saved take is handed - * here as a staged file rather than uploaded — the deferred general-resource - * flow. The upload tab stages through `uploadMethod` instead. - */ - onStageFile?: ((files: File[]) => void | Promise) | undefined; - /** Pre-select these files on the upload tab (see MediaUploadContent). */ - initialFiles?: File[] | undefined; - /** Keep the upload-tab selection after submit instead of clearing it (see MediaUploadContent). */ - keepFilesAfterSubmit?: boolean | undefined; -} - -function PassageRecordDlg(props: IProps) { - const { - visible, - onVisible, - mediaId, - artifactId, - afterUploadCb, - passageId, - planId, - defaultFilename, - onCancel, - ready, - metaData, - allowWave, - speaker, - onSpeaker, - team, - onFiles, - uploadType, - uploadMethod, - multiple, - inValue, - onNonAudio, - audioOnly, - validationMessage, - pendingRestore, - beforeUpload, - onStageFile, - initialFiles, - keepFilesAfterSubmit, - } = props; - const resourceStrings: IPassageDetailArtifactsStrings = useSelector( - resourceSelector, - shallowEqual - ); - const recordStrings: IPassageRecordStrings = useSelector( - passageRecordSelector, - shallowEqual - ); - const [reporter] = useGlobal('errorReporter'); - const { fetchMediaUrl, mediaState } = useFetchMediaUrl(reporter); - const { startSave } = useContext(UnsavedContext).state; - const [mode, setMode] = useState('upload'); - const [busy, setBusy] = useState(false); - const [statusText, setStatusText] = useState(''); - const [canSave, setCanSave] = useState(false); - // canCancel value is unused now that the record-mode Cancel button is gone, - // but MediaRecord still drives the setter. - const [, setCanCancel] = useState(false); - const [hasRights, setHasRights] = useState(false); - const [recording, setRecording] = useState(false); - // A take has been recorded since the record tab opened. Tracked separately - // from canSave, which stays false while a take is still processing (or is - // too big to save), so closing then must still confirm. - const [hasTake, setHasTake] = useState(false); - const [dialogWidth, setDialogWidth] = useState(0); - const [showConfirm, setShowConfirm] = useState(false); - const dialogRef = useRef(null); - const myToolId = 'PassageRecordDlg'; - - useEffect(() => { - if (visible) { - setMode('upload'); - setRecording(false); - setHasTake(false); - setShowConfirm(false); - } - }, [visible]); - - useEffect(() => { - if (mode === 'record') { - setBusy(false); - setStatusText(''); - setCanSave(false); - setCanCancel(false); - // Trust a preselected speaker, as the upload tab does: "Do later" in - // ProvideRights grants rights without creating an IP record, so - // SpeakerName can't re-derive them from the rights list on reopen. - setHasRights(Boolean(speaker?.trim())); - setRecording(false); - setHasTake(false); - } - // Only on tab entry: re-running on speaker change would override - // SpeakerName reporting no rights for a newly chosen, unlisted name. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [mode]); - - useEffect(() => { - if (mode === 'record' && mediaId !== mediaState.id) { - fetchMediaUrl({ id: mediaId }); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [mode, mediaId]); - - useEffect(() => setBusy(false), [visible]); - - const updateDialogWidth = useCallback(() => { - setDialogWidth(getRefWidth(dialogRef)); - }, []); - - useEffect(() => { - if (mode !== 'record') return; - updateDialogWidth(); - window.addEventListener('resize', updateDialogWidth); - return () => window.removeEventListener('resize', updateDialogWidth); - }, [mode, visible, updateDialogWidth]); - - const handleCancel = () => { - if (recording) return; - onCancel(); - if (!busy) onVisible(false); - }; - - const doClose = () => { - if (mode === 'record') { - handleCancel(); - } else { - onCancel(); - } - }; - - const requestClose = ( - _event?: object, - reason?: 'backdropClick' | 'escapeKeyDown' - ) => { - // outside click should not close dialog - if (reason === 'backdropClick') return; - // Can't close mid-recording (matches handleCancel's own guard). - if (recording) return; - // Confirm only when a take on the record tab would be lost; a file upload - // is cheap to redo, so it never prompts. - if (mode === 'record' && hasTake) { - setShowConfirm(true); - return; - } - doClose(); - }; - - const handleMode = (nextMode: AudioAddMode) => { - if (recording && nextMode === 'upload') return; - // Switching to record abandons any file selection made on the upload tab. - // Clear it so a stale multi-file general-resource selection can't keep - // blocking save once the user records instead. - if (nextMode === 'record') onFiles?.([]); - setMode(nextMode); - }; - - const handleSpeaker = (nextSpeaker: string) => { - onSpeaker?.(nextSpeaker); - }; - - const saveText = - uploadType === UploadType.ProjectResource - ? resourceStrings.next - : undefined; - - return ( - - - - {resourceStrings.addAudioResource} - - - - - - - {mode === 'record' ? ( - <> - - {!busy && ( - - )} - {busy && } - {/* Content-sized wrapper so WSAudioPlayer's height:100% cannot - cause vertical growth. May be unnecessary since this dialog - is not shown on actually mobile screens, but leaving it just in case*/} - - setBusy(true)} - onReady={() => setBusy(false)} - defaultFilename={defaultFilename} - allowRecord={hasRights} - allowWave={allowWave} - setCanSave={setCanSave} - setCanCancel={setCanCancel} - setStatusText={setStatusText} - width={dialogWidth} - height={160} - allowZoom={true} - allowNoNoise={true} - allowDeltaVoice={true} - onRecording={(isRecording) => { - setRecording(isRecording); - if (isRecording) setHasTake(true); - }} - pendingRestore={pendingRestore} - beforeUpload={beforeUpload} - onStageFile={onStageFile} - /> - - {metaData} - - - {statusText} - - - - ) : ( - - )} - {showConfirm && ( - setShowConfirm(false)} - yesResponse={() => { - setShowConfirm(false); - doClose(); - }} - /> - )} - - ); -} - -export default PassageRecordDlg; diff --git a/web/src/components/UploadType.ts b/web/src/components/UploadType.ts index 09c4cca20..f9b4e7b39 100644 --- a/web/src/components/UploadType.ts +++ b/web/src/components/UploadType.ts @@ -19,7 +19,7 @@ export enum UploadType { * file drop target, UPLOAD_LIST, and versioning. Shared so the hook and the * upload/resource UIs stay in agreement. */ -export const NO_LIST_TYPES = [ +export const NON_FILE_UPLOAD_TYPES = [ UploadType.Link, UploadType.MarkDown, UploadType.FaithbridgeLink, diff --git a/web/src/components/Uploader.test.tsx b/web/src/components/Uploader.test.tsx deleted file mode 100644 index c56ae81e1..000000000 --- a/web/src/components/Uploader.test.tsx +++ /dev/null @@ -1,179 +0,0 @@ -import { act, cleanup, render } from '@testing-library/react'; -import { UploadType } from './UploadType'; - -type PassageRecordDlgProps = { - afterUploadCb: (mediaId: string | undefined) => Promise; - beforeUpload?: () => Promise; -}; - -let capturedDlg: PassageRecordDlgProps | undefined; - -jest.mock('./PassageRecordDlg', () => ({ - __esModule: true, - default: (props: PassageRecordDlgProps) => { - capturedDlg = props; - return
; - }, -})); - -jest.mock('./MediaUploadDialog', () => ({ - __esModule: true, - default: () => null, -})); - -jest.mock('../store', () => ({ - uploadFiles: jest.fn(() => ({ type: 'UPLOAD_LIST' })), - nextUpload: jest.fn(() => ({ type: 'NEXT_UPLOAD' })), - uploadComplete: jest.fn(() => ({ type: 'UPLOAD_COMPLETE' })), -})); - -jest.mock('../selector', () => ({ - mediaTabSelector: () => ({ - uploadComplete: '{0} of {1} files uploaded successfully.', - unsupported: '{0}', - fileTooBig: '{0} {1} {2}', - selectFiles: 'Select files', - }), - sharedSelector: () => ({ - mediaAttached: 'Media attached', - }), -})); - -jest.mock('react-redux', () => ({ - shallowEqual: jest.fn(), - useDispatch: () => jest.fn((action: unknown) => action), - useSelector: (sel: (state: { upload: { errmsg: string } }) => unknown) => - sel({ upload: { errmsg: '' } }), -})); - -jest.mock('../context/TokenProvider', () => { - const ReactActual = jest.requireActual('react'); - return { - TokenContext: ReactActual.createContext({ - state: { accessToken: 'tok' }, - }), - }; -}); - -const mockMemory = { cache: { query: jest.fn(() => []) }, keyMap: {} }; -const mockCoordinator = { - getSource: jest.fn((name: string) => { - if (name === 'memory') return mockMemory; - return {}; - }), -}; - -jest.mock('../context/useGlobal', () => ({ - useGlobal: jest.fn((key: string) => { - const mockValues: Record = { - developer: false, - coordinator: mockCoordinator, - errorReporter: {}, - orbitRetries: 0, - importexportBusy: false, - plan: '', - user: 'user-1', - progress: 0, - }; - return [mockValues[key], jest.fn()]; - }), - useGetGlobal: jest.fn(() => (key: string) => { - if (key === 'offline') return false; - if (key === 'importexportBusy') return false; - return undefined; - }), -})); - -jest.mock('../crud', () => ({ - useMediaUpload: jest.fn(() => jest.fn(async () => true)), - findRecord: jest.fn(), - pullTableList: jest.fn(), - related: jest.fn(), - remoteIdNum: jest.fn((_table: string, id: string) => id), - useArtifactType: () => ({ - localizedArtifactTypeFromId: jest.fn(() => 'artifact-label'), - }), - useOfflnMediafileCreate: () => ({ - createMedia: jest.fn(), - }), - VernacularTag: null, -})); - -jest.mock('../utils', () => ({ - restoreScroll: jest.fn(), - infoMsg: jest.fn(), - logError: jest.fn(), - Severity: { error: 'error' }, -})); - -jest.mock('../utils/passageDefaultFilename', () => ({ - passageDefaultSuffix: jest.fn(() => ''), -})); - -jest.mock('../utils/typeLimit', () => ({ - typeLimit: jest.fn(() => 100), -})); - -jest.mock('../utils/contentType', () => ({ - getContentType: jest.fn(() => 'audio/webm'), -})); - -jest.mock('../store/upload/uploadTerminalMessages', () => ({ - formatUploadTerminalFailureMessage: jest.fn(() => 'upload failed'), -})); - -import Uploader from './Uploader'; - -function renderUploader(beforeUpload: () => Promise) { - const cancelled = { current: false }; - return render( - Promise.resolve())} - /> - ); -} - -describe('Uploader recorded path beforeUpload', () => { - beforeEach(() => { - capturedDlg = undefined; - jest.useFakeTimers(); - }); - - afterEach(() => { - act(() => { - jest.runOnlyPendingTimers(); - }); - jest.useRealTimers(); - cleanup(); - }); - - /** - * Recorded save goes MediaRecord → useMediaUpload (await beforeUpload, then - * stage) → Uploader.afterUploadCb on success. Copilot r3919030521: the - * after-upload hook must not commit again — SelectArtifactCategory.commit() - * is not idempotent if React has not re-rendered the new category yet. - */ - it('commits deferred metadata once when a recording upload succeeds', async () => { - const created: string[] = []; - const beforeUpload = jest.fn(async () => { - created.push(`cat-${created.length + 1}`); - }); - renderUploader(beforeUpload); - expect(capturedDlg?.beforeUpload).toBe(beforeUpload); - - await act(async () => { - await capturedDlg!.beforeUpload!(); - await capturedDlg!.afterUploadCb('media-1'); - }); - - expect(created).toEqual(['cat-1']); - }); -}); diff --git a/web/src/components/Uploader.tsx b/web/src/components/Uploader.tsx index 1705d77fe..609f313dc 100644 --- a/web/src/components/Uploader.tsx +++ b/web/src/components/Uploader.tsx @@ -1,30 +1,18 @@ import React, { useMemo } from 'react'; import MediaUploadDialog from './MediaUploadDialog'; -import PassageRecordDlg from './PassageRecordDlg'; import { useMediaUpload, VernacularTag, findRecord, related } from '../crud'; import { useGlobal } from '../context/useGlobal'; -import { infoMsg, logError, restoreScroll, Severity } from '../utils'; -import { toError } from '../utils/toError'; +import { restoreScroll } from '../utils'; import { splitFaithbridgeValue } from '../utils/contentType'; import { AlertSeverity } from '../hoc/SnackBar'; import { UploadType } from './UploadType'; import { Box } from '@mui/material'; import { BigDialogBp } from '../hoc/BigDialogBp'; -// The record/upload dialog names recordings from defaultFilename, so a host -// that turns on audioUploadOrRecord must supply one. -type RecordModeProps = - | { audioUploadOrRecord: true; defaultFilename: string } - | { - audioUploadOrRecord?: false | undefined; - defaultFilename?: string | undefined; - }; - -interface IBaseProps { +interface IProps { noBusy?: boolean | undefined; /** When true, do not wait for `importexportBusy` before staging upload (record save may hold it). */ skipImportExportWait?: boolean | undefined; - mediaId?: string | undefined; isOpen: boolean; onOpen: (visible: boolean) => void; showMessage?: @@ -54,7 +42,6 @@ interface IBaseProps { uploadType?: UploadType | undefined; inValue?: string | undefined; // used when adding Aquifer markdown team?: string | undefined; // used when adding a card to check speakers - onNonAudio?: ((nonAudio: boolean) => void) | undefined; audioOnly?: boolean | undefined; uploadDialogBp?: BigDialogBp; validationMessage?: string | undefined; @@ -62,37 +49,18 @@ interface IBaseProps { hideUploadCancel?: boolean | undefined; /** Domain restore metadata for pending-upload Retry (TT-7363). */ pendingRestore?: import('../store/upload/pendingMediaUploads').PendingRestoreInput; - /** - * When set, the Add Audio Resource dialog's Next stages the prepared file(s) - * via `onStageFiles` instead of uploading them. The general-resource flow - * uses this to defer the upload until the user picks passages/sections; the - * actual upload is then driven through `importList`. - */ - deferUpload?: boolean | undefined; - /** `recorded` is true when the staged file is a take from the record tab. */ - onStageFiles?: - ((files: File[], recorded?: boolean) => void | Promise) | undefined; - /** Pre-select these files when the dialog opens (see MediaUploadContent) — - * used to restore a staged file after the Add Resource wizard's Back. */ - initialFiles?: File[] | undefined; } -type IProps = IBaseProps & RecordModeProps; - /** - * The upload dialog (or, with `audioUploadOrRecord`, the record/upload dialog) - * driven by the shared useMediaUpload pipeline. + * The standalone upload dialog: a MediaUploadDialog driven by the shared useMediaUpload + * pipeline. */ export const Uploader = (props: IProps) => { const { noBusy, skipImportExportWait, - mediaId, - audioUploadOrRecord, - defaultFilename, isOpen, onOpen, - showMessage, cancelled, cancelReset, multiple, @@ -110,21 +78,16 @@ export const Uploader = (props: IProps) => { uploadType, inValue, team, - onNonAudio, audioOnly, finish, uploadDialogBp, validationMessage, hideUploadCancel, pendingRestore, - deferUpload, - onStageFiles, - initialFiles, } = props; const { metaData, ready, beforeUpload } = props; const [memory] = useGlobal('memory'); const [plan] = useGlobal('plan'); - const [errorReporter] = useGlobal('errorReporter'); const resolvedLocalPlanId = useMemo(() => { if (passageId) { @@ -187,45 +150,6 @@ export const Uploader = (props: IProps) => { importList, }); - // The record tab uploads through MediaRecord's own pipeline, which already - // reports progress and completion; only the host's `finish` is left to run. - const recordAfterUploadCb = async (mediaId: string | undefined) => { - if (cancelled) cancelled.current = !mediaId; - if (!finish) return; - try { - await finish(mediaId ? [mediaId] : []); - } catch (err) { - logError( - Severity.error, - errorReporter, - infoMsg(toError(err), 'upload finish failed') - ); - } - }; - - // Deferred general-resource flow: hand the prepared file(s) to the parent - // rather than uploading now. `onStageFiles` is async (it awaits category - // creation), so await it and report a failure instead of swallowing it. - const stageFiles = async (files: File[]) => { - try { - await onStageFiles?.(files); - return true; - } catch (err) { - const error = toError(err); - // Surface the failure (e.g. category creation) rather than silently - // re-enabling the dialog with no feedback, and log it for diagnosis. - showMessage?.(error.message, AlertSeverity.Error); - logError( - Severity.error, - errorReporter, - infoMsg(error, 'resource staging failed') - ); - return false; - } - }; - const deferring = Boolean(deferUpload && onStageFiles); - const effectiveUploadMethod = deferring ? stageFiles : uploadMedia; - const uploadCancel = () => { onOpen(false); if (cancelled) cancelled.current = true; @@ -237,45 +161,7 @@ export const Uploader = (props: IProps) => { return ( - {audioUploadOrRecord && !hasImport && ( - onStageFiles?.(files, /* recorded */ true) - : undefined - } - multiple={multiple} - onFiles={onFiles} - initialFiles={initialFiles} - keepFilesAfterSubmit={deferring} - inValue={effectiveInValue} - onNonAudio={onNonAudio} - audioOnly={audioOnly} - validationMessage={validationMessage} - pendingRestore={pendingRestore} - beforeUpload={beforeUpload} - /> - )} - {!audioUploadOrRecord && !hasImport && ( + {!hasImport && ( { } inValue={effectiveInValue} team={team} - onNonAudio={onNonAudio} audioOnly={audioOnly} onFiles={onFiles} - initialFiles={initialFiles} - keepFilesAfterSubmit={deferring} validationMessage={validationMessage} /> )} diff --git a/web/src/components/useRecordSave.ts b/web/src/components/useRecordSave.ts index 081fc49e0..3f032b6a5 100644 --- a/web/src/components/useRecordSave.ts +++ b/web/src/components/useRecordSave.ts @@ -4,7 +4,6 @@ import { convertToFormat, useMediaUpload } from '../crud'; import { AlertSeverity, type useSnackBar } from '../hoc/useSnackBar'; import { infoMsg, logError, Severity } from '../utils'; import { toError } from '../utils/toError'; -import type { IProps as MediaRecordProps } from './MediaRecord'; import type { SizeRejection, SizeStatus } from './useRecordSizeLimit'; export type RecordSaveInput = { @@ -28,7 +27,6 @@ export type RecordSaveInput = { onSaving?: () => void; onReady?: () => void; onSaveRejected?: () => void; - onStageFile?: MediaRecordProps['onStageFile']; /** Page work after the file is accepted. Called with the take that was sent. */ onUploaded: (mediaId: string, submitted: Blob | undefined) => Promise; upload: Omit[0], 'afterUploadCb'>; @@ -65,7 +63,6 @@ export function useRecordSave(input: RecordSaveInput) { onSaving, onReady, onSaveRejected, - onStageFile, onUploaded, upload, saveRequested, @@ -108,15 +105,6 @@ export function useRecordSave(input: RecordSaveInput) { const doUpload = async (blob: Blob, type: string, ext: string) => { const files = [new File([blob], defaultFilename + '.' + ext, { type })]; - if (onStageFile) { - // Hand the finished take up to be uploaded later, after passages are - // chosen. Await it so a failure rejects into the caller instead of - // being swallowed while the save is reported complete. - await onStageFile(files); - saveCompleted(toolId); - setStatusText(''); - return; - } setStatusText(saving); await uploadMedia(files); }; diff --git a/web/src/store/upload/actions.tsx b/web/src/store/upload/actions.tsx index 9e2025ef6..b0e8bad27 100644 --- a/web/src/store/upload/actions.tsx +++ b/web/src/store/upload/actions.tsx @@ -277,6 +277,7 @@ export interface NextUploadProps { * ImportTab sync (`importexportBusy`) can finish first. */ getImportExportBusy?: () => boolean; + // TODO cleanup: see if we can consolidate the props above, especially the error handling and end behavior ones } export const nextUpload = ({ @@ -295,15 +296,20 @@ export const nextUpload = }: NextUploadProps) => (dispatch: Dispatch) => { dispatch({ payload: n, type: UPLOAD_ITEM_PENDING }); + // We don't put general resources into the retry queue. They are a multi-step job the user must do in one go + const queueForRetry = + uploadType !== UploadType.ProjectResource || + Boolean(pendingUploadIdToClearOnSuccess); // TT-7365: a retried Save (e.g. re-clicked after an offline failure) may // not carry pendingUploadIdToClearOnSuccess (that's only wired from the // Pending Media Uploads dialog's Retry button). Reuse any pending row // already staged for this section/artifact/file so repeated Save clicks // update one row instead of appending a new one each time // writeFileLocal stages the same recording under a new versioned path. - let pendingIdToClear = - pendingUploadIdToClearOnSuccess ?? - findPendingUploadIdForIdentity(record as PendingUploadMediaRecord); + let pendingIdToClear = queueForRetry + ? (pendingUploadIdToClearOnSuccess ?? + findPendingUploadIdForIdentity(record as PendingUploadMediaRecord)) + : undefined; const sendError = (n: number, message: string, mediaid?: number): void => { dispatch({ payload: { @@ -506,7 +512,7 @@ export const nextUpload = } } - if (localAbsolutePath) { + if (localAbsolutePath && queueForRetry) { const queuePatch = { localAbsolutePath, fileSize: size, @@ -541,27 +547,29 @@ export const nextUpload = ); if (!cloudRowDeleted) failedRemoteMediaId = remoteId; } - const pathForQueue = - localAbsolutePath || - ((files[n] as File & { path?: string }).path ?? ''); - const queuePatch = { - localAbsolutePath: pathForQueue, - fileSize: size, - uploadType, - record: snapshotForPending(), - ...(pendingRestore ? { restore: pendingRestore } : {}), - }; - const pendingRecord = pendingIdToClear - ? (updatePendingMediaUpload(pendingIdToClear, queuePatch) ?? - appendPendingMediaUpload(queuePatch)) - : appendPendingMediaUpload(queuePatch); - onTerminalFailure?.({ - localAbsolutePath: pathForQueue || pendingRecord.localAbsolutePath, - originalFileName: name, - pendingRecord, - cloudRowDeleted, - failedRemoteMediaId, - }); + if (queueForRetry) { + const pathForQueue = + localAbsolutePath || + ((files[n] as File & { path?: string }).path ?? ''); + const queuePatch = { + localAbsolutePath: pathForQueue, + fileSize: size, + uploadType, + record: snapshotForPending(), + ...(pendingRestore ? { restore: pendingRestore } : {}), + }; + const pendingRecord = pendingIdToClear + ? (updatePendingMediaUpload(pendingIdToClear, queuePatch) ?? + appendPendingMediaUpload(queuePatch)) + : appendPendingMediaUpload(queuePatch); + onTerminalFailure?.({ + localAbsolutePath: pathForQueue || pendingRecord.localAbsolutePath, + originalFileName: name, + pendingRecord, + cloudRowDeleted, + failedRemoteMediaId, + }); + } completeCB(false, undefined, statusNum, statusText); }; From f0f89c48fd7b3f1451cfcfae948d8237d4886f57 Mon Sep 17 00:00:00 2001 From: Noel Chou Date: Mon, 9 Nov 2026 17:02:15 -0500 Subject: [PATCH 02/12] reviewed --- web/src/components/MediaRecord.tsx | 5 ++++- web/src/components/MediaUploadContent.tsx | 3 --- web/src/components/MediaUploadDialog.tsx | 10 ---------- 3 files changed, 4 insertions(+), 14 deletions(-) diff --git a/web/src/components/MediaRecord.tsx b/web/src/components/MediaRecord.tsx index 1aa096b6e..135c023d2 100644 --- a/web/src/components/MediaRecord.tsx +++ b/web/src/components/MediaRecord.tsx @@ -36,6 +36,9 @@ import { useRecordSave } from './useRecordSave'; import { shallowEqual, useSelector } from 'react-redux'; import { passageRecordSelector, sharedSelector } from '../selector'; +// TODO cleanup in next PR: no caller passes setCanCancel, onLoaded, +// hideControls, onProgress, onDuration or hasRecording, and cancelMethod is +// never read. (controlsRef is only passed by the Cypress specs; keep it.) export interface IProps { toolId: string; artifactId: string | null; @@ -462,7 +465,7 @@ function MediaRecord(props: IProps) { // TODO cleanup: (claude thinks we should do this, I'm not sure it will be as simple // as claude thinks, but don't have time to look into it now) // MediaRecord runs its own upload pipeline, separate from its - // host's (e.g. PassageRecordDlg already holds the upload tab's `uploadMethod`). + // host's (e.g. PassageRecordPanel already holds the upload tab's `uploadMethod`). // That's why pendingRestore/beforeUpload/finish/afterUploadCb/uploadType are all // threaded through here just to feed this copy, and why the record and upload // tabs drifted (this hardcoded Media until the general-resource Retry fix). diff --git a/web/src/components/MediaUploadContent.tsx b/web/src/components/MediaUploadContent.tsx index 8c2a472eb..685f813b4 100644 --- a/web/src/components/MediaUploadContent.tsx +++ b/web/src/components/MediaUploadContent.tsx @@ -172,7 +172,6 @@ interface IProps { team?: string | undefined; // used to check for speakers when adding a card onFiles?: ((files: File[]) => void) | undefined; inValue?: string | undefined; - onValue?: ((value: string) => void) | undefined; audioOnly?: boolean | undefined; saveButtonText?: string | undefined; validationMessage?: string | undefined; @@ -215,7 +214,6 @@ function MediaUploadContent(props: IProps) { team, onFiles, inValue, - onValue, audioOnly, saveButtonText, validationMessage, @@ -374,7 +372,6 @@ function MediaUploadContent(props: IProps) { const type = uploadType !== UploadType.MarkDown ? UriLinkType : MarkDownType; setFiles([{ name: newValue, size: newValue.length, type } as File]); - onValue && onValue(newValue); }; useEffect(() => { diff --git a/web/src/components/MediaUploadDialog.tsx b/web/src/components/MediaUploadDialog.tsx index f12b9c7d3..79708292f 100644 --- a/web/src/components/MediaUploadDialog.tsx +++ b/web/src/components/MediaUploadDialog.tsx @@ -17,7 +17,6 @@ interface IProps { ((files: File[]) => void | boolean | Promise) | undefined; multiple?: boolean | undefined; cancelMethod?: (() => void) | undefined; - cancelLabel?: string | undefined; metaData?: React.JSX.Element | undefined; ready?: (() => boolean) | undefined; speaker?: string | undefined; @@ -25,15 +24,12 @@ interface IProps { team?: string | undefined; // used to check for speakers when adding a card onFiles?: ((files: File[]) => void) | undefined; inValue?: string | undefined; - onValue?: ((value: string) => void) | undefined; audioOnly?: boolean | undefined; validationMessage?: string | undefined; /** Hide the bottom "Cancel" button (cancel is reached via the dialog's X). */ // I think we are moving towards using the dialog's X as the standard way to cancel instead of an explicit Cancel button. // hopefully in the future we can remove the explicit Cancel button entirely. hideCancel?: boolean | undefined; - /** Keep the selection after submit instead of clearing it (see MediaUploadContent). */ - keepFilesAfterSubmit?: boolean | undefined; } function MediaUploadDialog(props: IProps) { @@ -45,7 +41,6 @@ function MediaUploadDialog(props: IProps) { multiple, uploadMethod, cancelMethod, - cancelLabel, metaData, ready, speaker, @@ -53,11 +48,9 @@ function MediaUploadDialog(props: IProps) { team, onFiles, inValue, - onValue, audioOnly, validationMessage, hideCancel, - keepFilesAfterSubmit, } = props; const { isMobile } = useMobile(); const t: IMediaUploadStrings = useSelector(mediaUploadSelector, shallowEqual); @@ -97,7 +90,6 @@ function MediaUploadDialog(props: IProps) { multiple={multiple} uploadMethod={uploadMethod} cancelMethod={cancelMethod} - cancelLabel={cancelLabel} metaData={metaData} ready={ready} speaker={speaker} @@ -105,11 +97,9 @@ function MediaUploadDialog(props: IProps) { team={team} onFiles={onFiles} inValue={inValue} - onValue={onValue} audioOnly={audioOnly} validationMessage={validationMessage} hideCancel={hideCancel} - keepFilesAfterSubmit={keepFilesAfterSubmit} /> From 98365573c7c77a7146c51289828fa85c61051bb6 Mon Sep 17 00:00:00 2001 From: Noel Chou Date: Mon, 9 Nov 2026 19:31:21 -0500 Subject: [PATCH 03/12] reviewed --- web/src/components/MediaUploadContent.tsx | 6 +- .../AddResourceWizard.test.tsx | 525 +++++++++++ .../Internalization/AddResourceWizard.tsx | 176 ++++ .../PassageDetailArtifacts.test.tsx | 146 +-- .../PassageDetailArtifacts.tsx | 846 ++---------------- .../PassageDetailsArtifactsMobile.tsx | 827 ++--------------- .../ProjectResourceConfigure.tsx | 108 +-- .../Internalization/ResourceData.tsx | 12 +- .../Internalization/UploadRecordToggle.tsx | 14 +- .../Internalization/useResourceScopeLabels.ts | 34 + web/src/components/PassageRecordPanel.tsx | 241 +++++ web/src/components/Sheet/ScriptureTable.tsx | 2 - web/src/components/TitleUploader.tsx | 2 +- web/src/components/Uploader.tsx | 4 + web/src/control/ActionRow.tsx | 4 +- web/src/crud/useMediaUpload.ts | 6 +- web/src/store/localization/model.tsx | 1 - web/src/store/localization/reducers.tsx | 1 - 18 files changed, 1189 insertions(+), 1766 deletions(-) create mode 100644 web/src/components/PassageDetail/Internalization/AddResourceWizard.test.tsx create mode 100644 web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx create mode 100644 web/src/components/PassageDetail/Internalization/useResourceScopeLabels.ts create mode 100644 web/src/components/PassageRecordPanel.tsx diff --git a/web/src/components/MediaUploadContent.tsx b/web/src/components/MediaUploadContent.tsx index 685f813b4..8128ab790 100644 --- a/web/src/components/MediaUploadContent.tsx +++ b/web/src/components/MediaUploadContent.tsx @@ -173,7 +173,7 @@ interface IProps { onFiles?: ((files: File[]) => void) | undefined; inValue?: string | undefined; audioOnly?: boolean | undefined; - saveButtonText?: string | undefined; + primaryButtonText?: string | undefined; validationMessage?: string | undefined; controlsRef?: React.RefObject; onSaveDisabled?: ((disabled: boolean) => void) | undefined; @@ -215,7 +215,7 @@ function MediaUploadContent(props: IProps) { onFiles, inValue, audioOnly, - saveButtonText, + primaryButtonText, validationMessage, controlsRef, onSaveDisabled, @@ -485,7 +485,7 @@ function MediaUploadContent(props: IProps) { disabled={saveDisabled} sx={{ minWidth: '96px' }} > - {saveButtonText || t.upload} + {primaryButtonText || t.upload} )} diff --git a/web/src/components/PassageDetail/Internalization/AddResourceWizard.test.tsx b/web/src/components/PassageDetail/Internalization/AddResourceWizard.test.tsx new file mode 100644 index 000000000..0f2e9e4e1 --- /dev/null +++ b/web/src/components/PassageDetail/Internalization/AddResourceWizard.test.tsx @@ -0,0 +1,525 @@ +import React from 'react'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ThemeProvider } from '@mui/material/styles'; +import { createAppTheme } from '../../../theme'; +import AddResourceWizard from './AddResourceWizard'; +import { WizardLaunch } from './useAddResourceWizard'; +import { AddResourceAction } from './AddResourceAction'; +import usePassageDetailContext from '../../../context/usePassageDetailContext'; + +const theme = createAppTheme('en'); + +// --- strings ----------------------------------------------------------------- +jest.mock('react-redux', () => ({ + shallowEqual: (a: unknown, b: unknown) => a === b, + useSelector: () => ({ + addAudioResource: 'Add Audio Resource', + editGeneralResource: 'Edit General Resource', + selectPassagesSub: 'Select passages for {0}', + editingFile: 'You are editing {0}', + generalResourcesIndividually: + 'General resources should be uploaded individually', + confirmCloseTitle: 'Confirm Close', + confirmClose: 'Discard changes?', + keepOpen: 'Keep Open', + discardAndClose: 'Discard and Close', + noteResource: 'Note Resource', + passageResource: 'Passage Resource', + bookResource: 'Book Resource', + movementResource: 'Movement Resource', + // media-upload title strings (same mock object serves every selector) + resourceTitle: 'Add Resource', + linkTitle: 'Add Link', + markdownTitle: 'Add Text', + pdfResourceTitle: 'Add PDF Resource', + faithbridgeTitle: 'Add {0} Resource', + }), +})); + +jest.mock('../../../selector', () => ({ + passageDetailArtifactsSelector: jest.fn(), + sharedSelector: jest.fn(), + mediaUploadSelector: jest.fn(), +})); + +// --- context / data ---------------------------------------------------------- +jest.mock('../../../context/usePassageDetailContext', () => ({ + __esModule: true, + default: jest.fn(), +})); + +const mockArtifactTypes = [ + { id: 'resource-type', attributes: { typename: 'resource' } }, + { id: 'project-resource-type', attributes: { typename: 'projectresource' } }, +]; +const mockEmpty: unknown[] = []; +jest.mock('../../../hoc/useOrbitData', () => ({ + useOrbitData: (type: string) => + type === 'artifacttype' ? mockArtifactTypes : mockEmpty, +})); + +jest.mock('../../../context/useGlobal', () => ({ + useGlobal: jest.fn((key: string) => { + const values: Record = { + memory: { + update: jest.fn(() => Promise.resolve()), + cache: { query: jest.fn(() => undefined) }, + keyMap: {}, + }, + offlineOnly: false, + progress: 0, + plan: '', + }; + return [values[key], jest.fn()]; + }), +})); + +// --- crud / helpers ---------------------------------------------------------- +const mockAddSectionResource = jest.fn(); +jest.mock('../../../crud', () => ({ + remoteIdGuid: (_t: string, remId: string) => remId, + useSecResCreate: () => ({ + AddSectionResource: mockAddSectionResource, + InternalizationStep: jest.fn(() => ({ id: 'step-1' })), + }), + related: jest.fn(() => ''), + useOrganizedBy: () => ({ + getOrganizedBy: (current: boolean) => (current ? 'Section' : 'Project'), + }), + findRecord: jest.fn((_m: unknown, _t: string, id: string) => ({ + id, + type: 'mediafile', + attributes: { originalFile: 'a.mp3' }, + })), + usePlan: () => ({ getPlan: jest.fn(() => null) }), +})); + +jest.mock('../../../utils', () => ({ + safeFileBasename: (s?: string) => s ?? '', +})); + +jest.mock('./projectResourceAssignments', () => ({ + getProjectResourceAssignments: jest.fn(() => []), +})); + +jest.mock('./resourceArtifactName', () => ({ + descriptionRequiredForResource: jest.fn(() => false), +})); +jest.mock('./buildResourcePendingRestore', () => ({ + buildResourcePendingRestore: jest.fn(() => undefined), +})); +jest.mock('./resourceRows', () => ({ AIGenerated: 'Generated By AI' })); + +jest.mock('../../../hoc/SnackBar', () => ({ + useSnackBar: () => ({ showMessage: jest.fn() }), +})); + +// --- dialog + step child mocks ---------------------------------------------- +jest.mock('../../../hoc/BigDialog', () => ({ + __esModule: true, + default: ({ + isOpen, + title, + description, + children, + onOpen, + }: { + isOpen?: boolean; + title?: React.ReactNode; + description?: React.ReactNode; + children?: React.ReactNode; + onOpen?: (open: boolean) => void; + }) => + isOpen ? ( +
+
{title}
+ {description} + {children} + +
+ ) : null, +})); + +const file = (name: string) => new File([name], name, { type: 'audio/mpeg' }); + +jest.mock('./ResourceUploadStep', () => { + const { UploadType } = jest.requireActual('../../UploadType'); + type ControlsRef = { + current: { handleAddOrSave: (() => void) | null; handleCancel: null }; + }; + return { + __esModule: true, + default: ({ + active, + uploadType, + ready, + validationMessage, + onFiles, + deferred, + onStartRecording, + finish, + metaData, + }: { + active?: boolean; + uploadType?: unknown; + ready?: () => boolean; + validationMessage?: string; + onFiles?: (f: File[]) => void; + deferred?: { onNext: () => void; submitRef: ControlsRef }; + onStartRecording?: () => void; + finish?: (ids?: string[]) => void; + metaData?: React.ReactNode; + }) => { + const isProject = uploadType === UploadType.ProjectResource; + const onNext = deferred?.onNext; + const submitRef = deferred?.submitRef; + // The body stays mounted and holds its own selection; invoking the + // exposed submit drives a successful upload (finish with one id), as the + // real upload's `finish` would. The wizard calls this from SelectSections. + if (submitRef) { + submitRef.current.handleAddOrSave = () => finish?.(['media-1']); + } + return ( + <> + {active && ( +
+ uploader-open + {metaData} + + + {/* Deferred flow: pick a file, then Next only advances (no upload + here) — the retained selection is uploaded later by the wizard + via submitRef. */} + + {/* A real recording reports recording-start (onStartRecording) + when it begins, before Next advances. */} + + + {validationMessage &&
{validationMessage}
} + +
+ )} + + ); + }, + }; +}); + +jest.mock('./ResourceData', () => { + const { ResourceTypeEnum } = jest.requireActual('./ResourceTypeEnum'); + return { + __esModule: true, + default: ({ + onDescriptionChange, + onPassResChange, + }: { + onDescriptionChange: (d: string) => void; + onPassResChange?: (k: number) => void; + }) => ( +
+ + +
+ ), + }; +}); + +jest.mock('./SelectSections', () => ({ + __esModule: true, + default: ({ + uploadsOnNext, + uploading, + onSelect, + onBack, + }: { + uploadsOnNext?: boolean; + uploading?: boolean; + onSelect?: (items: unknown[], candidates: unknown[]) => void; + onBack?: () => void; + }) => ( +
+ SelectSections + {uploadsOnNext ? 'btn-upload' : 'btn-next'} + {uploading && uploading} + + {onBack && ( + + )} +
+ ), +})); + +jest.mock('./ProjectResourceConfigure', () => ({ + __esModule: true, + default: ({ + onBack, + onOpen, + }: { + onBack?: () => void; + onOpen?: (open: boolean) => void; + }) => ( +
+ Configure + {onBack && ( + + )} + +
+ ), +})); + +jest.mock('../../AlertDialog', () => ({ + __esModule: true, + default: ({ + text, + yes, + no, + yesResponse, + noResponse, + }: { + text?: string; + yes?: string; + no?: string; + yesResponse?: () => void; + noResponse?: () => void; + }) => ( +
+ {text} + + +
+ ), +})); + +const mockContext = usePassageDetailContext as jest.MockedFunction< + typeof usePassageDetailContext +>; + +// Host mirrors the real parent: it renders the wizard only while open and +// unmounts it on onClose (the wizard no longer hides itself). +const renderWizard = (launchSource: WizardLaunch) => { + const Host = () => { + const [open, setOpen] = React.useState(true); + return open ? ( + setOpen(false)} + /> + ) : null; + }; + return render( + + + + ); +}; + +// Drive the common add → General → stage path to the section-select step. +const stageToSelectSections = () => { + fireEvent.click(screen.getByText('set-general')); + fireEvent.click(screen.getByText('stage-one-file')); +}; + +// Same, but the staged audio is a recorded take (recorded=true) rather than a +// plain file upload — closing then confirms, since a recording is lost (#719). +const stageRecordingToSelectSections = () => { + fireEvent.click(screen.getByText('set-general')); + fireEvent.click(screen.getByText('stage-one-recording')); +}; + +describe('AddResourceWizard', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockContext.mockReturnValue({ + rowData: [], + section: { id: 'section-1', attributes: { level: 0 } }, + passage: { id: 'passage-1', attributes: { reference: 'GEN 1:1' } }, + currentstep: {} as never, + setSelected: jest.fn(), + } as never); + }); + + it('disables Next and shows the validation message for multi-file general uploads', () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + fireEvent.click(screen.getByText('set-general')); + fireEvent.click(screen.getByText('select-two-files')); + + expect( + screen.getByText('General resources should be uploaded individually') + ).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled(); + }); + + it('titles the single dialog by the upload step type', () => { + const audio = renderWizard({ + kind: 'add', + action: AddResourceAction.Audio, + }); + expect(screen.getByText('Add Audio Resource')).toBeInTheDocument(); + audio.unmount(); + + const pdf = renderWizard({ kind: 'add', action: AddResourceAction.Pdf }); + expect(screen.getByText('Add PDF Resource')).toBeInTheDocument(); + pdf.unmount(); + + renderWizard({ kind: 'add', action: AddResourceAction.Link }); + expect(screen.getByText('Add Link')).toBeInTheDocument(); + }); + + it('advances from upload to the section-select step when a single general file is staged', () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + stageToSelectSections(); + + expect(screen.getByTestId('select-sections')).toBeInTheDocument(); + // Fresh add with no media yet: the button uploads. + expect(screen.getByText('btn-upload')).toBeInTheDocument(); + }); + + it('returns to the upload step when going Back from section-select', () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + stageToSelectSections(); + + fireEvent.click(screen.getByText('sections-back')); + + // The staged file/take itself is preserved by the upload subtree staying + // mounted across the step change (not re-seeded), so here we just confirm + // Back returns to the upload step. + expect(screen.getByText('uploader-open')).toBeInTheDocument(); + }); + + it('keeps SelectSections mounted while on the configure step (Back preserves it)', async () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + stageToSelectSections(); + + // Choose sections → the wizard fires the deferred upload through submitRef, + // which completes → configure step. + fireEvent.click(screen.getByText('sections-select')); + + await waitFor(() => + expect(screen.getByTestId('configure')).toBeInTheDocument() + ); + // SelectSections stays mounted (CSS-hidden) under the same dialog so its + // selection survives Back with no re-seeding. + expect(screen.getByTestId('select-sections')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('configure-back')); + expect(screen.queryByTestId('configure')).not.toBeInTheDocument(); + expect(screen.getByTestId('select-sections')).toBeInTheDocument(); + }); + + it('opens an existing general resource at section-select with no upload, advancing straight to configure', () => { + renderWizard({ + kind: 'editGeneralResource', + media: { + id: 'm1', + type: 'mediafile', + attributes: { originalFile: 'f.mp3' }, + } as never, + }); + + expect(screen.getByTestId('select-sections')).toBeInTheDocument(); + // Media already exists: the button advances rather than uploads, and there + // is no Back (no previous upload step). + expect(screen.getByText('btn-next')).toBeInTheDocument(); + expect(screen.queryByText('sections-back')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByText('sections-select')); + // The media already exists, so this advances straight to configure with no + // upload (the wizard never invokes the upload step's submit). + expect(screen.getByTestId('configure')).toBeInTheDocument(); + }); + + it('closes the section-select step via the X after a discard confirm when a recording was staged', () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + stageRecordingToSelectSections(); + + fireEvent.click(screen.getByText('dialog-x')); + expect(screen.getByTestId('confirm')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('Discard and Close')); + expect(screen.queryByTestId('select-sections')).not.toBeInTheDocument(); + expect(screen.queryByTestId('post-dialog')).not.toBeInTheDocument(); + }); + + it('closes the section-select step via the X without confirming when only a file was staged (#719)', () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + stageToSelectSections(); + + fireEvent.click(screen.getByText('dialog-x')); + // A staged file upload is cheap to redo, so closing it does not prompt. + expect(screen.queryByTestId('confirm')).not.toBeInTheDocument(); + expect(screen.queryByTestId('select-sections')).not.toBeInTheDocument(); + expect(screen.queryByTestId('post-dialog')).not.toBeInTheDocument(); + }); + + it('closes the wizard after a terminal (section-resource) upload', async () => { + renderWizard({ kind: 'add', action: AddResourceAction.Audio }); + // No General toggle: a plain section resource. + fireEvent.click(screen.getByText('finish-upload')); + + await waitFor(() => + expect(screen.queryByText('uploader-open')).not.toBeInTheDocument() + ); + expect(mockAddSectionResource).toHaveBeenCalled(); + }); +}); diff --git a/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx b/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx new file mode 100644 index 000000000..2ae7dd1bb --- /dev/null +++ b/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx @@ -0,0 +1,176 @@ +import ResourceUploadStep from './ResourceUploadStep'; +import BigDialog from '../../../hoc/BigDialog'; +import { BigDialogBp } from '../../../hoc/BigDialogBp'; +import SelectSections from './SelectSections'; +import ResourceData from './ResourceData'; +import { Box, Typography } from '@mui/material'; +import ProjectResourceConfigure from './ProjectResourceConfigure'; +import Confirm from '../../AlertDialog'; +import { safeFileBasename } from '../../../utils'; +import { UploadType } from '../../UploadType'; +import { + useAddResourceWizard, + WizardStep, + type WizardLaunch, +} from './useAddResourceWizard'; + +interface IProps { + launchSource: WizardLaunch; + onClose: () => void; + configureWidth?: number; +} + +/** + * The upload-based resource flow: step 1 (ResourceUploadStep) is shared by every + * add/research path; only the General (project) resource path continues to + * step 2 (SelectSections) and step 3 (ProjectResourceConfigure). The step + * components keep their own state across Back/Next. + */ +export function AddResourceWizard({ + launchSource, + onClose, + configureWidth = 1000, +}: IProps) { + const w = useAddResourceWizard({ launchSource, onClose }); + + return ( + <> + + {w.isAddingAudioResource + ? w.t.selectPassagesSub.replace('{0}', w.getOrganizedBy(false)) + : w.t.editingFile.replace( + '{0}', + safeFileBasename(w.projMedia?.attributes?.originalFile) + )} + + ) : undefined + } + isOpen + onOpen={w.handleWizardClose} + bp={BigDialogBp.md} + disableBackdropClose + // Flex column so the step content fills the height and footers pin to the + // dialog bottom. + dialogContentSx={{ display: 'flex', flexDirection: 'column' }} + > + <> + {/* Step 1: stays mounted across the flow (gets css-hidden on other steps) so a + recorded take survives Next→Back (see PassageRecordPanel).*/} + {launchSource.kind !== 'editGeneralResource' && ( + + w.setRecordingStarted(true)} + isAudioMode={w.isAddingAudioResource} + active={w.step === WizardStep.Upload} + finish={w.afterUpload} + beforeUpload={w.handleBeforeUpload} + cancelled={w.cancelled} + artifactState={w.artifactState.current} + uploadType={w.uploadType} + ready={() => w.resourceReady} + performedBy={w.performedBy} + onSpeakerChange={w.setPerformedBy} + inValue={w.markdownValue} + eafUrl={w.eafUrl} + defaultFilename={w.filename} + pendingRestore={w.resourcePendingRestore} + onFiles={w.handleResourceUploadFiles} + deferred={ + w.uploadType === UploadType.ProjectResource + ? { onNext: w.handleUploadStepNext, submitRef: w.submitRef } + : undefined + } + validationMessage={w.resourceUploadValidationMessage} + metaData={ + + } + /> + + )} + {/* Step 2: SelectSections stays mounted while the dialog is open + (CSS-hidden on the configure step) so its selection survives Back + from configure with no re-seeding. */} + + + + {/* Step 3: mounts only on its step: the wavesurfer player is expensive + TODO cleanup: some changes have been made since that decision was made. See if it still + makes sense to mount the configure step only when needed. */} + {w.step === WizardStep.Configure && ( + + )} + + + {w.pendingCloseConfirmation && ( + w.setPendingCloseConfirmation(false)} + yesResponse={() => { + w.setPendingCloseConfirmation(false); + onClose(); + }} + /> + )} + + ); +} + +export default AddResourceWizard; diff --git a/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.test.tsx b/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.test.tsx index 81ef9f779..6b0e951db 100644 --- a/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.test.tsx +++ b/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.test.tsx @@ -1,7 +1,6 @@ import React from 'react'; import { render, screen } from '@testing-library/react'; import { ThemeProvider } from '@mui/material/styles'; -import { UploadType } from '../../UploadType'; import PassageDetailArtifacts from './PassageDetailArtifacts'; import usePassageDetailContext from '../../../context/usePassageDetailContext'; import { createAppTheme } from '../../../theme'; @@ -30,9 +29,6 @@ jest.mock('react-redux', () => ({ useSelector: () => ({ title: 'Title', addAudioResource: 'Add Audio Resource', - uploadProject: 'Upload {0}', - currentResource: 'Current {0}', - tip1a: 'Choose scope', passageResource: 'Passage Resource', noteResource: 'Note Resource', bookResource: 'Book Resource', @@ -40,14 +36,9 @@ jest.mock('react-redux', () => ({ findResource: 'Find {0}', findResourceDesc: 'Find resource description', sharedResource: 'Shared {0}', - generalResources: 'General Resources', - generalResourcesIndividually: - 'General resources should be uploaded individually', editAudioResource: 'Edit Audio Resource', editGeneralResource: 'Edit General Resource', editResource: 'Edit Resource', - editingFile: 'You are editing {0}', - selectPassagesSub: 'Select passages for {0}', confirmCloseTitle: 'Confirm Close', confirmClose: 'Discard changes?', keepOpen: 'Keep Open', @@ -67,18 +58,6 @@ jest.mock('../../../selector', () => ({ })); jest.mock('../../../crud', () => ({ - ArtifactTypeSlug: { - Vernacular: 'vernacular', - WholeBackTranslation: 'wholebacktranslation', - PhraseBackTranslation: 'backtranslation', - CarefulSpeech: 'carefulspeech', - Retell: 'retell', - QandA: 'qanda', - Comment: 'comment', - Activity: 'activity', - Resource: 'resource', - SharedResource: 'sharedresource', - }, remoteIdGuid: jest.fn(), useSecResCreate: () => ({ AddSectionResource: jest.fn(), @@ -101,32 +80,18 @@ jest.mock('../../../crud', () => ({ }), ArtifactCategoryType: { Resource: 'resource' }, usePlanType: () => () => ({ scripture: false, flat: false }), - usePlan: () => ({ getPlan: jest.fn(() => null) }), - useArtifactType: () => ({ getTypeId: jest.fn(() => '') }), + mediaFileName: jest.fn(() => ''), })); -// Stable module-level arrays: the real useOrbitData hook returns the same -// reference until the underlying data changes, so a mock that hands back a -// fresh array literal on every call would falsely destabilize useMemo/useEffect -// deps keyed on these results (e.g. resourceType/projResourceType above). -// Names are prefixed with `mock` so babel-plugin-jest-hoist allows referencing -// them from inside the hoisted jest.mock() factory below. const mockArtifactTypesResult = [ { id: 'resource-type', attributes: { typename: 'resource' } }, - { - id: 'project-resource-type', - attributes: { typename: 'projectresource' }, - }, + { id: 'project-resource-type', attributes: { typename: 'projectresource' } }, ]; const mockEmptyOrbitResult: unknown[] = []; jest.mock('../../../hoc/useOrbitData', () => ({ - useOrbitData: (type: string) => { - if (type === 'artifacttype') { - return mockArtifactTypesResult; - } - return mockEmptyOrbitResult; - }, + useOrbitData: (type: string) => + type === 'artifacttype' ? mockArtifactTypesResult : mockEmptyOrbitResult, })); jest.mock('../../../context/useGlobal', () => ({ @@ -137,7 +102,6 @@ jest.mock('../../../context/useGlobal', () => ({ remoteBusy: false, offline: false, offlineOnly: false, - progress: 0, plan: '', }; return [values[key], jest.fn()]; @@ -160,19 +124,10 @@ jest.mock('../../../crud/isLinkedNote', () => ({ isLinkedNote: jest.fn(() => false), })); -jest.mock('../../../hoc/SnackBar', () => ({ - useSnackBar: () => ({ showMessage: jest.fn() }), -})); - jest.mock('../../../utils', () => ({ getSegments: jest.fn(() => '[]'), NamedRegions: { ProjectResource: 'ProjectResource' }, - removeExtension: jest.fn(() => ({ name: 'topic' })), - isVisual: jest.fn(() => false), isUrl: jest.fn(() => true), - useMobile: () => ({ isMobileWidth: false }), - safeFileBasename: jest.requireActual('../../../utils/safeFileBasename') - .safeFileBasename, })); jest.mock('../../../control', () => ({ @@ -203,70 +158,23 @@ jest.mock('./AddResource', () => ({ ), })); -jest.mock('../../Uploader', () => ({ +// The wizard owns the whole upload flow; here we only assert the parent hands +// it the right launch request. +jest.mock('./AddResourceWizard', () => ({ __esModule: true, - default: ({ - isOpen, - uploadType, - ready, - validationMessage, - onFiles, - metaData, - }: { - isOpen?: boolean; - uploadType?: UploadType; - ready?: () => boolean; - validationMessage?: string; - onFiles?: (files: File[]) => void; - metaData?: React.ReactNode; - }) => { - if (!isOpen) return null; - return ( -
- {metaData} - - {validationMessage &&
{validationMessage}
} - -
- ); - }, + default: ({ launchSource }: { launchSource: unknown }) => ( +
{JSON.stringify(launchSource)}
+ ), })); jest.mock('./SortableHeader', () => () => null); jest.mock('./ReferenceTextRows', () => ({ ReferenceTextRows: () => null })); jest.mock('.', () => ({ - AIGenerated: 'ai-generated', SortableItem: () => null, - useFullReference: () => jest.fn(() => ''), -})); -jest.mock('../../../control/LinkEdit', () => ({ - LinkEdit: () => null, -})); - -jest.mock('../../../control/MarkDownEdit', () => ({ - MarkDownEdit: () => null, -})); - -jest.mock('../../../control/MarkDownView', () => ({ - MarkDownView: () => null, })); - jest.mock('../../MediaDisplay', () => () => null); jest.mock('./SelectSharedResource', () => () => null); -jest.mock('./SelectSections', () => () => null); -jest.mock('./ProjectResourceConfigure', () => () => null); +jest.mock('./ResourceData', () => () => null); jest.mock('../../AlertDialog', () => () => null); jest.mock('./FindTabs', () => () => null); jest.mock('./FindBibleBrain', () => () => null); @@ -274,19 +182,16 @@ jest.mock('../../LimitedMediaPlayer', () => () => null); jest.mock('./PassageResourceButton', () => ({ PassageResourceButton: () => null, })); -jest.mock('../../Sheet/SelectArtifactCategory', () => { - const MockSelectArtifactCategory = (): React.ReactElement => ( -
category-select
- ); - return MockSelectArtifactCategory; -}); +jest.mock('../../../control/MarkDownView', () => ({ + MarkDownView: () => null, +})); const mockUsePassageDetailContext = usePassageDetailContext as jest.MockedFunction< typeof usePassageDetailContext >; -describe('PassageDetailArtifacts general resource uploads', () => { +describe('PassageDetailArtifacts', () => { beforeEach(() => { mockUsePassageDetailContext.mockReturnValue({ rowData: [], @@ -307,23 +212,24 @@ describe('PassageDetailArtifacts general resource uploads', () => { } as never); }); - it('disables Next and shows the validation message for multi-file general uploads', () => { + const renderComponent = () => render( ); + it('starts with the add-resource wizard closed', () => { + renderComponent(); + expect(screen.queryByTestId('wizard-launch')).not.toBeInTheDocument(); + }); + + it('launches the wizard with an add request when Add Audio is chosen', () => { + renderComponent(); fireEvent.click(screen.getByRole('button', { name: 'open-audio-upload' })); - fireEvent.change(screen.getByLabelText('Title'), { - target: { value: 'Resource description' }, - }); - fireEvent.click(screen.getByLabelText('Upload Project')); - fireEvent.click(screen.getByRole('button', { name: 'select-two-files' })); - expect( - screen.getByText('General resources should be uploaded individually') - ).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled(); + const launch = screen.getByTestId('wizard-launch'); + expect(launch).toHaveTextContent('"kind":"add"'); + expect(launch).toHaveTextContent('"action":"audio"'); }); }); diff --git a/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.tsx b/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.tsx index 09dabb5f3..9b099e273 100644 --- a/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.tsx +++ b/web/src/components/PassageDetail/Internalization/PassageDetailArtifacts.tsx @@ -1,29 +1,20 @@ -import { useState, useMemo, useRef, useEffect, useCallback } from 'react'; +import { useState, useMemo, useRef, useEffect } from 'react'; import { useGlobal } from '../../../context/useGlobal'; import { IPassageDetailArtifactsStrings, - Passage, - Section, MediaFileD, SectionResourceD, - MediaFile, - ArtifactType, Resource, - SheetLevel, ISharedStrings, - PassageD, } from '../../../model'; import { arrayMoveImmutable as arrayMove } from 'array-move'; import { PlayInPlayer } from '../../../context/PlayInPlayer'; -import { useSnackBar } from '../../../hoc/SnackBar'; -import Uploader from '../../Uploader'; import AddResource from './AddResource'; import SortableHeader from './SortableHeader'; import { IRow } from '../../../context/PassageDetailContext'; import { Button } from '../../../control'; -import { AIGenerated, SortableItem } from '.'; +import { SortableItem } from '.'; import { - remoteIdGuid, useSecResCreate, useMediaResCreate, useSecResUpdate, @@ -38,14 +29,12 @@ import { IArtifactCategory, ArtifactCategoryType, usePlanType, - usePlan, mediaFileName, } from '../../../crud'; import BigDialog from '../../../hoc/BigDialog'; import { BigDialogBp } from '../../../hoc/BigDialogBp'; import MediaDisplay from '../../MediaDisplay'; import SelectSharedResource from './SelectSharedResource'; -import SelectSections from './SelectSections'; import ResourceData from './ResourceData'; import { MarkDownType, @@ -53,10 +42,7 @@ import { mediaContentType, } from '../../../utils/contentType'; import LimitedMediaPlayer from '../../LimitedMediaPlayer'; -import { - canSaveResourceEdit, - descriptionRequiredForResource, -} from './resourceArtifactName'; +import { canSaveResourceEdit } from './resourceArtifactName'; import { Badge, Box, @@ -69,37 +55,18 @@ import { } from '@mui/material'; import { ReplaceRelatedRecord } from '../../../model/baseModel'; import { PassageResourceButton } from './PassageResourceButton'; -import ProjectResourceConfigure from './ProjectResourceConfigure'; -import { useProjectResourceSave } from './useProjectResourceSave'; import Confirm from '../../AlertDialog'; -import { - getSegments, - NamedRegions, - removeExtension, - isVisual, - isUrl, - safeFileBasename, -} from '../../../utils'; +import { getSegments, NamedRegions, isUrl } from '../../../utils'; import { useOrbitData } from '../../../hoc/useOrbitData'; -import { - RecordIdentity, - RecordKeyMap, - RecordOperation, - RecordTransformBuilder, -} from '@orbit/records'; import { shallowEqual, useSelector } from 'react-redux'; import { passageDetailArtifactsSelector, sharedSelector, } from '../../../selector'; -import { passageTypeFromRef } from '../../../control/passageTypeFromRef'; -import { PassageTypeEnum } from '../../../model/passageType'; import { VertListDnd } from '../../../hoc/VertListDnd'; import usePassageDetailContext from '../../../context/usePassageDetailContext'; import { LaunchLink } from '../../../control/LaunchLink'; import { - getProjectResourceAssignments, - removeUnselectedProjectResourceAssignments, countProjectResourceCopies, removeProjectResource, } from './projectResourceAssignments'; @@ -108,10 +75,7 @@ import FindTabs from './FindTabs'; import { storedCompareKey } from '../../../utils/storedCompareKey'; import { useStepPermissions } from '../../../utils/useStepPermission'; import { isLinkedNote } from '../../../crud/isLinkedNote'; -import { - generalResourceMedia, - projectResourceTypeIds, -} from './generalResourceMedia'; +import { generalResourceMedia } from './generalResourceMedia'; import FindBibleBrain from './FindBibleBrain'; import { useHandleLink } from './addLinkKind'; import { usePassageRef } from './usePassageRef'; @@ -119,9 +83,11 @@ import { ReferenceTextRows } from './ReferenceTextRows'; import { MarkDownView } from '../../../control/MarkDownView'; import { UploadType } from '../../UploadType'; import { ResourceTypeEnum } from './ResourceTypeEnum'; -import { buildResourcePendingRestore } from './buildResourcePendingRestore'; -import { useResumePendingProjectResourceConfig } from './useResumePendingProjectResourceConfig'; import { AddResourceAction } from './AddResourceAction'; +import AddResourceWizard from './AddResourceWizard'; +import { WizardLaunch } from './useAddResourceWizard'; +import { useResourceScopeLabels } from './useResourceScopeLabels'; +import { useResourceArtifactTypes } from './useResourceArtifactTypes'; const MediaContainer = styled(Box)(({ theme }) => ({ marginRight: theme.spacing(2), @@ -138,13 +104,11 @@ export function PassageDetailArtifacts() { const theme = useTheme(); const sectionResources = useOrbitData('sectionresource'); const mediafiles = useOrbitData('mediafile'); - const artifactTypes = useOrbitData('artifacttype'); const [memory] = useGlobal('memory'); const [busy, setBusy] = useGlobal('importexportBusy'); //verified this is not used in a function 2/18/25 const [remoteBusy] = useGlobal('remoteBusy'); //verified this is not used in a function 2/18/25 const [offline] = useGlobal('offline'); //verified this is not used in a function 2/18/25 const [offlineOnly] = useGlobal('offlineOnly'); //will be constant here - const [, setComplete] = useGlobal('progress'); const { rowData, section, @@ -163,7 +127,7 @@ export function PassageDetailArtifacts() { sharedResource, } = usePassageDetailContext(); const { getOrganizedBy } = useOrganizedBy(); - const { AddSectionResource, InternalizationStep } = useSecResCreate(section); + const { AddSectionResource } = useSecResCreate(section); const AddSectionResourceUser = useSecResUserCreate(); const ReadSectionResourceUser = useSecResUserRead(); const RemoveSectionResourceUser = useSecResUserDelete(); @@ -172,43 +136,33 @@ export function PassageDetailArtifacts() { const DeleteSectionResource = useSecResDelete(); const { getArtifactCategorys } = useArtifactCategory(); const catRef = useRef([]); - const [uploadVisible, setUploadVisible] = useState(false); - const [aiGenerated, setAIGenerated] = useState(false); const [findOpen, setFindOpen] = useState(false); - const [visual, setVisual] = useState(false); const [sortKey, setSortKey] = useState(0); - const cancelled = useRef(false); const [displayId, setDisplayId] = useState(''); const [link, setLink] = useState(); const [markDown, setMarkDoan] = useState(''); const [audioScriptureVisible, setAudioScriptureVisible] = useState(false); - const [allowProject, setAllowProject] = useState(true); const [sharedResourceVisible, setSharedResourceVisible] = useState(false); - const [projResPassageVisible, setProjResPassageVisible] = useState(false); - const [projResWizVisible, setProjResWizVisible] = useState(false); - const [projResSetup, setProjResSetup] = useState(new Array()); const [editResource, setEditResource] = useState< SectionResourceD | undefined >(); const [allowEditSave, setAllowEditSave] = useState(false); - const [resourceReady, setResourceReady] = useState(true); - const [resourceUploadFiles, setResourceUploadFiles] = useState([]); - const [artifactState] = useState<{ id?: string | null }>({}); - // const [artifactTypeId, setArtifactTypeId] = useState(); + const [wizardIsOpen, setWizardIsOpen] = useState(false); + const [wizardLaunchSource, setWizardLaunchSource] = + useState(null); + const launchWizard = (source: WizardLaunch) => { + setWizardLaunchSource(source); + setWizardIsOpen(true); + }; const [uploadType, setUploadType] = useState(UploadType.Resource); - const [audioUploadOrRecord, setAudioUploadOrRecord] = - useState(false); const [editAudio, setEditAudio] = useState(false); const mediaRef = useRef(undefined); const textRef = useRef(undefined); const catIdRef = useRef(undefined); - // commit() handles for the two SelectArtifactCategory instances (edit dialog - // vs. the add/upload dialog). Kept separate so one dialog unmounting never - // clears the other's handle. Called at save to create a new category. + // commit() handle for the edit dialog's SelectArtifactCategory. Called at save + // to create a new category. const editCatCommitRef = useRef<(() => Promise) | null>(null); - const addCatCommitRef = useRef<(() => Promise) | null>(null); const descriptionRef = useRef(''); - const pendingResourceSeqRef = useRef(0); const [resourceKind, setResourceKindx] = useState( ResourceTypeEnum.sectionResource @@ -218,41 +172,14 @@ export function PassageDetailArtifacts() { resourceKindRef.current = kind; setResourceKindx(kind); }; - const projIdentRef = useRef([]); - /** Every passage/section the selection dialog offered; scopes cleanup. */ - const projCandidateRef = useRef([]); - const projMediaRef = useRef(undefined); - // True when the general-resource wizard was entered by adding a new audio - // resource ("Add Audio Resource"); false when configuring/editing an existing - // one ("Edit General Resource"). - const isAddingAudioResourceRef = useRef(false); - // Deferred general-resource upload: the prepared file(s) are held here and not - // uploaded until the user picks passages/sections on SelectSections. - const stagedResourceFilesRef = useRef(undefined); - // True between SelectSections' Upload and the upload completing, so afterUpload - // routes straight to the configure step (or visual write) instead of - // re-opening SelectSections. - const sectionsPreselectedRef = useRef(false); - // Drives the deferred (headless) upload through the always-mounted Uploader. - const [resourceImportList, setResourceImportList] = useState< - File[] | undefined - >(undefined); - // True while the general-resource upload runs. SelectSections stays open - // (selections preserved) with its Upload button disabled/spinner until the - // upload succeeds (advance to the wizard) or fails (re-enable for retry). - const [uploading, setUploading] = useState(false); + const [allResources, setAllResources] = useState(false); - const { showMessage } = useSnackBar(); const [confirm, setConfirm] = useState(''); const [mediaStart, setMediaStart] = useState(); const [mediaEnd, setMediaEnd] = useState(); - const [performedBy, setPerformedBy] = useState(''); - const [markdownValue, setMarkdownValue] = useState(''); - const projectResourceSave = useProjectResourceSave(); const { removeKey } = storedCompareKey(passage, section); const [plan] = useGlobal('plan'); //will be constant here const planType = usePlanType(); - const { getPlan } = usePlan(); const t: IPassageDetailArtifactsStrings = useSelector( passageDetailArtifactsSelector, shallowEqual @@ -267,95 +194,23 @@ export function PassageDetailArtifacts() { [hasPermission, offline, offlineOnly] ); const [biblebrainClose, setBiblebrainClose] = useState(false); - // Confirm-before-discard for the wizard and edit dialogs. In the Add Audio - // Resource wizard, closing only prompts when it would lose a recording - // or at the final configure step ('wiz'). - // Which dialog's close is awaiting confirmation ('passage' vs 'edit' differ - // only in what discarding tears down); null when no prompt is showing. - const [dialogPendingCloseConfirmation, setDialogPendingCloseConfirmation] = - useState(null); - // Whether the staged general-resource audio is a recorded take (not an uploaded file). - const [isStagedRecording, setIsStagedRecording] = useState(false); + const [editCloseConfirmation, setEditCloseConfirmation] = useState(false); const handleLink = useHandleLink({ passage, setLink }); const { passageRef } = usePassageRef(); - const planRec = plan ? getPlan(plan) : null; - const filename = planRec?.attributes?.slug - ? `${planRec.attributes.slug}resource` - : 'resource'; - - const resourceType = useMemo(() => { - const resourceType = artifactTypes.find( - (t) => - t.attributes?.typename === 'resource' && - Boolean(t?.keys?.remoteId) === !offlineOnly - ); - // setArtifactTypeId(resourceType?.id); - artifactState.id = resourceType?.id || null; - return resourceType?.id; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [artifactTypes, offlineOnly]); - const otherResourcesAvailable = useMemo( () => rowData.some((r) => r.passageId && r.passageId !== passage.id), [passage, rowData] ); - const handleNonAudio = (value: boolean) => setAllowProject(!value); - const isPassageResource = () => resourceKindRef.current === ResourceTypeEnum.passageResource; - const isProjectResource = () => - resourceKindRef.current === ResourceTypeEnum.projectResource; - - const projResourceType = useMemo(() => { - const resourceType = artifactTypes.find( - (t) => - t.attributes?.typename === 'projectresource' && - Boolean(t?.keys?.remoteId) === !offlineOnly - ); - return resourceType?.id; - }, [artifactTypes, offlineOnly]); // Both projectresource type records (offline + remote); used to resolve // general resources for the type label, Edit, and Delete (see - // [[generalResourceMedia]]). - const projResourceTypeIds = useMemo( - () => projectResourceTypeIds(artifactTypes), - [artifactTypes] - ); - - const resourcePendingRestore = useCallback(() => { - if (resourceKindRef.current === ResourceTypeEnum.projectResource) { - return buildResourcePendingRestore({ - resourceType: ResourceTypeEnum.projectResource, - sectionId: section.id, - passageId: passage.id, - description: descriptionRef.current || null, - sequenceNum: 0, - ...(catIdRef.current ? { artifactCategoryId: catIdRef.current } : {}), - }); - } - const step = InternalizationStep(); - if (!step?.id) return undefined; - pendingResourceSeqRef.current += 1; - return buildResourcePendingRestore({ - resourceType: resourceKindRef.current, - sectionId: section.id, - passageId: passage.id, - description: descriptionRef.current || null, - sequenceNum: rowData.length + pendingResourceSeqRef.current, - orgWorkflowStepId: step.id, - ...(catIdRef.current ? { artifactCategoryId: catIdRef.current } : {}), - }); - }, [InternalizationStep, section.id, passage.id, rowData.length]); - - useResumePendingProjectResourceConfig({ - memory, - mediafiles, - setProjResSetup, - isAddingAudioResourceRef, - }); + // [[generalResourceMedia]]). Shared with the add wizard via this hook so the + // two resolve the same records (see useResourceArtifactTypes). + const { projResourceTypeIds } = useResourceArtifactTypes(); const handlePlay = (id: string) => { if (id === playItem) { @@ -471,9 +326,6 @@ export function PassageDetailArtifacts() { setBusy(false); } }; - const handleUploadVisible = (v: boolean) => { - setUploadVisible(v); - }; const handleFindVisible = (v: boolean) => { setFindOpen(v); @@ -483,83 +335,6 @@ export function PassageDetailArtifacts() { setSharedResourceVisible(v); }; - const handleProjResPassageVisible = (v: boolean) => { - if (!v) { - if (isStagedRecording) setDialogPendingCloseConfirmation('passage'); - else handlePassageDiscard(); - return; - } - setProjResPassageVisible(v); - }; - const handlePassageDiscard = () => { - setDialogPendingCloseConfirmation(null); - setProjResPassageVisible(false); - // A genuine abandon (not a Back), unlike handleWizBack/handlePassageBack — clear - // the restore state so the next fresh Add Audio Resource does not inherit it. - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - }; - - // The wizard's X routes here (like the passage-select dialog): a close request - // opens the shared discard confirm; opening just shows the dialog. - const handleProjResWizVisible = (v: boolean) => { - if (!v) { - setDialogPendingCloseConfirmation('wiz'); - return; - } - setProjResWizVisible(v); - }; - // Actually hide the wizard dialog. Called on discard (handleWizDiscard) and - // when a save finishes (ProjectResourceConfigure's onOpen). Confirm-on-close is - // parent-owned via dialogPendingCloseConfirmation='wiz'. - const closeProjResWiz = () => { - setProjResWizVisible(false); - projMediaRef.current = undefined; - setVisual(false); - // The wizard is truly done (save or discard) — no more Back is possible, so - // clear the category/description/filename restore state kept alive by - // resetEdit's preserveResourceForm since the upload succeeded. - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - }; - const handleWizDiscard = () => { - setDialogPendingCloseConfirmation(null); - closeProjResWiz(); - }; - - // Configure step "Back" (add flow only): return to passage selection keeping - // the uploaded media (unlike closeProjResWiz, which discards it). No confirm — - // going back is not a close; the wizard clears its own dirty flag on unmount, - // and the prior selection is re-checked via SelectSections' initialItems - // (projIdentRef). Coming forward again just re-opens the wizard (no re-upload, - // since the media already exists). - const handleWizBack = () => { - setProjResWizVisible(false); - setProjResPassageVisible(true); - }; - - const handlePassageBack = () => { - // Back to the upload/record dialog to change the audio file. A media already - // uploaded (reached here from the configure step's Back) is left in place; - // uploading a replacement creates a new general resource and leaves the prior - // one — the same outcome as cancelling from the configure step. Preventing - // these orphans is not priority for us at this time. - setProjResPassageVisible(false); - projMediaRef.current = undefined; - // Reopen the Add Audio Resource upload dialog in general-resource mode, the - // same state the user staged the file from. - setResourceKind(ResourceTypeEnum.projectResource); - artifactState.id = projResourceType ?? null; - setUploadType(UploadType.ProjectResource); - syncResourceReady(UploadType.ProjectResource, descriptionRef.current); - setAudioUploadOrRecord(true); - setUploadVisible(true); - }; - const handleAllResources = () => { setAllResources(!allResources); }; @@ -581,8 +356,7 @@ export function PassageDetailArtifacts() { // simple edit dialog (mockup: "use Edit to also configure the General Resource"). if (projectMedia) { setResourceKind(ResourceTypeEnum.projectResource); - isAddingAudioResourceRef.current = false; - handleSelectProjectResource(projectMedia); + launchWizard({ kind: 'editGeneralResource', media: projectMedia }); return; } setEditResource(secRes); @@ -614,30 +388,17 @@ export function PassageDetailArtifacts() { }) ); }; - // preserveResourceForm: skip clearing the category/description/filename restore - // state. Used when the deferred general-resource upload succeeds and the wizard - // advances to the configure step — Back/Back from there must still return the - // user to an upload dialog seeded with what they already entered. - const resetEdit = (preserveResourceForm = false) => { + const resetEdit = () => { setEditResource(undefined); - if (!preserveResourceForm) { - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - } + catIdRef.current = undefined; + descriptionRef.current = ''; setResourceKind(ResourceTypeEnum.sectionResource); - setUploadVisible(false); - setMarkdownValue(''); - setAIGenerated(false); - setAudioUploadOrRecord(false); - setAllowProject(true); setEditAudio(false); }; const handleEditResourceVisible = (v: boolean) => { // The X routes here (backdrop close is disabled); always confirm before discarding. if (!v) { - setDialogPendingCloseConfirmation('edit'); + setEditCloseConfirmation(true); } }; const handleEditSave = async () => { @@ -700,113 +461,38 @@ export function PassageDetailArtifacts() { resetEdit(); }; const handleEditCancel = () => { - setDialogPendingCloseConfirmation('edit'); + setEditCloseConfirmation(true); }; const handleEditDiscard = () => { - setDialogPendingCloseConfirmation(null); + setEditCloseConfirmation(false); resetEdit(); }; - const hasGeneralResourceUploadConflict = ( - files: File[] = resourceUploadFiles, - kind: ResourceTypeEnum = resourceKindRef.current - ) => kind === ResourceTypeEnum.projectResource && files.length > 1; - const resourceUploadValidationMessage = hasGeneralResourceUploadConflict( - resourceUploadFiles, - resourceKind - ) - ? t.generalResourcesIndividually - : ''; - const syncResourceReady = ( - type: UploadType, - desc: string, - files: File[] = resourceUploadFiles - ) => { - const descriptionReady = descriptionRequiredForResource(undefined, type) - ? Boolean(desc.trim()) - : true; - setResourceReady( - descriptionReady && !hasGeneralResourceUploadConflict(files) - ); - }; const handleAction = (what: AddResourceAction) => { - artifactState.id = resourceType ?? null; - setResourceKind(ResourceTypeEnum.sectionResource); - if (what === AddResourceAction.Audio) { - mediaRef.current = undefined; - setUploadType(UploadType.Resource); - syncResourceReady(UploadType.Resource, descriptionRef.current); - setAudioUploadOrRecord(true); - setUploadVisible(true); - } else if (what === AddResourceAction.Scripture) { + if (what === AddResourceAction.Scripture) { setAudioScriptureVisible(true); - } else if (what === AddResourceAction.Link) { - setUploadType(UploadType.Link); - syncResourceReady(UploadType.Link, descriptionRef.current); - setAudioUploadOrRecord(false); - setUploadVisible(true); - } else if (what === AddResourceAction.Pdf) { - mediaRef.current = undefined; - setUploadType(UploadType.PdfResource); - syncResourceReady(UploadType.PdfResource, descriptionRef.current); - setAllowProject(false); - setAudioUploadOrRecord(false); - setUploadVisible(true); - } else if (what === AddResourceAction.Text) { - setUploadType(UploadType.MarkDown); - syncResourceReady(UploadType.MarkDown, descriptionRef.current); - setAudioUploadOrRecord(false); - setUploadVisible(true); } else if (what === AddResourceAction.Shared) { setResourceKind(ResourceTypeEnum.sectionResource); setSharedResourceVisible(true); + } else if ( + what === AddResourceAction.Audio || + what === AddResourceAction.Pdf || + what === AddResourceAction.Text || + what === AddResourceAction.Link + ) { + launchWizard({ kind: 'add', action: what }); } }; - const handleMarkdownValue = ( + const handleFaithbridgeResult = ( query: string, audioUrl: string, transcript: string ) => { - descriptionRef.current = query; - const nextType = audioUrl - ? UploadType.FaithbridgeLink - : UploadType.MarkDown; - setUploadType(nextType); - syncResourceReady(nextType, query); - setMarkdownValue(audioUrl ? `${audioUrl}||${transcript}` : transcript); - setAudioUploadOrRecord(false); - setAIGenerated(true); - setUploadVisible(true); + launchWizard({ kind: 'faithbridge', query, audioUrl, transcript }); }; - const passDesc = useMemo( - () => - passageTypeFromRef(passage?.attributes?.reference) === - PassageTypeEnum.NOTE - ? t.noteResource - : t.passageResource, - // eslint-disable-next-line react-hooks/exhaustive-deps - [passage] - ); - - const getSectionType = () => { - const level = section.attributes?.level; - if (level === SheetLevel.Book) return 'BOOK'; - if (level === SheetLevel.Movement) return 'MOVE'; - return undefined; - }; - - const sectDesc = useMemo( - () => - getSectionType() === PassageTypeEnum.BOOK - ? t.bookResource - : getSectionType() === PassageTypeEnum.MOVEMENT - ? t.movementResource - : getOrganizedBy(true), - // eslint-disable-next-line react-hooks/exhaustive-deps - [section] - ); + const { sectDesc, passDesc } = useResourceScopeLabels(); const listFilter = (r: IRow) => r?.isResource && @@ -858,112 +544,6 @@ export function PassageDetailArtifacts() { forceRefresh(newRows); }; - const afterUpload = async (mediaRemoteIds?: string[]) => { - let cnt = rowData.length; - const projRes = new Array(); - const removeMedia = new Array(); - const tr = new RecordTransformBuilder(); - if (mediaRemoteIds && mediaRemoteIds.length > 0) { - for (const remId of mediaRemoteIds) { - cnt += 1; - const id = - remoteIdGuid('mediafile', remId, memory?.keyMap as RecordKeyMap) || - remId; - const mediaRecId = { type: 'mediafile', id }; - if (cancelled.current) { - removeMedia.push(tr.removeRecord(mediaRecId).toOperation()); - continue; - } - if (descriptionRef.current) { - await memory.update((t) => [ - t.replaceAttribute(mediaRecId, 'topic', descriptionRef.current), - ]); - } - if (catIdRef.current) { - await memory.update((t) => [ - ...ReplaceRelatedRecord( - t, - mediaRecId, - 'artifactCategory', - 'artifactcategory', - catIdRef.current - ), - ]); - } - if (isPassageResource()) { - await memory.update((t) => [ - ...ReplaceRelatedRecord( - t, - mediaRecId, - 'passage', - 'passage', - passage.id - ), - ]); - } - if (!isProjectResource()) { - await AddSectionResource( - cnt, - descriptionRef.current, - mediaRecId, - isPassageResource() ? passage.id : null - ); - } else { - projRes.push(findRecord(memory, 'mediafile', id) as MediaFileD); - } - } - // Set when advancing to the configure step, which still offers Back to the - // upload dialog — resetEdit must then preserve the category/description/ - // filename restore state instead of clearing it (closeProjResWiz clears it - // once that step actually finishes). - let preserveResourceForm = false; - if (projRes.length === 1) { - isAddingAudioResourceRef.current = true; - if (sectionsPreselectedRef.current) { - // Deferred flow: passages/sections were already chosen on - // SelectSections (which stayed open during the upload). The upload - // succeeded, so close it now and go to the configure step, or write - // visual resources directly. - const media = projRes[0] as MediaFileD; - projMediaRef.current = media; - sectionsPreselectedRef.current = false; - stagedResourceFilesRef.current = undefined; - setResourceImportList(undefined); - setUploading(false); - setProjResPassageVisible(false); - if (isVisual(media)) { - await writeVisualResource(projIdentRef.current); - setVisual(false); - } else { - // The configure step plays the context's playerMediafile; load it here - // since this path bypasses handleSelectProjectResource. - setSelected(media.id, PlayInPlayer.yes); - setProjResWizVisible(true); - preserveResourceForm = true; - } - } else { - setProjResSetup(projRes); - } - } - resetEdit(preserveResourceForm); - } - if (removeMedia.length > 0) { - await memory.update(removeMedia); - } - cancelled.current = false; - // Deferred upload produced no media (the upload failed). SelectSections is - // still open with the user's selection intact, so just re-enable its Upload - // button (the error was already surfaced by the uploader) and keep the - // staged file so they can retry without re-selecting. (A general resource is - // a single configured source; adding several at once is unsupported and is - // prevented in the UI, so only the single-media path is handled here.) - if (sectionsPreselectedRef.current && projRes.length === 0) { - sectionsPreselectedRef.current = false; - setResourceImportList(undefined); - setUploading(false); - } - }; - const resourceSourcePassages = useMemo(() => { const results: number[] = []; sectionResources.forEach((sr) => { @@ -1002,100 +582,6 @@ export function PassageDetailArtifacts() { } }; - const handleSelectProjectResource = (m: MediaFileD) => { - setSelected(m.id, PlayInPlayer.yes); - projMediaRef.current = m; - setVisual(isVisual(m)); - setProjResPassageVisible(true); - }; - - // Deferred general-resource add: the Add Audio Resource dialog's Next hands - // the prepared file here instead of uploading. We keep the file, open - // SelectSections, and defer the real upload to that dialog's Upload button - // (handleSelectProjectResourcePassage). No media exists yet, so there are no - // existing assignments to pre-check. - const handleStageAudioFiles = async (files: File[], recorded?: boolean) => { - // we should only have one file if going through the general resource flow - if (!files || files.length !== 1) return; - setIsStagedRecording(Boolean(recorded)); - // Commit a newly-typed artifact category now, while the dialog's metaData is - // still mounted; the deferred upload runs after it unmounts. Null the ref so - // the later upload's beforeUpload does not create a second category. - pendingResourceSeqRef.current = 0; - if (addCatCommitRef.current) { - catIdRef.current = await addCatCommitRef.current(); - addCatCommitRef.current = null; - } - stagedResourceFilesRef.current = files; - // Also seed the upload-tab restore state (normally set by handleResourceUploadFiles - // via onFiles) so a recorded take — which bypasses that callback — is still - // pre-selected if the user Backs out to the upload dialog and returns. - setResourceUploadFiles(files); - cancelled.current = false; - isAddingAudioResourceRef.current = true; - projMediaRef.current = undefined; - // Fresh add: no prior selection to pre-check on SelectSections. (A Back from - // the configure step repopulates projIdentRef, so only clear it here.) - projIdentRef.current = []; - // Staging only happens for the "Add Audio Resource" → General Resource flow, - // which is always audio, so this is never a visual resource. (Visual general - // resources are reached by selecting an existing project-resource media, not - // through staging.) The visual-vs-wizard routing in afterUpload keys off the - // uploaded media's own type, so this only sets the SelectSections label. - setVisual(false); - setUploadVisible(false); - setProjResPassageVisible(true); - }; - - const writeVisualResource = async (items: RecordIdentity[]) => { - const t = new RecordTransformBuilder(); - let cnt = 0; - const total = items.length; - for (const i of items) { - const rec = memory.cache.query((q) => q.findRecord(i)) as - Passage | Section; - const secRec = - rec?.type === 'section' - ? (rec as Section) - : (memory.cache.query((q) => - q.findRecord({ - type: 'section', - // type is string, so the section check does not narrow. - // This arm is a cached passage, which is initialized. - id: related(rec as PassageD, 'section'), - }) - ) as Section); - const secNum = secRec?.attributes.sequencenum || 0; - const topicIn = - projMediaRef.current?.attributes?.topic || - removeExtension(projMediaRef.current?.attributes?.originalFile || '') - ?.name; - const passage = rec?.type === 'passage' ? (rec as Passage) : undefined; - await projectResourceSave({ - t, - media: projMediaRef.current as MediaFile, - i: { secNum, section: secRec, passage }, - topicIn, - limitValue: '', - mediafiles, - sectionResources, - }); - cnt += 1; - setComplete(Math.min((cnt * 100) / total, 100)); - } - await removeUnselectedProjectResourceAssignments({ - memory, - sourceMedia: projMediaRef.current, - selectedItems: items, - mediafiles, - sectionResources, - resourceTypeId: resourceType, - candidateItems: projCandidateRef.current, - }); - // Ensure setComplete(0) is always called after processing - setComplete(0); - }; - const handleTextChange = (text: string) => { textRef.current = text; const ct = mediaContentType(mediaRef.current); @@ -1110,98 +596,26 @@ export function PassageDetailArtifacts() { ); }; - useEffect(() => { - if (!projResPassageVisible && !projResWizVisible && projMediaRef.current) - setProjResSetup(projResSetup.filter((m) => m !== projMediaRef.current)); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [projResPassageVisible, projResWizVisible]); - - // If SelectSections closes without starting the deferred upload (the user - // discarded/closed it before clicking Upload), drop the staged file(s). - // Otherwise a later SelectSections run — e.g. configuring an existing general - // resource — would see stale files and wrongly upload them. When the upload - // has started, sectionsPreselectedRef is true and afterUpload clears them. - useEffect(() => { - if (!projResPassageVisible && !sectionsPreselectedRef.current) { - stagedResourceFilesRef.current = undefined; - } - }, [projResPassageVisible]); - - useEffect(() => { - if (projResSetup.length) { - handleSelectProjectResource(projResSetup[0] as MediaFileD); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [projResSetup]); - - const handleSelectProjectResourcePassage = ( - items: RecordIdentity[], - candidates: RecordIdentity[] - ) => { - projIdentRef.current = items; - projCandidateRef.current = candidates; - if (stagedResourceFilesRef.current) { - // Deferred new-add flow: the file has not been uploaded yet. Upload it now - // (headlessly, through the always-mounted Uploader's importList) while - // SelectSections stays open with its button spinner. afterUpload advances - // to the configure step on success, or re-enables the button on failure - // so the user can retry without losing this selection. - sectionsPreselectedRef.current = true; - setUploading(true); - setResourceImportList(stagedResourceFilesRef.current); - return; - } - if (isVisual(projMediaRef.current)) { - writeVisualResource(items).then(() => { - setProjResPassageVisible(false); - }); - } else { - setProjResWizVisible(true); - setProjResPassageVisible(false); - } - }; - const handleCategory = (categoryId: string) => { catIdRef.current = categoryId; }; - const handleResourceUploadFiles = (files: File[]) => { - setResourceUploadFiles(files); - syncResourceReady(uploadType, descriptionRef.current, files); - }; - const handleDescription = (desc: string) => { descriptionRef.current = desc; const ct = mediaContentType(mediaRef.current); - if (editResource) { - setAllowEditSave( - canSaveResourceEdit({ - contentType: ct, - description: desc, - text: textRef.current ?? '', - originalFile: mediaRef.current?.attributes?.originalFile, - isUrl, - }) - ); - } else { - syncResourceReady(uploadType, desc); - } + setAllowEditSave( + canSaveResourceEdit({ + contentType: ct, + description: desc, + text: textRef.current ?? '', + originalFile: mediaRef.current?.attributes?.originalFile, + isUrl, + }) + ); }; const handlePassRes = (newValue: ResourceTypeEnum) => { setResourceKind(newValue); - if (newValue === ResourceTypeEnum.projectResource) { - artifactState.id = projResourceType ?? null; - setUploadType(UploadType.ProjectResource); - syncResourceReady(UploadType.ProjectResource, descriptionRef.current); - } else if ( - artifactState.id === projResourceType || - uploadType === UploadType.ProjectResource - ) { - artifactState.id = resourceType ?? null; - setUploadType(UploadType.Resource); - syncResourceReady(UploadType.Resource, descriptionRef.current); - } }; const handleEnded = () => { @@ -1309,58 +723,12 @@ export function PassageDetailArtifacts() { /> ))} - { - pendingResourceSeqRef.current = 0; - if (addCatCommitRef.current) - catIdRef.current = await addCatCommitRef.current(); - }} - cancelled={cancelled} - cancelReset={resetEdit} - artifactState={artifactState} - uploadType={uploadType} - ready={() => resourceReady} - onNonAudio={handleNonAudio} - performedBy={performedBy} - onSpeakerChange={(value) => setPerformedBy(value)} - inValue={markdownValue} - eafUrl={aiGenerated ? AIGenerated : ''} - defaultFilename={filename} - pendingRestore={resourcePendingRestore} - importList={resourceImportList} - onFiles={handleResourceUploadFiles} - // When returning here via the back button, display the previously selected files - initialFiles={resourceUploadFiles} - deferUpload={uploadType === UploadType.ProjectResource} - onStageFiles={handleStageAudioFiles} - validationMessage={resourceUploadValidationMessage} - metaData={ - - } - /> + {wizardIsOpen && wizardLaunchSource && ( + setWizardIsOpen(false)} + /> + )} {t.findResourceDesc}} @@ -1371,7 +739,7 @@ export function PassageDetailArtifacts() { handleFindVisible(false)} canAdd={hasPermission} - onMarkdown={handleMarkdownValue} + onMarkdown={handleFaithbridgeResult} /> - - {isAddingAudioResourceRef.current - ? t.selectPassagesSub.replace('{0}', getOrganizedBy(false)) - : t.editingFile.replace( - '{0}', - safeFileBasename( - projMediaRef.current?.attributes?.originalFile - ) - )} - - } - isOpen={projResPassageVisible} - onOpen={handleProjResPassageVisible} - disableBackdropClose - > - {projResPassageVisible ? ( - 0 - ? projIdentRef.current - : getProjectResourceAssignments( - projMediaRef.current, - mediafiles, - sectionResources, - resourceType - ) - } - visual={visual} - // The button uploads only when a media has not been created yet; - // after a Back from configure the media exists, so it just advances. - uploadsOnNext={ - isAddingAudioResourceRef.current && !projMediaRef.current - } - uploading={uploading} - onSelect={handleSelectProjectResourcePassage} - onBack={ - isAddingAudioResourceRef.current ? handlePassageBack : undefined - } - /> - ) : ( - <> - )} - - - {projResWizVisible ? ( - - ) : ( - <> - )} - ))} - {dialogPendingCloseConfirmation && ( + {editCloseConfirmation && ( setDialogPendingCloseConfirmation(null)} - yesResponse={ - dialogPendingCloseConfirmation === 'passage' - ? handlePassageDiscard - : dialogPendingCloseConfirmation === 'wiz' - ? handleWizDiscard - : handleEditDiscard - } + noResponse={() => setEditCloseConfirmation(false)} + yesResponse={handleEditDiscard} /> )} {displayId && ( diff --git a/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx b/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx index 6956f7068..af2b89212 100644 --- a/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx +++ b/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx @@ -1,30 +1,20 @@ -import { useState, useMemo, useRef, useEffect, useCallback } from 'react'; +import { useState, useMemo, useRef, useEffect } from 'react'; import { useGlobal } from '../../../context/useGlobal'; import { IPassageDetailArtifactsStrings, - Passage, - Section, MediaFileD, SectionResourceD, - MediaFile, - ArtifactType, Resource, - SheetLevel, ISharedStrings, - PassageD, } from '../../../model'; import { arrayMoveImmutable as arrayMove } from 'array-move'; import { PlayInPlayer } from '../../../context/PlayInPlayer'; -import { useSnackBar } from '../../../hoc/SnackBar'; -import Uploader from '../../Uploader'; import AddResource from './AddResource'; import { IRow } from '../../../context/PassageDetailContext'; import { Button, GrowingSpacer } from '../../../control'; -import { AIGenerated } from '.'; import { AudioResourceCard } from './mobile components/AudioResourceCard'; import { TextResourceCard } from './mobile components/TextResourceCard'; import { - remoteIdGuid, useSecResCreate, useMediaResCreate, useSecResUpdate, @@ -39,7 +29,6 @@ import { IArtifactCategory, ArtifactCategoryType, usePlanType, - usePlan, useRole, ArtifactTypeSlug, mediaFileName, @@ -48,52 +37,29 @@ import BigDialog from '../../../hoc/BigDialog'; import { BigDialogBp } from '../../../hoc/BigDialogBp'; import MediaDisplay from '../../MediaDisplay'; import SelectSharedResource from './SelectSharedResource'; -import SelectSections from './SelectSections'; import ResourceData from './ResourceData'; import { MarkDownType, UriLinkType, mediaContentType, } from '../../../utils/contentType'; -import { - canSaveResourceEdit, - descriptionRequiredForResource, -} from './resourceArtifactName'; +import { canSaveResourceEdit } from './resourceArtifactName'; import { Box, Stack, Typography, MenuItem, MenuList } from '@mui/material'; import VisibilityIcon from '@mui/icons-material/Visibility'; import { ReplaceRelatedRecord } from '../../../model/baseModel'; -import ProjectResourceConfigure from './ProjectResourceConfigure'; -import { useProjectResourceSave } from './useProjectResourceSave'; import Confirm from '../../AlertDialog'; -import { - getSegments, - NamedRegions, - removeExtension, - isVisual, - isUrl, - useMobile, - safeFileBasename, -} from '../../../utils'; +import { getSegments, NamedRegions, isUrl, useMobile } from '../../../utils'; import { useOrbitData } from '../../../hoc/useOrbitData'; -import { - RecordIdentity, - RecordKeyMap, - RecordTransformBuilder, -} from '@orbit/records'; import { shallowEqual, useSelector } from 'react-redux'; import { passageDetailArtifactsSelector, sharedSelector, } from '../../../selector'; -import { passageTypeFromRef } from '../../../control/passageTypeFromRef'; -import { PassageTypeEnum } from '../../../model/passageType'; import { VertListDnd } from '../../../hoc/VertListDnd'; import usePassageDetailContext from '../../../context/usePassageDetailContext'; import { LaunchLink } from '../../../control/LaunchLink'; import FindTabs from './FindTabs'; import { - getProjectResourceAssignments, - removeUnselectedProjectResourceAssignments, countProjectResourceCopies, removeProjectResource, } from './projectResourceAssignments'; @@ -101,10 +67,7 @@ import GeneralResourceDeleteDialog from './GeneralResourceDeleteDialog'; import { storedCompareKey } from '../../../utils/storedCompareKey'; import { useStepPermissions } from '../../../utils/useStepPermission'; import { isLinkedNote } from '../../../crud/isLinkedNote'; -import { - generalResourceMedia, - projectResourceTypeIds, -} from './generalResourceMedia'; +import { generalResourceMedia } from './generalResourceMedia'; import FindBibleBrain from './FindBibleBrain'; import { useHandleLink } from './addLinkKind'; import { usePassageRef } from './usePassageRef'; @@ -112,22 +75,22 @@ import { ReferenceTextRows } from './ReferenceTextRows'; import { CompactMarkDownView } from '../../../control/MarkDownView'; import { UploadType } from '../../UploadType'; import { ResourceTypeEnum } from './ResourceTypeEnum'; -import { buildResourcePendingRestore } from './buildResourcePendingRestore'; -import { useResumePendingProjectResourceConfig } from './useResumePendingProjectResourceConfig'; import { AddResourceAction } from './AddResourceAction'; import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined'; import IconMenu from '../../../control/IconMenu'; +import AddResourceWizard from './AddResourceWizard'; +import { WizardLaunch } from './useAddResourceWizard'; +import { useResourceScopeLabels } from './useResourceScopeLabels'; +import { useResourceArtifactTypes } from './useResourceArtifactTypes'; export function PassageDetailArtifactsMobile() { const sectionResources = useOrbitData('sectionresource'); const mediafiles = useOrbitData('mediafile'); - const artifactTypes = useOrbitData('artifacttype'); const [memory] = useGlobal('memory'); const [busy, setBusy] = useGlobal('importexportBusy'); //verified this is not used in a function 2/18/25 const [remoteBusy] = useGlobal('remoteBusy'); //verified this is not used in a function 2/18/25 const [offline] = useGlobal('offline'); //verified this is not used in a function 2/18/25 const [offlineOnly] = useGlobal('offlineOnly'); //will be constant here - const [, setComplete] = useGlobal('progress'); const { rowData, section, @@ -145,7 +108,7 @@ export function PassageDetailArtifactsMobile() { sharedResource, } = usePassageDetailContext(); const { getOrganizedBy } = useOrganizedBy(); - const { AddSectionResource, InternalizationStep } = useSecResCreate(section); + const { AddSectionResource } = useSecResCreate(section); const AddSectionResourceUser = useSecResUserCreate(); const ReadSectionResourceUser = useSecResUserRead(); const RemoveSectionResourceUser = useSecResUserDelete(); @@ -154,44 +117,34 @@ export function PassageDetailArtifactsMobile() { const DeleteSectionResource = useSecResDelete(); const { getArtifactCategorys } = useArtifactCategory(); const catRef = useRef([]); - const [uploadVisible, setUploadVisible] = useState(false); - const [aiGenerated, setAIGenerated] = useState(false); const [findOpen, setFindOpen] = useState(false); - const [visual, setVisual] = useState(false); const [sortKey, setSortKey] = useState(0); - const cancelled = useRef(false); const [displayId, setDisplayId] = useState(''); const [link, setLink] = useState(); const [markDown, setMarkDoan] = useState(''); const [markDownTitle, setMarkDownTitle] = useState(''); const [audioScriptureVisible, setAudioScriptureVisible] = useState(false); - const [allowProject, setAllowProject] = useState(true); const [sharedResourceVisible, setSharedResourceVisible] = useState(false); - const [projResPassageVisible, setProjResPassageVisible] = useState(false); - const [projResWizVisible, setProjResWizVisible] = useState(false); - const [projResSetup, setProjResSetup] = useState(new Array()); const [editResource, setEditResource] = useState< SectionResourceD | undefined >(); const [allowEditSave, setAllowEditSave] = useState(false); - const [resourceReady, setResourceReady] = useState(true); - const [resourceUploadFiles, setResourceUploadFiles] = useState([]); - const [artifactState] = useState<{ id?: string | null }>({}); - // const [artifactTypeId, setArtifactTypeId] = useState(); + const [wizardIsOpen, setWizardIsOpen] = useState(false); + const [wizardLaunchSource, setWizardLaunchSource] = + useState(null); + const launchWizard = (source: WizardLaunch) => { + setWizardLaunchSource(source); + setWizardIsOpen(true); + }; const [uploadType, setUploadType] = useState(UploadType.Resource); - const [audioUploadOrRecord, setAudioUploadOrRecord] = - useState(false); const [editAudio, setEditAudio] = useState(false); const mediaRef = useRef(undefined); const textRef = useRef(undefined); const catIdRef = useRef(undefined); - // Separate commit() handles for the edit dialog vs. the add/upload dialog so - // one unmounting never clears the other's. Called at save to create a new - // category the user typed (deferred from blur). + // commit() handle for the edit dialog's SelectArtifactCategory. Called at save + // to create a new category. const editCatCommitRef = useRef<(() => Promise) | null>(null); - const addCatCommitRef = useRef<(() => Promise) | null>(null); const descriptionRef = useRef(''); - const pendingResourceSeqRef = useRef(0); const [resourceKind, setResourceKindx] = useState( ResourceTypeEnum.sectionResource @@ -201,41 +154,14 @@ export function PassageDetailArtifactsMobile() { resourceKindRef.current = kind; setResourceKindx(kind); }; - const projIdentRef = useRef([]); - /** Every passage/section the selection dialog offered; scopes cleanup. */ - const projCandidateRef = useRef([]); - const projMediaRef = useRef(undefined); - // True when the general-resource wizard was entered by adding a new audio - // resource (title "Add Audio Resource"); false when configuring/editing an - // existing one ("Edit General Resource"). - const isAddingAudioResourceRef = useRef(false); - // Deferred general-resource upload: the prepared file(s) are held here and not - // uploaded until the user picks passages/sections on SelectSections. - const stagedResourceFilesRef = useRef(undefined); - // True between SelectSections' Upload and the upload completing, so afterUpload - // routes straight to the configure step (or visual write) instead of - // re-opening SelectSections. - const sectionsPreselectedRef = useRef(false); - // Drives the deferred (headless) upload through the always-mounted Uploader. - const [resourceImportList, setResourceImportList] = useState< - File[] | undefined - >(undefined); - // True while the general-resource upload runs. SelectSections stays open - // (selections preserved) with its Upload button disabled/spinner until the - // upload succeeds (advance to the wizard) or fails (re-enable for retry). - const [uploading, setUploading] = useState(false); + const [allResources, setAllResources] = useState(false); - const { showMessage } = useSnackBar(); const [confirm, setConfirm] = useState(''); const [mediaStart, setMediaStart] = useState(); const [mediaEnd, setMediaEnd] = useState(); - const [performedBy, setPerformedBy] = useState(''); - const [markdownValue, setMarkdownValue] = useState(''); - const projectResourceSave = useProjectResourceSave(); const { removeKey } = storedCompareKey(passage, section); const [plan] = useGlobal('plan'); //will be constant here const planType = usePlanType(); - const { getPlan } = usePlan(); const t: IPassageDetailArtifactsStrings = useSelector( passageDetailArtifactsSelector, shallowEqual @@ -262,15 +188,7 @@ export function PassageDetailArtifactsMobile() { ? row.artifactType : undefined; const [biblebrainClose, setBiblebrainClose] = useState(false); - // Confirm-before-discard for the wizard and edit dialogs. In the Add Audio - // Resource wizard, closing only prompts when it would lose a recording (a - // file upload is cheap to redo) or at the final configure step ('wiz'). - // Which dialog's close is awaiting confirmation ('passage' vs 'edit' differ - // only in what discarding tears down); null when no prompt is showing. - const [dialogPendingCloseConfirmation, setDialogPendingCloseConfirmation] = - useState(null); - // The staged general-resource audio is a recorded take (not an uploaded file). - const [isStagedRecording, setIsStagedRecording] = useState(false); + const [editCloseConfirmation, setEditCloseConfirmation] = useState(false); const handleLink = useHandleLink({ passage, setLink }); const { passageRef } = usePassageRef(); const { isMobileWidth } = useMobile(); @@ -278,83 +196,19 @@ export function PassageDetailArtifactsMobile() { string | null >(null); - const planRec = plan ? getPlan(plan) : null; - const filename = planRec?.attributes?.slug - ? `${planRec.attributes.slug}resource` - : 'resource'; - - const resourceType = useMemo(() => { - const resourceType = artifactTypes.find( - (t) => - t.attributes?.typename === 'resource' && - Boolean(t?.keys?.remoteId) === !offlineOnly - ); - // setArtifactTypeId(resourceType?.id); - artifactState.id = resourceType?.id || null; - return resourceType?.id; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [artifactTypes, offlineOnly]); - const otherResourcesAvailable = useMemo( () => rowData.some((r) => r.passageId && r.passageId !== passage.id), [passage, rowData] ); - const handleNonAudio = (value: boolean) => setAllowProject(!value); - const isPassageResource = () => resourceKindRef.current === ResourceTypeEnum.passageResource; - const isProjectResource = () => - resourceKindRef.current === ResourceTypeEnum.projectResource; - - const projResourceType = useMemo(() => { - const resourceType = artifactTypes.find( - (t) => - t.attributes?.typename === 'projectresource' && - Boolean(t?.keys?.remoteId) === !offlineOnly - ); - return resourceType?.id; - }, [artifactTypes, offlineOnly]); // Both projectresource type records (offline + remote); used to resolve // general resources for the type label, Edit, and Delete (see - // [[generalResourceMedia]]). - const projResourceTypeIds = useMemo( - () => projectResourceTypeIds(artifactTypes), - [artifactTypes] - ); - - const resourcePendingRestore = useCallback(() => { - if (resourceKindRef.current === ResourceTypeEnum.projectResource) { - return buildResourcePendingRestore({ - resourceType: ResourceTypeEnum.projectResource, - sectionId: section.id, - passageId: passage.id, - description: descriptionRef.current || null, - sequenceNum: 0, - ...(catIdRef.current ? { artifactCategoryId: catIdRef.current } : {}), - }); - } - const step = InternalizationStep(); - if (!step?.id) return undefined; - pendingResourceSeqRef.current += 1; - return buildResourcePendingRestore({ - resourceType: resourceKindRef.current, - sectionId: section.id, - passageId: passage.id, - description: descriptionRef.current || null, - sequenceNum: rowData.length + pendingResourceSeqRef.current, - orgWorkflowStepId: step.id, - ...(catIdRef.current ? { artifactCategoryId: catIdRef.current } : {}), - }); - }, [InternalizationStep, section.id, passage.id, rowData.length]); - - useResumePendingProjectResourceConfig({ - memory, - mediafiles, - setProjResSetup, - isAddingAudioResourceRef, - }); + // [[generalResourceMedia]]). Shared with the add wizard via this hook so the + // two resolve the same records (see useResourceArtifactTypes). + const { projResourceTypeIds } = useResourceArtifactTypes(); const handlePlay = (id: string) => { if (id === playItem) { @@ -473,9 +327,6 @@ export function PassageDetailArtifactsMobile() { setBusy(false); } }; - const handleUploadVisible = (v: boolean) => { - setUploadVisible(v); - }; const handleFindVisible = (v: boolean) => { setFindOpen(v); @@ -485,83 +336,6 @@ export function PassageDetailArtifactsMobile() { setSharedResourceVisible(v); }; - const handleProjResPassageVisible = (v: boolean) => { - if (!v) { - if (isStagedRecording) setDialogPendingCloseConfirmation('passage'); - else handlePassageDiscard(); - return; - } - setProjResPassageVisible(v); - }; - const handlePassageDiscard = () => { - setDialogPendingCloseConfirmation(null); - setProjResPassageVisible(false); - // A genuine abandon (not a Back), unlike handleWizBack/handlePassageBack — clear - // the restore state so the next fresh Add Audio Resource does not inherit it. - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - }; - - // The wizard's X routes here (like the passage-select dialog): a close request - // opens the shared discard confirm; opening just shows the dialog. - const handleProjResWizVisible = (v: boolean) => { - if (!v) { - setDialogPendingCloseConfirmation('wiz'); - return; - } - setProjResWizVisible(v); - }; - // Actually hide the wizard dialog. Called on discard (handleWizDiscard) and - // when a save finishes (ProjectResourceConfigure's onOpen). Confirm-on-close is - // parent-owned via dialogPendingCloseConfirmation='wiz'. - const closeProjResWiz = () => { - setProjResWizVisible(false); - projMediaRef.current = undefined; - setVisual(false); - // The wizard is truly done (save or discard) — no more Back is possible, so - // clear the category/description/filename restore state kept alive by - // resetEdit's preserveResourceForm since the upload succeeded. - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - }; - const handleWizDiscard = () => { - setDialogPendingCloseConfirmation(null); - closeProjResWiz(); - }; - - // Configure step "Back" (add flow only): return to passage selection keeping - // the uploaded media (unlike closeProjResWiz, which discards it). No confirm — - // going back is not a close; the wizard clears its own dirty flag on unmount, - // and the prior selection is re-checked via SelectSections' initialItems - // (projIdentRef). Coming forward again just re-opens the wizard (no re-upload, - // since the media already exists). - const handleWizBack = () => { - setProjResWizVisible(false); - setProjResPassageVisible(true); - }; - - const handlePassageBack = () => { - // Back to the upload/record dialog to change the audio file. A media already - // uploaded (reached here from the configure step's Back) is left in place; - // uploading a replacement creates a new general resource and leaves the prior - // one — the same outcome as cancelling from the configure step. Preventing - // these orphans is not priority for us at this time. - setProjResPassageVisible(false); - projMediaRef.current = undefined; - // Reopen the Add Audio Resource upload dialog in general-resource mode, the - // same state the user staged the file from. - setResourceKind(ResourceTypeEnum.projectResource); - artifactState.id = projResourceType ?? null; - setUploadType(UploadType.ProjectResource); - syncResourceReady(UploadType.ProjectResource, descriptionRef.current); - setAudioUploadOrRecord(true); - setUploadVisible(true); - }; - const handleAllResources = () => { setAllResources(!allResources); }; @@ -583,8 +357,7 @@ export function PassageDetailArtifactsMobile() { // simple edit dialog (mockup: "use Edit to also configure the General Resource"). if (projectMedia) { setResourceKind(ResourceTypeEnum.projectResource); - isAddingAudioResourceRef.current = false; - handleSelectProjectResource(projectMedia); + launchWizard({ kind: 'editGeneralResource', media: projectMedia }); return; } setEditResource(secRes); @@ -616,29 +389,16 @@ export function PassageDetailArtifactsMobile() { }) ); }; - // preserveResourceForm: skip clearing the category/description/filename restore - // state. Used when the deferred general-resource upload succeeds and the wizard - // advances to the configure step — Back/Back from there must still return the - // user to an upload dialog seeded with what they already entered. - const resetEdit = (preserveResourceForm = false) => { + const resetEdit = () => { setEditResource(undefined); - if (!preserveResourceForm) { - catIdRef.current = undefined; - descriptionRef.current = ''; - setResourceUploadFiles([]); - setIsStagedRecording(false); - } + catIdRef.current = undefined; + descriptionRef.current = ''; setResourceKind(ResourceTypeEnum.sectionResource); - setUploadVisible(false); - setMarkdownValue(''); - setAIGenerated(false); - setAudioUploadOrRecord(false); - setAllowProject(true); setEditAudio(false); }; const handleEditResourceVisible = (v: boolean) => { if (!v) { - setDialogPendingCloseConfirmation('edit'); + setEditCloseConfirmation(true); } }; const handleEditSave = async () => { @@ -701,113 +461,38 @@ export function PassageDetailArtifactsMobile() { resetEdit(); }; const handleEditCancel = () => { - setDialogPendingCloseConfirmation('edit'); + setEditCloseConfirmation(true); }; const handleEditDiscard = () => { - setDialogPendingCloseConfirmation(null); + setEditCloseConfirmation(false); resetEdit(); }; - const hasGeneralResourceUploadConflict = ( - files: File[] = resourceUploadFiles, - kind: ResourceTypeEnum = resourceKindRef.current - ) => kind === ResourceTypeEnum.projectResource && files.length > 1; - const resourceUploadValidationMessage = hasGeneralResourceUploadConflict( - resourceUploadFiles, - resourceKind - ) - ? t.generalResourcesIndividually - : ''; - const syncResourceReady = ( - type: UploadType, - desc: string, - files: File[] = resourceUploadFiles - ) => { - const descriptionReady = descriptionRequiredForResource(undefined, type) - ? Boolean(desc.trim()) - : true; - setResourceReady( - descriptionReady && !hasGeneralResourceUploadConflict(files) - ); - }; const handleAction = (what: AddResourceAction) => { - artifactState.id = resourceType ?? null; - setResourceKind(ResourceTypeEnum.sectionResource); - if (what === AddResourceAction.Audio) { - mediaRef.current = undefined; - setUploadType(UploadType.Resource); - syncResourceReady(UploadType.Resource, descriptionRef.current); - setAudioUploadOrRecord(true); - setUploadVisible(true); - } else if (what === AddResourceAction.Scripture) { + if (what === AddResourceAction.Scripture) { setAudioScriptureVisible(true); - } else if (what === AddResourceAction.Link) { - setUploadType(UploadType.Link); - syncResourceReady(UploadType.Link, descriptionRef.current); - setAudioUploadOrRecord(false); - setUploadVisible(true); - } else if (what === AddResourceAction.Pdf) { - mediaRef.current = undefined; - setUploadType(UploadType.PdfResource); - syncResourceReady(UploadType.PdfResource, descriptionRef.current); - setAllowProject(false); - setAudioUploadOrRecord(false); - setUploadVisible(true); - } else if (what === AddResourceAction.Text) { - setUploadType(UploadType.MarkDown); - syncResourceReady(UploadType.MarkDown, descriptionRef.current); - setAudioUploadOrRecord(false); - setUploadVisible(true); } else if (what === AddResourceAction.Shared) { setResourceKind(ResourceTypeEnum.sectionResource); setSharedResourceVisible(true); + } else if ( + what === AddResourceAction.Audio || + what === AddResourceAction.Pdf || + what === AddResourceAction.Text || + what === AddResourceAction.Link + ) { + launchWizard({ kind: 'add', action: what }); } }; - const handleMarkdownValue = ( + const handleFaithbridgeResult = ( query: string, audioUrl: string, transcript: string ) => { - descriptionRef.current = query; - const nextType = audioUrl - ? UploadType.FaithbridgeLink - : UploadType.MarkDown; - setUploadType(nextType); - syncResourceReady(nextType, query); - setMarkdownValue(audioUrl ? `${audioUrl}||${transcript}` : transcript); - setAudioUploadOrRecord(false); - setAIGenerated(true); - setUploadVisible(true); + launchWizard({ kind: 'faithbridge', query, audioUrl, transcript }); }; - const passDesc = useMemo( - () => - passageTypeFromRef(passage?.attributes?.reference) === - PassageTypeEnum.NOTE - ? t.noteResource - : t.passageResource, - // eslint-disable-next-line react-hooks/exhaustive-deps - [passage] - ); - - const getSectionType = () => { - const level = section.attributes?.level; - if (level === SheetLevel.Book) return 'BOOK'; - if (level === SheetLevel.Movement) return 'MOVE'; - return undefined; - }; - - const sectDesc = useMemo( - () => - getSectionType() === PassageTypeEnum.BOOK - ? t.bookResource - : getSectionType() === PassageTypeEnum.MOVEMENT - ? t.movementResource - : getOrganizedBy(true), - // eslint-disable-next-line react-hooks/exhaustive-deps - [section] - ); + const { sectDesc, passDesc } = useResourceScopeLabels(); const listFilter = (r: IRow) => r?.isResource && @@ -859,102 +544,6 @@ export function PassageDetailArtifactsMobile() { forceRefresh(newRows); }; - const afterUpload = async (mediaRemoteIds?: string[]) => { - let cnt = rowData.length; - const projRes = new Array(); - if (mediaRemoteIds && mediaRemoteIds.length > 0) { - for (const remId of mediaRemoteIds) { - cnt += 1; - const id = - remoteIdGuid('mediafile', remId, memory?.keyMap as RecordKeyMap) || - remId; - const mediaRecId = { type: 'mediafile', id }; - if (descriptionRef.current) { - await memory.update((t) => [ - t.replaceAttribute(mediaRecId, 'topic', descriptionRef.current), - ]); - } - if (catIdRef.current) { - await memory.update((t) => [ - ...ReplaceRelatedRecord( - t, - mediaRecId, - 'artifactCategory', - 'artifactcategory', - catIdRef.current - ), - ]); - } - if (isPassageResource()) { - await memory.update((t) => [ - ...ReplaceRelatedRecord( - t, - mediaRecId, - 'passage', - 'passage', - passage.id - ), - ]); - } - if (!isProjectResource()) { - await AddSectionResource( - cnt, - descriptionRef.current, - mediaRecId, - isPassageResource() ? passage.id : null - ); - } else { - projRes.push(findRecord(memory, 'mediafile', id) as MediaFileD); - } - } - // Set when advancing to the configure step, which still offers Back to the - // upload dialog — resetEdit must then preserve the category/description/ - // filename restore state instead of clearing it (closeProjResWiz clears it - // once that step actually finishes). - let preserveResourceForm = false; - if (projRes.length === 1) { - isAddingAudioResourceRef.current = true; - if (sectionsPreselectedRef.current) { - // Deferred flow: passages/sections were already chosen on - // SelectSections (which stayed open during the upload). The upload - // succeeded, so close it now and go to the configure step, or write - // visual resources directly. - const media = projRes[0] as MediaFileD; - projMediaRef.current = media; - sectionsPreselectedRef.current = false; - stagedResourceFilesRef.current = undefined; - setResourceImportList(undefined); - setUploading(false); - setProjResPassageVisible(false); - if (isVisual(media)) { - await writeVisualResource(projIdentRef.current); - setVisual(false); - } else { - // The configure step plays the context's playerMediafile; load it here - // since this path bypasses handleSelectProjectResource. - setSelected(media.id, PlayInPlayer.yes); - setProjResWizVisible(true); - preserveResourceForm = true; - } - } else { - setProjResSetup(projRes); - } - } - resetEdit(preserveResourceForm); - } - // Deferred upload produced no media (the upload failed). SelectSections is - // still open with the user's selection intact, so just re-enable its Upload - // button (the error was already surfaced by the uploader) and keep the - // staged file so they can retry without re-selecting. (A general resource is - // a single configured source; adding several at once is unsupported and is - // prevented in the UI, so only the single-media path is handled here.) - if (sectionsPreselectedRef.current && projRes.length === 0) { - sectionsPreselectedRef.current = false; - setResourceImportList(undefined); - setUploading(false); - } - }; - const resourceSourcePassages = useMemo(() => { const results: number[] = []; sectionResources.forEach((sr) => { @@ -993,100 +582,6 @@ export function PassageDetailArtifactsMobile() { } }; - const handleSelectProjectResource = (m: MediaFileD) => { - setSelected(m.id, PlayInPlayer.yes); - projMediaRef.current = m; - setVisual(isVisual(m)); - setProjResPassageVisible(true); - }; - - // Deferred general-resource add: the Add Audio Resource dialog's Next hands - // the prepared file here instead of uploading. We keep the file, open - // SelectSections, and defer the real upload to that dialog's Upload button - // (handleSelectProjectResourcePassage). No media exists yet, so there are no - // existing assignments to pre-check. - const handleStageAudioFiles = async (files: File[], recorded?: boolean) => { - // we should only have one file if going through the general resource flow - if (!files || files.length !== 1) return; - setIsStagedRecording(Boolean(recorded)); - // Commit a newly-typed artifact category now, while the dialog's metaData is - // still mounted; the deferred upload runs after it unmounts. Null the ref so - // the later upload's beforeUpload does not create a second category. - pendingResourceSeqRef.current = 0; - if (addCatCommitRef.current) { - catIdRef.current = await addCatCommitRef.current(); - addCatCommitRef.current = null; - } - stagedResourceFilesRef.current = files; - // Also seed the upload-tab restore state (normally set by handleResourceUploadFiles - // via onFiles) so a recorded take — which bypasses that callback — is still - // pre-selected if the user Backs out to the upload dialog and returns. - setResourceUploadFiles(files); - cancelled.current = false; - isAddingAudioResourceRef.current = true; - projMediaRef.current = undefined; - // Fresh add: no prior selection to pre-check on SelectSections. (A Back from - // the configure step repopulates projIdentRef, so only clear it here.) - projIdentRef.current = []; - // Staging only happens for the "Add Audio Resource" → General Resource flow, - // which is always audio, so this is never a visual resource. (Visual general - // resources are reached by selecting an existing project-resource media, not - // through staging.) The visual-vs-wizard routing in afterUpload keys off the - // uploaded media's own type, so this only sets the SelectSections label. - setVisual(false); - setUploadVisible(false); - setProjResPassageVisible(true); - }; - - const writeVisualResource = async (items: RecordIdentity[]) => { - const t = new RecordTransformBuilder(); - let cnt = 0; - const total = items.length; - for (const i of items) { - const rec = memory.cache.query((q) => q.findRecord(i)) as - Passage | Section; - const secRec = - rec?.type === 'section' - ? (rec as Section) - : (memory.cache.query((q) => - q.findRecord({ - type: 'section', - // type is string, so the section check does not narrow. - // This arm is a cached passage, which is initialized. - id: related(rec as PassageD, 'section'), - }) - ) as Section); - const secNum = secRec?.attributes.sequencenum || 0; - const topicIn = - projMediaRef.current?.attributes?.topic || - removeExtension(projMediaRef.current?.attributes?.originalFile || '') - ?.name; - const passage = rec?.type === 'passage' ? (rec as Passage) : undefined; - await projectResourceSave({ - t, - media: projMediaRef.current as MediaFile, - i: { secNum, section: secRec, passage }, - topicIn, - limitValue: '', - mediafiles, - sectionResources, - }); - cnt += 1; - setComplete(Math.min((cnt * 100) / total, 100)); - } - await removeUnselectedProjectResourceAssignments({ - memory, - sourceMedia: projMediaRef.current, - selectedItems: items, - mediafiles, - sectionResources, - resourceTypeId: resourceType, - candidateItems: projCandidateRef.current, - }); - // Ensure setComplete(0) is always called after processing - setComplete(0); - }; - const handleTextChange = (text: string) => { textRef.current = text; const ct = mediaContentType(mediaRef.current); @@ -1101,98 +596,26 @@ export function PassageDetailArtifactsMobile() { ); }; - useEffect(() => { - if (!projResPassageVisible && !projResWizVisible && projMediaRef.current) - setProjResSetup(projResSetup.filter((m) => m !== projMediaRef.current)); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [projResPassageVisible, projResWizVisible]); - - // If SelectSections closes without starting the deferred upload (the user - // discarded/closed it before clicking Upload), drop the staged file(s). - // Otherwise a later SelectSections run — e.g. configuring an existing general - // resource — would see stale files and wrongly upload them. When the upload - // has started, sectionsPreselectedRef is true and afterUpload clears them. - useEffect(() => { - if (!projResPassageVisible && !sectionsPreselectedRef.current) { - stagedResourceFilesRef.current = undefined; - } - }, [projResPassageVisible]); - - useEffect(() => { - if (projResSetup.length) { - handleSelectProjectResource(projResSetup[0] as MediaFileD); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [projResSetup]); - - const handleSelectProjectResourcePassage = ( - items: RecordIdentity[], - candidates: RecordIdentity[] - ) => { - projIdentRef.current = items; - projCandidateRef.current = candidates; - if (stagedResourceFilesRef.current) { - // Deferred new-add flow: the file has not been uploaded yet. Upload it now - // (headlessly, through the always-mounted Uploader's importList) while - // SelectSections stays open with its button spinner. afterUpload advances - // to the configure step on success, or re-enables the button on failure - // so the user can retry without losing this selection. - sectionsPreselectedRef.current = true; - setUploading(true); - setResourceImportList(stagedResourceFilesRef.current); - return; - } - if (isVisual(projMediaRef.current)) { - writeVisualResource(items).then(() => { - setProjResPassageVisible(false); - }); - } else { - setProjResWizVisible(true); - setProjResPassageVisible(false); - } - }; - const handleCategory = (categoryId: string) => { catIdRef.current = categoryId; }; - const handleResourceUploadFiles = (files: File[]) => { - setResourceUploadFiles(files); - syncResourceReady(uploadType, descriptionRef.current, files); - }; - const handleDescription = (desc: string) => { descriptionRef.current = desc; const ct = mediaContentType(mediaRef.current); - if (editResource) { - setAllowEditSave( - canSaveResourceEdit({ - contentType: ct, - description: desc, - text: textRef.current ?? '', - originalFile: mediaRef.current?.attributes?.originalFile, - isUrl, - }) - ); - } else { - syncResourceReady(uploadType, desc); - } + setAllowEditSave( + canSaveResourceEdit({ + contentType: ct, + description: desc, + text: textRef.current ?? '', + originalFile: mediaRef.current?.attributes?.originalFile, + isUrl, + }) + ); }; const handlePassRes = (newValue: ResourceTypeEnum) => { setResourceKind(newValue); - if (newValue === ResourceTypeEnum.projectResource) { - artifactState.id = projResourceType ?? null; - setUploadType(UploadType.ProjectResource); - syncResourceReady(UploadType.ProjectResource, descriptionRef.current); - } else if ( - artifactState.id === projResourceType || - uploadType === UploadType.ProjectResource - ) { - artifactState.id = resourceType ?? null; - setUploadType(UploadType.Resource); - syncResourceReady(UploadType.Resource, descriptionRef.current); - } }; const handleEnded = () => { @@ -1286,58 +709,13 @@ export function PassageDetailArtifactsMobile() { ))}
- { - pendingResourceSeqRef.current = 0; - if (addCatCommitRef.current) - catIdRef.current = await addCatCommitRef.current(); - }} - cancelled={cancelled} - cancelReset={resetEdit} - artifactState={artifactState} - uploadType={uploadType} - ready={() => resourceReady} - onNonAudio={handleNonAudio} - performedBy={performedBy} - onSpeakerChange={(value) => setPerformedBy(value)} - inValue={markdownValue} - eafUrl={aiGenerated ? AIGenerated : ''} - defaultFilename={filename} - pendingRestore={resourcePendingRestore} - importList={resourceImportList} - onFiles={handleResourceUploadFiles} - // When returning here via the back button, display the previously selected files - initialFiles={resourceUploadFiles} - deferUpload={uploadType === UploadType.ProjectResource} - onStageFiles={handleStageAudioFiles} - validationMessage={resourceUploadValidationMessage} - metaData={ - - } - /> + {wizardIsOpen && wizardLaunchSource && ( + setWizardIsOpen(false)} + configureWidth={800} + /> + )} handleFindVisible(false)} canAdd={hasPermission} - onMarkdown={handleMarkdownValue} + onMarkdown={handleFaithbridgeResult} /> - - {isAddingAudioResourceRef.current - ? t.selectPassagesSub.replace('{0}', getOrganizedBy(false)) - : t.editingFile.replace( - '{0}', - safeFileBasename( - projMediaRef.current?.attributes?.originalFile - ) - )} - - } - isOpen={projResPassageVisible} - onOpen={handleProjResPassageVisible} - disableBackdropClose - > - {projResPassageVisible ? ( - 0 - ? projIdentRef.current - : getProjectResourceAssignments( - projMediaRef.current, - mediafiles, - sectionResources, - resourceType - ) - } - visual={visual} - // The button uploads only when a media has not been created yet; - // after a Back from configure the media exists, so it just advances. - uploadsOnNext={ - isAddingAudioResourceRef.current && !projMediaRef.current - } - uploading={uploading} - onSelect={handleSelectProjectResourcePassage} - onBack={ - isAddingAudioResourceRef.current ? handlePassageBack : undefined - } - /> - ) : ( - <> - )} - - - {projResWizVisible ? ( - - ) : ( - <> - )} - ))} - {dialogPendingCloseConfirmation && ( + {editCloseConfirmation && ( setDialogPendingCloseConfirmation(null)} - yesResponse={ - dialogPendingCloseConfirmation === 'passage' - ? handlePassageDiscard - : dialogPendingCloseConfirmation === 'wiz' - ? handleWizDiscard - : handleEditDiscard - } + noResponse={() => setEditCloseConfirmation(false)} + yesResponse={handleEditDiscard} /> )} {displayId && ( diff --git a/web/src/components/PassageDetail/Internalization/ProjectResourceConfigure.tsx b/web/src/components/PassageDetail/Internalization/ProjectResourceConfigure.tsx index 4478fc721..89f26ce72 100644 --- a/web/src/components/PassageDetail/Internalization/ProjectResourceConfigure.tsx +++ b/web/src/components/PassageDetail/Internalization/ProjectResourceConfigure.tsx @@ -3,11 +3,11 @@ import { useEffect, useMemo, useRef, - useContext, ChangeEvent, ReactNode, } from 'react'; import { useGlobal } from '../../../context/useGlobal'; +import { logError, Severity } from '../../../utils'; import { Section, IPassageDetailArtifactsStrings, @@ -46,7 +46,6 @@ import { transcriptionTabSelector, } from '../../../selector'; import { shallowEqual, useSelector } from 'react-redux'; -import { UnsavedContext } from '../../../context/UnsavedContext'; import { useProjectResourceSave } from './useProjectResourceSave'; import { useProjectSegmentSave } from './useProjectSegmentSave'; import { useFullReference, IInfo } from './useFullReference'; @@ -56,8 +55,6 @@ import { RecordIdentity, RecordTransformBuilder } from '@orbit/records'; import { useOrbitData } from '../../../hoc/useOrbitData'; import { removeUnselectedProjectResourceAssignments } from './projectResourceAssignments'; -const wizToolId = 'ProjResWizard'; - const StyledPaper = styled(Paper)(({ theme }) => ({ backgroundColor: theme.palette.background.default, marginBottom: theme.spacing(1), @@ -205,10 +202,9 @@ interface IProps { onOpen?: (open: boolean) => void; /** * When set, a "Back" button (the reverse of the selection dialog's Next) is - * shown — for now only in developer mode. It returns to SelectSections - * keeping the media, so the caller must not tear down the media on this - * path. Undefined hides the button (e.g. the edit flow, which has no - * previous wizard step). + * shown. It returns to SelectSections keeping the media, so the caller must + * not tear down the media on this path. Undefined hides the button (e.g. the + * edit flow, which has no previous wizard step). */ onBack?: () => void; bookData?: BookName[]; @@ -227,8 +223,8 @@ export const ProjectResourceConfigure = (props: IProps) => { const mediafiles = useOrbitData('mediafile'); const sectionResources = useOrbitData('sectionresource'); const [memory] = useGlobal('memory'); + const [errorReporter] = useGlobal('errorReporter'); const [, setComplete] = useGlobal('progress'); - const [isDeveloper] = useGlobal('developer'); const [data, setDatax] = useState([]); const [suffix, setSuffix] = useState(''); const [numSegments, setNumSegments] = useState(0); @@ -252,17 +248,7 @@ export const ProjectResourceConfigure = (props: IProps) => { // Match useFullReference's book-data resolution so the display label uses the // same source as the (unchanged) stored reference. const labelBookData = props.bookData ?? reduxBookData; - const { - toolChanged, - toolsChanged, - isChanged, - saveRequested, - startSave, - saveCompleted, - clearRequested, - clearCompleted, - } = useContext(UnsavedContext).state; - const savingRef = useRef(false); + const [saving, setSaving] = useState(false); const projectResourceSave = useProjectResourceSave(); const projectSegmentSave = useProjectSegmentSave(); const { showMessage } = useSnackBar(); @@ -300,6 +286,9 @@ export const ProjectResourceConfigure = (props: IProps) => { setDatax(newData); dataRef.current = newData; }; + // TODO cleanup in next PR: this only mounts on the wizard's Configure step, + // after `items` is set, so the table could be built once as lazy initial state + // instead of in an effect (mind the handleSegment call). useEffect(() => { if (items?.length > 0) { const newData: ICell[][] = emptyTable(); @@ -331,14 +320,14 @@ export const ProjectResourceConfigure = (props: IProps) => { }); infoRef.current = newInfo; setData(newData); - if (segmentsRef.current) handleSegment(segmentsRef.current, true); + if (segmentsRef.current) handleSegment(segmentsRef.current); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [items]); const writeResources = async () => { - if (!savingRef.current) { - savingRef.current = true; + if (!saving) { + setSaving(true); if (media) { const t = new RecordTransformBuilder(); let ix = 0; @@ -389,15 +378,11 @@ export const ProjectResourceConfigure = (props: IProps) => { segmentsRef.current ), }) - .then(() => { - saveCompleted(wizToolId); - }) .catch((err) => { - //so we don't come here...we go to continue/logout - saveCompleted(wizToolId, err.message); + showMessage(err.message); }) .finally(() => { - savingRef.current = false; + setSaving(false); setComplete(0); onOpen && onOpen(false); }); @@ -406,27 +391,9 @@ export const ProjectResourceConfigure = (props: IProps) => { }; const handleCreate = () => { - if (!saveRequested(wizToolId)) { - startSave(wizToolId); - } + void writeResources(); }; - useEffect(() => { - if (saveRequested(wizToolId) && !savingRef.current) writeResources(); - else if (clearRequested(wizToolId)) clearCompleted(wizToolId); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [toolsChanged]); - - // Real edits mark the tool dirty (see the Title and segment handlers) so - // a browser/app close mid-edit fires the beforeunload "unsaved changes" warning - // (AppHead reads the global `changed` flag). The dialog's own close is - // confirm-gated by the parent; clear the flag on unmount so a normal - // discard/save close doesn't leak it into the rest of the app. - useEffect(() => { - return () => toolChanged(wizToolId, false); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - const handleCopy = () => { const config: string[] = []; dataRef.current @@ -440,16 +407,22 @@ export const ProjectResourceConfigure = (props: IProps) => { }); const content = config.join('\n'); - if (content.length > 0) - navigator.clipboard - .writeText(content) - .then(() => { - showMessage(tt.availableOnClipboard); - }) - .catch(() => { - showMessage(ts.cantCopy); - }); - else showMessage(tt.noData.replace('{0}', t.projectResourceConfigure)); + if (content.length === 0) { + logError( + Severity.error, + errorReporter, + 'ProjectResourceConfigure: copy found no rows to copy. Should not have been reachable with no content.' + ); + return; + } + navigator.clipboard + .writeText(content) + .then(() => { + showMessage(tt.availableOnClipboard); + }) + .catch(() => { + showMessage(ts.cantCopy); + }); }; const loadPastedSegments = (newData: ICell[][]) => { @@ -556,12 +529,9 @@ export const ProjectResourceConfigure = (props: IProps) => { newData[c.row][c.col].value = c.value; }); setData(newData); - // Editing a Title marks the wizard dirty so a browser/app close warns - // (same tracking the segment handler uses). - if (!isChanged(wizToolId)) toolChanged(wizToolId); }; - const handleSegment = (segments: string, init: boolean) => { + const handleSegment = (segments: string) => { if (dataRef.current.length === 0) return; const regions = parseRegions(segments).regions.sort( (i, j) => i.start - j.start @@ -633,7 +603,6 @@ export const ProjectResourceConfigure = (props: IProps) => { if (change) { setData(newData); setPastedSegments(''); - if (!init && !isChanged(wizToolId)) toolChanged(wizToolId); } }; @@ -656,9 +625,6 @@ export const ProjectResourceConfigure = (props: IProps) => { const handleSuffix = (e: ChangeEvent) => { setSuffix(e.target.value); - // The suffix feeds the saved topic, so editing it marks the wizard dirty too - // (so a browser/app close mid-edit warns). - if (!isChanged(wizToolId)) toolChanged(wizToolId); }; // Reference cells carry their row's `info`; derive the localized label here so @@ -767,12 +733,8 @@ export const ProjectResourceConfigure = (props: IProps) => { Box neutralizes its flexGrow:1 inside this flex column. */} - {onBack && isDeveloper && ( - )} @@ -780,7 +742,7 @@ export const ProjectResourceConfigure = (props: IProps) => { + + + ) : ( + {}} + uploadType={uploadType} + primaryButtonText={primaryButtonText} + onNext={onNext} + controlsRef={controlsRef} + multiple + uploadMethod={uploadMethod} + metaData={metaData} + ready={ready} + speaker={speaker} + onSpeaker={uploadType === UploadType.Media ? onSpeaker : undefined} + onFiles={onFiles} + keepFilesAfterSubmit={Boolean(deferred)} + validationMessage={validationMessage} + /> + )} + + ); +} + +export default PassageRecordPanel; diff --git a/web/src/components/Sheet/ScriptureTable.tsx b/web/src/components/Sheet/ScriptureTable.tsx index 756c7794f..e6251165d 100644 --- a/web/src/components/Sheet/ScriptureTable.tsx +++ b/web/src/components/Sheet/ScriptureTable.tsx @@ -1492,8 +1492,6 @@ export function ScriptureTable(props: Readonly) { /> )} ) : ( diff --git a/web/src/components/Uploader.tsx b/web/src/components/Uploader.tsx index 609f313dc..d2cc3fcf0 100644 --- a/web/src/components/Uploader.tsx +++ b/web/src/components/Uploader.tsx @@ -9,6 +9,10 @@ import { UploadType } from './UploadType'; import { Box } from '@mui/material'; import { BigDialogBp } from '../hoc/BigDialogBp'; +// TODO cleanup in next PR: no caller passes metaData, beforeUpload, cancelReset, +// onFiles, eafUrl, inValue, team, uploadDialogBp, validationMessage or +// hideUploadCancel (only the old Add Resource flow did, before the wizard), and +// showMessage is never read. Remove them, plus the Faithbridge split (inValue). interface IProps { noBusy?: boolean | undefined; /** When true, do not wait for `importexportBusy` before staging upload (record save may hold it). */ diff --git a/web/src/control/ActionRow.tsx b/web/src/control/ActionRow.tsx index c6051008c..7e0116fe0 100644 --- a/web/src/control/ActionRow.tsx +++ b/web/src/control/ActionRow.tsx @@ -1,13 +1,15 @@ import { Box, BoxProps } from '@mui/material'; -export const ActionRow = ({ children, ...rest }: BoxProps) => ( +export const ActionRow = ({ children, sx, ...rest }: BoxProps) => ( diff --git a/web/src/crud/useMediaUpload.ts b/web/src/crud/useMediaUpload.ts index 867882011..f935a1d1e 100644 --- a/web/src/crud/useMediaUpload.ts +++ b/web/src/crud/useMediaUpload.ts @@ -12,7 +12,7 @@ import JSONAPISource from '@orbit/jsonapi'; import { TokenContext } from '../context/TokenProvider'; import { shallowEqual, useDispatch, useSelector } from 'react-redux'; import { IndexedDBSource } from '@orbit/indexeddb'; -import { NO_LIST_TYPES, UploadType } from '../components/UploadType'; +import { NON_FILE_UPLOAD_TYPES, UploadType } from '../components/UploadType'; import { RecordKeyMap } from '@orbit/records'; import { getContentType } from '../utils/contentType'; import { ISharedStrings, MediaFileAttributes, MediaFileD } from '../model'; @@ -230,7 +230,7 @@ export const useMediaUpload = ({ /** Rename files that lack the passage version suffix (opt-in, upload tab only). */ const applyVersionSuffix = (files: File[]) => { - if (!versionFilenames || NO_LIST_TYPES.includes(effectiveType)) + if (!versionFilenames || NON_FILE_UPLOAD_TYPES.includes(effectiveType)) return files; // passageDefaultSuffix looks the plan up in the local Orbit cache, so it // needs the local plan id (UUID) @@ -387,7 +387,7 @@ export const useMediaUpload = ({ if (!files || files.length === 0) return false; if (beforeUpload) await beforeUpload(); const staged = applyVersionSuffix(files); - if (!NO_LIST_TYPES.includes(effectiveType)) uploadFiles(staged); + if (!NON_FILE_UPLOAD_TYPES.includes(effectiveType)) uploadFiles(staged); const startedBusy = Boolean(getGlobal('importexportBusy')); if (!noBusy) setBusy(true); diff --git a/web/src/store/localization/model.tsx b/web/src/store/localization/model.tsx index ad29f7234..e830836be 100644 --- a/web/src/store/localization/model.tsx +++ b/web/src/store/localization/model.tsx @@ -1122,7 +1122,6 @@ export interface IPassageDetailArtifactsStrings extends Localize.LocalizedString "pasteFormat": string; "pasteError": string; "pasteNoChange": string; - "projectResourceConfigure": string; "recordResource": string; "reference": string; "referenceTextBookMissing": string; diff --git a/web/src/store/localization/reducers.tsx b/web/src/store/localization/reducers.tsx index 1965e3fbd..31bb3ed94 100644 --- a/web/src/store/localization/reducers.tsx +++ b/web/src/store/localization/reducers.tsx @@ -1181,7 +1181,6 @@ const initialState = { "pasteFormat": "Pasted data must contain two or three columns. One of them must be the reference.", "pasteError": "Unable to parse {0} segment boundaries. {1} segment boundaries were adjusted.", "pasteNoChange": "Nothing changed! Perhaps no references matched?", - "projectResourceConfigure": "Chunk into Resources", "recordResource": "Record", "reference": "Reference", "referenceTextBookMissing": "This Bible does not include this book.", From 21997f8891c92bd012f5884960d17117fa83d425 Mon Sep 17 00:00:00 2001 From: Noel Chou Date: Tue, 10 Nov 2026 13:58:19 -0500 Subject: [PATCH 04/12] cleanups and reviewed --- .../Internalization/AddResourceWizard.tsx | 16 +- .../PassageDetailArtifacts.tsx | 5 - .../PassageDetailsArtifactsMobile.tsx | 5 - .../Internalization/ResourceData.tsx | 37 +- .../ResourceUploadStep.test.tsx | 214 +++++++ .../Internalization/ResourceUploadStep.tsx | 145 +++++ .../Internalization/SelectSections.tsx | 121 ++-- .../Internalization/useAddResourceWizard.ts | 540 ++++++++++++++++++ .../useResourceArtifactTypes.test.ts | 43 ++ .../useResourceArtifactTypes.ts | 41 ++ .../Internalization/useResourceScopeLabels.ts | 34 -- 11 files changed, 1047 insertions(+), 154 deletions(-) create mode 100644 web/src/components/PassageDetail/Internalization/ResourceUploadStep.test.tsx create mode 100644 web/src/components/PassageDetail/Internalization/ResourceUploadStep.tsx create mode 100644 web/src/components/PassageDetail/Internalization/useAddResourceWizard.ts create mode 100644 web/src/components/PassageDetail/Internalization/useResourceArtifactTypes.test.ts create mode 100644 web/src/components/PassageDetail/Internalization/useResourceArtifactTypes.ts delete mode 100644 web/src/components/PassageDetail/Internalization/useResourceScopeLabels.ts diff --git a/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx b/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx index 2ae7dd1bb..d66734121 100644 --- a/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx +++ b/web/src/components/PassageDetail/Internalization/AddResourceWizard.tsx @@ -8,6 +8,7 @@ import ProjectResourceConfigure from './ProjectResourceConfigure'; import Confirm from '../../AlertDialog'; import { safeFileBasename } from '../../../utils'; import { UploadType } from '../../UploadType'; +import { useOrganizedBy } from '../../../crud'; import { useAddResourceWizard, WizardStep, @@ -32,6 +33,7 @@ export function AddResourceWizard({ configureWidth = 1000, }: IProps) { const w = useAddResourceWizard({ launchSource, onClose }); + const { getOrganizedBy } = useOrganizedBy(); return ( <> @@ -41,7 +43,7 @@ export function AddResourceWizard({ w.step === WizardStep.SelectSections ? ( {w.isAddingAudioResource - ? w.t.selectPassagesSub.replace('{0}', w.getOrganizedBy(false)) + ? w.t.selectPassagesSub.replace('{0}', getOrganizedBy(false)) : w.t.editingFile.replace( '{0}', safeFileBasename(w.projMedia?.attributes?.originalFile) @@ -76,11 +78,11 @@ export function AddResourceWizard({ finish={w.afterUpload} beforeUpload={w.handleBeforeUpload} cancelled={w.cancelled} - artifactState={w.artifactState.current} + artifactId={w.artifactId} uploadType={w.uploadType} ready={() => w.resourceReady} - performedBy={w.performedBy} - onSpeakerChange={w.setPerformedBy} + speaker={w.speaker} + onSpeaker={w.setSpeaker} inValue={w.markdownValue} eafUrl={w.eafUrl} defaultFilename={w.filename} @@ -96,7 +98,7 @@ export function AddResourceWizard({ } /> @@ -124,7 +124,7 @@ export function AddResourceWizard({ }} > (({ theme }) => ({ @@ -492,8 +491,6 @@ export function PassageDetailArtifacts() { launchWizard({ kind: 'faithbridge', query, audioUrl, transcript }); }; - const { sectDesc, passDesc } = useResourceScopeLabels(); - const listFilter = (r: IRow) => r?.isResource && (allResources || r.passageId === '' || r.passageId === passage.id); @@ -785,8 +782,6 @@ export function PassageDetailArtifacts() { onPassResChange={handlePassRes} allowGeneralResourceOption={false} onTextChange={handleTextChange} - sectDesc={sectDesc} - passDesc={passDesc} /> {confirm && diff --git a/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx b/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx index af2b89212..42d7b63bd 100644 --- a/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx +++ b/web/src/components/PassageDetail/Internalization/PassageDetailsArtifactsMobile.tsx @@ -80,7 +80,6 @@ import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined'; import IconMenu from '../../../control/IconMenu'; import AddResourceWizard from './AddResourceWizard'; import { WizardLaunch } from './useAddResourceWizard'; -import { useResourceScopeLabels } from './useResourceScopeLabels'; import { useResourceArtifactTypes } from './useResourceArtifactTypes'; export function PassageDetailArtifactsMobile() { @@ -492,8 +491,6 @@ export function PassageDetailArtifactsMobile() { launchWizard({ kind: 'faithbridge', query, audioUrl, transcript }); }; - const { sectDesc, passDesc } = useResourceScopeLabels(); - const listFilter = (r: IRow) => r?.isResource && (allResources || r.passageId === '' || r.passageId === passage.id); @@ -787,8 +784,6 @@ export function PassageDetailArtifactsMobile() { allowGeneralResourceOption={false} onTextChange={handleTextChange} wrapPreviewOverflow - sectDesc={sectDesc} - passDesc={passDesc} /> {confirm && diff --git a/web/src/components/PassageDetail/Internalization/ResourceData.tsx b/web/src/components/PassageDetail/Internalization/ResourceData.tsx index 7e6402e09..faa33d82a 100644 --- a/web/src/components/PassageDetail/Internalization/ResourceData.tsx +++ b/web/src/components/PassageDetail/Internalization/ResourceData.tsx @@ -12,7 +12,13 @@ import { import React, { useEffect, useState, type RefObject } from 'react'; import { shallowEqual, useSelector } from 'react-redux'; import { ArtifactCategoryType, useOrganizedBy } from '../../../crud'; -import { IPassageDetailArtifactsStrings, MediaFileD } from '../../../model'; +import { + IPassageDetailArtifactsStrings, + MediaFileD, + SheetLevel, +} from '../../../model'; +import { PassageTypeEnum } from '../../../model/passageTypeEnum'; +import { passageTypeFromRef } from '../../../control/passageTypeFromRef'; import { passageDetailArtifactsSelector } from '../../../selector'; import SelectArtifactCategory from '../../Sheet/SelectArtifactCategory'; import { ResourceTypeEnum } from './ResourceTypeEnum'; @@ -24,6 +30,7 @@ import { mediaContentType } from '../../../utils/contentType'; import { MarkDownView } from '../../../control/MarkDownView'; import { ArtCatScr } from '../../../components/Sheet/ArtCatScr'; import { descriptionRequiredForResource } from './resourceArtifactName'; +import usePassageDetailContext from '../../../context/usePassageDetailContext'; type ResourceKindRadio = 'section' | 'passage' | 'general'; @@ -60,8 +67,6 @@ interface IProps { // Forwarded to SelectArtifactCategory so the parent form can create a new // category at submission (rather than on blur). catCommitRef?: RefObject<(() => Promise) | null> | undefined; - sectDesc?: string | undefined; - passDesc?: string | undefined; wrapPreviewOverflow?: boolean; } export function ResourceData(props: IProps) { @@ -75,8 +80,6 @@ export function ResourceData(props: IProps) { catRequired, catAllowNew, allowGeneralResourceOption, - sectDesc, - passDesc, media, uploadType, onTextChange, @@ -85,11 +88,25 @@ export function ResourceData(props: IProps) { } = props; const [description, setDescription] = useState(initDescription); const { getOrganizedBy } = useOrganizedBy(); + const { section, passage } = usePassageDetailContext(); const [text, setText] = useState(media?.attributes?.originalFile ?? ''); const t: IPassageDetailArtifactsStrings = useSelector( passageDetailArtifactsSelector, shallowEqual ); + // Scope radio labels: Book/Movement sections and Note passages get their own wording. + const sectionLevel = section?.attributes?.level; + const sectionScopeLabel = + sectionLevel === SheetLevel.Book + ? t.bookResource + : sectionLevel === SheetLevel.Movement + ? t.movementResource + : getOrganizedBy(true); + const passageScopeLabel = + passageTypeFromRef(passage?.attributes?.reference ?? undefined) === + PassageTypeEnum.NOTE + ? t.noteResource + : t.passageResource; const descriptionRequired = descriptionRequiredForResource( mediaContentType(media), uploadType, @@ -161,18 +178,12 @@ export function ResourceData(props: IProps) { } - label={t.currentResource.replace( - '{0}', - sectDesc ?? getOrganizedBy(true) - )} + label={t.currentResource.replace('{0}', sectionScopeLabel)} /> } - label={t.currentResource.replace( - '{0}', - passDesc ?? t.passageResource - )} + label={t.currentResource.replace('{0}', passageScopeLabel)} /> {allowGeneralResourceOption && !NON_FILE_UPLOAD_TYPES.includes( diff --git a/web/src/components/PassageDetail/Internalization/ResourceUploadStep.test.tsx b/web/src/components/PassageDetail/Internalization/ResourceUploadStep.test.tsx new file mode 100644 index 000000000..eab29eae7 --- /dev/null +++ b/web/src/components/PassageDetail/Internalization/ResourceUploadStep.test.tsx @@ -0,0 +1,214 @@ +import { act, cleanup, render } from '@testing-library/react'; +import { UploadType } from '../../UploadType'; + +type PanelProps = { + artifactId?: string | null; + finish: (mediaRemoteIds?: string[]) => Promise; + uploadMethod?: unknown; +}; +type ContentProps = { + inValue?: string; + uploadMethod?: unknown; +}; + +let capturedPanel: PanelProps | undefined; +let capturedContent: ContentProps | undefined; + +jest.mock('../../PassageRecordPanel', () => ({ + __esModule: true, + default: (props: PanelProps) => { + capturedPanel = props; + return
; + }, +})); + +jest.mock('../../MediaUploadContent', () => ({ + __esModule: true, + default: (props: ContentProps) => { + capturedContent = props; + return
; + }, +})); + +// The upload pipeline is covered by useMediaUpload's own tests; here we only +// check the config ResourceUploadStep hands it and where its result goes. +const mockUploadMethod = jest.fn(); +const mockUseMediaUpload = jest.fn((_opts: unknown) => mockUploadMethod); +jest.mock('../../../crud', () => ({ + useMediaUpload: (opts: unknown) => mockUseMediaUpload(opts), + VernacularTag: 'vern-tag', +})); + +jest.mock('../../../utils', () => ({ + restoreScroll: jest.fn(), +})); + +const mockSplitFaithbridgeValue = jest.fn((value: string) => { + const [url, transcription] = value.split('||'); + return { url, transcription }; +}); +jest.mock('../../../utils/contentType', () => ({ + splitFaithbridgeValue: (value: string) => mockSplitFaithbridgeValue(value), +})); + +import ResourceUploadStep from './ResourceUploadStep'; + +type StepProps = React.ComponentProps; + +function renderStep(overrides: Partial = {}) { + const props: StepProps = { + active: true, + isAudioMode: true, + uploadType: UploadType.Media, + cancelled: { current: false }, + finish: jest.fn(), + defaultFilename: 'resource', + ...overrides, + }; + render(); + return props; +} + +function hookOptions() { + return mockUseMediaUpload.mock.calls.at(-1)?.[0] as { + fields: Record; + [key: string]: unknown; + }; +} + +describe('ResourceUploadStep', () => { + beforeEach(() => { + capturedPanel = undefined; + capturedContent = undefined; + jest.clearAllMocks(); + }); + afterEach(cleanup); + + describe('record finish', () => { + it('clears cancelled and forwards ids when the recording uploaded', async () => { + const cancelled = { current: true }; + const { finish } = renderStep({ cancelled }); + + await act(async () => { + await capturedPanel!.finish(['media-1']); + }); + + expect(cancelled.current).toBe(false); + expect(finish).toHaveBeenCalledWith(['media-1']); + }); + + it.each([ + ['no ids', undefined], + ['empty ids', [] as string[]], + ])('marks cancelled and still calls finish with %s', async (_, ids) => { + const cancelled = { current: false }; + const { finish } = renderStep({ cancelled }); + + await act(async () => { + await capturedPanel!.finish(ids); + }); + + expect(cancelled.current).toBe(true); + expect(finish).toHaveBeenCalledWith(ids); + }); + + it('resolves without a finish prop', async () => { + const cancelled = { current: false }; + renderStep({ cancelled, finish: undefined }); + + await act(async () => { + await expect( + capturedPanel!.finish(['media-1']) + ).resolves.toBeUndefined(); + }); + expect(cancelled.current).toBe(false); + }); + }); + + describe('mode', () => { + it('renders the record panel in audio mode, wired to the upload hook', () => { + renderStep({ isAudioMode: true }); + + expect(capturedPanel?.uploadMethod).toBe(mockUploadMethod); + expect(capturedContent).toBeUndefined(); + }); + + it('renders the upload content otherwise, wired to the upload hook', () => { + renderStep({ isAudioMode: false }); + + expect(capturedContent?.uploadMethod).toBe(mockUploadMethod); + expect(capturedPanel).toBeUndefined(); + }); + }); + + describe('Faithbridge link value', () => { + it('shows only the url and sends the transcription to the upload', () => { + renderStep({ + isAudioMode: false, + uploadType: UploadType.FaithbridgeLink, + inValue: 'https://fb.example/x||hello world', + }); + + expect(capturedContent?.inValue).toBe('https://fb.example/x'); + expect(hookOptions().fields.transcription).toBe('hello world'); + }); + + it('passes inValue through untouched for other upload types', () => { + renderStep({ + isAudioMode: false, + uploadType: UploadType.Link, + inValue: 'https://example.com/a||b', + }); + + expect(mockSplitFaithbridgeValue).not.toHaveBeenCalled(); + expect(capturedContent?.inValue).toBe('https://example.com/a||b'); + expect(hookOptions().fields.transcription).toBeUndefined(); + }); + }); + + describe('artifactId', () => { + it.each([ + ['undefined', undefined], + ['null', null], + ])('defaults to VernacularTag when %s', (_, artifactId) => { + renderStep({ artifactId }); + + expect(hookOptions().fields.artifactId).toBe('vern-tag'); + expect(capturedPanel?.artifactId).toBe('vern-tag'); + }); + + it('uses the given artifactId', () => { + renderStep({ artifactId: 'art-1' }); + + expect(hookOptions().fields.artifactId).toBe('art-1'); + expect(capturedPanel?.artifactId).toBe('art-1'); + }); + }); + + it('configures the upload hook from its props', () => { + const beforeUpload = jest.fn(async () => {}); + const pendingRestore = {} as StepProps['pendingRestore']; + const props = renderStep({ + speaker: 'Ann', + eafUrl: 'eaf-url', + uploadType: UploadType.Media, + beforeUpload, + pendingRestore, + }); + + expect(hookOptions()).toEqual( + expect.objectContaining({ + fields: expect.objectContaining({ + performedBy: 'Ann', + eafUrl: 'eaf-url', + }), + uploadType: UploadType.Media, + finish: props.finish, + cancelled: props.cancelled, + beforeUpload, + pendingRestore, + versionFilenames: true, + }) + ); + }); +}); diff --git a/web/src/components/PassageDetail/Internalization/ResourceUploadStep.tsx b/web/src/components/PassageDetail/Internalization/ResourceUploadStep.tsx new file mode 100644 index 000000000..b8ab91516 --- /dev/null +++ b/web/src/components/PassageDetail/Internalization/ResourceUploadStep.tsx @@ -0,0 +1,145 @@ +import { RefObject } from 'react'; +import { Box } from '@mui/material'; +import MediaUploadContent from '../../MediaUploadContent'; +import PassageRecordPanel, { IDeferredUpload } from '../../PassageRecordPanel'; +import { useMediaUpload, VernacularTag } from '../../../crud'; +import { splitFaithbridgeValue } from '../../../utils/contentType'; +import { UploadType } from '../../UploadType'; +import type { PendingRestoreInput } from '../../../store/upload/pendingMediaUploads'; + +interface IProps { + active: boolean; + isAudioMode: boolean; //shows a Record option as well as upload + uploadType: UploadType; + artifactId?: string | null | undefined; + speaker?: string | undefined; + onSpeaker?: ((speaker: string) => void) | undefined; + eafUrl?: string | undefined; + inValue?: string | undefined; + defaultFilename: string; + ready?: (() => boolean) | undefined; + validationMessage?: string | undefined; + metaData?: React.JSX.Element | undefined; + finish?: ((mediaRemoteIds?: string[]) => void | Promise) | undefined; + beforeUpload?: (() => Promise) | undefined; + cancelled: RefObject; + pendingRestore?: PendingRestoreInput | undefined; + onFiles?: ((files: File[]) => void) | undefined; + deferred?: IDeferredUpload | undefined; // for the general-resource flow which defers uploading the media until the next step + onStartRecording?: (() => void) | undefined; +} + +/** + * The add-resource wizard's step-1 body: the Upload/Record UI, embedded (no + * dialog of its own) so the wizard shows/hides it as a step and it stays mounted + * across the flow — a recorded take survives Next→Back. Drives the shared + * useMediaUpload pipeline directly (the standalone dialog path is Uploader). + */ +export function ResourceUploadStep(props: IProps) { + const { + active, + isAudioMode, + uploadType, + artifactId: artifactIdProp, + speaker, + onSpeaker, + eafUrl, + inValue, + defaultFilename, + ready, + validationMessage, + metaData, + finish, + beforeUpload, + cancelled, + pendingRestore, + onFiles, + deferred, + onStartRecording, + } = props; + const artifactId = artifactIdProp ?? VernacularTag; + + // A Faithbridge link arrives as `url||transcript` in inValue; split it here + const faithbridge = + uploadType === UploadType.FaithbridgeLink && inValue + ? splitFaithbridgeValue(inValue) + : undefined; + const effectiveInValue = faithbridge ? faithbridge.url : inValue; + + const uploadMedia = useMediaUpload({ + fields: { + artifactId, + performedBy: speaker, + eafUrl, + transcription: faithbridge?.transcription, + }, + uploadType, + pendingRestore, + finish, + cancelled, + beforeUpload, + versionFilenames: true, + }); + + const recordFinish = async (mediaRemoteIds?: string[]) => { + cancelled.current = !mediaRemoteIds?.length; + await finish?.(mediaRemoteIds); + }; + + return ( + .MuiDialogActions-root': { p: 0, pb: 1 }, + '& > .MuiDialogActions-root > .MuiButton-root': { m: 0 }, + }} + > + {isAudioMode ? ( + + ) : ( + {}} + uploadType={uploadType} + multiple + uploadMethod={uploadMedia} + metaData={metaData} + ready={ready} + speaker={speaker} + onFiles={onFiles} + inValue={effectiveInValue} + validationMessage={validationMessage} + /> + )} + + ); +} + +export default ResourceUploadStep; diff --git a/web/src/components/PassageDetail/Internalization/SelectSections.tsx b/web/src/components/PassageDetail/Internalization/SelectSections.tsx index b26d307ed..f1b9f2747 100644 --- a/web/src/components/PassageDetail/Internalization/SelectSections.tsx +++ b/web/src/components/PassageDetail/Internalization/SelectSections.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useMemo } from 'react'; +import { useState, useMemo } from 'react'; import { useGlobal } from '../../../context/useGlobal'; import { useSelector, shallowEqual } from 'react-redux'; import { @@ -17,7 +17,6 @@ import { Box, Checkbox, CircularProgress, - debounce, Paper, PaperProps, styled, @@ -38,7 +37,7 @@ import { Button } from '../../../control/Button'; const StyledPaper = styled(Paper)(({ theme }) => ({ backgroundColor: theme.palette.background.default, - marginBottom: theme.spacing(1), + marginBottom: theme.spacing(2), '& .MuiPaper-rounded': { borderRadius: '8px', }, @@ -49,79 +48,33 @@ type IRow = SelectSectionRow; interface IProps { initialItems?: RecordIdentity[]; - /** Visual resources are written immediately, so the button says so. */ - visual?: boolean; - /** - * True when clicking Next now performs the (deferred) media upload — the - * new-add general-resource flow. The button then reads "Upload" instead of - * "Next". Editing an existing resource leaves this false (Next just advances - * to the configure step; the media already exists). - */ - uploadsOnNext?: boolean; - /** - * True while the deferred upload triggered by this dialog's Upload button is - * in flight. The dialog stays open (so selections survive) with the button - * disabled and a spinner; on success the caller advances to the configure - * step, on failure it re-enables so the user can retry without re-selecting. - */ - uploading?: boolean; - /** - * `candidates` is every identity offered by the dialog; the caller needs it to - * limit cleanup of unselected assignments to what the user could actually see. - */ + uploadsOnNext?: boolean; // need to upload after selecting sections in the "deferred" flow of adding a new resource + uploading?: boolean; // deferred upload is in flight, keep dialog open with button disabled and spinner, retry may be needed onSelect?: (items: RecordIdentity[], candidates: RecordIdentity[]) => void; - /** - * When set, a "Back" button (the reverse of Next/Upload) is shown — for now - * only in developer mode. The add flow wires this to reopen the upload - * dialog; leaving it undefined hides the button for entry points that have no - * previous step here. - */ - onBack?: () => void; + onBack?: () => void; // show back button if present } export function SelectSections(props: IProps) { - const { initialItems, visual, uploadsOnNext, uploading, onSelect, onBack } = - props; - const initialSelectionKey = (initialItems ?? []) - .map((item) => `${item.type}:${item.id}`) - .join('|'); + const { initialItems, uploadsOnNext, uploading, onSelect, onBack } = props; const passages = useOrbitData('passage'); const sections = useOrbitData('section'); const [memory] = useGlobal('memory'); - const [plan] = useGlobal('plan'); //will be constant here - const [isDeveloper] = useGlobal('developer'); - const [data, setData] = useState(Array()); - const [heightStyle, setHeightStyle] = useState({ - maxHeight: `${window.innerHeight - 200}px`, - }); + const [plan] = useGlobal('plan'); // will be constant here const { getOrganizedBy } = useOrganizedBy(); - // User cannot change the language while dialog is open, so for now it should be okay if this component does not - // respond to changes in the language setting until the dialog is reopened. + // There is no way for the user to change the language while dialog is open const ta: IPassageDetailArtifactsStrings = useSelector( passageDetailArtifactsSelector, shallowEqual ); const ts: ISharedStrings = useSelector(sharedSelector, shallowEqual); const allBookData = useSelector((state: IState) => state.books.bookData); - const [selected, setSelected] = useState>(new Set()); - const setDimensions = () => { - setHeightStyle({ - maxHeight: `${window.innerHeight - 200}px`, - }); - }; + // Seeded once at mount; later changes to initialItems must not reset the + // user's ticks (the wizard keeps this mounted across steps). + const [selected, setSelected] = useState>( + () => new Set((initialItems ?? []).map((item) => `${item.type}:${item.id}`)) + ); const planType = usePlanType(); - useEffect(() => { - setDimensions(); - const handleResize = debounce(() => { - setDimensions(); - }, 100); - window.addEventListener('resize', handleResize); - return () => { - window.removeEventListener('resize', handleResize); - }; - }, []); - const planRec = useMemo( () => findRecord(memory, 'plan', plan) as Plan | undefined, // eslint-disable-next-line react-hooks/exhaustive-deps @@ -133,8 +86,8 @@ export function SelectSections(props: IProps) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [plan]); - useEffect(() => { - setData( + const data = useMemo( + () => buildSelectSectionRows({ passages, sections, @@ -142,16 +95,10 @@ export function SelectSections(props: IProps) { planId: planRec?.id, isFlat: Boolean(isFlat), organizedBy: getOrganizedBy(true), - }) - ); + }), // eslint-disable-next-line react-hooks/exhaustive-deps - }, [plan, passages, sections, allBookData, isFlat]); - - useEffect(() => { - setSelected( - new Set(initialSelectionKey ? initialSelectionKey.split('|') : []) - ); - }, [initialSelectionKey]); + [plan, passages, sections, allBookData, isFlat] + ); /** `passage:` keys of each section's passage rows, by section id. */ const passageKeysBySection = useMemo(() => { @@ -167,9 +114,8 @@ export function SelectSections(props: IProps) { /** * A section's checkbox has its own selection state, independent of its - * passages. Checking a section is the one cross-influence: as a convenience it - * also checks every passage in the section. Unchecking a section only clears - * the section itself and leaves its passages as they were. + * passages. Checking a section also checks every passage in the section. + * Unchecking a section only clears the section itself and leaves its passages as they were. */ const toggleSection = (sectionId: string) => { setSelected((current) => { @@ -179,7 +125,6 @@ export function SelectSections(props: IProps) { next.delete(sectionKey); } else { next.add(sectionKey); - // Checking a section checks all of its passages (default behavior). (passageKeysBySection.get(sectionId) ?? []).forEach((key) => next.add(key) ); @@ -206,7 +151,6 @@ export function SelectSections(props: IProps) { const allSelected = data.length > 0 && rowKeys().every((key) => selected.has(key)); - /** Tick every row's box, or clear them all when everything is already ticked. */ const toggleAll = () => { setSelected((current) => rowKeys().every((key) => current.has(key)) @@ -221,8 +165,7 @@ export function SelectSections(props: IProps) { type: row.kind, id: row.recId, })) as RecordIdentity[]; - // Section and passage checkboxes are independent, so create an assignment - // for each row whose own box is ticked: a checked section yields a section + // Section and passage checkboxes are independent, a checked section yields a section // assignment, a checked passage a passage assignment. onSelect?.( identities( @@ -235,7 +178,14 @@ export function SelectSections(props: IProps) { return (