UNPKG

@atlaskit/editor-plugin-placeholder

Version:

Placeholder plugin for @atlaskit/editor-core.

58 lines 3.06 kB
import { TYPEWRITER_CYCLE_DELAY, TYPEWRITER_ERASE_DELAY, TYPEWRITER_PAUSE_BEFORE_ERASE, TYPEWRITER_TYPE_DELAY } from './constants'; export const cycleThroughPlaceholderPrompts = (placeholderPrompts, activeTypewriterTimeouts, placeholderNodeWithText, initialDelayWhenUserTypedAndDeleted = 0, options) => { const prefersReducedMotion = typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (prefersReducedMotion) { var _placeholderPrompts$; placeholderNodeWithText.textContent = (_placeholderPrompts$ = placeholderPrompts[0]) !== null && _placeholderPrompts$ !== void 0 ? _placeholderPrompts$ : ''; return; } let currentPromptIndex = 0; let displayedText = ''; let animationTimeouts = []; const clearAllTimeouts = () => { animationTimeouts.forEach(timeoutId => clearTimeout(timeoutId)); animationTimeouts = []; }; const scheduleTimeout = (callback, delay) => { const timeoutId = setTimeout(callback, delay); animationTimeouts.push(timeoutId); return timeoutId; }; const startAnimationCycle = () => { var _options$eraseDelay, _options$pauseBeforeE; const currentPrompt = placeholderPrompts[currentPromptIndex]; const eraseDelay = (_options$eraseDelay = options === null || options === void 0 ? void 0 : options.eraseDelay) !== null && _options$eraseDelay !== void 0 ? _options$eraseDelay : TYPEWRITER_ERASE_DELAY; const pauseBeforeErase = (_options$pauseBeforeE = options === null || options === void 0 ? void 0 : options.pauseBeforeErase) !== null && _options$pauseBeforeE !== void 0 ? _options$pauseBeforeE : TYPEWRITER_PAUSE_BEFORE_ERASE; let characterIndex = 0; const typeNextCharacter = () => { if (characterIndex < currentPrompt.length) { displayedText = currentPrompt.substring(0, characterIndex + 1); placeholderNodeWithText.textContent = displayedText; characterIndex++; scheduleTimeout(typeNextCharacter, TYPEWRITER_TYPE_DELAY); } else { scheduleTimeout(eraseLastCharacter, pauseBeforeErase); } }; const eraseLastCharacter = () => { if (displayedText.length > 1) { displayedText = displayedText.substring(0, displayedText.length - 1); placeholderNodeWithText.textContent = displayedText; scheduleTimeout(eraseLastCharacter, eraseDelay); } else { displayedText = ' '; placeholderNodeWithText.textContent = displayedText; currentPromptIndex = (currentPromptIndex + 1) % placeholderPrompts.length; scheduleTimeout(startAnimationCycle, TYPEWRITER_CYCLE_DELAY); } }; typeNextCharacter(); }; activeTypewriterTimeouts === null || activeTypewriterTimeouts === void 0 ? void 0 : activeTypewriterTimeouts.push(clearAllTimeouts); if (initialDelayWhenUserTypedAndDeleted > 0) { placeholderNodeWithText.textContent = ' '; scheduleTimeout(startAnimationCycle, initialDelayWhenUserTypedAndDeleted); } else { startAnimationCycle(); } };