diff --git a/.oxlintrc.json b/.oxlintrc.json index 18b148b3299..885074f72ae 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -276,10 +276,16 @@ } }, { - "files": ["src/**/*.{js,mjs,cjs,ts,mts,cts,vue}"], - "excludeFiles": ["src/**/*.test.{ts,tsx}"], + "files": [ + "src/**/*.{js,mjs,cjs,ts,mts,cts,vue}", + "packages/*/src/**/*.{js,mjs,cjs,ts,mts,cts,vue}" + ], + "excludeFiles": [ + "src/**/*.test.{ts,tsx}", + "packages/*/src/**/*.test.{ts,tsx}" + ], "rules": { - "comfy/no-es2023-array-copy-method": "error" + "comfy/no-es2023-array-method": "error" } }, { diff --git a/packages/account-ui/src/billing/tab/billingBannerView.ts b/packages/account-ui/src/billing/tab/billingBannerView.ts index f17219ac0bc..d76bacab34d 100644 --- a/packages/account-ui/src/billing/tab/billingBannerView.ts +++ b/packages/account-ui/src/billing/tab/billingBannerView.ts @@ -210,7 +210,5 @@ export function selectBillingBanners( const suppressCredit = suppressesCreditBanners(views.map(({ kind }) => kind)) return views .filter(({ kind }) => !(suppressCredit && CREDIT_KINDS.has(kind))) - .toSorted( - (a, b) => STACK_ORDER.indexOf(a.kind) - STACK_ORDER.indexOf(b.kind) - ) + .sort((a, b) => STACK_ORDER.indexOf(a.kind) - STACK_ORDER.indexOf(b.kind)) } diff --git a/src/composables/videoConcat/videoSequence.ts b/src/composables/videoConcat/videoSequence.ts index 2f446bd65c8..aba56fcb79b 100644 --- a/src/composables/videoConcat/videoSequence.ts +++ b/src/composables/videoConcat/videoSequence.ts @@ -1,3 +1,5 @@ +import { findLastIndex } from '@/utils/arrayUtil' + interface SequencePosition { index: number offset: number @@ -19,7 +21,8 @@ export function locateSequenceTime( const starts = sequenceStarts(durations) const lastIndex = durations.length - 1 if (lastIndex < 0) return { index: 0, offset: 0 } - const index = starts.findLastIndex( + const index = findLastIndex( + starts, (start, i) => start <= time && (i === lastIndex || durations[i] > 0) ) if (index < 0) return { index: 0, offset: 0 } diff --git a/src/core/graph/widgets/dynamicWidgets.ts b/src/core/graph/widgets/dynamicWidgets.ts index 15b894cbea5..a575f1bcd41 100644 --- a/src/core/graph/widgets/dynamicWidgets.ts +++ b/src/core/graph/widgets/dynamicWidgets.ts @@ -35,6 +35,7 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { WidgetValue } from '@/types/simplifiedWidget' import { widgetId } from '@comfyorg/graph-model/widgetId' import { dynamicGroupWidget } from './dynamicGroupWidget' +import { findLastIndex } from '@/utils/arrayUtil' import { realignInputLinkSlots } from '@/lib/litegraph/src/linkDeduplication' import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation' @@ -523,7 +524,7 @@ function addAutogrowGroup( groupName, node ).name - const lastIndex = node.inputs.findLastIndex((inp) => + const lastIndex = findLastIndex(node.inputs, (inp) => inp.name.startsWith(targetName) ) const insertionIndex = diff --git a/src/platform/assets/composables/media/assetMappers.ts b/src/platform/assets/composables/media/assetMappers.ts index 697e06ebb2c..4c4fe1a3b6c 100644 --- a/src/platform/assets/composables/media/assetMappers.ts +++ b/src/platform/assets/composables/media/assetMappers.ts @@ -14,6 +14,7 @@ import { getMediaTypeFromFilename, isPreviewableMediaType } from '@/utils/formatUtil' +import { findLast } from '@/utils/arrayUtil' /** * Extract asset type from tags array @@ -133,11 +134,9 @@ export function unflattenOutputAssets( const grouped = [...assetsByJob.entries()].map(([job_id, assets]) => { const ordered = [...assets].sort(byCreatedAtAsc) const representative = - [...ordered] - .sort(byIsTemp) - .findLast((asset) => - isPreviewableMediaType(getMediaTypeFromFilename(asset.name)) - ) ?? ordered.at(-1)! + findLast([...ordered].sort(byIsTemp), (asset) => + isPreviewableMediaType(getMediaTypeFromFilename(asset.name)) + ) ?? ordered.at(-1)! return { ...representative, id: job_id, diff --git a/src/platform/assets/composables/useAssetSelection.ts b/src/platform/assets/composables/useAssetSelection.ts index 82b155f05aa..471fb7d5540 100644 --- a/src/platform/assets/composables/useAssetSelection.ts +++ b/src/platform/assets/composables/useAssetSelection.ts @@ -7,6 +7,7 @@ import { getAssetOutputCount, getTotalAssetOutputCount } from '@/platform/assets/utils/outputAssetCountUtil' +import { findLastIndex } from '@/utils/arrayUtil' export function useAssetSelection() { const selectionStore = useAssetSelectionStore() @@ -129,7 +130,7 @@ export function useAssetSelection() { function setSelectedIds(ids: string[], allAssets: AssetItem[]) { selectionStore.setSelection(ids) const selected = new Set(ids) - const anchorIndex = allAssets.findLastIndex((asset) => + const anchorIndex = findLastIndex(allAssets, (asset) => selected.has(asset.id) ) setAnchor(anchorIndex, anchorIndex >= 0 ? allAssets[anchorIndex].id : null) diff --git a/src/scripts/ui/toggleSwitch.test.ts b/src/scripts/ui/toggleSwitch.test.ts index 7b6f71ab2d8..81d06daa987 100644 --- a/src/scripts/ui/toggleSwitch.test.ts +++ b/src/scripts/ui/toggleSwitch.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { toggleSwitch } from './toggleSwitch' @@ -70,6 +70,34 @@ describe('toggleSwitch', () => { }) }) + describe('on a browser without Array.prototype.findLastIndex', () => { + const descriptor = Object.getOwnPropertyDescriptor( + Array.prototype, + 'findLastIndex' + ) + + afterEach(() => { + if (descriptor) { + Object.defineProperty(Array.prototype, 'findLastIndex', descriptor) + } + }) + + it('still honours the last selected item', () => { + Reflect.deleteProperty(Array.prototype, 'findLastIndex') + + const container = toggleSwitch('mode', [ + { text: 'a', selected: true }, + { text: 'b', value: 'B', selected: true }, + { text: 'c' } + ]) + + expect(readState(container)).toEqual({ + selected: [false, true, false], + checked: [false, true, false] + }) + }) + }) + it('renders value, tooltip and radio grouping', () => { const container = toggleSwitch('mode', [ { text: 'Fast', value: 'fast', tooltip: 'Go fast' }, diff --git a/src/scripts/ui/toggleSwitch.ts b/src/scripts/ui/toggleSwitch.ts index ff16cabfb4f..b5b2b9da2e4 100644 --- a/src/scripts/ui/toggleSwitch.ts +++ b/src/scripts/ui/toggleSwitch.ts @@ -1,3 +1,5 @@ +import { findLastIndex } from '@/utils/arrayUtil' + import { $el } from './utils' interface ToggleSwitchItem { @@ -31,7 +33,7 @@ export function toggleSwitch( : { ...item, value: item.value ?? item.text } ) const initialIndex = Math.max( - switchItems.findLastIndex((item) => item.selected), + findLastIndex(switchItems, (item) => item.selected), 0 ) diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index 9e119701434..54b604c6105 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -49,6 +49,7 @@ import { } from '@/utils/executionErrorUtil' import { executionIdToNodeLocatorId } from '@/utils/graphTraversalUtil' import { createRafCoalescer } from '@/utils/rafBatch' +import { findLast } from '@/utils/arrayUtil' import type { z } from 'zod' type PromptOutputsSkippedData = z.infer @@ -1321,7 +1322,7 @@ export const useExecutionStore = defineStore('execution', () => { const startedJobIds = Object.keys(queuedJobs.value).filter( (jobId) => queuedJobs.value[jobId].executionStartedAt !== undefined ) - const ownedJobId = startedJobIds.findLast((jobId) => + const ownedJobId = findLast(startedJobIds, (jobId) => rememberStampAndCheckActiveWorkflow(jobId) ) executionIdToLocatorCache.clear() diff --git a/src/stores/queueStore.ts b/src/stores/queueStore.ts index b16b9ac4e8c..9f93fdc3c5a 100644 --- a/src/stores/queueStore.ts +++ b/src/stores/queueStore.ts @@ -23,6 +23,7 @@ import { useExecutionStore } from '@/stores/executionStore' import { useJobModelDownloadStore } from '@/stores/jobModelDownloadStore' import { tryNormalizeNodeExecutionId } from '@comfyorg/graph-model/nodeIdentification' import { useSettingStore } from '@/platform/settings/settingStore' +import { findLast } from '@/utils/arrayUtil' enum TaskItemDisplayStatus { Running = 'Running', @@ -85,7 +86,7 @@ export class TaskItemImpl { const previewable = this.previewableOutputs // Prefer the last saved media file (most recent result) over temp previews return ( - previewable.findLast((output) => output.type === 'output') ?? + findLast(previewable, (output) => output.type === 'output') ?? previewable.at(-1) ) } diff --git a/src/utils/arrayUtil.test.ts b/src/utils/arrayUtil.test.ts new file mode 100644 index 00000000000..21f6e799c42 --- /dev/null +++ b/src/utils/arrayUtil.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { findLast, findLastIndex } from './arrayUtil' + +describe('findLastIndex', () => { + it.for([ + { name: 'returns the last match', array: [1, 2, 3, 4], expected: 3 }, + { name: 'returns -1 with no match', array: [1, 1], expected: -1 }, + { name: 'returns -1 when empty', array: [], expected: -1 } + ])('$name', ({ array, expected }) => { + expect(findLastIndex(array, (value) => value % 2 === 0)).toBe(expected) + }) + + it('searches from the end and stops at the first match', () => { + const predicate = vi.fn((value: number) => value === 2) + expect(findLastIndex([1, 2, 3], predicate)).toBe(1) + expect(predicate.mock.calls.map(([value]) => value)).toEqual([3, 2]) + }) + + it('passes the index and the array to the predicate', () => { + const array = ['a', 'b'] + const predicate = vi.fn(() => false) + findLastIndex(array, predicate) + expect(predicate.mock.calls).toEqual([ + ['b', 1, array], + ['a', 0, array] + ]) + }) + + it('treats any truthy predicate result as a match', () => { + expect(findLastIndex([0, 1, 0], (value) => value)).toBe(1) + }) +}) + +describe('findLast', () => { + beforeEach(() => { + const descriptor = Object.getOwnPropertyDescriptor( + Array.prototype, + 'findLast' + ) + Reflect.deleteProperty(Array.prototype, 'findLast') + + return () => { + if (descriptor) { + Object.defineProperty(Array.prototype, 'findLast', descriptor) + } + } + }) + + it.for([ + { name: 'returns the last match', array: [1, 2, 3, 4], expected: 4 }, + { + name: 'returns undefined with no match', + array: [1, 3], + expected: undefined + }, + { name: 'returns undefined when empty', array: [], expected: undefined }, + { name: 'returns a matched falsy element', array: [0], expected: 0 } + ])('$name', ({ array, expected }) => { + expect(findLast(array, (value) => value % 2 === 0)).toBe(expected) + }) + + it('returns the matched value before the predicate changes the array', () => { + const array = [1, 2, 3] + + expect( + findLast(array, () => { + array.pop() + return true + }) + ).toBe(3) + }) +}) diff --git a/src/utils/arrayUtil.ts b/src/utils/arrayUtil.ts new file mode 100644 index 00000000000..ec7fa369893 --- /dev/null +++ b/src/utils/arrayUtil.ts @@ -0,0 +1,22 @@ +/** ES2022-safe equivalent of `Array.prototype.findLastIndex`. */ +export function findLastIndex( + array: readonly T[], + predicate: (value: T, index: number, array: readonly T[]) => unknown +): number { + for (let index = array.length - 1; index >= 0; index--) { + if (predicate(array[index], index, array)) return index + } + return -1 +} + +/** ES2022-safe equivalent of `Array.prototype.findLast`. */ +export function findLast( + array: readonly T[], + predicate: (value: T, index: number, array: readonly T[]) => unknown +): T | undefined { + for (let index = array.length - 1; index >= 0; index--) { + const value = array[index] + if (predicate(value, index, array)) return value + } + return undefined +} diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 16ca29b0e35..05c6fb9947b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -197,6 +197,7 @@ import { attachAgentWriteOverwriteWatch } from './crdt/agentWriteOverwrites' import { attachDocOpMinter } from './crdt/docOpMinter' import { attachRestoreOpMinter } from './crdt/restoreOpMinter' import { useAgentCrdtFollower } from './crdt/useAgentCrdtFollower' +import { findLast } from '@/utils/arrayUtil' const CrdtDevPanel = defineAsyncComponent( () => import('./crdt/CrdtDevPanel.vue') @@ -1384,15 +1385,17 @@ useEventListener( const completedTurnClaimedCanvasContent = ref(false) function completedTurnCanClaimCanvasContent(): boolean { - const lastCanvasTool = conversationMessages.value - .at(-1) - ?.parts.findLast( - (part) => - part.type === 'tool' && - (part.name === 'clear_canvas' - ? part.ok === true - : part.ok !== false && toolCanClaimCanvasContent(part.name)) - ) + const lastParts = conversationMessages.value.at(-1)?.parts + const lastCanvasTool = lastParts + ? findLast( + lastParts, + (part) => + part.type === 'tool' && + (part.name === 'clear_canvas' + ? part.ok === true + : part.ok !== false && toolCanClaimCanvasContent(part.name)) + ) + : undefined return ( lastCanvasTool?.type === 'tool' && lastCanvasTool.name !== 'clear_canvas' ) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 7c69db71cc8..346be2e69f3 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -74,6 +74,7 @@ import { useAgentWorkflowTabBindingStore } from '@/workbench/extensions/agent/st import type { ComposerAttachment } from '@/workbench/extensions/agent/types/composerAttachment' import type { WorkflowReference } from '@/workbench/extensions/agent/types/workflowReference' import { serializeWorkflowReferences } from '@/workbench/extensions/agent/utils/workflowReferenceText' +import { findLast } from '@/utils/arrayUtil' export interface AgentEventSource { subscribe(listener: (raw: unknown) => void): () => void @@ -3009,7 +3010,8 @@ export function useAgentSession(deps: AgentSessionDeps) { if (latest && !isTerminalTurnStatus(latest.status)) return { kind: 'streaming', - pendingAsk: rows.findLast( + pendingAsk: findLast( + rows, (row) => !isTerminalTurnStatus(row.status) && row.pending_ask !== undefined )?.pending_ask diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index 0830a0b2754..57cc92fce6f 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -22,6 +22,7 @@ import { isOpenAskPart, toAskOrNoticePart } from './agentMessageParts' +import { findLast } from '@/utils/arrayUtil' type AttachmentKind = 'image' | 'video' | 'audio' @@ -544,7 +545,7 @@ function keepAuthoritativeAsk( isAskRetired: (askId: string) => boolean ): void { const rowAsk = row.status === 'streaming' ? row.pending_ask : undefined - const priorAvailableAskId = message.parts.findLast((part) => { + const priorAvailableAskId = findLast(message.parts, (part) => { const askId = askIdOf(part) return ( isOpenAskPart(part) && diff --git a/tools/oxlint-plugins/comfy.ts b/tools/oxlint-plugins/comfy.ts index 0b506be960e..f37e10d0f35 100644 --- a/tools/oxlint-plugins/comfy.ts +++ b/tools/oxlint-plugins/comfy.ts @@ -20,7 +20,7 @@ import { noDeprecatedApiSchema, noDirectSelectionWrite, noDomInComputed, - noEs2023ArrayCopyMethod, + noEs2023ArrayMethod, noJsPrivateClassMembers, noMisplacedSpecFiles, noNewZodForRemoteApiTypes, @@ -55,7 +55,7 @@ export default { 'no-js-extension-imports': noJsExtensionImports, 'no-js-private-class-members': noJsPrivateClassMembers, 'no-duplicate-ingest-type': noDuplicateIngestType, - 'no-es2023-array-copy-method': noEs2023ArrayCopyMethod, + 'no-es2023-array-method': noEs2023ArrayMethod, 'no-import-actual': noImportActual, 'no-misplaced-spec-files': noMisplacedSpecFiles, 'no-mocked-in-expect': noMockedInExpect, diff --git a/tools/oxlint-plugins/restrictedSyntax.test.ts b/tools/oxlint-plugins/restrictedSyntax.test.ts index 24c829b4d5d..eb3c086de6b 100644 --- a/tools/oxlint-plugins/restrictedSyntax.test.ts +++ b/tools/oxlint-plugins/restrictedSyntax.test.ts @@ -15,6 +15,7 @@ const privateSigil = '#' const probeDirs = { source: path.resolve('src/__restricted_syntax_probes__'), + package: path.resolve('packages/__restricted_syntax_probes__'), app: path.resolve('apps/__restricted_syntax_probes__/src'), remote: path.resolve('src/platform/remote/__restricted_syntax_probes__'), selection: path.resolve('src/composables/graph/__restricted_syntax_probes__'), @@ -200,8 +201,16 @@ const method = 'map' as const items[method]() items.sort() void fn +items.findLast((item) => item > 1) +items.findLastIndex((item) => item > 1) ` }, + ...['arrayPackage.ts', 'arrayPackage.test.ts'].map((name) => ({ + file: path.join(probeDirs.package, 'src', name), + source: `const items = [1, 2] +items.findLastIndex((item) => item > 1) +` + })), { file: path.join(probeDirs.source, 'arrayCopy.vue'), source: `