Skip to main content

@twick/timeline - v0.15.0

Table of contents​

Interfaces​

Classes​

Functions​

References​

Type Aliases​

Variables​

Functions​

TimelineProvider​

▸ TimelineProvider(props): Element

Provider component for the Timeline context. Wraps the timeline functionality with PostHog analytics and undo/redo support. Manages the global state for timeline instances including tracks, elements, playback state, and history management.

Parameters​

NameTypeDescription
propsTimelineProviderPropsTimeline provider configuration

Returns​

Element

Context provider with timeline state management

Example

<TimelineProvider
contextId="my-timeline"
initialData={{ tracks: [], version: 1 }}
undoRedoPersistenceKey="timeline-state"
>
<YourApp />
</TimelineProvider>

Example

Disable analytics:

<TimelineProvider
contextId="my-timeline"
analytics={{ enabled: false }}
>
<YourApp />
</TimelineProvider>

Defined in​

context/timeline-context.tsx:356


useTimelineContext​

▸ useTimelineContext(): TimelineContextType

Hook to access the Timeline context. Provides access to timeline state, editor instance, and timeline management functions. Must be used within a TimelineProvider component.

Returns​

TimelineContextType

TimelineContextType object with all timeline state and controls

Throws

Error if used outside of TimelineProvider

Example

const {
editor,
selectedItem,
totalDuration,
canUndo,
canRedo,
setSelectedItem,
setTimelineAction
} = useTimelineContext();

// Access the timeline editor
const tracks = editor.getTracks();

// Check if undo is available
if (canUndo) {
editor.undo();
}

// Set timeline action
setTimelineAction(TIMELINE_ACTION.SET_PLAYER_STATE, { playing: true });

Defined in​

context/timeline-context.tsx:456


getCaptionElements​

▸ getCaptionElements(project, language?): CaptionLike[]

Parameters​

NameType
projectProjectJSON
language?string

Returns​

CaptionLike[]

Defined in​

utils/caption-export.ts:40


getCaptionLanguages​

▸ getCaptionLanguages(project): string[]

Parameters​

NameType
projectProjectJSON

Returns​

string[]

Defined in​

utils/caption-export.ts:63


exportCaptionsAsSRT​

▸ exportCaptionsAsSRT(project, language?): string

Parameters​

NameType
projectProjectJSON
language?string

Returns​

string

Defined in​

utils/caption-export.ts:70


exportCaptionsAsVTT​

▸ exportCaptionsAsVTT(project, language?): string

Parameters​

NameType
projectProjectJSON
language?string

Returns​

string

Defined in​

utils/caption-export.ts:85


computeCaptionGeometry​

▸ computeCaptionGeometry(fontSize, captionStyle): CaptionGeometry

Compute caption geometry (stroke width and rect gap) from a font size.

The current implementation uses a simple proportional mapping so that:

  • Stroke width stays visually subtle across sizes
  • Horizontal gaps scale with the font to avoid overcrowding or excessive spacing

This function is the single source of truth for caption stroke + rect layout.

Parameters​

NameType
fontSizenumber
captionStylestring

Returns​

CaptionGeometry

Defined in​

utils/caption-geometry.ts:36


getChapterMarkers​

▸ getChapterMarkers(project): ChapterMarker[]

Parameters​

NameType
projectProjectJSON

Returns​

ChapterMarker[]

Defined in​

utils/chapter-export.ts:14


exportChaptersAsYouTube​

▸ exportChaptersAsYouTube(project): string

Parameters​

NameType
projectProjectJSON

Returns​

string

Defined in​

utils/chapter-export.ts:19


exportChaptersAsJSON​

▸ exportChaptersAsJSON(project): string

Parameters​

NameType
projectProjectJSON

Returns​

string

Defined in​

utils/chapter-export.ts:26


migrateProject​

▸ migrateProject(project, targetVersion?): ProjectJSON

Parameters​

NameTypeDefault value
projectProjectJSONundefined
targetVersionnumberCURRENT_PROJECT_VERSION

Returns​

ProjectJSON

