frontispiece / packages / ink-processor / src / utils / immutable-utils.ts
immutable-utils.ts
Raw
/*
 * 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 https://mozilla.org/MPL/2.0/.
 */

import { VisualInkState } from "../types"

// helper functions to replace various pieces as needed with new objects or arrays
export const refreshSections = (draftState: VisualInkState, originalState: VisualInkState) => {
	if (draftState.sections !== originalState.sections) {
		return draftState.sections
	}
	draftState.sections = [...originalState.sections]
	return draftState.sections
}

export const refreshSection = (
	draftState: VisualInkState,
	originalState: VisualInkState,
	sectionIndex: number
) => {
	if (draftState.sections[sectionIndex] !== originalState.sections[sectionIndex]) {
		return draftState.sections[sectionIndex]
	}
	refreshSections(draftState, originalState)
	draftState.sections[sectionIndex] = { ...originalState.sections[sectionIndex] }
	return draftState.sections[sectionIndex]
}

export const refreshSectionLines = (
	draftState: VisualInkState,
	originalState: VisualInkState,
	sectionIndex: number
) => {
	if (draftState.sections[sectionIndex]?.lines !== originalState.sections[sectionIndex]?.lines) {
		return draftState.sections[sectionIndex]?.lines
	}
	refreshSection(draftState, originalState, sectionIndex)
	draftState.sections[sectionIndex].lines = [...originalState.sections[sectionIndex]?.lines]
	return draftState.sections[sectionIndex]?.lines
}

export const refreshLineInSection = (
	draftState: VisualInkState,
	originalState: VisualInkState,
	sectionIndex: number,
	lineIndex: number
) => {
	if (
		draftState.sections[sectionIndex]?.lines[lineIndex] !==
		originalState.sections[sectionIndex]?.lines[lineIndex]
	) {
		return draftState.sections[sectionIndex]?.lines[lineIndex]
	}
	refreshSectionLines(draftState, originalState, sectionIndex)
	draftState.sections[sectionIndex].lines[lineIndex] = {
		...originalState.sections[sectionIndex].lines[lineIndex],
	}
	return draftState.sections[sectionIndex]?.lines[lineIndex]
}