frontispiece / apps / example / view / ink-story.ts
ink-story.ts
Raw
import { Fragment } from "preact"
import { useState } from "preact/hooks"
import { html, useInkHookState } from "./bootstrap"
import { LineViewer } from "./line-viewer"
import { SectionView } from "./section-view"

export const InkStoryView = () => {
	const [showLog, setShowLog] = useState(false)
	const inkState = useInkHookState()
	const lines = inkState.getVisibleLines({
		showHidden: showLog,
		showCommands: false,
	})
	const renderStory = () => {
		return html`<div>
			${lines.map((line) => {
				if (line.type === "command") {
					return html`<div class="command-view">>> ${line.command}</div>`
				}
				return html`<${LineViewer} line=${line} />`
			})}
		</div>`
	}

	const renderAdvanceButton = () => {
		if (inkState.getCanAdvance()) {
			return html`<button
				className="choice"
				onclick=${() => {
					inkState.advance()
				}}
			>
				Continue
			</button>`
		}
		return null
	}

	const renderChoices = () => {
		if (!inkState.shouldShowChoices()) {
			return null
		}

		return html`<div>
			${inkState.getChoices().map((choice) => {
				return html`<button
					className="choice"
					onclick=${() => {
						inkState.hideAllVisible()
						inkState.makeChoice(choice.index)
						inkState.advance()
					}}
				>
					${choice.index}: ${choice.text}
				</button>`
			})}
		</div>`
	}

	const renderLogButton = () => {
		const logButtonText = showLog ? "Hide Log" : "Show Log"
		return html`<button
			onclick=${() => {
				setShowLog(!showLog)
			}}
		>
			${logButtonText}
		</button>`
	}

	const renderHideButton = () => {
		return html`<button
			onclick=${() => {
				inkState.hideAllVisible()
			}}
		>
			Hide All Text
		</button>`
	}

	const renderHideOldButton = () => {
		return html`<button
			onclick=${() => {
				inkState.hideOlderLines(3)
			}}
		>
			Hide All but 3 lines
		</button>`
	}

	const renderResetButton = () => {
		return html`<button
			onclick=${() => {
				inkState.reset()
			}}
		>
			Reset
		</button>`
	}

	return html`<main>
		<div>${renderStory()} ${renderAdvanceButton()} ${renderChoices()}</div>
		<div>
			${renderLogButton()} ${renderHideButton()} ${renderHideOldButton()} ${renderResetButton()}
		</div>
		<${SectionView} />
	</main>`
}