Defined in​

utils/migrations.ts:31


resolveId​

▸ resolveId(id, tracks): Track | TrackElement | null

Resolve a single ID to Track | TrackElement | null

Parameters​

NameType
idstring
tracksTrack[]

Returns​

Track | TrackElement | null

Defined in​

utils/selection.ts:13


resolveIds​

▸ resolveIds(ids, tracks): (Track | TrackElement)[]

Resolve multiple IDs to (Track | TrackElement)[]

Parameters​

NameType
idsSet<string>
tracksTrack[]

Returns​

(Track | TrackElement)[]

Defined in​

utils/selection.ts:28


getElementIdsInRange​

▸ getElementIdsInRange(track, fromElementId, toElementId): string[]

Get all element IDs in a track between two elements (inclusive). Used for Shift+click range selection.

Parameters​

NameType
trackTrack
fromElementIdstring
toElementIdstring

Returns​

string[]

Defined in​

utils/selection.ts:44


snapTime​

▸ snapTime(time, targets, thresholdSec?): SnapResult

Snaps a time value to the nearest target within the threshold. Returns the snapped time and whether snapping occurred.

Parameters​

NameTypeDefault valueDescription
timenumberundefinedThe candidate time in seconds
targetsnumber[]undefinedArray of snap target times in seconds
thresholdSecnumber0.1Maximum distance (in seconds) to snap. Default 0.1.

Returns​

SnapResult

SnapResult with time, didSnap, and optional snapTarget

Example

snapTime(5.07, [0, 5, 10], 0.1)  // { time: 5, didSnap: true, snapTarget: 5 }
snapTime(5.5, [0, 5, 10], 0.1) // { time: 5.5, didSnap: false }
snapTime(9.95, [0, 5, 10], 0.1) // { time: 10, didSnap: true, snapTarget: 10 }

Defined in​

utils/snap.ts:33


pxToSecThreshold​

▸ pxToSecThreshold(thresholdPx, pixelsPerSecond): number

Converts a snap threshold from pixels to seconds.

Parameters​

NameTypeDescription
thresholdPxnumberDistance in pixels
pixelsPerSecondnumberTimeline zoom (px per second)

Returns​

number

Threshold in seconds

Defined in​

utils/snap.ts:67


formatTimeWithFrames​

▸ formatTimeWithFrames(timeSeconds, fps?): string

Formats time in seconds to MM:SS.FF (minutes:seconds.frames). Frame count is zero-padded to 2 digits for standard frame rates.

Parameters​

NameTypeDefault valueDescription
timeSecondsnumberundefinedTime in seconds (can be fractional)
fpsnumber30Frames per second (default: 30)

Returns​

string

Formatted string e.g. "01:23.15" for 1m 23.5s at 30fps

Example

formatTimeWithFrames(0, 30)      // "00:00.00"
formatTimeWithFrames(65.5, 30) // "01:05.15"
formatTimeWithFrames(90, 24) // "01:30.00"

Defined in​

utils/time-format.ts:23


formatTimeSimple​

▸ formatTimeSimple(timeSeconds): string

Formats time in seconds to MM:SS (minutes:seconds, no frames).

Parameters​

NameTypeDescription
timeSecondsnumberTime in seconds

Returns​

string

Formatted string e.g. "01:23"

Example

formatTimeSimple(65.5)  // "01:05"

Defined in​

utils/time-format.ts:50


getDecimalNumber​

▸ getDecimalNumber(num, precision?): number

Rounds a number to a specified decimal precision. Useful for ensuring consistent decimal places in timeline calculations.

Parameters​

NameTypeDefault valueDescription
numnumberundefinedThe number to round
precisionnumber3The number of decimal places to round to

Returns​

number

The rounded number

Example

const rounded = getDecimalNumber(3.14159, 2);
// rounded = 3.14

Defined in​

utils/timeline.utils.ts:21


getTotalDuration​

▸ getTotalDuration(tracks): number

Calculates the total duration of all tracks in a timeline. Finds the maximum end time across all elements in all tracks to determine the overall timeline duration.

