@twick/timeline - v0.15.0
Table of contents
Interfaces
- TimelineProviderProps
- SplitResult
- ElementVisitor
- Position
- Size
- Frame
- ElementTransitionJSON
- ElementJSON
- TrackJSON
- ProjectJSON
- ChapterMarker
- ProjectMetadata
- WatermarkJSON
- BaseMediaProps
- VideoProps
- AudioProps
- ImageProps
- TextProps
- RectProps
- CircleProps
- IconProps
- ArrowProps
- LineProps
- TextEffect
- FrameEffectProps
- FrameEffect
- EffectProps
- Animation
- SnapResult
Classes
- ElementAnimation
- ElementFrameEffect
- ElementTextEffect
- Watermark
- TimelineEditor
- ArrowElement
- AudioElement
- TrackElement
- CaptionElement
- CircleElement
- EffectElement
- IconElement
- ImageElement
- LineElement
- PlaceholderElement
- RectElement
- TextElement
- VideoElement
- Track
- ElementAdder
- ElementCloner
- ElementDeserializer
- ElementRemover
- ElementSerializer
- ElementSplitter
- ElementUpdater
- ValidationError
- ElementValidator
Functions
- TimelineProvider
- useTimelineContext
- getCaptionElements
- getCaptionLanguages
- exportCaptionsAsSRT
- exportCaptionsAsVTT
- getChapterMarkers
- exportChaptersAsYouTube
- exportChaptersAsJSON
- migrateProject
- resolveId
- resolveIds
- getElementIdsInRange
- snapTime
- pxToSecThreshold
- formatTimeWithFrames
- formatTimeSimple
- getDecimalNumber
- getTotalDuration
- generateShortUuid
- getCurrentElements
- canSplitElement
- isElementId
- isTrackId
- extractVideoAudio
Type Aliases
Variables
- VALIDATION_ERROR_CODE
- TRACK_TYPES
- INITIAL_TIMELINE_DATA
- PLAYER_STATE
- CAPTION_STYLE
- CAPTION_STYLE_OPTIONS
- CAPTION_FONT
- CAPTION_COLOR
- WORDS_PER_PHRASE
- TIMELINE_ACTION
- TIMELINE_ELEMENT_TYPE
- PROCESS_STATE
- CURRENT_PROJECT_VERSION
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
| Name | Type | Description |
|---|---|---|
props | TimelineProviderProps | Timeline 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 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
| Name | Type |
|---|---|
project | ProjectJSON |
language? | string |
Returns
CaptionLike[]
Defined in
getCaptionLanguages
▸ getCaptionLanguages(project): string[]
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
Returns
string[]
Defined in
exportCaptionsAsSRT
▸ exportCaptionsAsSRT(project, language?): string
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
language? | string |
Returns
string
Defined in
exportCaptionsAsVTT
▸ exportCaptionsAsVTT(project, language?): string
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
language? | string |
Returns
string
Defined in
getChapterMarkers
▸ getChapterMarkers(project): ChapterMarker[]
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
Returns
Defined in
exportChaptersAsYouTube
▸ exportChaptersAsYouTube(project): string
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
Returns
string
Defined in
exportChaptersAsJSON
▸ exportChaptersAsJSON(project): string
Parameters
| Name | Type |
|---|---|
project | ProjectJSON |
Returns
string
Defined in
migrateProject
▸ migrateProject(project, targetVersion?): ProjectJSON
Parameters
| Name | Type | Default value |
|---|---|---|
project | ProjectJSON | undefined |
targetVersion | number | CURRENT_PROJECT_VERSION |
Returns
Defined in
resolveId
▸ resolveId(id, tracks): Track | TrackElement | null
Resolve a single ID to Track | TrackElement | null
Parameters
| Name | Type |
|---|---|
id | string |
tracks | Track[] |
Returns
Track | TrackElement | null
Defined in
resolveIds
▸ resolveIds(ids, tracks): (Track | TrackElement)[]
Resolve multiple IDs to (Track | TrackElement)[]
Parameters
| Name | Type |
|---|---|
ids | Set<string> |
tracks | Track[] |
Returns
(Track | TrackElement)[]
Defined in
getElementIdsInRange
▸ getElementIdsInRange(track, fromElementId, toElementId): string[]
Get all element IDs in a track between two elements (inclusive). Used for Shift+click range selection.
Parameters
| Name | Type |
|---|---|
track | Track |
fromElementId | string |
toElementId | string |
Returns
string[]
Defined in
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
| Name | Type | Default value | Description |
|---|---|---|---|
time | number | undefined | The candidate time in seconds |
targets | number[] | undefined | Array of snap target times in seconds |
thresholdSec | number | 0.1 | Maximum distance (in seconds) to snap. Default 0.1. |
Returns
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
pxToSecThreshold
▸ pxToSecThreshold(thresholdPx, pixelsPerSecond): number
Converts a snap threshold from pixels to seconds.
Parameters
| Name | Type | Description |
|---|---|---|
thresholdPx | number | Distance in pixels |
pixelsPerSecond | number | Timeline zoom (px per second) |
Returns
number
Threshold in seconds
Defined in
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
| Name | Type | Default value | Description |
|---|---|---|---|
timeSeconds | number | undefined | Time in seconds (can be fractional) |
fps | number | 30 | Frames 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
formatTimeSimple
▸ formatTimeSimple(timeSeconds): string
Formats time in seconds to MM:SS (minutes:seconds, no frames).
Parameters
| Name | Type | Description |
|---|---|---|
timeSeconds | number | Time in seconds |
Returns
string
Formatted string e.g. "01:23"
Example
formatTimeSimple(65.5) // "01:05"
Defined in
getDecimalNumber
▸ getDecimalNumber(num, precision?): number
Rounds a number to a specified decimal precision. Useful for ensuring consistent decimal places in timeline calculations.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
num | number | undefined | The number to round |
precision | number | 3 | The number of decimal places to round to |
Returns
number
The rounded number
Example
const rounded = getDecimalNumber(3.14159, 2);
// rounded = 3.14
Defined in
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
| Name | Type | Description |
|---|---|---|
tracks | TrackJSON[] | 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
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
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
| Name | Type | Description |
|---|---|---|
currentTime | number | The current playback time in seconds |
tracks | Track[] | 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
canSplitElement
▸ canSplitElement(element, currentTime): boolean
Checks if an element can be split at the specified time. Determines if the current time falls within the element's start and end time range.
Parameters
| Name | Type | Description |
|---|---|---|
element | TrackElement | The element to check for splitting |
currentTime | number | The time at which to check if splitting is possible |
Returns
boolean
True if the element can be split at the specified time
Example
const canSplit = canSplitElement(videoElement, 10.5);
// canSplit = true if element spans across 10.5 seconds
Defined in
isElementId
▸ isElementId(id): boolean
Checks if an ID represents an element. Validates if the ID follows the element naming convention.
Parameters
| Name | Type | Description |
|---|---|---|
id | string | The ID to check |
Returns
boolean
True if the ID represents an element
Example
const isElement = isElementId("e-abc123");
// isElement = true
Defined in
isTrackId
▸ isTrackId(id): boolean
Checks if an ID represents a track. Validates if the ID follows the track naming convention.
Parameters
| Name | Type | Description |
|---|---|---|
id | string | The ID to check |
Returns
boolean
True if the ID represents a track
Example
const isTrack = isTrackId("t-xyz789");
// isTrack = true
Defined in
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
| Name | Type | Description |
|---|---|---|
tracks | Track[] | Array of track objects containing video elements |
duration | number | The 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
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
| Name | Type | Description |
|---|---|---|
contextId | string | Unique identifier for this timeline context |
editor | TimelineEditor | The timeline editor instance for this context |
selectedItem | Track | TrackElement | null | Currently selected track or element (primary selection, for backward compat) |
selectedIds | Set<string> | Set of selected IDs (tracks and elements) for multi-select |
changeLog | number | Change counter for tracking modifications |
timelineAction | { type: string ; payload: any } | Current timeline action being performed |
timelineAction.type | string | - |
timelineAction.payload | any | - |
videoResolution | Size | Resolution of the video |
totalDuration | number | Total duration of the timeline in seconds |
present | ProjectJSON | null | Current project state |
canUndo | boolean | Whether undo operation is available |
canRedo | boolean | Whether 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 | - |
followPlayheadEnabled | boolean | Whether 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:32
ElementMetadata
Ƭ ElementMetadata: Record<string, unknown>
Defined in
ObjectFit
Ƭ ObjectFit: "contain" | "cover" | "fill" | "none" | "scale-down"
Defined in
TextAlign
Ƭ TextAlign: "left" | "center" | "right" | "justify"
Defined in
TrackType
Ƭ TrackType: typeof TRACK_TYPES[keyof typeof TRACK_TYPES]
Union type of valid track type strings
Defined in
Variables
VALIDATION_ERROR_CODE
• Const VALIDATION_ERROR_CODE: Object
Type declaration
| Name | Type |
|---|---|
ELEMENT_NOT_FOUND | string |
ELEMENT_NOT_ADDED | string |
ELEMENT_NOT_UPDATED | string |
ELEMENT_NOT_REMOVED | string |
COLLISION_ERROR | string |
INVALID_TIMING | string |
Defined in
core/visitor/element-validator.ts:15
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
| Name | Type | Description |
|---|---|---|
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
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
| Name | Type |
|---|---|
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" } }[] }[] |
version | number |
Defined in
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
| Name | Type | Description |
|---|---|---|
REFRESH | "Refresh" | Player is refreshing/reloading content |
PLAYING | "Playing" | Player is actively playing content |
PAUSED | "Paused" | Player is paused |
Defined in
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
| Name | Type | Description |
|---|---|---|
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 |
POP_SCALE | "pop_scale" | Pop / scale: words pop in with a short scale animation |
Defined in
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
| Name | Type |
|---|---|
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" |
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
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
| Name | Type | Description |
|---|---|---|
size | 40 | Font size in pixels |
Defined in
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
| Name | Type | Description |
|---|---|---|
text | "#ffffff" | Text color in hex format |
highlight | "#ff4081" | Highlight color in hex format |
bgColor | "#8C52FF" | Background color in hex format |
Defined in
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
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
| Name | Type | Description |
|---|---|---|
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
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
| Name | Type | Description |
|---|---|---|
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 |
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
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
| Name | Type | Description |
|---|---|---|
IDLE | "Idle" | Process is idle |
PROCESSING | "Processing" | Process is currently running |
COMPLETED | "Completed" | Process has completed successfully |
FAILED | "Failed" | Process has failed |
Defined in
CURRENT_PROJECT_VERSION
• Const CURRENT_PROJECT_VERSION: 2