UNPKG

typeit-react

Version:

React component for the most versatile JavaScript animated typing utility on the planet.

1,261 lines 57.9 kB
var __defProp = Object.defineProperty; var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var _TypeIt_instances, empty_fn, fire_fn, move_fn, prepLoop_fn, fireItemWithContext_fn, wait_fn, attachCursor_fn, elementIsInput_fn, queueAndReturn_fn, maybeAppendPause_fn, generateTemporaryOptionQueueItems_fn, updateOptions_fn, generateQueue_fn, _buildOptions, prependHardcodedStrings_fn, setUpCursor_fn, addSplitPause_fn, type_fn, delete_fn, removeNode_fn, getPace_fn, derivedCursorPosition_get, isInput_get, shouldRenderCursor_get, allChars_get, _a; import require$$0, { forwardRef, useRef, useState, useEffect } from "react"; var jsxRuntime = { exports: {} }; var reactJsxRuntime_production = {}; /** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReactJsxRuntime_production; function requireReactJsxRuntime_production() { if (hasRequiredReactJsxRuntime_production) return reactJsxRuntime_production; hasRequiredReactJsxRuntime_production = 1; var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); function jsxProd(type, config, maybeKey) { var key = null; void 0 !== maybeKey && (key = "" + maybeKey); void 0 !== config.key && (key = "" + config.key); if ("key" in config) { maybeKey = {}; for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]); } else maybeKey = config; config = maybeKey.ref; return { $$typeof: REACT_ELEMENT_TYPE, type, key, ref: void 0 !== config ? config : null, props: maybeKey }; } reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE; reactJsxRuntime_production.jsx = jsxProd; reactJsxRuntime_production.jsxs = jsxProd; return reactJsxRuntime_production; } var reactJsxRuntime_development = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReactJsxRuntime_development; function requireReactJsxRuntime_development() { if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development; hasRequiredReactJsxRuntime_development = 1; "production" !== process.env.NODE_ENV && function() { function getComponentNameFromType(type) { if (null == type) return null; if ("function" === typeof type) return type.$$typeof === REACT_CLIENT_REFERENCE$2 ? null : type.displayName || type.name || null; if ("string" === typeof type) return type; switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if ("object" === typeof type) switch ("number" === typeof type.tag && console.error( "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." ), type.$$typeof) { case REACT_CONTEXT_TYPE: return (type.displayName || "Context") + ".Provider"; case REACT_CONSUMER_TYPE: return (type._context.displayName || "Context") + ".Consumer"; case REACT_FORWARD_REF_TYPE: var innerType = type.render; type = type.displayName; type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"); return type; case REACT_MEMO_TYPE: return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo"; case REACT_LAZY_TYPE: innerType = type._payload; type = type._init; try { return getComponentNameFromType(type(innerType)); } catch (x) { } } return null; } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { try { testStringCoercion(value); var JSCompiler_inline_result = false; } catch (e) { JSCompiler_inline_result = true; } if (JSCompiler_inline_result) { JSCompiler_inline_result = console; var JSCompiler_temp_const = JSCompiler_inline_result.error; var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; JSCompiler_temp_const.call( JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0 ); return testStringCoercion(value); } } function disabledLog() { } function disableLogs() { if (0 === disabledDepth) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } function reenableLogs() { disabledDepth--; if (0 === disabledDepth) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } 0 > disabledDepth && console.error( "disabledDepth fell below zero. This is a bug in React. Please file an issue." ); } function describeBuiltInComponentFrame(name) { if (void 0 === prefix) try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; suffix = -1 < x.stack.indexOf("\n at") ? " (<anonymous>)" : -1 < x.stack.indexOf("@") ? "@unknown:0:0" : ""; } return "\n" + prefix + name + suffix; } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) return ""; var frame = componentFrameCache.get(fn); if (void 0 !== frame) return frame; reentry = true; frame = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher = null; previousDispatcher = ReactSharedInternals.H; ReactSharedInternals.H = null; disableLogs(); try { var RunInRootFrame = { DetermineComponentFrameRoot: function() { try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if ("object" === typeof Reflect && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { var control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x$0) { control = x$0; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x$1) { control = x$1; } (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() { }); } } catch (sample) { if (sample && control && "string" === typeof sample.stack) return [sample.stack, control.stack]; } return [null, null]; } }; RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot"; var namePropDescriptor = Object.getOwnPropertyDescriptor( RunInRootFrame.DetermineComponentFrameRoot, "name" ); namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty( RunInRootFrame.DetermineComponentFrameRoot, "name", { value: "DetermineComponentFrameRoot" } ); var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1]; if (sampleStack && controlStack) { var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n"); for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes( "DetermineComponentFrameRoot" ); ) namePropDescriptor++; for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes( "DetermineComponentFrameRoot" ); ) _RunInRootFrame$Deter++; if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length) for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; ) _RunInRootFrame$Deter--; for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--) if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) { if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) { do if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) { var _frame = "\n" + sampleLines[namePropDescriptor].replace( " at new ", " at " ); fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName)); "function" === typeof fn && componentFrameCache.set(fn, _frame); return _frame; } while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter); } break; } } } finally { reentry = false, ReactSharedInternals.H = previousDispatcher, reenableLogs(), Error.prepareStackTrace = frame; } sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : ""; "function" === typeof fn && componentFrameCache.set(fn, sampleLines); return sampleLines; } function describeUnknownElementTypeFrameInDEV(type) { if (null == type) return ""; if ("function" === typeof type) { var prototype = type.prototype; return describeNativeComponentFrame( type, !(!prototype || !prototype.isReactComponent) ); } if ("string" === typeof type) return describeBuiltInComponentFrame(type); switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if ("object" === typeof type) switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return type = describeNativeComponentFrame(type.render, false), type; case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type.type); case REACT_LAZY_TYPE: prototype = type._payload; type = type._init; try { return describeUnknownElementTypeFrameInDEV(type(prototype)); } catch (x) { } } return ""; } function getOwner() { var dispatcher = ReactSharedInternals.A; return null === dispatcher ? null : dispatcher.getOwner(); } function hasValidKey(config) { if (hasOwnProperty.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) return false; } return void 0 !== config.key; } function defineKeyPropWarningGetter(props, displayName) { function warnAboutAccessingKey() { specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error( "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName )); } warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } function elementRefGetterWithDeprecationWarning() { var componentName = getComponentNameFromType(this.type); didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error( "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." )); componentName = this.props.ref; return void 0 !== componentName ? componentName : null; } function ReactElement(type, key, self, source, owner, props) { self = props.ref; type = { $$typeof: REACT_ELEMENT_TYPE, type, key, props, _owner: owner }; null !== (void 0 !== self ? self : null) ? Object.defineProperty(type, "ref", { enumerable: false, get: elementRefGetterWithDeprecationWarning }) : Object.defineProperty(type, "ref", { enumerable: false, value: null }); type._store = {}; Object.defineProperty(type._store, "validated", { configurable: false, enumerable: false, writable: true, value: 0 }); Object.defineProperty(type, "_debugInfo", { configurable: false, enumerable: false, writable: true, value: null }); Object.freeze && (Object.freeze(type.props), Object.freeze(type)); return type; } function jsxDEVImpl(type, config, maybeKey, isStaticChildren, source, self) { if ("string" === typeof type || "function" === typeof type || type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_OFFSCREEN_TYPE || "object" === typeof type && null !== type && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_CONSUMER_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_CLIENT_REFERENCE$1 || void 0 !== type.getModuleId)) { var children = config.children; if (void 0 !== children) if (isStaticChildren) if (isArrayImpl(children)) { for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++) validateChildKeys(children[isStaticChildren], type); Object.freeze && Object.freeze(children); } else console.error( "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." ); else validateChildKeys(children, type); } else { children = ""; if (void 0 === type || "object" === typeof type && null !== type && 0 === Object.keys(type).length) children += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; null === type ? isStaticChildren = "null" : isArrayImpl(type) ? isStaticChildren = "array" : void 0 !== type && type.$$typeof === REACT_ELEMENT_TYPE ? (isStaticChildren = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />", children = " Did you accidentally export a JSX literal instead of a component?") : isStaticChildren = typeof type; console.error( "React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", isStaticChildren, children ); } if (hasOwnProperty.call(config, "key")) { children = getComponentNameFromType(type); var keys = Object.keys(config).filter(function(k) { return "key" !== k; }); isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}"; didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error( 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', isStaticChildren, children, keys, children ), didWarnAboutKeySpread[children + isStaticChildren] = true); } children = null; void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey); hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key); if ("key" in config) { maybeKey = {}; for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]); } else maybeKey = config; children && defineKeyPropWarningGetter( maybeKey, "function" === typeof type ? type.displayName || type.name || "Unknown" : type ); return ReactElement(type, children, self, source, getOwner(), maybeKey); } function validateChildKeys(node, parentType) { if ("object" === typeof node && node && node.$$typeof !== REACT_CLIENT_REFERENCE) { if (isArrayImpl(node)) for (var i = 0; i < node.length; i++) { var child = node[i]; isValidElement(child) && validateExplicitKey(child, parentType); } else if (isValidElement(node)) node._store && (node._store.validated = 1); else if (null === node || "object" !== typeof node ? i = null : (i = MAYBE_ITERATOR_SYMBOL && node[MAYBE_ITERATOR_SYMBOL] || node["@@iterator"], i = "function" === typeof i ? i : null), "function" === typeof i && i !== node.entries && (i = i.call(node), i !== node)) for (; !(node = i.next()).done; ) isValidElement(node.value) && validateExplicitKey(node.value, parentType); } } function isValidElement(object) { return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; } function validateExplicitKey(element, parentType) { if (element._store && !element._store.validated && null == element.key && (element._store.validated = 1, parentType = getCurrentComponentErrorInfo(parentType), !ownerHasKeyUseWarning[parentType])) { ownerHasKeyUseWarning[parentType] = true; var childOwner = ""; element && null != element._owner && element._owner !== getOwner() && (childOwner = null, "number" === typeof element._owner.tag ? childOwner = getComponentNameFromType(element._owner.type) : "string" === typeof element._owner.name && (childOwner = element._owner.name), childOwner = " It was passed a child from " + childOwner + "."); var prevGetCurrentStack = ReactSharedInternals.getCurrentStack; ReactSharedInternals.getCurrentStack = function() { var stack = describeUnknownElementTypeFrameInDEV(element.type); prevGetCurrentStack && (stack += prevGetCurrentStack() || ""); return stack; }; console.error( 'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.', parentType, childOwner ); ReactSharedInternals.getCurrentStack = prevGetCurrentStack; } } function getCurrentComponentErrorInfo(parentType) { var info = "", owner = getOwner(); owner && (owner = getComponentNameFromType(owner.type)) && (info = "\n\nCheck the render method of `" + owner + "`."); info || (parentType = getComponentNameFromType(parentType)) && (info = "\n\nCheck the top-level render call using <" + parentType + ">."); return info; } var React = require$$0, REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE$2 = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, assign = Object.assign, REACT_CLIENT_REFERENCE$1 = Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd; disabledLog.__reactDisabledLog = true; var prefix, suffix, reentry = false; var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)(); var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), specialPropKeyWarningShown; var didWarnAboutElementRef = {}; var didWarnAboutKeySpread = {}, ownerHasKeyUseWarning = {}; reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE; reactJsxRuntime_development.jsx = function(type, config, maybeKey, source, self) { return jsxDEVImpl(type, config, maybeKey, false, source, self); }; reactJsxRuntime_development.jsxs = function(type, config, maybeKey, source, self) { return jsxDEVImpl(type, config, maybeKey, true, source, self); }; }(); return reactJsxRuntime_development; } var hasRequiredJsxRuntime; function requireJsxRuntime() { if (hasRequiredJsxRuntime) return jsxRuntime.exports; hasRequiredJsxRuntime = 1; if (process.env.NODE_ENV === "production") { jsxRuntime.exports = requireReactJsxRuntime_production(); } else { jsxRuntime.exports = requireReactJsxRuntime_development(); } return jsxRuntime.exports; } var jsxRuntimeExports = requireJsxRuntime(); const isArray = (thing) => Array.isArray(thing); const asArray = (value) => isArray(value) ? value : [value]; let Queue = function(initialItems) { let add = function(steps) { asArray(steps).forEach((step) => { var _a2; return _q.set(Symbol((_a2 = step.char) == null ? void 0 : _a2.innerText), buildQueueItem({ ...step })); }); return this; }; let getTypeable = () => rawValues().filter((value) => value.typeable); let set = function(index, item) { let keys = [..._q.keys()]; _q.set(keys[index], buildQueueItem(item)); }; let buildQueueItem = (queueItem) => { queueItem.shouldPauseCursor = function() { return Boolean(this.typeable || this.cursorable || this.deletable); }; return queueItem; }; let reset = function() { _q.forEach((item) => delete item.done); }; let wipe = function() { _q = /* @__PURE__ */ new Map(); add(initialItems); }; let getQueue = () => _q; let rawValues = () => Array.from(_q.values()); let destroy = (key) => _q.delete(key); let getPendingQueueItems = () => { const pending = []; for (let [, value] of getQueue()) { if (!value.done) { pending.push(value); } } return pending; }; let getItems = (all = false) => all ? rawValues() : rawValues().filter((i) => !i.done); let done = (key, shouldDestroy = false) => shouldDestroy ? _q.delete(key) : _q.get(key).done = true; let _q = /* @__PURE__ */ new Map(); add(initialItems); return { add, set, wipe, done, reset, destroy, getItems, getQueue, getTypeable, getPendingQueueItems }; }; const DATA_ATTRIBUTE = "data-typeit-id"; const CURSOR_CLASS = "ti-cursor"; const END = "END"; const DEFAULT_STATUSES = { started: false, completed: false, frozen: false, destroyed: false }; const DEFAULT_OPTIONS = { breakLines: true, cursor: { autoPause: true, autoPauseDelay: 500, animation: { frames: [0, 0, 1].map((n) => { return { opacity: n }; }), options: { iterations: Infinity, easing: "steps(2, start)", fill: "forwards" } } }, cursorChar: "|", cursorSpeed: 1e3, deleteSpeed: null, html: true, lifeLike: true, loop: false, loopDelay: 750, nextStringDelay: 750, speed: 100, startDelay: 250, startDelete: false, strings: [], waitUntilVisible: false, beforeString: () => { }, afterString: () => { }, beforeStep: () => { }, afterStep: () => { }, afterComplete: () => { } }; const PLACEHOLDER_CSS = `[${DATA_ATTRIBUTE}]:before {content: '.'; display: inline-block; width: 0; visibility: hidden;}`; const createElement = (el) => document.createElement(el); const createTextNode = (content) => document.createTextNode(content); const appendStyleBlock = (styles, id = "") => { let styleBlock = createElement("style"); styleBlock.id = id; styleBlock.appendChild(createTextNode(styles)); document.head.appendChild(styleBlock); }; const calculateDelay = (delayArg) => { if (!isArray(delayArg)) { delayArg = [delayArg / 2, delayArg / 2]; } return delayArg; }; const randomInRange = (value, range2) => { return Math.abs( Math.random() * (value + range2 - (value - range2)) + (value - range2) ); }; let range = (val) => val / 2; function calculatePace(options) { let { speed, deleteSpeed, lifeLike } = options; deleteSpeed = deleteSpeed !== null ? deleteSpeed : speed / 3; return lifeLike ? [ randomInRange(speed, range(speed)), randomInRange(deleteSpeed, range(deleteSpeed)) ] : [speed, deleteSpeed]; } const toArray = (val) => Array.from(val); let expandTextNodes = (element) => { [...element.childNodes].forEach((child) => { if (child.nodeValue) { [...child.nodeValue].forEach((c) => { child.parentNode.insertBefore(createTextNode(c), child); }); child.remove(); return; } expandTextNodes(child); }); return element; }; const getParsedBody = (content) => { let doc = document.implementation.createHTMLDocument(); doc.body.innerHTML = content; return expandTextNodes(doc.body); }; function walkElementNodes(element, shouldReverse = false, shouldIncludeCursor = false) { let cursor = element.querySelector(`.${CURSOR_CLASS}`); let walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL, { acceptNode: (node) => { var _a2, _b; if (cursor && shouldIncludeCursor) { if ((_a2 = node.classList) == null ? void 0 : _a2.contains(CURSOR_CLASS)) { return NodeFilter.FILTER_ACCEPT; } if (cursor.contains(node)) { return NodeFilter.FILTER_REJECT; } } return ((_b = node.classList) == null ? void 0 : _b.contains(CURSOR_CLASS)) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT; } }); let nextNode; let nodes = []; while (nextNode = walker.nextNode()) { if (!nextNode.originalParent) { nextNode.originalParent = nextNode.parentNode; } nodes.push(nextNode); } return shouldReverse ? nodes.reverse() : nodes; } function chunkStringAsHtml(string) { return walkElementNodes(getParsedBody(string)); } function maybeChunkStringAsHtml(str, asHtml = true) { return asHtml ? chunkStringAsHtml(str) : toArray(str).map(createTextNode); } const cleanUpSkipped = ({ index, newIndex, queueItems, cleanUp }) => { for (let i = index + 1; i < newIndex + 1; i++) { cleanUp(queueItems[i][0]); } }; const isNumber = (value) => Number.isInteger(value); const countStepsToSelector = ({ queueItems, selector, cursorPosition, to }) => { if (isNumber(selector)) { return selector * -1; } let isMovingToEnd = new RegExp(END, "i").test(to); let selectorIndex = selector ? [...queueItems].reverse().findIndex(({ char }) => { let parentElement = char.parentElement; let parentMatches = parentElement.matches(selector); if (isMovingToEnd && parentMatches) { return true; } return parentMatches && parentElement.firstChild.isSameNode(char); }) : -1; if (selectorIndex < 0) { selectorIndex = isMovingToEnd ? 0 : queueItems.length - 1; } let offset = isMovingToEnd ? 0 : 1; return selectorIndex - cursorPosition + offset; }; const destroyTimeouts = (timeouts) => { timeouts.forEach(clearTimeout); return []; }; const duplicate = (value, times) => new Array(times).fill(value); let beforePaint = (cb) => { return new Promise((resolve) => { requestAnimationFrame(async () => { resolve(await cb()); }); }); }; let getAnimationFromElement = (element) => { return element == null ? void 0 : element.getAnimations().find((animation) => { return animation.id === element.dataset.tiAnimationId; }); }; let setCursorAnimation = ({ cursor, frames, options }) => { let animation = cursor.animate(frames, options); animation.pause(); animation.id = cursor.dataset.tiAnimationId; beforePaint(() => { beforePaint(() => { animation.play(); }); }); return animation; }; let rebuildCursorAnimation = ({ cursor, options, cursorOptions }) => { if (!cursor || !cursorOptions) return; let animation = getAnimationFromElement(cursor); let oldCurrentTime; if (animation) { options.delay = animation.effect.getComputedTiming().delay; oldCurrentTime = animation.currentTime; animation.cancel(); } let newAnimation = setCursorAnimation({ cursor, frames: cursorOptions.animation.frames, options }); if (oldCurrentTime) { newAnimation.currentTime = oldCurrentTime; } return newAnimation; }; let execute = (queueItem) => { var _a2; return (_a2 = queueItem.func) == null ? void 0 : _a2.call(null); }; let fireItem = async ({ index, queueItems, wait: wait2, cursor, cursorOptions }) => { let queueItem = queueItems[index][1]; let instantQueue = []; let tempIndex = index; let futureItem = queueItem; let shouldBeGrouped = () => futureItem && !futureItem.delay; let shouldPauseCursor = queueItem.shouldPauseCursor() && cursorOptions.autoPause; while (shouldBeGrouped()) { instantQueue.push(futureItem); shouldBeGrouped() && tempIndex++; futureItem = queueItems[tempIndex] ? queueItems[tempIndex][1] : null; } if (instantQueue.length) { await beforePaint(async () => { for (let q of instantQueue) { await execute(q); } }); return tempIndex - 1; } let animation = getAnimationFromElement(cursor); let options; if (animation) { options = { ...animation.effect.getComputedTiming(), delay: shouldPauseCursor ? cursorOptions.autoPauseDelay : 0 }; } await wait2(async () => { if (animation && shouldPauseCursor) { animation.cancel(); } await beforePaint(() => { execute(queueItem); }); }, queueItem.delay); await rebuildCursorAnimation({ cursor, options, cursorOptions }); return index; }; const fireWhenVisible = (element, func) => { let observer = new IntersectionObserver( (entries, observer2) => { entries.forEach((entry) => { if (entry.isIntersecting) { func(); observer2.unobserve(element); } }); }, { threshold: 1 } ); observer.observe(element); }; const generateHash = () => Math.random().toString().substring(2, 9); const isInput = (el) => { return "value" in el; }; let getAllChars = (element) => { if (isInput(element)) { return toArray(element.value); } return walkElementNodes(element, true).filter( (c) => !(c.childNodes.length > 0) ); }; let handleFunctionalArg = (arg) => { return typeof arg === "function" ? arg() : arg; }; let select = (selector, element = document, all = false) => { return element[`querySelector${all ? "All" : ""}`](selector); }; let isBodyElement = (node) => /body/i.test(node == null ? void 0 : node.tagName); let insertIntoElement = (originalTarget, character) => { if (isInput(originalTarget)) { originalTarget.value = `${originalTarget.value}${character.textContent}`; return; } character.innerHTML = ""; let target = isBodyElement(character.originalParent) ? originalTarget : ( // If we add one-off fresh elements, there will be no // "originalParent", so always fall back to the default target. character.originalParent || originalTarget ); let cursorNode = select("." + CURSOR_CLASS, target) || null; if (cursorNode && cursorNode.parentElement !== target) { target = cursorNode.parentElement; } target.insertBefore(character, cursorNode); }; const isNonVoidElement = (el) => /<(.+)>(.*?)<\/(.+)>/.test(el.outerHTML); const merge = (originalObj, newObj) => Object.assign({}, originalObj, newObj); let processCursorOptions = (cursorOptions) => { var _a2, _b; if (typeof cursorOptions === "object") { let newOptions = {}; let { frames: defaultFrames, options: defaultOptions } = DEFAULT_OPTIONS.cursor.animation; newOptions.animation = cursorOptions.animation || {}; newOptions.animation.frames = ((_a2 = cursorOptions.animation) == null ? void 0 : _a2.frames) || defaultFrames; newOptions.animation.options = merge( defaultOptions, ((_b = cursorOptions.animation) == null ? void 0 : _b.options) || {} ); newOptions.autoPause = cursorOptions.autoPause ?? DEFAULT_OPTIONS.cursor.autoPause; newOptions.autoPauseDelay = cursorOptions.autoPauseDelay || DEFAULT_OPTIONS.cursor.autoPauseDelay; return newOptions; } if (cursorOptions === true) { return DEFAULT_OPTIONS.cursor; } return cursorOptions; }; const removeNode = (node, rootElement) => { if (!node) return; let nodeParent = node.parentNode; let nodeToRemove = nodeParent.childNodes.length > 1 || nodeParent.isSameNode(rootElement) ? ( // This parent still needs to exist. node ) : ( // There's nothing else in there, so just delete the entire thing. // By doing this, we clean up markup as we go along. nodeParent ); nodeToRemove.remove(); }; const repositionCursor = (element, allChars, newCursorPosition) => { let nodeToInsertBefore = allChars[newCursorPosition - 1]; let cursor = select(`.${CURSOR_CLASS}`, element); element = (nodeToInsertBefore == null ? void 0 : nodeToInsertBefore.parentNode) || element; element.insertBefore(cursor, nodeToInsertBefore || null); }; function selectorToElement(thing) { return typeof thing === "string" ? select(thing) : thing; } let cursorFontStyles = { "font-family": "", "font-weight": "", "font-size": "", "font-style": "", "line-height": "", color: "", transform: "translateX(-.125em)" }; let setCursorStyles = (id, element) => { let rootSelector = `[${DATA_ATTRIBUTE}='${id}']`; let cursorSelector = `${rootSelector} .${CURSOR_CLASS}`; let computedStyles = getComputedStyle(element); let customProperties = Object.entries(cursorFontStyles).reduce( (accumulator, [item, value]) => { return `${accumulator} ${item}: var(--ti-cursor-${item}, ${value || computedStyles[item]});`; }, "" ); appendStyleBlock( `${cursorSelector} { display: inline-block; width: 0; ${customProperties} }`, id ); }; function splitOnBreak(str) { return str.replace(/<!--(.+?)-->/g, "").trim().split(/<br(?:\s*?)(?:\/)?>/); } let updateCursorPosition = (steps, cursorPosition, printedCharacters) => { return Math.min( Math.max(cursorPosition + steps, 0), printedCharacters.length ); }; let wait = (callback, delay, timeouts) => { return new Promise((resolve) => { let cb = async () => { await callback(); resolve(); }; timeouts.push(setTimeout(cb, delay || 0)); }); }; let TypeIt$1 = (_a = class { constructor(element, options = {}) { __privateAdd(this, _TypeIt_instances); __publicField(this, "element"); __publicField(this, "timeouts"); __publicField(this, "cursorPosition"); __publicField(this, "predictedCursorPosition"); __publicField(this, "statuses", { started: false, completed: false, frozen: false, destroyed: false, firing: false }); __publicField(this, "opts"); __publicField(this, "id"); __publicField(this, "queue"); __publicField(this, "cursor"); __publicField(this, "flushCallback", null); __publicField(this, "unfreeze", () => { }); __publicField(this, "is", function(key) { return this.statuses[key]; }); __privateAdd(this, _buildOptions, (options) => { this.opts.cursor = processCursorOptions( options.cursor ?? DEFAULT_OPTIONS.cursor ); this.opts.strings = __privateMethod(this, _TypeIt_instances, prependHardcodedStrings_fn).call(this, asArray(this.opts.strings)); this.opts = merge(this.opts, { html: !__privateGet(this, _TypeIt_instances, isInput_get) && this.opts.html, nextStringDelay: calculateDelay(this.opts.nextStringDelay), loopDelay: calculateDelay(this.opts.loopDelay) }); }); this.opts = merge(DEFAULT_OPTIONS, options); this.element = selectorToElement(element); this.timeouts = []; this.cursorPosition = 0; this.unfreeze = () => { }; this.predictedCursorPosition = null; this.statuses = merge({}, DEFAULT_STATUSES); this.id = generateHash(); this.queue = Queue([{ delay: this.opts.startDelay }]); __privateGet(this, _buildOptions).call(this, options); this.cursor = __privateMethod(this, _TypeIt_instances, setUpCursor_fn).call(this); this.element.dataset.typeitId = this.id; appendStyleBlock(PLACEHOLDER_CSS); if (this.opts.strings.length) { __privateMethod(this, _TypeIt_instances, generateQueue_fn).call(this); } } /** * Can only be called once. */ go() { if (this.statuses.started) { return this; } __privateMethod(this, _TypeIt_instances, attachCursor_fn).call(this); if (!this.opts.waitUntilVisible) { __privateMethod(this, _TypeIt_instances, fire_fn).call(this); return this; } fireWhenVisible(this.element, __privateMethod(this, _TypeIt_instances, fire_fn).bind(this)); return this; } destroy(shouldRemoveCursor = true) { this.timeouts = destroyTimeouts(this.timeouts); handleFunctionalArg(shouldRemoveCursor) && this.cursor && __privateMethod(this, _TypeIt_instances, removeNode_fn).call(this, this.cursor); this.statuses.destroyed = true; } reset(rebuild) { !this.is("destroyed") && this.destroy(); if (rebuild) { this.queue.wipe(); rebuild(this); } else { this.queue.reset(); } this.cursorPosition = 0; for (let property in this.statuses) { this.statuses[property] = false; } this.element[__privateMethod(this, _TypeIt_instances, elementIsInput_fn).call(this) ? "value" : "innerHTML"] = ""; return this; } type(string, actionOpts = {}) { string = handleFunctionalArg(string); let { instant } = actionOpts; let bookEndQueueItems = __privateMethod(this, _TypeIt_instances, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); let chars = maybeChunkStringAsHtml(string, this.opts.html); let charsAsQueueItems = chars.map((char) => { return { func: () => __privateMethod(this, _TypeIt_instances, type_fn).call(this, char), char, delay: instant || isNonVoidElement(char) ? 0 : __privateMethod(this, _TypeIt_instances, getPace_fn).call(this), typeable: char.nodeType === Node.TEXT_NODE }; }); let itemsToQueue = [ bookEndQueueItems[0], { func: async () => await this.opts.beforeString(string, this) }, ...charsAsQueueItems, { func: async () => await this.opts.afterString(string, this) }, bookEndQueueItems[1] ]; return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, itemsToQueue, actionOpts); } break(actionOpts = {}) { return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, { func: () => __privateMethod(this, _TypeIt_instances, type_fn).call(this, createElement("BR")), typeable: true }, actionOpts); } move(movementArg, actionOpts = {}) { movementArg = handleFunctionalArg(movementArg); let bookEndQueueItems = __privateMethod(this, _TypeIt_instances, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); let { instant, to } = actionOpts; let numberOfSteps = countStepsToSelector({ queueItems: this.queue.getTypeable(), selector: movementArg === null ? "" : movementArg, to, cursorPosition: __privateGet(this, _TypeIt_instances, derivedCursorPosition_get) }); let directionalStep = numberOfSteps < 0 ? -1 : 1; this.predictedCursorPosition = __privateGet(this, _TypeIt_instances, derivedCursorPosition_get) + numberOfSteps; return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, [ bookEndQueueItems[0], ...duplicate( { func: () => __privateMethod(this, _TypeIt_instances, move_fn).call(this, directionalStep), delay: instant ? 0 : __privateMethod(this, _TypeIt_instances, getPace_fn).call(this), cursorable: true }, Math.abs(numberOfSteps) ), bookEndQueueItems[1] ], actionOpts); } exec(func, actionOpts = {}) { let bookEndQueueItems = __privateMethod(this, _TypeIt_instances, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, [bookEndQueueItems[0], { func: () => func(this) }, bookEndQueueItems[1]], actionOpts); } options(opts, actionOpts = {}) { opts = handleFunctionalArg(opts); __privateMethod(this, _TypeIt_instances, updateOptions_fn).call(this, opts); return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, {}, actionOpts); } pause(milliseconds, actionOpts = {}) { return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, { delay: handleFunctionalArg(milliseconds) }, actionOpts); } delete(numCharacters = null, actionOpts = {}) { numCharacters = handleFunctionalArg(numCharacters); let bookEndQueueItems = __privateMethod(this, _TypeIt_instances, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); let num = numCharacters; let { instant, to } = actionOpts; let typeableQueueItems = this.queue.getTypeable(); let rounds = (() => { if (num === null) { return typeableQueueItems.length; } if (isNumber(num)) { return num; } return countStepsToSelector({ queueItems: typeableQueueItems, selector: num, cursorPosition: __privateGet(this, _TypeIt_instances, derivedCursorPosition_get), to }); })(); return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, [ bookEndQueueItems[0], ...duplicate( { func: __privateMethod(this, _TypeIt_instances, delete_fn).bind(this), delay: instant ? 0 : __privateMethod(this, _TypeIt_instances, getPace_fn).call(this, 1), deletable: true }, rounds ), bookEndQueueItems[1] ], actionOpts); } freeze() { this.statuses.frozen = true; } /** * Like `.go()`, but more... "off the grid." * * - won't trigger `afterComplete` callback * - items won't be replayed after `.reset()` * * When called, all non-done items will be "flushed" -- * that is, executed, but not remembered. */ flush(cb = null) { this.flushCallback = cb || this.flushCallback; if (this.statuses.firing) { return this; } __privateMethod(this, _TypeIt_instances, attachCursor_fn).call(this); __privateMethod(this, _TypeIt_instances, fire_fn).call(this, false).then(() => { if (this.queue.getPendingQueueItems().length > 0) { return this.flush(); } this.flushCallback(); this.flushCallback = null; }); return this; } getQueue() { return this.queue; } getOptions() { return this.opts; } updateOptions(options) { return __privateMethod(this, _TypeIt_instances, updateOptions_fn).call(this, options); } getElement() { return this.element; } empty(actionOpts = {}) { return __privateMethod(this, _TypeIt_instances, queueAndReturn_fn).call(this, { func: __privateMethod(this, _TypeIt_instances, empty_fn).bind(this) }, actionOpts); } }, _TypeIt_instances = new WeakSet(), empty_fn = async function() { if (__privateMethod(this, _TypeIt_instances, elementIsInput_fn).call(this)) { this.element.value = ""; return; } __privateGet(this, _TypeIt_instances, allChars_get).forEach(__privateMethod(this, _TypeIt_instances, removeNode_fn).bind(this)); return; }, fire_fn = async function(remember = true) { this.statuses.started = true; this.statuses.firing = true; let cleanUp = (qKey) => { this.queue.done(qKey, !remember); }; try { let queueItems = [...this.queue.getQueue()]; for (let index = 0; index < queueItems.length; index++) { let [queueKey, queueItem] = queueItems[index]; if (queueItem.done) continue; if (!queueItem.deletable || queueItem.deletable && __privateGet(this, _TypeIt_instances, allChars_get).length) { let newIndex = await __privateMethod(this, _TypeIt_instances, fireItemWithContext_fn).call(this, index, queueItems); cleanUpSkipped({ index, newIndex, queueItems, cleanUp }); index = newIndex; } cleanUp(queueKey); } if (!remember) { this.statuses.firing = false; return this; } this.statuses.completed = true; this.statuses.firing = false; await this.opts.afterComplete(this); if (!this.opts.loop) { throw ""; } let delay = this.opts.loopDelay; __privateMethod(this, _TypeIt_instances, wait_fn).call(this, async () => { await __privateMethod(this, _TypeIt_instances, prepLoop_fn).call(this, delay[0]); __privateMethod(this, _TypeIt_instances, fire_fn).call(this); }, delay[1]); } catch (e) { } this.statuses.firing = false; return this; }, move_fn = async function(step) { this.cursorPosition = updateCursorPosition( step, this.cursorPosition, __privateGet(this, _TypeIt_instances, allChars_get) ); repositionCursor(this.element, __privateGet(this, _TypeIt_instances, allChars_get), thi