Parameters​

NameTypeDescription
tracksTrackJSON[]Array of track data containing elements

Returns​

number

The total duration in seconds

Example

const duration = getTotalDuration(tracks);
// duration = 120.5 (2 minutes and 0.5 seconds)

Defined in​

utils/timeline.utils.ts:39


generateShortUuid​

▸ generateShortUuid(): string

Generates a short UUID for element and track identification. Creates a 12-character unique identifier using a simplified UUID generation algorithm.

Returns​

string

A 12-character unique identifier string

Example

const id = generateShortUuid();
// id = "a1b2c3d4e5f6"

Defined in​

utils/timeline.utils.ts:66


getCurrentElements​

▸ getCurrentElements(currentTime, tracks): Readonly<TrackElement>[]

Gets all elements that are currently active at the specified time. Searches through all tracks to find elements whose time range includes the current playback time.

Parameters​

NameTypeDescription
currentTimenumberThe current playback time in seconds
tracksTrack[]Array of track objects to search through

Returns​

Readonly<TrackElement>[]

Array of elements currently active at the specified time

Example

const activeElements = getCurrentElements(5.5, tracks);
// Returns all elements active at 5.5 seconds

Defined in​

utils/timeline.utils.ts:89


canSplitElement​

▸ canSplitElement(element, currentTime): boolean

Parameters​

NameType
elementTrackElement
currentTimenumber

Returns​

boolean

Defined in​

utils/timeline.utils.ts:131


isElementId​

▸ isElementId(id): boolean

Checks if an ID represents an element. Validates if the ID follows the element naming convention.

Parameters​

NameTypeDescription
idstringThe ID to check

Returns​

boolean

True if the ID represents an element

Example

const isElement = isElementId("e-abc123");
// isElement = true

Defined in​

utils/timeline.utils.ts:151


isTrackId​

▸ isTrackId(id): boolean

Checks if an ID represents a track. Validates if the ID follows the track naming convention.

Parameters​

NameTypeDescription
idstringThe ID to check

Returns​

boolean

True if the ID represents a track

Example

const isTrack = isTrackId("t-xyz789");
// isTrack = true

Defined in​

utils/timeline.utils.ts:166


extractVideoAudio​

▸ extractVideoAudio(tracks, duration): Promise<any>

Extracts and stitches audio from video elements across all tracks. Processes all video elements in the timeline, extracts their audio segments, and combines them into a single audio file with proper timing.

Parameters​

NameTypeDescription
tracksTrack[]Array of track objects containing video elements
durationnumberThe total duration of the output audio

Returns​

Promise<any>

Promise resolving to a Blob URL of the combined audio

Example

const audioUrl = await extractVideoAudio(tracks, 120);
// audioUrl = "blob:http://localhost:3000/abc123"

Defined in​

utils/timeline.utils.ts:183

References​

ColorFilterPreset​

Renames and re-exports COLOR_FILTERS

Type Aliases​

TimelineContextType​

Ƭ TimelineContextType: Object

Type definition for the Timeline context. Contains all the state and functions needed to manage a timeline instance. Provides access to the timeline editor, selected items, undo/redo functionality, and timeline actions.

Example

const {
editor,
selectedItem,
totalDuration,
canUndo,
canRedo,
setSelectedItem,
setTimelineAction
} = useTimelineContext();

Type declaration​

NameTypeDescription
contextIdstringUnique identifier for this timeline context
editorTimelineEditorThe timeline editor instance for this context
selectedItemTrack | TrackElement | nullCurrently selected track or element (primary selection, for backward compat)
selectedIdsSet<string>Set of selected IDs (tracks and elements) for multi-select
changeLognumberChange counter for tracking modifications
timelineAction{ type: string ; payload: any }Current timeline action being performed
timelineAction.typestring-
timelineAction.payloadany-
videoResolutionSizeResolution of the video
totalDurationnumberTotal duration of the timeline in seconds
presentProjectJSON | nullCurrent project state
canUndobooleanWhether undo operation is available
canRedobooleanWhether redo operation is available
setSelectedItem(item: Track | TrackElement | null) => void-
setSelection(ids: Set<string> | (prev: Set<string>) => Set<string>) => void-
setTimelineAction(type: string, payload: any) => void-
setVideoResolution(size: Size) => void-
followPlayheadEnabledbooleanWhether timeline follows playhead during playback
setFollowPlayheadEnabled(enabled: boolean) => void-

