function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = _object_without_properties_loose(source, excluded);
    var key, i;
    if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceSymbolKeys.length; i++){
            key = sourceSymbolKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { ConfigProvider } from "antd";
import classNames from "classnames";
import { motion, useInView } from "framer-motion";
import { isString } from "lodash";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { resolveSegments } from "../TextAnimate";
import { useTypingAnimationStyle } from "./style";
export function TypingAnimation(_param) {
    var children = _param.children, words = _param.words, className = _param.className, _param_duration = _param.duration, duration = _param_duration === void 0 ? 100 : _param_duration, typeSpeed = _param.typeSpeed, deleteSpeed = _param.deleteSpeed, _param_delay = _param.delay, delay = _param_delay === void 0 ? 0 : _param_delay, _param_pauseDelay = _param.pauseDelay, pauseDelay = _param_pauseDelay === void 0 ? 1000 : _param_pauseDelay, _param_loop = _param.loop, loop = _param_loop === void 0 ? false : _param_loop, tmp = _param.as, Component = tmp === void 0 ? 'span' : tmp, _param_startOnView = _param.startOnView, startOnView = _param_startOnView === void 0 ? true : _param_startOnView, _param_showCursor = _param.showCursor, showCursor = _param_showCursor === void 0 ? true : _param_showCursor, _param_blinkCursor = _param.blinkCursor, blinkCursor = _param_blinkCursor === void 0 ? true : _param_blinkCursor, _param_cursorStyle = _param.cursorStyle, cursorStyle = _param_cursorStyle === void 0 ? 'line' : _param_cursorStyle, props = _object_without_properties(_param, [
        "children",
        "words",
        "className",
        "duration",
        "typeSpeed",
        "deleteSpeed",
        "delay",
        "pauseDelay",
        "loop",
        "as",
        "startOnView",
        "showCursor",
        "blinkCursor",
        "cursorStyle"
    ]);
    var MotionComponent = motion(Component, {
        forwardMotionProps: true
    });
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('typing-animation');
    var _useTypingAnimationStyle = useTypingAnimationStyle(prefixCls), wrapSSR = _useTypingAnimationStyle.wrapSSR, hashId = _useTypingAnimationStyle.hashId;
    var _useState = _sliced_to_array(useState([]), 2), displayedText = _useState[0], setDisplayedText = _useState[1];
    var _useState1 = _sliced_to_array(useState(0), 2), currentWordIndex = _useState1[0], setCurrentWordIndex = _useState1[1];
    var _useState2 = _sliced_to_array(useState(0), 2), currentCharIndex = _useState2[0], setCurrentCharIndex = _useState2[1];
    var _useState3 = _sliced_to_array(useState('typing'), 2), phase = _useState3[0], setPhase = _useState3[1];
    var elementRef = useRef(null);
    var isInView = useInView(elementRef, {
        amount: 0.3,
        once: true
    });
    var wordsToAnimate = useMemo(function() {
        return words || [
            resolveSegments(children, 'character')
        ];
    }, [
        words,
        children
    ]);
    var hasMultipleWords = wordsToAnimate.length > 1;
    var typingSpeed = typeSpeed || duration;
    var deletingSpeed = deleteSpeed || typingSpeed / 2;
    var shouldStart = startOnView ? isInView : true;
    useEffect(function() {
        if (!shouldStart || wordsToAnimate.length === 0) return;
        var timeoutDelay = delay > 0 && displayedText.length === 0 ? delay : phase === 'typing' ? typingSpeed : phase === 'deleting' ? deletingSpeed : pauseDelay;
        var timeout = setTimeout(function() {
            var currentWord = wordsToAnimate[currentWordIndex] || '';
            var graphemes = isString(currentWord) ? Array.from(currentWord) : currentWord;
            switch(phase){
                case 'typing':
                    if (currentCharIndex < graphemes.length) {
                        setDisplayedText(graphemes.slice(0, currentCharIndex + 1));
                        setCurrentCharIndex(currentCharIndex + 1);
                    } else {
                        if (hasMultipleWords || loop) {
                            var isLastWord = currentWordIndex === wordsToAnimate.length - 1;
                            if (!isLastWord || loop) {
                                setPhase('pause');
                            }
                        }
                    }
                    break;
                case 'pause':
                    setPhase('deleting');
                    break;
                case 'deleting':
                    if (currentCharIndex > 0) {
                        setDisplayedText(graphemes.slice(0, currentCharIndex - 1));
                        setCurrentCharIndex(currentCharIndex - 1);
                    } else {
                        var nextIndex = (currentWordIndex + 1) % wordsToAnimate.length;
                        setCurrentWordIndex(nextIndex);
                        setPhase('typing');
                    }
                    break;
            }
        }, timeoutDelay);
        return function() {
            return clearTimeout(timeout);
        };
    }, [
        shouldStart,
        phase,
        currentCharIndex,
        currentWordIndex,
        displayedText,
        wordsToAnimate,
        hasMultipleWords,
        loop,
        typingSpeed,
        deletingSpeed,
        pauseDelay,
        delay
    ]);
    var currentWordGraphemes = isString(wordsToAnimate[currentWordIndex]) ? Array.from(wordsToAnimate[currentWordIndex]) : [
        wordsToAnimate[currentWordIndex]
    ];
    var isComplete = !loop && currentWordIndex === wordsToAnimate.length - 1 && currentCharIndex >= currentWordGraphemes.length && phase !== 'deleting';
    var shouldShowCursor = showCursor && !isComplete && (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length);
    var getCursorChar = function() {
        switch(cursorStyle){
            case 'block':
                return '▌';
            case 'underscore':
                return '_';
            case 'line':
            default:
                return '|';
        }
    };
    return wrapSSR(/*#__PURE__*/ React.createElement(MotionComponent, _object_spread({
        ref: elementRef,
        className: classNames(prefixCls, hashId, className)
    }, props), displayedText, shouldShowCursor && /*#__PURE__*/ React.createElement("span", {
        className: classNames("".concat(prefixCls, "-cursor"), hashId, blinkCursor && "".concat(prefixCls, "-cursor-blinking"))
    }, getCursorChar())));
}
