The swiss army knife of lossless video/audio editing
Enable 8 more lint rules: autofixes plus a few small manual fixes
Claude95be152968d2
diff --git a/.oxlintrc.json b/.oxlintrc.jsonindex 3993594b..f71c157f 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -32,26 +32,20 @@"react/exhaustive-effect-dependencies": "off", // (81)"typescript/promise-function-async": "off", // (50)"react/only-export-components": "off", // (48)- "no-implicit-coercion": "off", // (25)"unicorn/consistent-function-scoping": "off", // (23)"promise/prefer-await-to-then": "off", // (13)"jsx-a11y/prefer-tag-over-role": "off", // (60)"react/hooks": "off", // (32)"react/memo-dependencies": "off", // (20)"unicorn/prefer-number-coercion": "off", // (95)- "unicorn-js/prefer-minimal-ternary": "off", // (19)"unicorn-js/prefer-simple-condition-first": "off", // (17)- "unicorn-js/prefer-combined-guards": "off", // (19)"unicorn-js/prefer-early-return": "off", // (26)- "unicorn-js/no-negated-array-predicate": "off", // (7)"unicorn/max-nested-calls": "off", // (22)"unicorn-js/no-declarations-before-early-exit": "off", // (15)"unicorn-js/no-top-level-assignment-in-function": "off", // (25)- "unicorn-js/prefer-continue": "off", // (6)"unicorn-js/no-unnecessary-array-flat-map": "off", // (20)"unicorn-js/prefer-await": "off", // (14)"unicorn-js/no-computed-property-existence-check": "off", // (15)- "unicorn-js/no-useless-concat": "off", // (11)"typescript/prefer-nullish-coalescing": "off", // (33)"typescript/strict-boolean-expressions": "off", // (275)"typescript/no-unsafe-assignment": "off", // (69)@@ -65,11 +59,9 @@"typescript/no-duplicate-type-constituents": "off", // (11)"typescript/no-floating-promises": "off", // (116)"typescript/no-unnecessary-type-conversion": "off", // (9)- "typescript/prefer-optional-chain": "off", // (17)"typescript/no-redundant-type-constituents": "off", // (8)"typescript/require-await": "off", // (19)"typescript/no-misused-promises": "off", // (121)- "typescript/no-unnecessary-boolean-literal-compare": "off", // (7)"@eslint-react/use-state": "off", // (87)"@eslint-react/no-forward-ref": "off", // (7)"vitest/prefer-snapshot-hint": "off", // (11)diff --git a/script/afterPack.ts b/script/afterPack.tsindex bcebe03a..b5c46e8e 100644--- a/script/afterPack.ts+++ b/script/afterPack.ts@@ -15,10 +15,9 @@ export default async function afterPack({ appOutDir, arch, electronPlatformName,// If the binary can run on this machine, check that it does (e.g. not a broken download or missing libraries).// Mac App Store builds have electronPlatformName 'mas', so they're not run (the dmg builds use the same binaries)- if (electronPlatformName === process.platform && Arch[arch] === process.arch) {- // Like the app does on Linux (see src/main/ffmpeg.ts)- const { stdout } = await execa(path, ['-hide_banner', '-version'], { env: { LD_LIBRARY_PATH: resourcesDir } });- console.log(stdout.split('\n', 1)[0]);- }+ if (electronPlatformName !== process.platform || Arch[arch] !== process.arch) continue;+ // Like the app does on Linux (see src/main/ffmpeg.ts)+ const { stdout } = await execa(path, ['-hide_banner', '-version'], { env: { LD_LIBRARY_PATH: resourcesDir } });+ console.log(stdout.split('\n', 1)[0]);}}diff --git a/script/featureMedia.ts b/script/featureMedia.tsindex e8da8935..5376c7b3 100644--- a/script/featureMedia.ts+++ b/script/featureMedia.ts@@ -85,15 +85,14 @@ assert.ok(music == null || await exists(music), `--music must be one of ${Objectconst clipsUrl = process.env['FEATURE_MEDIA_CLIPS_URL'] ?? 'https://static.mifi.no/losslesscut';for (const clip of scenario.clips) {const path = join(clips, clip);- if (!await exists(path)) {- const sourceArgs = clipSources[clip];- if (sourceArgs != null) {- console.log('Making', clip, 'from its sources');- await ffmpegDownload(sourceArgs, path);- } else {- console.log('Downloading', clip);- await download(`${clipsUrl}/${clip}`, path);- }+ if (await exists(path)) continue;+ const sourceArgs = clipSources[clip];+ if (sourceArgs != null) {+ console.log('Making', clip, 'from its sources');+ await ffmpegDownload(sourceArgs, path);+ } else {+ console.log('Downloading', clip);+ await download(`${clipsUrl}/${clip}`, path);}}diff --git a/script/generateVersions.ts b/script/generateVersions.tsindex 562f4e99..cce5e8ed 100644--- a/script/generateVersions.ts+++ b/script/generateVersions.ts@@ -7,11 +7,13 @@ const versions: { version: string, highlightsMd?: string | undefined }[] = [];// eslint-disable-next-line unicorn-js/no-unreadable-for-of-expression -- TODO fix (new rule in @mifi/lint-config)for (const file of await readdir(versionsDir, { withFileTypes: true })) {- if (file.isFile() && file.name.endsWith('.md')) {- const version = file.name.replace(/.md$/, '');- const content = await readFile(new URL(file.name, versionsDir), { encoding: 'utf8' });- versions.push({ version, highlightsMd: content.trim() !== '' ? content : undefined });+ if (!(file.isFile() && file.name.endsWith('.md'))) {+ continue;}++ const version = file.name.replace(/.md$/, '');+ const content = await readFile(new URL(file.name, versionsDir), { encoding: 'utf8' });+ versions.push({ version, highlightsMd: content.trim() !== '' ? content : undefined });}await writeFile(new URL('../src/renderer/src/versions.json', import.meta.url), JSON.stringify(versions, null, 2));diff --git a/src/common/util.ts b/src/common/util.tsindex 81b5ce8f..745bc588 100644--- a/src/common/util.ts+++ b/src/common/util.ts@@ -59,8 +59,7 @@ export function parseRatio(str: string, char = '/') {if (split.length !== 2) return undefined;const num = parseInt(split[0]!, 10);const den = parseInt(split[1]!, 10);- if (Number.isNaN(num) || Number.isNaN(den)) return undefined;- if (den <= 0) return undefined;+ if (Number.isNaN(num) || Number.isNaN(den) || (den <= 0)) return undefined;return num / den;}diff --git a/src/main/ffmpeg.ts b/src/main/ffmpeg.tsindex 0f9320a7..763789fe 100644--- a/src/main/ffmpeg.ts+++ b/src/main/ffmpeg.ts@@ -96,8 +96,7 @@ function handleProgress(onProgress: (a: number) => void,customMatcher?: (a: string) => void,) {- if (!onProgress) return;- if (process.stderr == null) return;+ if (!onProgress || (process.stderr == null)) return;onProgress(0);const rl = readline.createInterface({ input: process.stderr });diff --git a/src/main/httpServerUtil.ts b/src/main/httpServerUtil.tsindex 12ca23fd..d1b81a91 100644--- a/src/main/httpServerUtil.ts+++ b/src/main/httpServerUtil.ts@@ -9,8 +9,7 @@ export function isRequestAllowed({ host, origin, port }: {origin: string | undefined,port: number,}) {- if (origin != null) return false;- if (host == null) return false;+ if ((origin != null) || (host == null)) return false;const allowedHosts = ['127.0.0.1', 'localhost', '[::1]'];const hostLower = host.toLowerCase();// a browser omits the port from `Host` when it's the default port for the schemediff --git a/src/main/networking.ts b/src/main/networking.tsindex 6636527d..9c8a7d0f 100644--- a/src/main/networking.ts+++ b/src/main/networking.ts@@ -1,6 +1,6 @@let disableNetworking: boolean;-export const hasDisabledNetworking = () => !!disableNetworking;+export const hasDisabledNetworking = () => Boolean(disableNetworking);export function throwIfDisabledNetworking() {if (hasDisabledNetworking()) {diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex c2ec13f3..2037039d 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -236,7 +236,7 @@ function App() {ipcRenderer.send('setLanguage', language);}, [language]);- const isFileOpened = !!filePath;+ const isFileOpened = Boolean(filePath);const [hoveringTime, setHoveringTime] = useState<number>();@@ -281,7 +281,7 @@ function App() {const toggleExportConfirmEnabled = useCallback(() => setExportConfirmEnabled((v) => {const newVal = !v;- showNotification({ text: newVal ? i18n.t('Export options will be shown before exporting.') : i18n.t('Export options will not be shown before exporting.') });+ showNotification({ text: i18n.t(newVal ? 'Export options will be shown before exporting.' : 'Export options will not be shown before exporting.') });return newVal;}), [setExportConfirmEnabled, showNotification]);@@ -450,7 +450,7 @@ function App() {}), [showNotification, setKeyframeCut]);const toggleSimpleMode = useCallback(() => setSimpleMode((v) => {- showNotification({ text: v ? i18n.t('Advanced view has been enabled. You will now also see non-essential buttons and functions') : i18n.t('Advanced view disabled. You will now see only the most essential buttons and functions') });+ showNotification({ text: i18n.t(v ? 'Advanced view has been enabled. You will now also see non-essential buttons and functions' : 'Advanced view disabled. You will now see only the most essential buttons and functions') });return !v;}), [setSimpleMode, showNotification]);@@ -493,7 +493,7 @@ function App() {const segColorsContext = useMemo<SegColorsContextType>(() => ({getSegColor: (seg: SegmentColorIndex | undefined) => {const color = getSegColor(seg);- return preferStrongColors ? color.desaturate(0.2) : color.desaturate(0.6);+ return color.desaturate(preferStrongColors ? 0.2 : 0.6);},nextSegColorIndex: isInitialSegment(cutSegments) ? segColorCounter : segColorCounter + 1,}), [cutSegments, preferStrongColors, segColorCounter]);@@ -544,8 +544,8 @@ function App() {// total number of streams for ALL filesconst numStreamsTotal = Object.values(allFilesMeta).flatMap(({ streams }) => streams).length;- const hasAudio = !!mainAudioStream;- const hasVideo = !!mainVideoStream;+ const hasAudio = Boolean(mainAudioStream);+ const hasVideo = Boolean(mainVideoStream);const forceBigWaveform = !hasVideo && hasAudio;@@ -630,7 +630,7 @@ function App() {const shouldShowPlaybackStreamSelector = videoStreams.length > 0 || audioStreams.length > 0 || (subtitleStreams.length > 0 && !compatPlayerEnabled);- const usingPreviewFile = !!previewFilePath;+ const usingPreviewFile = Boolean(previewFilePath);const effectiveFilePath = previewFilePath || filePath;useEffect(() => {if (!effectiveFilePath) return undefined;@@ -782,7 +782,7 @@ function App() {const firstSegmentAtCursorIndex = segmentsAtCursorIndexes[0];const playingSegment = firstSegmentAtCursorIndex != null ? cutSegments[firstSegmentAtCursorIndex] : undefined;- if (playbackModeRef.current != null && playingRef.current && playingSegment && playingSegment.end != null) {+ if (playbackModeRef.current != null && playingRef.current && playingSegment?.end != null) {const nextAction = getPlaybackAction({ playbackMode: playbackModeRef.current, currentTime, playingSegment: { start: playingSegment.start, end: playingSegment.end } });const exit = () => {@@ -1620,8 +1620,7 @@ function App() {// todo merge with userOpenFiles?const batchOpenSingleFile = useCallback(async (path: string) => {- if (workingRef.current) return;- if (filePath === path) return;+ if (workingRef.current || (filePath === path)) return;setWorking({ text: i18n.t('Loading file') });try {await withErrorHandling(async () => {@@ -1693,11 +1692,7 @@ function App() {}, []);const extractAllStreams = useCallback(async () => {- if (!filePath) return;-- if (!(await confirmDialog({ focusConfirm: true, description: t('Please confirm that you want to extract all tracks as separate files'), confirmButtonText: t('Extract all tracks') }))) return;-- if (workingRef.current) return;+ if (!filePath || !(await confirmDialog({ focusConfirm: true, description: t('Please confirm that you want to extract all tracks as separate files'), confirmButtonText: t('Extract all tracks') })) || workingRef.current) return;try {setWorking({ text: i18n.t('Extracting all streams') });setStreamsSelectorShown(false);@@ -1822,7 +1817,7 @@ function App() {setBatchFiles((existingFiles) => {const mapPathsToFiles = (paths: string[]) => paths.map((path) => ({ path, name: basename(path) }));if (append) {- const newUniquePaths = newPaths.filter((newPath) => !existingFiles.some(({ path: existingPath }) => newPath === existingPath));+ const newUniquePaths = newPaths.filter((newPath) => existingFiles.every(({ path: existingPath }) => newPath !== existingPath));const [firstNewUniquePath] = newUniquePaths;if (firstNewUniquePath == null) return existingFiles;setSelectedBatchFiles([firstNewUniquePath]);@@ -1899,7 +1894,7 @@ function App() {const inputOptions: { open?: string, project?: string, tracks?: string, subtitles?: string, addToBatch?: string, mergeWithCurrentFile?: string } = {};if (newFilePaths.length === 1) {- inputOptions.open = isFileOpened ? i18n.t('Open the file instead of the current one') : i18n.t('Open the file');+ inputOptions.open = i18n.t(isFileOpened ? 'Open the file instead of the current one' : 'Open the file');}if (isFileOpened && newFilePaths.length === 1) {@@ -2245,9 +2240,7 @@ function App() {}, [askBeforeClose, isFileOpened]);const extractSingleStream = useCallback(async (index: number) => {- if (!filePath) return;-- if (workingRef.current) return;+ if (!filePath || workingRef.current) return;try {setWorking({ text: i18n.t('Extracting track') });// setStreamsSelectorShown(false);diff --git a/src/renderer/src/BottomBar.tsx b/src/renderer/src/BottomBar.tsxindex b5e7aae8..d2205fce 100644--- a/src/renderer/src/BottomBar.tsx+++ b/src/renderer/src/BottomBar.tsx@@ -55,9 +55,7 @@ const InvertCutModeButton = memo(({ invertCutSegments, setInvertCutSegments }: {setInvertCutSegments((v) => {const newVal = !v;getSwal().toast.fire({- title: newVal- ? t('When you export, selected segments on the timeline will be REMOVED - the surrounding areas will be KEPT')- : t('When you export, selected segments on the timeline will be KEPT - the surrounding areas will be REMOVED.'),+ title: t(newVal ? 'When you export, selected segments on the timeline will be REMOVED - the surrounding areas will be KEPT' : 'When you export, selected segments on the timeline will be KEPT - the surrounding areas will be REMOVED.'),});return newVal;});@@ -71,7 +69,7 @@ const InvertCutModeButton = memo(({ invertCutSegments, setInvertCutSegments }: {><FaYinYangrole="button"- title={invertCutSegments ? t('Discard selected segments') : t('Keep selected segments')}+ title={t(invertCutSegments ? 'Discard selected segments' : 'Keep selected segments')}style={{ display: 'block', fontSize: '1.5em', color: invertCutSegments ? dangerColor : undefined }}onClick={onYinYangClick}/>@@ -267,7 +265,7 @@ const CutTimeInput = memo(({ disabled, darkMode, cutTime, setCutTime, startTimeOdisabled={disabled}style={style}type="text"- title={isStart ? t('Manually input current segment\'s start time') : t('Manually input current segment\'s end time')}+ title={t(isStart ? 'Manually input current segment\'s start time' : 'Manually input current segment\'s end time')}onChange={(e) => handleCutTimeInput(e.target.value)}onPaste={handleCutTimePaste}onBlur={handleInputBlur}@@ -391,7 +389,7 @@ function BottomBar({}, [playStyle, selectedSegments]);const keyframeStyle = useMemo(() => ({- color: currentFrame != null && currentFrame.keyframe ? primaryTextColor : undefined,+ color: currentFrame?.keyframe ? primaryTextColor : undefined,}), [currentFrame]);const { invertCutSegments, setInvertCutSegments, simpleMode, toggleSimpleMode, exportConfirmEnabled } = useUserSettings();@@ -428,7 +426,7 @@ function BottomBar({<divstyle={segButtonStyle}role="button"- title={`${direction > 0 ? t('Select next segment') : t('Select previous segment')} (${newIndex + 1})`}+ title={`${t(direction > 0 ? 'Select next segment' : 'Select previous segment')} (${newIndex + 1})`}onClick={() => seg && setCurrentSegIndex(newIndex)}>{text}diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex ba1ceb6d..27af6dfd 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -68,7 +68,7 @@ interface EditingStream {path: string;}-const getStreamDispositionsObj = (stream: FFprobeStream) => ((stream && stream.disposition) || {});+const getStreamDispositionsObj = (stream: FFprobeStream) => (stream?.disposition || {});const getStreamParams = ({ paramsByFile, filePath, streamId }: { paramsByFile: ParamsByFile, filePath: string, streamId: number }) => (paramsByFile.get(filePath)?.paramsByStream.get(streamId)@@ -163,7 +163,7 @@ function AspectEditor({ stream, streamParams, updateStreamParams }: {return (<><div style={{ fontSize: '.85em', color: 'var(--gray-11)', marginBottom: '.4em' }}>- {isSar ? t('Losslessly change the sample aspect ratio (SAR) of this track with a bitstream filter.') : t('Losslessly change the display aspect ratio of this track at the container level.')}+ {t(isSar ? 'Losslessly change the sample aspect ratio (SAR) of this track with a bitstream filter.' : 'Losslessly change the display aspect ratio of this track at the container level.')}{' '}{t('Note that this is not supported in all video players.')}</div>@@ -413,7 +413,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, patconst updateCurrentStreamParams = (setter: (a: StreamParams) => void) => updateStreamParams(editingFile, editingStreamId, setter);return (- <Dialog.Root open={editingStream != null} onOpenChange={(v) => v === false && setEditingStream(undefined)}>+ <Dialog.Root open={editingStream != null} onOpenChange={(v) => !v && setEditingStream(undefined)}><Dialog.Portal><Dialog.Overlay /><Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={cancelTagEditOnEscape(editingKey, setEditingKey)}>@@ -453,7 +453,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'h264_mp4toannexb' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams?.bsfH264Mp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfH264Mp4toannexb = checked === true; })} />}+ value={<Switch checked={Boolean(streamParams?.bsfH264Mp4toannexb)} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfH264Mp4toannexb = checked; })} />}/>)}@@ -462,13 +462,13 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'hevc_mp4toannexb' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams?.bsfHevcMp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcMp4toannexb = checked === true; })} />}+ value={<Switch checked={Boolean(streamParams?.bsfHevcMp4toannexb)} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcMp4toannexb = checked; })} />}/><KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'hevc_metadata=aud=insert' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams?.bsfHevcAudInsert} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcAudInsert = checked === true; })} />}+ value={<Switch checked={Boolean(streamParams?.bsfHevcAudInsert)} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcAudInsert = checked; })} />}/></>)}@@ -571,7 +571,7 @@ const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStreconst sampleRate = Number(stream.sample_rate);const title = stream.tags?.title;- const onClick = () => onToggle && onToggle(stream.index);+ const onClick = () => onToggle?.(stream.index);const onDispositionChange = useCallback<ChangeEventHandler<HTMLSelectElement>>((e) => {let newDisposition: ContentDispositionOptions | 'llc_disposition_remove' | undefined;@@ -798,7 +798,7 @@ function StreamsSelector({const { t } = useTranslation();function getFormatDuration(format: FFprobeFormat | undefined) {- if (!format || !format.duration) return undefined;+ if (!format?.duration) return undefined;const parsed = parseFloat(format.duration);if (Number.isNaN(parsed)) return undefined;return parsed;@@ -919,7 +919,7 @@ function StreamsSelector({</div>{editingFile != null && (- <Dialog.Root defaultOpen onOpenChange={(v) => v === false && setEditingFile(undefined)}>+ <Dialog.Root defaultOpen onOpenChange={(v) => !v && setEditingFile(undefined)}><Dialog.Portal><Dialog.Overlay /><Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={cancelTagEditOnEscape(editingKey, setEditingKey)}>diff --git a/src/renderer/src/TopMenu.tsx b/src/renderer/src/TopMenu.tsxindex 7f0292a4..da4e42d0 100644--- a/src/renderer/src/TopMenu.tsx+++ b/src/renderer/src/TopMenu.tsx@@ -59,7 +59,7 @@ function TopMenu({const onOutFormatLockedClick = useCallback(() => setOutFormatLocked((v) => (v ? undefined : fileFormat)), [fileFormat, setOutFormatLocked]);- const showClearWorkingDirButton = !!customOutDir;+ const showClearWorkingDirButton = Boolean(customOutDir);function renderFormatLock() {const Icon = outFormatLocked ? FaLock : FaUnlock;@@ -126,7 +126,7 @@ function TopMenu({title={customOutDir}style={{ paddingLeft: showClearWorkingDirButton ? '.4em' : undefined }}>- {customOutDir ? t('Working dir set') : t('Working dir unset')}+ {t(customOutDir ? 'Working dir set' : 'Working dir unset')}</Button></OutDirSelector>diff --git a/src/renderer/src/cmx3600.ts b/src/renderer/src/cmx3600.tsindex 2caa3ffd..5e90971a 100644--- a/src/renderer/src/cmx3600.ts+++ b/src/renderer/src/cmx3600.ts@@ -15,20 +15,22 @@ export default function parseCmx3600(edlContent: string) {// trim BOM from first line.for (const line of [...(firstLine ? [firstLine.trim()] : []), ...lines]) {- if (/^\d+\s+/.test(line)) {- const parts = line.trim().split(/\s+/);- if (parts.length >= 8) {- events.push({- eventNumber: parts[0]!,- reelNumber: parts[1]!,- trackType: parts[2]!,- transition: parts[3]!,- sourceIn: parts[4]!,- sourceOut: parts[5]!,- recordIn: parts[6]!,- recordOut: parts[7]!,- });- }+ if (!/^\d+\s+/.test(line)) {+ continue;+ }++ const parts = line.trim().split(/\s+/);+ if (parts.length >= 8) {+ events.push({+ eventNumber: parts[0]!,+ reelNumber: parts[1]!,+ trackType: parts[2]!,+ transition: parts[3]!,+ sourceIn: parts[4]!,+ sourceOut: parts[5]!,+ recordIn: parts[6]!,+ recordOut: parts[7]!,+ });}}diff --git a/src/renderer/src/components/AutoExportToggler.tsx b/src/renderer/src/components/AutoExportToggler.tsxindex d1211ac8..7556c269 100644--- a/src/renderer/src/components/AutoExportToggler.tsx+++ b/src/renderer/src/components/AutoExportToggler.tsx@@ -14,7 +14,7 @@ function AutoExportToggler() {return (<Button style={{ padding: '0.3em 1em' }} onClick={() => setAutoExportExtraStreams(!autoExportExtraStreams)}>- <Icon style={{ verticalAlign: 'middle', marginRight: '.5em', color: autoExportExtraStreams ? undefined : dangerColor }} />{autoExportExtraStreams ? t('Extract') : t('Discard')}+ <Icon style={{ verticalAlign: 'middle', marginRight: '.5em', color: autoExportExtraStreams ? undefined : dangerColor }} />{t(autoExportExtraStreams ? 'Extract' : 'Discard')}</Button>);}diff --git a/src/renderer/src/components/ExportButton.tsx b/src/renderer/src/components/ExportButton.tsxindex e8ece5c6..a6360711 100644--- a/src/renderer/src/components/ExportButton.tsx+++ b/src/renderer/src/components/ExportButton.tsx@@ -37,7 +37,7 @@ const ExportButton = forwardRef<HTMLButtonElement, Props>(({title = t('Export {{ num }} segments', { num: segmentsToExport.length });}- const text = autoMerge && segmentsToExport && segmentsToExport.length > 1 ? t('Export+merge') : t('Export');+ const text = t(autoMerge && segmentsToExport && segmentsToExport.length > 1 ? 'Export+merge' : 'Export');return (<buttondiff --git a/src/renderer/src/components/ExportConfirm.tsx b/src/renderer/src/components/ExportConfirm.tsxindex 97670e35..b0b3b983 100644--- a/src/renderer/src/components/ExportConfirm.tsx+++ b/src/renderer/src/components/ExportConfirm.tsx@@ -256,7 +256,7 @@ function ExportConfirm({return {generic,specific,- totalNum: generic.filter((n) => n.warning).length + Object.values(specific).filter((n) => n != null && n.warning).length,+ totalNum: generic.filter((n) => n.warning).length + Object.values(specific).filter((n) => n?.warning).length,};}, [effectiveExportMode, areWeCuttingProblematicStreams, mainCopiedThumbnailStreams, isMov, isIpod, movFastStart, t, preserveMovData, areWeCutting, needSmartCut, isEncoding, keyframeCut, enableOverwriteOutput, simpleMode, willMerge, avoidNegativeTs, outFormat, outputPlaybackRate, keyframesEnabled, haveSegmentWithProblematicKeyframe, hvc1NeededStreams]);diff --git a/src/renderer/src/components/FileNameTemplateEditor.tsx b/src/renderer/src/components/FileNameTemplateEditor.tsxindex 70467ce6..842e569a 100644--- a/src/renderer/src/components/FileNameTemplateEditor.tsx+++ b/src/renderer/src/components/FileNameTemplateEditor.tsx@@ -196,7 +196,7 @@ function FileNameTemplateEditor(opts: {<div>{generated != null && (<div style={{ marginBottom: '.3em' }}>- <HighlightedText title={open ? t('Close') : t('Edit')} role="button" onClick={handleSampleClick} style={{ wordBreak: 'break-word', cursor: 'pointer' }}>+ <HighlightedText title={t(open ? 'Close' : 'Edit')} role="button" onClick={handleSampleClick} style={{ wordBreak: 'break-word', cursor: 'pointer' }}>{generated.problems.error != null && <FaExclamationTriangle style={{ color: dangerColor, marginRight: '.2em', verticalAlign: 'middle' }} />}{generated.originalFileNames != null && formatCurrentSegFileOrFirst(generated.fileNames)}<span style={generated.originalFileNames != null ? { textDecoration: 'line-through', marginLeft: '.3em', color: dangerColor } : undefined}>diff --git a/src/renderer/src/components/GenericDialog.tsx b/src/renderer/src/components/GenericDialog.tsxindex 372496d2..376626dc 100644--- a/src/renderer/src/components/GenericDialog.tsx+++ b/src/renderer/src/components/GenericDialog.tsx@@ -55,7 +55,7 @@ export default function GenericDialog({ dialog, onOpenChange }: {</Dialog.Root>{/* Alert dialog */ }- <AlertDialog.Root open={dialog != null && !!dialog.isAlert} onOpenChange={onOpenChange}>+ <AlertDialog.Root open={dialog != null && Boolean(dialog.isAlert)} onOpenChange={onOpenChange}><AlertDialog.Portal><AlertDialog.Overlay />@@ -220,7 +220,7 @@ export function useDialog() {function CleanupChoices() {const [choices, setChoices] = useState(cleanupChoicesInitial);- const getVal = (key: CleanupChoice) => !!choices[key];+ const getVal = (key: CleanupChoice) => Boolean(choices[key]);const onChange = (key: CleanupChoice, val: boolean | string) => setChoices((oldChoices) => {const newChoices = { ...oldChoices, [key]: Boolean(val) };diff --git a/src/renderer/src/components/KeyboardShortcuts.tsx b/src/renderer/src/components/KeyboardShortcuts.tsxindex 8618d91d..abe56092 100644--- a/src/renderer/src/components/KeyboardShortcuts.tsx+++ b/src/renderer/src/components/KeyboardShortcuts.tsx@@ -40,8 +40,7 @@ const renderKeys = (keys: string[]) => keys.map((key, i) => (function fixKeys(keys: string[]) {const uniqed = uniq(keys);const nonModifierKeys = keys.filter((key) => !allModifiers.has(key));- if (nonModifierKeys.length === 0) return []; // only modifiers is invalid- if (nonModifierKeys.length > 1) return []; // can only have one non-modifier+ if (nonModifierKeys.length !== 1) return []; // only modifiers is invalid, and there can only be one non-modifierreturn orderBy(uniqed, [(key) => !shiftModifiers.has(key), (key) => !controlModifiers.has(key), (key) => !altModifiers.has(key), (key) => !metaModifiers.has(key), (key) => key]);}@@ -96,7 +95,7 @@ const CreateBinding = memo(({if (action == null) return null;return (- <Dialog.Root open={isShown} onOpenChange={(v) => v === false && setCreatingBinding(undefined)}>+ <Dialog.Root open={isShown} onOpenChange={(v) => !v && setCreatingBinding(undefined)}><Dialog.Portal><Dialog.Overlay /><Dialog.Content style={{ width: '40em' }} aria-describedby={undefined}>@@ -812,13 +811,13 @@ const KeyboardShortcuts = memo(({}, []);const searchQueryTrimmed = searchQuery.toLowerCase().trim();- const isSearching = !!searchQueryTrimmed;+ const isSearching = Boolean(searchQueryTrimmed);const actionEntries = useMemo(() => (Object.entries(actionsMap) as unknown as [keyof typeof actionsMap, typeof actionsMap[keyof typeof actionsMap]][]).filter(([key, { name, category }]) => (!isSearching|| key.toLocaleLowerCase().includes(searchQueryTrimmed)|| name.toLowerCase().includes(searchQueryTrimmed)- || (category != null && category.toLowerCase().includes(searchQueryTrimmed))+ || category?.toLowerCase().includes(searchQueryTrimmed))), [actionsMap, isSearching, searchQueryTrimmed]);const categoriesWithActions = useMemo(() => Object.entries(groupBy(actionEntries, ([, { category }]) => category)), [actionEntries]);@@ -833,8 +832,10 @@ const KeyboardShortcuts = memo(({const onResetClick = useCallback(async () => {// Double confirmation!- if (!(await confirmDialog({ description: t('Are you sure you want to reset all keyboard bindings?') }))) return;- if (!(await confirmDialog({ description: t('Are you sure you want to reset all keyboard bindings?') }))) return;+ if (+ !(await confirmDialog({ description: t('Are you sure you want to reset all keyboard bindings?') }))+ || !(await confirmDialog({ description: t('Are you sure you want to reset all keyboard bindings?') }))+ ) return;resetKeyBindings();}, [confirmDialog, resetKeyBindings, t]);@@ -945,7 +946,7 @@ function KeyboardShortcutsDialog({return (- <Dialog.Root open={isShown} onOpenChange={(v) => v === false && onHide()}>+ <Dialog.Root open={isShown} onOpenChange={(v) => !v && onHide()}><Dialog.Portal><Dialog.Overlay /><Dialog.Content style={{ width: '40em' }} aria-describedby={undefined}>diff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsxindex c8548eaf..cd4605cf 100644--- a/src/renderer/src/components/Settings.tsx+++ b/src/renderer/src/components/Settings.tsx@@ -168,7 +168,7 @@ function Settings({<td><Button disabled={!autoSaveProjectFile} onClick={toggleStoreProjectInWorkingDir}>{storeProjectInWorkingDir ? <FaFolder style={{ verticalAlign: 'middle', fontSize: '1.1em', marginRight: '.3em' }} /> : <FaFile style={{ verticalAlign: 'middle', fontSize: '1.1em', marginRight: '.3em' }} />}- {storeProjectInWorkingDir ? t('Store in working directory') : t('Store next to media file')}+ {t(storeProjectInWorkingDir ? 'Store in working directory' : 'Store next to media file')}</Button></td></Row>@@ -185,7 +185,7 @@ function Settings({<td><Truncated maxWidth="15em">{customFfPath}</Truncated><Button onClick={changeCustomFfPath}>- <FaCogs style={{ verticalAlign: 'middle', marginRight: '.4em' }} />{customFfPath ? t('Using external ffmpeg') : t('Using built-in ffmpeg')}+ <FaCogs style={{ verticalAlign: 'middle', marginRight: '.4em' }} />{t(customFfPath ? 'Using external ffmpeg' : 'Using built-in ffmpeg')}</Button>{customFfPath && (<Button onClick={clearCustomFfPath} title={t('Clear')}>@@ -230,7 +230,7 @@ function Settings({</KeyCell><td><Button onClick={() => setInvertCutSegments((v) => !v)}>- <FaYinYang style={{ verticalAlign: 'middle', marginRight: '.3em', color: invertCutSegments ? dangerColor : undefined }} /> {invertCutSegments ? t('Remove') : t('Keep')}+ <FaYinYang style={{ verticalAlign: 'middle', marginRight: '.3em', color: invertCutSegments ? dangerColor : undefined }} /> {t(invertCutSegments ? 'Remove' : 'Keep')}</Button></td></Row>@@ -247,7 +247,7 @@ function Settings({<OutDirSelector><Button>{customOutDir ? <FaFolder style={{ marginRight: '.3em', verticalAlign: 'middle' }} /> : <FaFile style={{ marginRight: '.3em', verticalAlign: 'middle' }} />}- {customOutDir ? t('Custom working directory') : t('Same directory as input file')}...+ {t(customOutDir ? 'Custom working directory' : 'Same directory as input file')}...</Button></OutDirSelector></td>@@ -341,7 +341,7 @@ function Settings({</KeyCell><td><Button onClick={() => setCaptureFrameMethod((existing) => (existing === 'ffmpeg' ? 'videotag' : 'ffmpeg'))}>- {captureFrameMethod === 'ffmpeg' ? t('FFmpeg') : t('HTML video tag')}+ {t(captureFrameMethod === 'ffmpeg' ? 'FFmpeg' : 'HTML video tag')}</Button></td></Row>@@ -364,7 +364,7 @@ function Settings({<td><Button onClick={() => setCaptureFrameFileNameFormat((existing) => (existing === 'timestamp' ? 'index' : 'timestamp'))}>{captureFrameFileNameFormat === 'timestamp' ? <FaClock style={{ verticalAlign: 'middle', marginRight: '.3em' }} /> : <FaHashtag style={{ verticalAlign: 'middle', marginRight: '.3em' }} />}- {captureFrameFileNameFormat === 'timestamp' ? t('Frame timestamp') : t('Frame number')}+ {t(captureFrameFileNameFormat === 'timestamp' ? 'Frame timestamp' : 'Frame number')}</Button></td></Row>diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsxindex 45b33c98..821e5a52 100644--- a/src/renderer/src/components/TagEditor.tsx+++ b/src/renderer/src/components/TagEditor.tsx@@ -64,7 +64,7 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editiconst newTagKey = editingTag != null ? newTagKeyState : undefined;const [newTagKeyInput, setNewTagKeyInput] = useState<string>('');- const newTagKeyInputError = useMemo(() => !!newTagKeyInput && newTagKeyInput.includes('='), [newTagKeyInput]);+ const newTagKeyInputError = useMemo(() => Boolean(newTagKeyInput) && newTagKeyInput.includes('='), [newTagKeyInput]);const effectiveTags = useMemo(() => ({...existingTags,@@ -193,7 +193,7 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editiconst thisTagCustom = customTags[tag] != null;const thisTagNew = existingTags[tag] == null;const value = effectiveTags[tag];- const isDeletedExisting = !!canDeleteExisting && !value && !thisTagNew;+ const isDeletedExisting = Boolean(canDeleteExisting) && !value && !thisTagNew;const editingOther = editingTag != null && !editingThis;return (diff --git a/src/renderer/src/dialogs/index.tsx b/src/renderer/src/dialogs/index.tsxindex 7dff7a06..453a545c 100644--- a/src/renderer/src/dialogs/index.tsx+++ b/src/renderer/src/dialogs/index.tsx@@ -87,7 +87,7 @@ export async function askForInputDir(defaultPath?: string | undefined) {message: i18n.t('Press confirm to grant LosslessCut access to write the project file (due to App Sandbox restrictions).'),buttonLabel: i18n.t('Confirm'),});- return (filePaths && filePaths.length === 1) ? filePaths[0] : undefined;+ return (filePaths?.length === 1) ? filePaths[0] : undefined;}export async function askForOutDir(defaultPath?: string | undefined) {@@ -116,7 +116,7 @@ export async function askForFfPath(defaultPath?: string | undefined) {defaultPath: defaultPath!,title: i18n.t('Select custom FFmpeg directory'),});- return (filePaths && filePaths.length === 1) ? filePaths[0] : undefined;+ return (filePaths?.length === 1) ? filePaths[0] : undefined;}export type OpenFileResponse = 'open' | 'project' | 'tracks' | 'subtitles' | 'addToBatch' | 'mergeWithCurrentFile';@@ -624,8 +624,7 @@ export async function checkAppPath() {return;}const pathSeg = pathMatch[1];- if (pathSeg == null) return;- if (pathSeg.startsWith(`57275${mf}.${ap}_`)) return;+ if ((pathSeg == null) || pathSeg.startsWith(`57275${mf}.${ap}_`)) return;// this will report the path and may return a msgpayload = `msstore-app-id:${pathSeg}`;// also check all store fakes (different title:)diff --git a/src/renderer/src/edlFormats.ts b/src/renderer/src/edlFormats.tsindex d13a5470..67273902 100644--- a/src/renderer/src/edlFormats.ts+++ b/src/renderer/src/edlFormats.ts@@ -95,10 +95,7 @@ export function parseCsv(csvStr: string, parseTimeFn: (a: string) => number | un}];});- if (!mapped.every(({ start, end }) => (- !Number.isNaN(start)- && (end === undefined || !Number.isNaN(end))- ))) {+ if (mapped.some(({ start, end }) => Number.isNaN(start) || (end !== undefined && Number.isNaN(end)))) {console.log(mapped);throw new UserFacingError(i18n.t('Invalid start or end value. Must contain a number of seconds'));}@@ -175,8 +172,7 @@ export async function parseMplayerEdl(text: string) {const start = parseFloat(match[1]!);const end = parseFloat(match[2]!);const type = parseInt(match[3]!, 10);- if (Number.isNaN(start) || Number.isNaN(end)) return [];- if (start < 0 || end < 0 || start >= end) return [];+ if (Number.isNaN(start) || Number.isNaN(end) || start < 0 || end < 0 || start >= end) return [];return [{ start, end, type }];});@@ -519,11 +515,10 @@ export function parseDjiGps2(lines: string[]) {if (pairsMatch == null) return undefined;for (const match of pairsMatch) {const split = match.split(':');- if (split.length === 2) {- const [key, value] = split;- if (key != null && value != null) {- records[key.trim()] = value.trim();- }+ if (split.length !== 2) continue;+ const [key, value] = split;+ if (key != null && value != null) {+ records[key.trim()] = value.trim();}}const altitude = parseFloat(records['abs_alt']!);diff --git a/src/renderer/src/ffmpeg.ts b/src/renderer/src/ffmpeg.tsindex f2a93d64..80e6892d 100644--- a/src/renderer/src/ffmpeg.ts+++ b/src/renderer/src/ffmpeg.ts@@ -159,12 +159,8 @@ export function getSafeCutTime(frames: Frame[], cutTime: number, nextMode: booleif (index === -1) throw new UserFacingError(i18n.t('Failed to find any prev frame'));if (index === 0) throw new UserFacingError(i18n.t('We are on the first frame'));- if (index === frames.length - 1) {- // Last frame of video, no need to modify cut time- return undefined;- }- if (frames[index + 1]!.keyframe) {- // Already on frame before keyframe, no need to modify cut time+ if (index === frames.length - 1 || frames[index + 1]!.keyframe) {+ // Last frame of video, or already on frame before keyframe: no need to modify cut timereturn undefined;}@@ -450,9 +446,9 @@ export async function extractWaveform({ filePath, outPath }: { filePath: string,}export function isIphoneHevc(format: FFprobeFormat, streams: FFprobeStream[]) {- if (!streams.some((s) => s.codec_name === 'hevc')) return false;- const makeTag = format.tags && format.tags['com.apple.quicktime.make'];- const modelTag = format.tags && format.tags['com.apple.quicktime.model'];+ if (streams.every((s) => s.codec_name !== 'hevc')) return false;+ const makeTag = format.tags?.['com.apple.quicktime.make'];+ const modelTag = format.tags?.['com.apple.quicktime.model'];return (makeTag === 'Apple' && modelTag?.startsWith('iPhone'));}@@ -512,7 +508,7 @@ export function getTimecodeFromStreams(streams: FFprobeStream[]) {// eslint-disable-next-line unicorn-js/no-unused-builtin-method-return -- TODO fix (new rule in @mifi/lint-config)streams.find((stream) => {try {- if (stream.tags && stream.tags['timecode']) {+ if (stream.tags?.['timecode']) {const fps = getStreamFps(stream);foundTimecode = parseTimecode(stream.tags['timecode'], fps);console.log('Loaded timecode', stream.tags['timecode'], 'from stream', stream.index);diff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.tsindex b3470f73..337c40eb 100644--- a/src/renderer/src/hooks/useFfmpegOperations.ts+++ b/src/renderer/src/hooks/useFfmpegOperations.ts@@ -378,6 +378,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treafor (const [fileId, { paramsByStream }] of paramsByFile.entries()) {for (const [streamId, streamParams] of paramsByStream.entries()) {const outputIndex = mapInputStreamIndexToOutputIndex(fileId, streamId);+ // eslint-disable-next-line unicorn-js/prefer-continue -- dedenting this long block would make a large diffif (outputIndex != null) {const { disposition } = streamParams;if (disposition != null) {diff --git a/src/renderer/src/hooks/useHtml5ify.tsx b/src/renderer/src/hooks/useHtml5ify.tsxindex 969cbc7e..d63159ae 100644--- a/src/renderer/src/hooks/useHtml5ify.tsx+++ b/src/renderer/src/hooks/useHtml5ify.tsx@@ -75,7 +75,7 @@ export default function useHtml5ify({ filePath, hasVideo, hasAudio, workingRef,const { t } = useTranslation();const [option, setOption] = useState(initialOption != null && inputOptions[initialOption] ? initialOption : Object.keys(inputOptions)[0]! as Html5ifyMode);- const [remember, setRemember] = useState(!!initialOption);+ const [remember, setRemember] = useState(Boolean(initialOption));const onOptionChange = useCallback<ChangeEventHandler<HTMLInputElement>>((e) => setOption(e.currentTarget.value as Html5ifyMode), []);diff --git a/src/renderer/src/hooks/useKeyboard.ts b/src/renderer/src/hooks/useKeyboard.tsindex 6c55be29..1cfbc65b 100644--- a/src/renderer/src/hooks/useKeyboard.ts+++ b/src/renderer/src/hooks/useKeyboard.ts@@ -148,15 +148,11 @@ export default ({ keyBindings, keyUpActions, getKeyboardAction, closeExportConfi// only use first one, if multiple matches (shouldn't happen anyway)const matchingKeyBinding = (keyBindingsByKeyCode[e.code] ?? []).find((kb) => {const kbKeys = new Set(kb.keys.split('+'));- // eslint-disable-next-line unicorn-js/no-chained-comparison -- false positive: this compares a boolean on purpose- if ((controlModifiers.intersection(kbKeys).size > 0) !== ctrl) return false;- // eslint-disable-next-line unicorn-js/no-chained-comparison -- false positive: this compares a boolean on purpose- if ((shiftModifiers.intersection(kbKeys).size > 0) !== shift) return false;- // eslint-disable-next-line unicorn-js/no-chained-comparison -- false positive: this compares a boolean on purpose- if ((altModifiers.intersection(kbKeys).size > 0) !== alt) return false;- // eslint-disable-next-line unicorn-js/no-chained-comparison -- false positive: this compares a boolean on purpose- if ((metaModifiers.intersection(kbKeys).size > 0) !== meta) return false;- return true;+ const modifierMatches = (modifiers: Set<string>, pressed: boolean) => {+ const inBinding = !modifiers.isDisjointFrom(kbKeys);+ return inBinding === pressed;+ };+ return modifierMatches(controlModifiers, ctrl) && modifierMatches(shiftModifiers, shift) && modifierMatches(altModifiers, alt) && modifierMatches(metaModifiers, meta);});if (ev === 'keyup') onKeyUp({ e, action: matchingKeyBinding?.action });diff --git a/src/renderer/src/hooks/useLoading.ts b/src/renderer/src/hooks/useLoading.tsindex 65ea8926..83879171 100644--- a/src/renderer/src/hooks/useLoading.ts+++ b/src/renderer/src/hooks/useLoading.ts@@ -14,10 +14,10 @@ export default function useLoading() {const [working, setWorkingState] = useState<WorkingState | undefined>();// Store "working" in a ref so we can avoid race conditions- const workingRef = useRef(!!working);+ const workingRef = useRef(Boolean(working));const setWorking = useCallback((valOrBool?: WorkingState | true | undefined) => {- workingRef.current = !!valOrBool;+ workingRef.current = Boolean(valOrBool);const val = valOrBool === true ? { text: t('Loading') } : valOrBool;setWorkingState(val);}, [t]);diff --git a/src/renderer/src/hooks/useSegments.tsx b/src/renderer/src/hooks/useSegments.tsxindex e71795e7..b2365b64 100644--- a/src/renderer/src/hooks/useSegments.tsx+++ b/src/renderer/src/hooks/useSegments.tsx@@ -185,8 +185,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStreaerrorText: string,fn: (onSegmentDetected: (seg: SegmentBase) => void) => Promise<{ ffmpegArgs: string[] }>,}) => {- if (!filePath) return;- if (workingRef.current) return;+ if (!filePath || workingRef.current) return;try {setWorking({ text: workingText });setProgress(0);diff --git a/src/renderer/src/hooks/useSegmentsAutoSave.ts b/src/renderer/src/hooks/useSegmentsAutoSave.tsindex 6fa3f509..14118004 100644--- a/src/renderer/src/hooks/useSegmentsAutoSave.ts+++ b/src/renderer/src/hooks/useSegmentsAutoSave.ts@@ -39,8 +39,7 @@ export default ({ autoSaveProjectFile, storeProjectInWorkingDir, filePath, custoasync function save() {try {if (!autoSaveProjectFile- || !debouncedSaveOperation- || debouncedSaveOperation.filePath == null+ || debouncedSaveOperation?.filePath == null// Don't create llc file if no segments yet|| debouncedSaveOperation.cutSegments.length === 0// or if initial segment (and not deselected): https://github.com/mifi/lossless-cut/issues/2745#issuecomment-3979480707diff --git a/src/renderer/src/hooks/useStreamsMeta.tsx b/src/renderer/src/hooks/useStreamsMeta.tsxindex 1e4e98b1..04c1e8c1 100644--- a/src/renderer/src/hooks/useStreamsMeta.tsx+++ b/src/renderer/src/hooks/useStreamsMeta.tsx@@ -30,7 +30,7 @@ export default function useStreamsMeta({ mainStreams, externalFilesMeta, filePatconst [enabledStreamsFilter, setEnabledStreamsFilter] = useState<string>();const isCopyingStreamId = useCallback((path: string | undefined, streamId: number) => (- !!((path != null && copyStreamIdsByFile[path]) || {})[streamId]+ Boolean(path != null && copyStreamIdsByFile[path]?.[streamId])), [copyStreamIdsByFile]);const mainCopiedStreams = useMemo(() => mainStreams.filter((stream) => isCopyingStreamId(filePath, stream.index)), [filePath, isCopyingStreamId, mainStreams]);diff --git a/src/renderer/src/hooks/useSubtitles.ts b/src/renderer/src/hooks/useSubtitles.tsindex 5b1a7e8c..1968f2a8 100644--- a/src/renderer/src/hooks/useSubtitles.ts+++ b/src/renderer/src/hooks/useSubtitles.ts@@ -8,14 +8,14 @@ export default () => {const loadSubtitle = useCallback(async ({ filePath, index, subtitleStream }: { filePath: string, index: number, subtitleStream: FFprobeStream }) => {const url = await extractSubtitleTrackVtt(filePath, index);- setSubtitlesByStreamId((old) => ({ ...old, [index]: { url, lang: subtitleStream.tags && subtitleStream.tags.language } }));+ setSubtitlesByStreamId((old) => ({ ...old, [index]: { url, lang: subtitleStream.tags?.language } }));}, []);// Cleanup removed subtitlesconst subtitlesByStreamIdRef = useRef<typeof subtitlesByStreamId>({});useEffect(() => {Object.values(subtitlesByStreamIdRef.current).forEach(({ url, lang }) => {- if (!Object.values(subtitlesByStreamId).some((existingSubtitle) => existingSubtitle.url === url)) {+ if (Object.values(subtitlesByStreamId).every((existingSubtitle) => existingSubtitle.url !== url)) {console.log('Cleanup subtitle', lang);URL.revokeObjectURL(url);}diff --git a/src/renderer/src/segments.ts b/src/renderer/src/segments.tsindex cb549c4f..812fd459 100644--- a/src/renderer/src/segments.ts+++ b/src/renderer/src/segments.ts@@ -165,9 +165,7 @@ export function invertSegments() {const sortedSegments = sortedSegmentsIn.map((seg) => ({ ...seg, end: seg.end ?? seg.start }));- if (sortedSegments.length === 0) return [];-- if (hasAnySegmentOverlap(sortedSegments)) return [];+ if ((sortedSegments.length === 0) || hasAnySegmentOverlap(sortedSegments)) return [];const ret: { start: number, end?: number | undefined, segId?: string | undefined, name?: string | undefined }[] = [];diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.tsindex 0a18fb22..b578d933 100644--- a/src/renderer/src/util.ts+++ b/src/renderer/src/util.ts@@ -98,10 +98,8 @@ export async function checkDirWriteAccess(dirPath: string) {try {await access(dirPath, W_OK);} catch (err) {- if (err instanceof Error && 'code' in err) {- if (err.code === 'EPERM') return false; // Thrown on Mac (MAS build) when user has not yet allowed access- if (err.code === 'EACCES') return false; // Thrown on Linux when user doesn't have access to output dir- }+ // EPERM: thrown on Mac (MAS build) when user has not yet allowed access. EACCES: thrown on Linux when user doesn't have access to output dir+ if (err instanceof Error && 'code' in err && (err.code === 'EPERM' || err.code === 'EACCES')) return false;console.error(err);}return true;@@ -253,7 +251,7 @@ export async function findExistingHtml5FriendlyFile(fp: string, cod: string | unif (entryWithSuffix) matches = [...matches, { entry: entryWithSuffix, suffix }];});- const nonMatches = html5ifiedDirEntries.filter((entry) => !matches.some((m) => m.entry === entry)).map((entry) => ({ entry }));+ const nonMatches = html5ifiedDirEntries.filter((entry) => matches.every((m) => m.entry !== entry)).map((entry) => ({ entry }));// Allow for non-suffix matches too, e.g. user has a custom html5ified- file but with none of the suffixes above (but last priority)matches = [...matches, ...nonMatches];@@ -309,7 +307,7 @@ export const getStdioString = (stdio: string | Uint8Array) => (stdio instanceof// A bit hacky but it works, unless someone has a file called "No space left on device" ( ͡° ͜ʖ ͡°)export const isOutOfSpaceError = (err: InvariantExecaError) => (err.exitCode !== 0- && !!getStdioString(err.stderr)?.includes('No space left on device')+ && Boolean(getStdioString(err.stderr)?.includes('No space left on device')));export const isMuxNotSupported = (err: InvariantExecaError) => (diff --git a/src/renderer/src/util/rate-calculator.test.ts b/src/renderer/src/util/rate-calculator.test.tsindex cd54a00e..90d3da15 100644--- a/src/renderer/src/util/rate-calculator.test.ts+++ b/src/renderer/src/util/rate-calculator.test.ts@@ -9,12 +9,12 @@ it('inverts for reverse direction', () => {it('uses default rate', () => {const r = adjustRate(1, 1);- expect(r).toBe(1 * DEFAULT_PLAYBACK_RATE);+ expect(r).toBe(Number(DEFAULT_PLAYBACK_RATE));});it('allows multiplier override', () => {const r = adjustRate(1, 1, Math.PI);- expect(r).toBe(1 * Math.PI);+ expect(r).toBe(Math.PI);});describe('speeding up', () => {diff --git a/src/renderer/src/util/streams.ts b/src/renderer/src/util/streams.tsindex 6fde49d8..a466b25c 100644--- a/src/renderer/src/util/streams.ts+++ b/src/renderer/src/util/streams.ts@@ -118,13 +118,13 @@ export const isAspectRatioActive = (aspectRatio: BsfAspectRatioParams | undefine// Disposition doesn't count: it's shown and changed in the track row, and is also set automatically (e.g. for captured cover art)export const hasStreamEdits = (params: StreamParams | undefined) => params != null && (Object.keys(params.metadata).length > 0- || !!params.bsfH264Mp4toannexb || !!params.bsfHevcMp4toannexb || !!params.bsfHevcAudInsert+ || Boolean(params.bsfH264Mp4toannexb) || Boolean(params.bsfHevcMp4toannexb) || Boolean(params.bsfHevcAudInsert)|| params.tag != null|| isCropActive(params.crop)|| isAspectRatioActive(params.aspectRatio));-export const hasFileEdits = (params: FileParams | undefined) => params != null && (Object.keys(params.metadata).length > 0 || !!params.offset);+export const hasFileEdits = (params: FileParams | undefined) => params != null && (Object.keys(params.metadata).length > 0 || Boolean(params.offset));type GetVideoArgsFn = (a: { streamIndex: number, outputIndex: number }) => string[] | undefined;@@ -282,7 +282,7 @@ export function shouldCopyStreamByDefault(stream: FFprobeStream) {export const attachedPicDisposition = 'attached_pic';export function isStreamThumbnail(stream: Pick<FFprobeStream, 'codec_type' | 'disposition'>) {- return stream && stream.codec_type === 'video' && stream.disposition?.[attachedPicDisposition] === 1;+ return stream?.codec_type === 'video' && stream.disposition?.[attachedPicDisposition] === 1;}/**@@ -350,8 +350,7 @@ export function getKeyframeCutSeekCompensation({ formatName, streams, cutFrom }:streams: Pick<FFprobeStream, 'has_b_frames'>[],cutFrom: number,}) {- if (cutFrom <= 0 || !(formatName ?? '').split(',').some((f) => isMatroska(f))) return 0;- if (!streams.some((stream) => (stream.has_b_frames ?? 0) > 0)) return 0;+ if (cutFrom <= 0 || (formatName ?? '').split(',').every((f) => !isMatroska(f)) || streams.every((stream) => !((stream.has_b_frames ?? 0) > 0))) return 0;return 3 / 23 + 0.001;}@@ -502,7 +501,7 @@ export function isAudioDefinitelyNotSupported(streams: FFprobeStream[]) {}export function getVideoTimebase(videoStream: Pick<FFprobeStream, 'time_base'>) {- const timebaseMatch = videoStream.time_base && videoStream.time_base.split('/');+ const timebaseMatch = videoStream.time_base?.split('/');if (timebaseMatch) {const timebaseParsed = parseInt(timebaseMatch[1]!, 10);if (!Number.isNaN(timebaseParsed)) return timebaseParsed;