recital / packages / ext-common-commands / src / tools / fragment-tools.ts
fragment-tools.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import { FlatObject, FragmentObject, SceneObject } from '@a-morphous/recital/dist/types/types'

export const getSceneThatFragmentBelongsTo = (
	stageObjects: FlatObject[],
	fragment: FragmentObject
): SceneObject | undefined => {
	const index = stageObjects.indexOf(fragment)

	if (index === -1) {
		return undefined
	}

	for (let i = index; i >= 0; i--) {
		const pointer = stageObjects[i]

		if (pointer.type === 'scene') {
			return pointer
		}
	}

	return undefined
}

export const findFragment = (
	stageObjects: FlatObject[],
	primary?: string,
	title?: string
): FragmentObject | undefined => {
	if (!primary && !title) {
		return undefined
	}

	if (primary && title) {
		return stageObjects.find((val) => {
			return val.type === 'fragment' && val.primary === primary && val.title === title
		}) as FragmentObject
	}

	if (primary) {
		return stageObjects.find((val) => {
			return val.type === 'fragment' && val.primary === primary
		}) as FragmentObject
	}

	if (title) {
		return stageObjects.find((val) => {
			return val.type === 'fragment' && val.title === title
		}) as FragmentObject
	}
}