Defined in​

context/timeline-context.tsx:47


TimelineEditorEvent​

Ƭ TimelineEditorEvent: "element:added" | "element:removed" | "element:updated" | "elements:removed" | "track:added" | "track:removed" | "track:reordered" | "project:loaded"

Event names emitted by TimelineEditor after mutations

Defined in​

core/editor/timeline.editor.ts:33


ElementMetadata​

Ƭ ElementMetadata: Record<string, unknown>

Defined in​

types.ts:128


ObjectFit​

Ƭ ObjectFit: "contain" | "cover" | "fill" | "none" | "scale-down"

Defined in​

types.ts:292


TextAlign​

Ƭ TextAlign: "left" | "center" | "right" | "justify"

Defined in​

types.ts:293


TrackType​

Ƭ TrackType: typeof TRACK_TYPES[keyof typeof TRACK_TYPES]

Union type of valid track type strings

Defined in​

utils/constants.ts:27

Variables​

COLOR_FILTERS​

• COLOR_FILTERS: any


VALIDATION_ERROR_CODE​

• Const VALIDATION_ERROR_CODE: Object

Type declaration​

NameType
ELEMENT_NOT_FOUNDstring
ELEMENT_NOT_ADDEDstring
ELEMENT_NOT_UPDATEDstring
ELEMENT_NOT_REMOVEDstring
COLLISION_ERRORstring
INVALID_TIMINGstring

Defined in​

core/visitor/element-validator.ts:16


TRACK_TYPES​

• Const TRACK_TYPES: Object

Track type constants for timeline tracks. Use these instead of raw strings for type safety and consistency.

Example

import { TRACK_TYPES } from '@twick/timeline';

editor.addTrack("Video", TRACK_TYPES.VIDEO);
const captionsTrack = editor.getCaptionsTrack(); // first track with type TRACK_TYPES.CAPTION

Type declaration​

NameTypeDescription
VIDEO"video"Video track – video clips
AUDIO"audio"Audio track – audio clips
CAPTION"caption"Caption track – captions / captions
SCENE"scene"Scene track – scene containers (e.g. image/video as full scene)
ELEMENT"element"Element track – text, shapes, icons, images (overlay elements)

Defined in​

utils/constants.ts:13


INITIAL_TIMELINE_DATA​

• Const INITIAL_TIMELINE_DATA: Object

Initial timeline data structure for new video editor projects. Provides a default timeline with a sample text element to get started.

Example

import { INITIAL_TIMELINE_DATA } from '@twick/timeline';

// Use as starting point for new projects
const newProject = {
...INITIAL_TIMELINE_DATA,
tracks: [...INITIAL_TIMELINE_DATA.tracks, newTrack]
};

Type declaration​

NameType
tracks{ type: "element" = TRACK_TYPES.ELEMENT; id: string = "t-sample"; name: string = "sample"; elements: { id: string = "e-sample"; trackId: string = "t-sample"; name: string = "sample"; type: string = "text"; s: number = 0; e: number = 5; props: { text: string = "Twick SDK"; fill: string = "#FFFFFF" } }[] }[]
versionnumber

Defined in​

utils/constants.ts:44


PLAYER_STATE​

• Const PLAYER_STATE: Object

Player state constants for timeline playback control. Defines the different states that a timeline player can be in during playback.

Example

import { PLAYER_STATE } from '@twick/timeline';

if (playerState === PLAYER_STATE.PLAYING) {
console.log('Timeline is currently playing');
}

Type declaration​

NameTypeDescription
REFRESH"Refresh"Player is refreshing/reloading content
PLAYING"Playing"Player is actively playing content
PAUSED"Paused"Player is paused

Defined in​

utils/constants.ts:82


CAPTION_STYLE​

• Const CAPTION_STYLE: Object

Caption styling options for text elements. Defines different visual styles for caption text rendering.

Example

import { CAPTION_STYLE } from '@twick/timeline';

const captionElement = new CaptionElement({
style: CAPTION_STYLE.WORD_BY_WORD
});

Type declaration​

NameTypeDescription
WORD_BG_HIGHLIGHT"highlight_bg"Highlights background of each word
WORD_BY_WORD"word_by_word"Animates text word by word
WORD_BY_WORD_WITH_BG"word_by_word_with_bg"Animates text word by word with background highlighting
OUTLINE_ONLY"outline_only"Classic outline: white text with black stroke, no background
SOFT_BOX"soft_box"Soft box: full phrase in semi-transparent rounded box
LOWER_THIRD"lower_third"Lower third: single line with optional bar (broadcast style)
TYPEWRITER"typewriter"Typewriter: characters appear one by one
KARAOKE"karaoke"Karaoke: one word highlighted at a time
KARAOKE_WORD"karaoke-word"Karaoke-word: previous words dim while current stays highlighted
POP_SCALE"pop_scale"Pop / scale: words pop in with a short scale animation

Defined in​

utils/constants.ts:104


CAPTION_STYLE_OPTIONS​

• Const CAPTION_STYLE_OPTIONS: Object

Human-readable options for caption styles. Provides user-friendly labels for caption style selection.

Example

import { CAPTION_STYLE_OPTIONS } from '@twick/timeline';

const options = Object.values(CAPTION_STYLE_OPTIONS);
// Returns array of style options with labels

Type declaration​

NameType
highlight_bg{ label: "Highlight Background" = "Highlight Background"; value: "highlight_bg" = CAPTION_STYLE.WORD_BG_HIGHLIGHT }
highlight_bg.label"Highlight Background"
highlight_bg.value"highlight_bg"
word_by_word{ label: "Word by Word" = "Word by Word"; value: "word_by_word" = CAPTION_STYLE.WORD_BY_WORD }
word_by_word.label"Word by Word"
word_by_word.value"word_by_word"
word_by_word_with_bg{ label: "Word with Background" = "Word with Background"; value: "word_by_word_with_bg" = CAPTION_STYLE.WORD_BY_WORD_WITH_BG }
word_by_word_with_bg.label"Word with Background"
word_by_word_with_bg.value"word_by_word_with_bg"
outline_only{ label: "Classic Outline" = "Classic Outline"; value: "outline_only" = CAPTION_STYLE.OUTLINE_ONLY }
outline_only.label"Classic Outline"
outline_only.value"outline_only"
soft_box{ label: "Soft Box" = "Soft Box"; value: "soft_box" = CAPTION_STYLE.SOFT_BOX }
soft_box.label"Soft Box"
soft_box.value"soft_box"
lower_third{ label: "Lower Third" = "Lower Third"; value: "lower_third" = CAPTION_STYLE.LOWER_THIRD }
lower_third.label"Lower Third"
lower_third.value"lower_third"
typewriter{ label: "Typewriter" = "Typewriter"; value: "typewriter" = CAPTION_STYLE.TYPEWRITER }
typewriter.label"Typewriter"
typewriter.value"typewriter"
karaoke{ label: "Karaoke" = "Karaoke"; value: "karaoke" = CAPTION_STYLE.KARAOKE }
karaoke.label"Karaoke"
karaoke.value"karaoke"
karaoke-word{ label: "Karaoke (Word Fade)" = "Karaoke (Word Fade)"; value: "karaoke-word" = CAPTION_STYLE.KARAOKE_WORD }
karaoke-word.label"Karaoke (Word Fade)"
karaoke-word.value"karaoke-word"
pop_scale{ label: "Pop / Scale" = "Pop / Scale"; value: "pop_scale" = CAPTION_STYLE.POP_SCALE }
pop_scale.label"Pop / Scale"
pop_scale.value"pop_scale"

Defined in​

utils/constants.ts:139


CAPTION_FONT​

• Const CAPTION_FONT: Object

Default font settings for caption elements. Defines the standard typography configuration for captions.

Example

import { CAPTION_FONT } from '@twick/timeline';

const fontSize = CAPTION_FONT.size; // 40

Type declaration​

NameTypeDescription
size40Font size in pixels

Defined in​

utils/constants.ts:193


CAPTION_COLOR​

• Const CAPTION_COLOR: Object

Default color scheme for caption elements. Defines the standard color palette for caption text and backgrounds.

Example

import { CAPTION_COLOR } from '@twick/timeline';

const textColor = CAPTION_COLOR.text; // "#ffffff"
const highlightColor = CAPTION_COLOR.highlight; // "#ff4081"

Type declaration​

NameTypeDescription
text"#ffffff"Text color in hex format
highlight"#ff4081"Highlight color in hex format
bgColor"#8C52FF"Background color in hex format

Defined in​

utils/constants.ts:210


WORDS_PER_PHRASE​

• Const WORDS_PER_PHRASE: 4

Number of words to display per phrase in caption animations. Controls the chunking of text for word-by-word animations.

Example

import { WORDS_PER_PHRASE } from '@twick/timeline';

const phraseLength = WORDS_PER_PHRASE; // 4

Defined in​

utils/constants.ts:230


TIMELINE_ACTION​

• Const TIMELINE_ACTION: Object

Timeline action types for state management. Defines the different actions that can be performed on the timeline.

Example

import { TIMELINE_ACTION } from '@twick/timeline';

if (action.type === TIMELINE_ACTION.SET_PLAYER_STATE) {
// Handle player state change
}

Type declaration​

NameTypeDescription
NONE"none"No action being performed
SET_PLAYER_STATE"setPlayerState"Setting the player state (play/pause)
UPDATE_PLAYER_DATA"updatePlayerData"Updating player data
ON_PLAYER_UPDATED"onPlayerUpdated"Player has been updated

Defined in​

utils/constants.ts:245


TIMELINE_ELEMENT_TYPE​

• Const TIMELINE_ELEMENT_TYPE: Object

Element type constants for timeline elements. Defines the different types of elements that can be added to timeline tracks.

Example

import { TIMELINE_ELEMENT_TYPE } from '@twick/timeline';

if (element.type === TIMELINE_ELEMENT_TYPE.VIDEO) {
// Handle video element
}

Type declaration​

NameTypeDescription
VIDEO"video"Video element type
CAPTION"caption"Caption element type
IMAGE"image"Image element type
AUDIO"audio"Audio element type
TEXT"text"Text element type
RECT"rect"Rectangle element type
CIRCLE"circle"Circle element type
ICON"icon"Icon element type
EMOJI"emoji"Emoji sticker element type
PLACEHOLDER"placeholder"Placeholder element type (e.g. for lazy-loaded media)
LINE"line"Line annotation / shape element type
ARROW"arrow"Arrow annotation element type
EFFECT"effect"Global / adjustment-layer style effect element

Defined in​

utils/constants.ts:269


PROCESS_STATE​

• Const PROCESS_STATE: Object

Process state constants for async operations. Defines the different states of background processing operations.

Example

import { PROCESS_STATE } from '@twick/timeline';

if (processState === PROCESS_STATE.PROCESSING) {
// Show loading indicator
}

Type declaration​

NameTypeDescription
IDLE"Idle"Process is idle
PROCESSING"Processing"Process is currently running
COMPLETED"Completed"Process has completed successfully
FAILED"Failed"Process has failed

Defined in​

utils/constants.ts:311


CURRENT_PROJECT_VERSION​

• Const CURRENT_PROJECT_VERSION: 2

Defined in​

utils/migrations.ts:3


SPLIT_EDGE_BUFFER_SEC​

• Const SPLIT_EDGE_BUFFER_SEC: 0.1

Disallow split when playhead is too close to element edges.

Defined in​

utils/timeline.utils.ts:129