typeit-react
Advanced tools
Comparing version 2.6.4 to 2.7.0
import React from "react"; | ||
import { TypeItOptions } from "typeit"; | ||
import type { TypeIt as ITypeIt } from "typeit"; | ||
export interface TypeItProps { | ||
@@ -7,4 +8,4 @@ as?: keyof JSX.IntrinsicElements; | ||
children?: React.ReactNode; | ||
getBeforeInit?: (instance: any) => Function; | ||
getAfterInit?: (instance: any) => Function; | ||
getBeforeInit?: (instance: ITypeIt) => Function; | ||
getAfterInit?: (instance: ITypeIt) => Function; | ||
[key: string]: any; | ||
@@ -11,0 +12,0 @@ } |
1171
dist/index.es.js
@@ -0,11 +1,33 @@ | ||
var __defProp = Object.defineProperty; | ||
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); | ||
return value; | ||
}; | ||
var __accessCheck = (obj, member, msg) => { | ||
if (!member.has(obj)) | ||
throw TypeError("Cannot " + msg); | ||
}; | ||
var __privateGet = (obj, member, getter) => { | ||
__accessCheck(obj, member, "read from private field"); | ||
return getter ? getter.call(obj) : member.get(obj); | ||
}; | ||
var __privateAdd = (obj, member, value) => { | ||
if (member.has(obj)) | ||
throw 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"); | ||
return method; | ||
}; | ||
var _empty, empty_fn, _fire, fire_fn, _move, move_fn, _prepLoop, prepLoop_fn, _fireItemWithContext, fireItemWithContext_fn, _wait, wait_fn, _attachCursor, attachCursor_fn, _elementIsInput, elementIsInput_fn, _queueAndReturn, queueAndReturn_fn, _maybeAppendPause, maybeAppendPause_fn, _generateTemporaryOptionQueueItems, generateTemporaryOptionQueueItems_fn, _updateOptions, updateOptions_fn, _generateQueue, generateQueue_fn, _buildOptions, _prependHardcodedStrings, prependHardcodedStrings_fn, _setUpCursor, setUpCursor_fn, _addSplitPause, addSplitPause_fn, _type, type_fn, _delete, delete_fn, _removeNode, removeNode_fn, _getPace, getPace_fn, _derivedCursorPosition, derivedCursorPosition_get, _isInput, isInput_get, _shouldRenderCursor, shouldRenderCursor_get, _allChars, allChars_get, _a; | ||
import React, { forwardRef, useRef, useState, useEffect } from "react"; | ||
const isArray = (thing) => Array.isArray(thing); | ||
const asArray = (value) => { | ||
return isArray(value) ? value : [value]; | ||
}; | ||
const asArray = (value) => isArray(value) ? value : [value]; | ||
let Queue = function(initialItems) { | ||
let add = function(steps) { | ||
asArray(steps).forEach((step) => { | ||
var _a; | ||
return _q.set(Symbol((_a = step.char) == null ? void 0 : _a.innerText), buildQueueItem({ ...step })); | ||
var _a2; | ||
return _q.set(Symbol((_a2 = step.char) == null ? void 0 : _a2.innerText), buildQueueItem({ ...step })); | ||
}); | ||
@@ -43,5 +65,5 @@ return this; | ||
wipe, | ||
done, | ||
reset, | ||
destroy, | ||
done, | ||
getItems, | ||
@@ -52,22 +74,2 @@ getQueue, | ||
}; | ||
const toArray = (val) => Array.from(val); | ||
const createTextNode = (content) => document.createTextNode(content); | ||
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); | ||
}; | ||
const DATA_ATTRIBUTE = "data-typeit-id"; | ||
@@ -123,35 +125,4 @@ const CURSOR_CLASS = "ti-cursor"; | ||
const PLACEHOLDER_CSS = `[${DATA_ATTRIBUTE}]:before {content: '.'; display: inline-block; width: 0; visibility: hidden;}`; | ||
function walkElementNodes(element, shouldReverse = false, shouldIncludeCursor = false) { | ||
let cursor = element.querySelector(`.${CURSOR_CLASS}`); | ||
let walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL, { | ||
acceptNode: (node) => { | ||
var _a, _b; | ||
if (cursor && shouldIncludeCursor) { | ||
if ((_a = node.classList) == null ? void 0 : _a.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 createElement = (el) => document.createElement(el); | ||
const createTextNode = (content) => document.createTextNode(content); | ||
const appendStyleBlock = (styles, id = "") => { | ||
@@ -183,108 +154,54 @@ let styleBlock = createElement("style"); | ||
} | ||
const destroyTimeouts = (timeouts) => { | ||
timeouts.forEach(clearTimeout); | ||
return []; | ||
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 generateHash = () => Math.random().toString().substring(2, 9); | ||
const isInput = (el) => "value" in el; | ||
let getAllChars = (element) => { | ||
if (isInput(element)) { | ||
return toArray(element.value); | ||
} | ||
return walkElementNodes(element, true).filter( | ||
(c) => !(c.childNodes.length > 0) | ||
); | ||
const getParsedBody = (content) => { | ||
let doc = document.implementation.createHTMLDocument(); | ||
doc.body.innerHTML = content; | ||
return expandTextNodes(doc.body); | ||
}; | ||
const fireWhenVisible = (element, func) => { | ||
let observer = new IntersectionObserver( | ||
(entries, observer2) => { | ||
entries.forEach((entry) => { | ||
if (entry.isIntersecting) { | ||
func(); | ||
observer2.unobserve(element); | ||
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; | ||
} | ||
}); | ||
}, | ||
{ threshold: 1 } | ||
); | ||
observer.observe(element); | ||
}; | ||
let handleFunctionalArg = (arg) => { | ||
return typeof arg === "function" ? arg() : arg; | ||
}; | ||
const isNumber = (value) => Number.isInteger(value); | ||
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; | ||
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); | ||
} | ||
character.innerHTML = ""; | ||
let target = isBodyElement(character.originalParent) ? originalTarget : character.originalParent || originalTarget; | ||
target.insertBefore( | ||
character, | ||
select("." + CURSOR_CLASS, target) || null | ||
); | ||
}; | ||
let updateCursorPosition = (steps, cursorPosition, printedCharacters) => { | ||
return Math.min( | ||
Math.max(cursorPosition + steps, 0), | ||
printedCharacters.length | ||
); | ||
}; | ||
const merge = (originalObj, newObj) => Object.assign({}, originalObj, newObj); | ||
const removeNode = (node, rootElement) => { | ||
if (!node) | ||
return; | ||
let nodeParent = node.parentNode; | ||
let nodeToRemove = nodeParent.childNodes.length > 1 || nodeParent.isSameNode(rootElement) ? node : 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; | ||
return shouldReverse ? nodes.reverse() : nodes; | ||
} | ||
const isNonVoidElement = (el) => /<(.+)>(.*?)<\/(.+)>/.test(el.outerHTML); | ||
let wait = (callback, delay, timeouts) => { | ||
return new Promise((resolve) => { | ||
let cb = async () => { | ||
await callback(); | ||
resolve(); | ||
}; | ||
timeouts.push(setTimeout(cb, delay || 0)); | ||
}); | ||
}; | ||
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 | ||
); | ||
}; | ||
const duplicate = (value, times) => new Array(times).fill(value); | ||
function chunkStringAsHtml(string) { | ||
return walkElementNodes(getParsedBody(string)); | ||
} | ||
function maybeChunkStringAsHtml(str, asHtml = true) { | ||
return asHtml ? chunkStringAsHtml(str) : toArray(str).map(createTextNode); | ||
} | ||
const isNumber = (value) => Number.isInteger(value); | ||
const countStepsToSelector = ({ | ||
@@ -314,2 +231,7 @@ queueItems, | ||
}; | ||
const destroyTimeouts = (timeouts) => { | ||
timeouts.forEach(clearTimeout); | ||
return []; | ||
}; | ||
const duplicate = (value, times) => new Array(times).fill(value); | ||
let beforePaint = (cb) => { | ||
@@ -367,4 +289,4 @@ return new Promise((resolve) => { | ||
let execute = (queueItem) => { | ||
var _a; | ||
return (_a = queueItem.func) == null ? void 0 : _a.call(null); | ||
var _a2; | ||
return (_a2 = queueItem.func) == null ? void 0 : _a2.call(null); | ||
}; | ||
@@ -420,4 +342,53 @@ let fireItem = async ({ | ||
}; | ||
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) => "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 | ||
); | ||
target.insertBefore( | ||
character, | ||
select("." + CURSOR_CLASS, target) || null | ||
); | ||
}; | ||
const isNonVoidElement = (el) => /<(.+)>(.*?)<\/(.+)>/.test(el.outerHTML); | ||
const merge = (originalObj, newObj) => Object.assign({}, originalObj, newObj); | ||
let processCursorOptions = (cursorOptions) => { | ||
var _a, _b; | ||
var _a2, _b; | ||
if (typeof cursorOptions === "object") { | ||
@@ -427,3 +398,3 @@ let newOptions = {}; | ||
newOptions.animation = cursorOptions.animation || {}; | ||
newOptions.animation.frames = ((_a = cursorOptions.animation) == null ? void 0 : _a.frames) || defaultFrames; | ||
newOptions.animation.frames = ((_a2 = cursorOptions.animation) == null ? void 0 : _a2.frames) || defaultFrames; | ||
newOptions.animation.options = merge( | ||
@@ -442,221 +413,268 @@ defaultOptions, | ||
}; | ||
const TypeIt$1 = function(element, options = {}) { | ||
let _wait = async (callback, delay, silent = false) => { | ||
if (_statuses.frozen) { | ||
await new Promise((resolve) => { | ||
this.unfreeze = () => { | ||
_statuses.frozen = false; | ||
resolve(); | ||
}; | ||
}); | ||
} | ||
silent || await _opts.beforeStep(this); | ||
await wait(callback, delay, _timeouts); | ||
silent || await _opts.afterStep(this); | ||
}; | ||
let _fireItemWithContext = (index, queueItems) => { | ||
return fireItem({ | ||
index, | ||
queueItems, | ||
wait: _wait, | ||
cursor: _cursor, | ||
cursorOptions: _opts.cursor | ||
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, _empty); | ||
/** | ||
* Execute items in the queue. | ||
* | ||
* @param remember If false, each queue item will be destroyed once executed. | ||
* @returns | ||
*/ | ||
__privateAdd(this, _fire); | ||
__privateAdd(this, _move); | ||
/** | ||
* 1. Reset queue. | ||
* 2. Reset initial pause. | ||
*/ | ||
__privateAdd(this, _prepLoop); | ||
__privateAdd(this, _fireItemWithContext); | ||
__privateAdd(this, _wait); | ||
/** | ||
* Attach it to the DOM so, along with the required CSS transition. | ||
*/ | ||
__privateAdd(this, _attachCursor); | ||
__privateAdd(this, _elementIsInput); | ||
__privateAdd(this, _queueAndReturn); | ||
__privateAdd(this, _maybeAppendPause); | ||
__privateAdd(this, _generateTemporaryOptionQueueItems); | ||
__privateAdd(this, _updateOptions); | ||
/** | ||
* Based on provided strings, generate a TypeIt queue | ||
* to be fired for each character in the string. | ||
*/ | ||
__privateAdd(this, _generateQueue); | ||
__privateAdd(this, _prependHardcodedStrings); | ||
/** | ||
* Provided it's a non-form element and the options is provided, | ||
* set up the cursor element for the animation. | ||
*/ | ||
__privateAdd(this, _setUpCursor); | ||
__privateAdd(this, _addSplitPause); | ||
__privateAdd(this, _type); | ||
__privateAdd(this, _delete); | ||
__privateAdd(this, _removeNode); | ||
__privateAdd(this, _getPace); | ||
__privateAdd(this, _derivedCursorPosition); | ||
__privateAdd(this, _isInput); | ||
__privateAdd(this, _shouldRenderCursor); | ||
__privateAdd(this, _allChars); | ||
__publicField(this, "element"); | ||
__publicField(this, "timeouts"); | ||
__publicField(this, "cursorPosition"); | ||
__publicField(this, "predictedCursorPosition"); | ||
__publicField(this, "statuses", { | ||
started: false, | ||
completed: false, | ||
frozen: false, | ||
destroyed: false | ||
}); | ||
}; | ||
let _removeNode = (node) => removeNode(node, _element); | ||
let _elementIsInput = () => isInput(_element); | ||
let _getPace = (index = 0) => calculatePace(_opts)[index]; | ||
let _getAllChars = () => getAllChars(_element); | ||
let _maybeAppendPause = (opts = {}) => { | ||
let delay = opts.delay; | ||
delay && _queue.add({ delay }); | ||
}; | ||
let _queueAndReturn = (steps, opts) => { | ||
_queue.add(steps); | ||
_maybeAppendPause(opts); | ||
return this; | ||
}; | ||
let _getDerivedCursorPosition = () => _predictedCursorPosition ?? _cursorPosition; | ||
let _generateTemporaryOptionQueueItems = (newOptions = {}) => { | ||
return [ | ||
{ func: () => _options(newOptions) }, | ||
{ func: () => _options(_opts) } | ||
]; | ||
}; | ||
let _addSplitPause = (items) => { | ||
let delay = _opts.nextStringDelay; | ||
_queue.add([{ delay: delay[0] }, ...items, { delay: delay[1] }]); | ||
}; | ||
let _setUpCursor = () => { | ||
if (_elementIsInput()) { | ||
return; | ||
} | ||
let cursor = createElement("span"); | ||
cursor.className = CURSOR_CLASS; | ||
if (!_shouldRenderCursor) { | ||
cursor.style.visibility = "hidden"; | ||
return cursor; | ||
} | ||
cursor.innerHTML = getParsedBody(_opts.cursorChar).innerHTML; | ||
return cursor; | ||
}; | ||
let _attachCursor = async () => { | ||
!_elementIsInput() && _cursor && _element.appendChild(_cursor); | ||
if (_shouldRenderCursor) { | ||
setCursorStyles(_id, _element); | ||
_cursor.dataset.tiAnimationId = _id; | ||
let { animation } = _opts.cursor; | ||
let { frames, options: options2 } = animation; | ||
setCursorAnimation({ | ||
frames, | ||
cursor: _cursor, | ||
options: { | ||
duration: _opts.cursorSpeed, | ||
...options2 | ||
} | ||
__publicField(this, "opts"); | ||
__publicField(this, "id"); | ||
__publicField(this, "queue"); | ||
__publicField(this, "cursor"); | ||
__publicField(this, "unfreeze", () => { | ||
}); | ||
__publicField(this, "is", function(key) { | ||
return this.statuses[key]; | ||
}); | ||
__privateAdd(this, _buildOptions, (options) => { | ||
options.cursor = processCursorOptions( | ||
options.cursor ?? DEFAULT_OPTIONS.cursor | ||
); | ||
this.opts.strings = __privateMethod(this, _prependHardcodedStrings, prependHardcodedStrings_fn).call(this, asArray(this.opts.strings)); | ||
this.opts = merge(this.opts, { | ||
html: !__privateGet(this, _isInput, isInput_get) && this.opts.html, | ||
nextStringDelay: calculateDelay(this.opts.nextStringDelay), | ||
loopDelay: calculateDelay(this.opts.loopDelay) | ||
}); | ||
} | ||
}; | ||
let _generateQueue = () => { | ||
let strings = _opts.strings.filter((string) => !!string); | ||
strings.forEach((string, index) => { | ||
this.type(string); | ||
if (index + 1 === strings.length) { | ||
return; | ||
} | ||
let splitItems = _opts.breakLines ? [{ func: () => _type(createElement("BR")), typeable: true }] : duplicate( | ||
{ | ||
func: _delete, | ||
delay: _getPace(1) | ||
}, | ||
_queue.getTypeable().length | ||
); | ||
_addSplitPause(splitItems); | ||
}); | ||
}; | ||
let _prepLoop = async (delay) => { | ||
let derivedCursorPosition = _getDerivedCursorPosition(); | ||
derivedCursorPosition && await _move({ value: derivedCursorPosition }); | ||
let queueItems = _getAllChars().map((c) => { | ||
return [ | ||
Symbol(), | ||
{ | ||
func: _delete, | ||
delay: _getPace(1), | ||
deletable: true, | ||
shouldPauseCursor: () => true | ||
} | ||
]; | ||
}); | ||
for (let index = 0; index < queueItems.length; index++) { | ||
await _fireItemWithContext(index, queueItems); | ||
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, _setUpCursor, setUpCursor_fn).call(this); | ||
this.element.dataset.typeitId = this.id; | ||
appendStyleBlock(PLACEHOLDER_CSS); | ||
if (this.opts.strings.length) { | ||
__privateMethod(this, _generateQueue, generateQueue_fn).call(this); | ||
} | ||
_queue.reset(); | ||
_queue.set(0, { delay }); | ||
}; | ||
let _maybePrependHardcodedStrings = (strings) => { | ||
let existingMarkup = _element.innerHTML; | ||
if (!existingMarkup) { | ||
return strings; | ||
} | ||
/** | ||
* Can only be called once. | ||
*/ | ||
go() { | ||
if (this.statuses.started) { | ||
return this; | ||
} | ||
_element.innerHTML = ""; | ||
if (_opts.startDelete) { | ||
_element.innerHTML = existingMarkup; | ||
expandTextNodes(_element); | ||
_addSplitPause( | ||
duplicate( | ||
{ | ||
func: _delete, | ||
delay: _getPace(1), | ||
deletable: true | ||
}, | ||
_getAllChars().length | ||
) | ||
); | ||
return strings; | ||
__privateMethod(this, _attachCursor, attachCursor_fn).call(this); | ||
if (!this.opts.waitUntilVisible) { | ||
__privateMethod(this, _fire, fire_fn).call(this); | ||
return this; | ||
} | ||
let hardCodedStrings = existingMarkup.replace(/<!--(.+?)-->/g, "").trim().split(/<br(?:\s*?)(?:\/)?>/); | ||
return hardCodedStrings.concat(strings); | ||
}; | ||
let _fire = async (remember = true) => { | ||
_statuses.started = true; | ||
let cleanUp = (qKey) => { | ||
_queue.done(qKey, !remember); | ||
}; | ||
try { | ||
let queueItems = [..._queue.getQueue()]; | ||
for (let index = 0; index < queueItems.length; index++) { | ||
let [queueKey, queueItem] = queueItems[index]; | ||
if (queueItem.done) | ||
continue; | ||
if (!queueItem.deletable || queueItem.deletable && _getAllChars().length) { | ||
let newIndex = await _fireItemWithContext(index, queueItems); | ||
Array(newIndex - index).fill(index + 1).map((x, y) => x + y).forEach((i) => { | ||
let [key] = queueItems[i]; | ||
cleanUp(key); | ||
}); | ||
index = newIndex; | ||
} | ||
cleanUp(queueKey); | ||
} | ||
if (!remember) { | ||
return this; | ||
} | ||
_statuses.completed = true; | ||
await _opts.afterComplete(this); | ||
if (!_opts.loop) { | ||
throw ""; | ||
} | ||
let delay = _opts.loopDelay; | ||
_wait(async () => { | ||
await _prepLoop(delay[0]); | ||
_fire(); | ||
}, delay[1]); | ||
} catch (e) { | ||
} | ||
fireWhenVisible(this.element, __privateMethod(this, _fire, fire_fn).bind(this)); | ||
return this; | ||
}; | ||
let _move = async (step) => { | ||
_cursorPosition = updateCursorPosition( | ||
step, | ||
_cursorPosition, | ||
_getAllChars() | ||
); | ||
repositionCursor(_element, _getAllChars(), _cursorPosition); | ||
}; | ||
let _type = (char) => insertIntoElement(_element, char); | ||
let _options = async (opts) => _opts = merge(_opts, opts); | ||
let _empty = async () => { | ||
if (_elementIsInput()) { | ||
_element.value = ""; | ||
return; | ||
} | ||
_getAllChars().forEach(_removeNode); | ||
return; | ||
}; | ||
let _delete = () => { | ||
let allChars = _getAllChars(); | ||
if (!allChars.length) | ||
return; | ||
if (_elementIsInput()) { | ||
_element.value = _element.value.slice(0, -1); | ||
} | ||
destroy(shouldRemoveCursor = true) { | ||
this.timeouts = destroyTimeouts(this.timeouts); | ||
handleFunctionalArg(shouldRemoveCursor) && this.cursor && __privateMethod(this, _removeNode, 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 { | ||
_removeNode(allChars[_cursorPosition]); | ||
this.queue.reset(); | ||
} | ||
}; | ||
this.break = function(actionOpts) { | ||
return _queueAndReturn( | ||
{ | ||
func: () => _type(createElement("BR")), | ||
typeable: true | ||
}, | ||
actionOpts | ||
); | ||
}; | ||
this.delete = function(numCharacters = null, actionOpts = {}) { | ||
this.cursorPosition = 0; | ||
for (let property in this.statuses) { | ||
this.statuses[property] = false; | ||
} | ||
this.element[__privateMethod(this, _elementIsInput, elementIsInput_fn).call(this) ? "value" : "innerHTML"] = ""; | ||
return this; | ||
} | ||
type(string, actionOpts = {}) { | ||
string = handleFunctionalArg(string); | ||
let { instant } = actionOpts; | ||
let bookEndQueueItems = __privateMethod(this, _generateTemporaryOptionQueueItems, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); | ||
let chars = maybeChunkStringAsHtml(string, this.opts.html); | ||
let charsAsQueueItems = chars.map((char) => { | ||
return { | ||
func: () => __privateMethod(this, _type, type_fn).call(this, char), | ||
char, | ||
delay: instant || isNonVoidElement(char) ? 0 : __privateMethod(this, _getPace, 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, _queueAndReturn, queueAndReturn_fn).call(this, itemsToQueue, actionOpts); | ||
} | ||
break(actionOpts = {}) { | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, { | ||
func: () => __privateMethod(this, _type, type_fn).call(this, createElement("BR")), | ||
typeable: true | ||
}, actionOpts); | ||
} | ||
move(movementArg, actionOpts = {}) { | ||
movementArg = handleFunctionalArg(movementArg); | ||
let bookEndQueueItems = __privateMethod(this, _generateTemporaryOptionQueueItems, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); | ||
let { instant, to } = actionOpts; | ||
let numberOfSteps = countStepsToSelector({ | ||
queueItems: this.queue.getTypeable(), | ||
selector: movementArg === null ? "" : movementArg, | ||
to, | ||
cursorPosition: __privateGet(this, _derivedCursorPosition, derivedCursorPosition_get) | ||
}); | ||
let directionalStep = numberOfSteps < 0 ? -1 : 1; | ||
this.predictedCursorPosition = __privateGet(this, _derivedCursorPosition, derivedCursorPosition_get) + numberOfSteps; | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, [ | ||
bookEndQueueItems[0], | ||
...duplicate( | ||
{ | ||
func: () => __privateMethod(this, _move, move_fn).call(this, directionalStep), | ||
delay: instant ? 0 : __privateMethod(this, _getPace, getPace_fn).call(this), | ||
cursorable: true | ||
}, | ||
Math.abs(numberOfSteps) | ||
), | ||
bookEndQueueItems[1] | ||
], actionOpts); | ||
} | ||
exec(func, actionOpts = {}) { | ||
let bookEndQueueItems = __privateMethod(this, _generateTemporaryOptionQueueItems, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, [bookEndQueueItems[0], { func: () => func(this) }, bookEndQueueItems[1]], actionOpts); | ||
} | ||
options(opts, actionOpts = {}) { | ||
opts = handleFunctionalArg(opts); | ||
__privateMethod(this, _updateOptions, updateOptions_fn).call(this, opts); | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, {}, actionOpts); | ||
} | ||
pause(milliseconds, actionOpts = {}) { | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, { delay: handleFunctionalArg(milliseconds) }, actionOpts); | ||
} | ||
delete(numCharacters = null, actionOpts = {}) { | ||
numCharacters = handleFunctionalArg(numCharacters); | ||
let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); | ||
let bookEndQueueItems = __privateMethod(this, _generateTemporaryOptionQueueItems, generateTemporaryOptionQueueItems_fn).call(this, actionOpts); | ||
let num = numCharacters; | ||
let { instant, to } = actionOpts; | ||
let typeableQueueItems = _queue.getTypeable(); | ||
let typeableQueueItems = this.queue.getTypeable(); | ||
let rounds = (() => { | ||
@@ -672,174 +690,248 @@ if (num === null) { | ||
selector: num, | ||
cursorPosition: _getDerivedCursorPosition(), | ||
cursorPosition: __privateGet(this, _derivedCursorPosition, derivedCursorPosition_get), | ||
to | ||
}); | ||
})(); | ||
return _queueAndReturn( | ||
[ | ||
bookEndQueueItems[0], | ||
...duplicate( | ||
{ | ||
func: _delete, | ||
delay: instant ? 0 : _getPace(1), | ||
deletable: true | ||
}, | ||
rounds | ||
), | ||
bookEndQueueItems[1] | ||
], | ||
actionOpts | ||
); | ||
}; | ||
this.empty = function(actionOpts = {}) { | ||
return _queueAndReturn({ func: _empty }, actionOpts); | ||
}; | ||
this.exec = function(func, actionOpts = {}) { | ||
let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); | ||
return _queueAndReturn( | ||
[bookEndQueueItems[0], { func: () => func(this) }, bookEndQueueItems[1]], | ||
actionOpts | ||
); | ||
}; | ||
this.move = function(movementArg, actionOpts = {}) { | ||
movementArg = handleFunctionalArg(movementArg); | ||
let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); | ||
let { instant, to } = actionOpts; | ||
let numberOfSteps = countStepsToSelector({ | ||
queueItems: _queue.getTypeable(), | ||
selector: movementArg === null ? "" : movementArg, | ||
to, | ||
cursorPosition: _getDerivedCursorPosition() | ||
}); | ||
let directionalStep = numberOfSteps < 0 ? -1 : 1; | ||
_predictedCursorPosition = _getDerivedCursorPosition() + numberOfSteps; | ||
return _queueAndReturn( | ||
[ | ||
bookEndQueueItems[0], | ||
...duplicate( | ||
{ | ||
func: () => _move(directionalStep), | ||
delay: instant ? 0 : _getPace(), | ||
cursorable: true | ||
}, | ||
Math.abs(numberOfSteps) | ||
), | ||
bookEndQueueItems[1] | ||
], | ||
actionOpts | ||
); | ||
}; | ||
this.options = function(opts, actionOpts = {}) { | ||
opts = handleFunctionalArg(opts); | ||
_options(opts); | ||
return _queueAndReturn({}, actionOpts); | ||
}; | ||
this.pause = function(milliseconds, actionOpts = {}) { | ||
return _queueAndReturn( | ||
{ delay: handleFunctionalArg(milliseconds) }, | ||
actionOpts | ||
); | ||
}; | ||
this.type = function(string, actionOpts = {}) { | ||
string = handleFunctionalArg(string); | ||
let { instant } = actionOpts; | ||
let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); | ||
let chars = maybeChunkStringAsHtml(string, _opts.html); | ||
let charsAsQueueItems = chars.map((char) => { | ||
return { | ||
func: () => _type(char), | ||
char, | ||
delay: instant || isNonVoidElement(char) ? 0 : _getPace(), | ||
typeable: char.nodeType === Node.TEXT_NODE | ||
}; | ||
}); | ||
let itemsToQueue = [ | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, [ | ||
bookEndQueueItems[0], | ||
{ func: async () => await _opts.beforeString(string, this) }, | ||
...charsAsQueueItems, | ||
{ func: async () => await _opts.afterString(string, this) }, | ||
...duplicate( | ||
{ | ||
func: __privateMethod(this, _delete, delete_fn).bind(this), | ||
delay: instant ? 0 : __privateMethod(this, _getPace, getPace_fn).call(this, 1), | ||
deletable: true | ||
}, | ||
rounds | ||
), | ||
bookEndQueueItems[1] | ||
]; | ||
return _queueAndReturn(itemsToQueue, actionOpts); | ||
}; | ||
this.is = function(key) { | ||
return _statuses[key]; | ||
}; | ||
this.destroy = function(shouldRemoveCursor = true) { | ||
_timeouts = destroyTimeouts(_timeouts); | ||
handleFunctionalArg(shouldRemoveCursor) && _cursor && _removeNode(_cursor); | ||
_statuses.destroyed = true; | ||
}; | ||
this.freeze = function() { | ||
_statuses.frozen = true; | ||
}; | ||
this.unfreeze = () => { | ||
}; | ||
this.reset = function(rebuild) { | ||
!this.is("destroyed") && this.destroy(); | ||
if (rebuild) { | ||
_queue.wipe(); | ||
rebuild(this); | ||
} else { | ||
_queue.reset(); | ||
} | ||
_cursorPosition = 0; | ||
for (let property in _statuses) { | ||
_statuses[property] = false; | ||
} | ||
_element[_elementIsInput() ? "value" : "innerHTML"] = ""; | ||
], 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 = () => { | ||
}) { | ||
__privateMethod(this, _attachCursor, attachCursor_fn).call(this); | ||
__privateMethod(this, _fire, fire_fn).call(this, false).then(cb); | ||
return this; | ||
} | ||
getQueue() { | ||
return this.queue; | ||
} | ||
getOptions() { | ||
return this.opts; | ||
} | ||
updateOptions(options) { | ||
return __privateMethod(this, _updateOptions, updateOptions_fn).call(this, options); | ||
} | ||
getElement() { | ||
return this.element; | ||
} | ||
empty(actionOpts = {}) { | ||
return __privateMethod(this, _queueAndReturn, queueAndReturn_fn).call(this, { func: __privateMethod(this, _empty, empty_fn).bind(this) }, actionOpts); | ||
} | ||
}, _empty = new WeakSet(), empty_fn = async function() { | ||
if (__privateMethod(this, _elementIsInput, elementIsInput_fn).call(this)) { | ||
this.element.value = ""; | ||
return; | ||
} | ||
__privateGet(this, _allChars, allChars_get).forEach(__privateMethod(this, _removeNode, removeNode_fn).bind(this)); | ||
return; | ||
}, _fire = new WeakSet(), fire_fn = async function(remember = true) { | ||
this.statuses.started = true; | ||
let cleanUp = (qKey) => { | ||
this.queue.done(qKey, !remember); | ||
}; | ||
this.go = function() { | ||
if (_statuses.started) { | ||
return this; | ||
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, _allChars, allChars_get).length) { | ||
let newIndex = await __privateMethod(this, _fireItemWithContext, fireItemWithContext_fn).call(this, index, queueItems); | ||
Array(newIndex - index).fill(index + 1).map((x, y) => x + y).forEach((i) => { | ||
let [key] = queueItems[i]; | ||
cleanUp(key); | ||
}); | ||
index = newIndex; | ||
} | ||
cleanUp(queueKey); | ||
} | ||
_attachCursor(); | ||
if (!_opts.waitUntilVisible) { | ||
_fire(); | ||
if (!remember) { | ||
return this; | ||
} | ||
fireWhenVisible(_element, _fire.bind(this)); | ||
return this; | ||
}; | ||
this.flush = function(cb = () => { | ||
}) { | ||
_attachCursor(); | ||
_fire(false).then(cb); | ||
return this; | ||
}; | ||
this.getQueue = () => _queue; | ||
this.getOptions = () => _opts; | ||
this.updateOptions = (options2) => _options(options2); | ||
this.getElement = () => _element; | ||
let _element = selectorToElement(element); | ||
let _timeouts = []; | ||
let _cursorPosition = 0; | ||
let _predictedCursorPosition = null; | ||
let _statuses = merge({}, DEFAULT_STATUSES); | ||
options.cursor = processCursorOptions( | ||
options.cursor ?? DEFAULT_OPTIONS.cursor | ||
this.statuses.completed = true; | ||
await this.opts.afterComplete(this); | ||
if (!this.opts.loop) { | ||
throw ""; | ||
} | ||
let delay = this.opts.loopDelay; | ||
__privateMethod(this, _wait, wait_fn).call(this, async () => { | ||
await __privateMethod(this, _prepLoop, prepLoop_fn).call(this, delay[0]); | ||
__privateMethod(this, _fire, fire_fn).call(this); | ||
}, delay[1]); | ||
} catch (e) { | ||
} | ||
return this; | ||
}, _move = new WeakSet(), move_fn = async function(step) { | ||
this.cursorPosition = updateCursorPosition( | ||
step, | ||
this.cursorPosition, | ||
__privateGet(this, _allChars, allChars_get) | ||
); | ||
let _opts = merge(DEFAULT_OPTIONS, options); | ||
_opts = merge(_opts, { | ||
html: !_elementIsInput() && _opts.html, | ||
nextStringDelay: calculateDelay(_opts.nextStringDelay), | ||
loopDelay: calculateDelay(_opts.loopDelay) | ||
repositionCursor(this.element, __privateGet(this, _allChars, allChars_get), this.cursorPosition); | ||
}, _prepLoop = new WeakSet(), prepLoop_fn = async function(delay) { | ||
let derivedCursorPosition = __privateGet(this, _derivedCursorPosition, derivedCursorPosition_get); | ||
derivedCursorPosition && await __privateMethod(this, _move, move_fn).call(this, { value: derivedCursorPosition }); | ||
let queueItems = __privateGet(this, _allChars, allChars_get).map((c) => { | ||
return [ | ||
Symbol(), | ||
{ | ||
func: __privateMethod(this, _delete, delete_fn).bind(this), | ||
delay: __privateMethod(this, _getPace, getPace_fn).call(this, 1), | ||
deletable: true, | ||
shouldPauseCursor: () => true | ||
} | ||
]; | ||
}); | ||
let _id = generateHash(); | ||
let _queue = Queue([{ delay: _opts.startDelay }]); | ||
_element.dataset.typeitId = _id; | ||
appendStyleBlock(PLACEHOLDER_CSS); | ||
let _shouldRenderCursor = !!_opts.cursor && !_elementIsInput(); | ||
let _cursor = _setUpCursor(); | ||
_opts.strings = _maybePrependHardcodedStrings(asArray(_opts.strings)); | ||
if (_opts.strings.length) { | ||
_generateQueue(); | ||
for (let index = 0; index < queueItems.length; index++) { | ||
await __privateMethod(this, _fireItemWithContext, fireItemWithContext_fn).call(this, index, queueItems); | ||
} | ||
}; | ||
const defaultProps = { | ||
as: "span", | ||
options: {}, | ||
getBeforeInit: (instance) => instance, | ||
getAfterInit: (instance) => instance | ||
}; | ||
this.queue.reset(); | ||
this.queue.set(0, { delay }); | ||
}, _fireItemWithContext = new WeakSet(), fireItemWithContext_fn = function(index, queueItems) { | ||
return fireItem({ | ||
index, | ||
queueItems, | ||
wait: __privateMethod(this, _wait, wait_fn).bind(this), | ||
cursor: this.cursor, | ||
cursorOptions: this.opts.cursor | ||
}); | ||
}, _wait = new WeakSet(), wait_fn = async function(callback, delay, silent = false) { | ||
if (this.statuses.frozen) { | ||
await new Promise((resolve) => { | ||
this.unfreeze = () => { | ||
this.statuses.frozen = false; | ||
resolve(); | ||
}; | ||
}); | ||
} | ||
silent || await this.opts.beforeStep(this); | ||
await wait(callback, delay, this.timeouts); | ||
silent || await this.opts.afterStep(this); | ||
}, _attachCursor = new WeakSet(), attachCursor_fn = async function() { | ||
!__privateMethod(this, _elementIsInput, elementIsInput_fn).call(this) && this.cursor && this.element.appendChild(this.cursor); | ||
if (__privateGet(this, _shouldRenderCursor, shouldRenderCursor_get)) { | ||
setCursorStyles(this.id, this.element); | ||
this.cursor.dataset.tiAnimationId = this.id; | ||
let { animation } = this.opts.cursor; | ||
let { frames, options } = animation; | ||
setCursorAnimation({ | ||
frames, | ||
cursor: this.cursor, | ||
options: { | ||
duration: this.opts.cursorSpeed, | ||
...options | ||
} | ||
}); | ||
} | ||
}, _elementIsInput = new WeakSet(), elementIsInput_fn = function() { | ||
return isInput(this.element); | ||
}, _queueAndReturn = new WeakSet(), queueAndReturn_fn = function(steps, opts) { | ||
this.queue.add(steps); | ||
__privateMethod(this, _maybeAppendPause, maybeAppendPause_fn).call(this, opts); | ||
return this; | ||
}, _maybeAppendPause = new WeakSet(), maybeAppendPause_fn = function(opts = {}) { | ||
let delay = opts.delay; | ||
delay && this.queue.add({ delay }); | ||
}, _generateTemporaryOptionQueueItems = new WeakSet(), generateTemporaryOptionQueueItems_fn = function(newOptions = {}) { | ||
return [ | ||
{ func: () => __privateMethod(this, _updateOptions, updateOptions_fn).call(this, newOptions) }, | ||
{ func: () => __privateMethod(this, _updateOptions, updateOptions_fn).call(this, this.opts) } | ||
]; | ||
}, _updateOptions = new WeakSet(), updateOptions_fn = async function(opts) { | ||
this.opts = merge(this.opts, opts); | ||
}, _generateQueue = new WeakSet(), generateQueue_fn = function() { | ||
let strings = this.opts.strings.filter((string) => !!string); | ||
strings.forEach((string, index) => { | ||
this.type(string); | ||
if (index + 1 === strings.length) { | ||
return; | ||
} | ||
let splitItems = this.opts.breakLines ? [{ func: () => __privateMethod(this, _type, type_fn).call(this, createElement("BR")), typeable: true }] : duplicate( | ||
{ | ||
func: __privateMethod(this, _delete, delete_fn).bind(this), | ||
delay: __privateMethod(this, _getPace, getPace_fn).call(this, 1) | ||
}, | ||
this.queue.getTypeable().length | ||
); | ||
__privateMethod(this, _addSplitPause, addSplitPause_fn).call(this, splitItems); | ||
}); | ||
}, _buildOptions = new WeakMap(), _prependHardcodedStrings = new WeakSet(), prependHardcodedStrings_fn = function(strings) { | ||
let existingMarkup = this.element.innerHTML; | ||
if (!existingMarkup) { | ||
return strings; | ||
} | ||
this.element.innerHTML = ""; | ||
if (this.opts.startDelete) { | ||
this.element.innerHTML = existingMarkup; | ||
expandTextNodes(this.element); | ||
__privateMethod(this, _addSplitPause, addSplitPause_fn).call(this, duplicate( | ||
{ | ||
func: __privateMethod(this, _delete, delete_fn).bind(this), | ||
delay: __privateMethod(this, _getPace, getPace_fn).call(this, 1), | ||
deletable: true | ||
}, | ||
__privateGet(this, _allChars, allChars_get).length | ||
)); | ||
return strings; | ||
} | ||
return splitOnBreak(existingMarkup).concat(strings); | ||
}, _setUpCursor = new WeakSet(), setUpCursor_fn = function() { | ||
if (__privateGet(this, _isInput, isInput_get)) { | ||
return null; | ||
} | ||
let cursor = createElement("span"); | ||
cursor.className = CURSOR_CLASS; | ||
if (!__privateGet(this, _shouldRenderCursor, shouldRenderCursor_get)) { | ||
cursor.style.visibility = "hidden"; | ||
return cursor; | ||
} | ||
cursor.innerHTML = getParsedBody(this.opts.cursorChar).innerHTML; | ||
return cursor; | ||
}, _addSplitPause = new WeakSet(), addSplitPause_fn = function(items) { | ||
let delay = this.opts.nextStringDelay; | ||
this.queue.add([{ delay: delay[0] }, ...items, { delay: delay[1] }]); | ||
}, _type = new WeakSet(), type_fn = function(char) { | ||
insertIntoElement(this.element, char); | ||
}, _delete = new WeakSet(), delete_fn = function() { | ||
if (!__privateGet(this, _allChars, allChars_get).length) | ||
return; | ||
if (__privateGet(this, _isInput, isInput_get)) { | ||
this.element.value = this.element.value.slice(0, -1); | ||
} else { | ||
__privateMethod(this, _removeNode, removeNode_fn).call(this, __privateGet(this, _allChars, allChars_get)[this.cursorPosition]); | ||
} | ||
}, _removeNode = new WeakSet(), removeNode_fn = function(node) { | ||
removeNode(node, this.element); | ||
}, _getPace = new WeakSet(), getPace_fn = function(index = 0) { | ||
return calculatePace(this.opts)[index]; | ||
}, _derivedCursorPosition = new WeakSet(), derivedCursorPosition_get = function() { | ||
return this.predictedCursorPosition ?? this.cursorPosition; | ||
}, _isInput = new WeakSet(), isInput_get = function() { | ||
return isInput(this.element); | ||
}, _shouldRenderCursor = new WeakSet(), shouldRenderCursor_get = function() { | ||
return !!this.opts.cursor && !__privateGet(this, _isInput, isInput_get); | ||
}, _allChars = new WeakSet(), allChars_get = function() { | ||
return getAllChars(this.element); | ||
}, _a); | ||
const DynamicElementComponent = forwardRef((props, ref) => { | ||
@@ -849,6 +941,13 @@ const { as: As } = props; | ||
}); | ||
const TypeIt = (props) => { | ||
const defaultPropOptions = {}; | ||
const TypeIt = ({ | ||
as = "span", | ||
options = defaultPropOptions, | ||
children = null, | ||
getBeforeInit = (instance) => instance, | ||
getAfterInit = (instance) => instance, | ||
...remainingProps | ||
}) => { | ||
const elementRef = useRef(null); | ||
const instanceRef = useRef(null); | ||
const { options, children, getBeforeInit, getAfterInit, ...remainingProps } = props; | ||
const [shouldShowChildren, setShouldShowChildren] = useState(true); | ||
@@ -874,11 +973,11 @@ const [instanceOptions, setInstanceOptions] = useState(null); | ||
useEffect(() => { | ||
var _a; | ||
var _a2; | ||
if (!instanceOptions) | ||
return; | ||
((_a = instanceRef.current) == null ? void 0 : _a.updateOptions(instanceOptions)) || generateNewInstance(); | ||
((_a2 = instanceRef.current) == null ? void 0 : _a2.updateOptions(instanceOptions)) || generateNewInstance(); | ||
}, [instanceOptions]); | ||
useEffect(() => { | ||
return () => { | ||
var _a; | ||
return (_a = instanceRef.current) == null ? void 0 : _a.destroy(); | ||
var _a2; | ||
return (_a2 = instanceRef.current) == null ? void 0 : _a2.destroy(); | ||
}; | ||
@@ -890,2 +989,3 @@ }, []); | ||
ref: elementRef, | ||
as, | ||
children: shouldShowChildren ? children : null, | ||
@@ -897,5 +997,4 @@ style: { opacity: shouldShowChildren ? 0 : 1 }, | ||
}; | ||
TypeIt.defaultProps = defaultProps; | ||
export { | ||
TypeIt as default | ||
}; |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).TypeIt=t(e.React)}(this,(function(e){"use strict";const t=e=>Array.isArray(e),n=e=>t(e)?e:[e];const r=e=>Array.from(e),i=e=>document.createTextNode(e);let a=e=>([...e.childNodes].forEach((e=>{if(e.nodeValue)return[...e.nodeValue].forEach((t=>{e.parentNode.insertBefore(i(t),e)})),void e.remove();a(e)})),e);const o=e=>{let t=document.implementation.createHTMLDocument();return t.body.innerHTML=e,a(t.body)},s="data-typeit-id",l="ti-cursor",u={started:!1,completed:!1,frozen:!1,destroyed:!1},c={breakLines:!0,cursor:{autoPause:!0,autoPauseDelay:500,animation:{frames:[0,0,1].map((e=>({opacity:e}))),options:{iterations:1/0,easing:"steps(2, start)",fill:"forwards"}}},cursorChar:"|",cursorSpeed:1e3,deleteSpeed:null,html:!0,lifeLike:!0,loop:!1,loopDelay:750,nextStringDelay:750,speed:100,startDelay:250,startDelete:!1,strings:[],waitUntilVisible:!1,beforeString:()=>{},afterString:()=>{},beforeStep:()=>{},afterStep:()=>{},afterComplete:()=>{}},d=`[${s}]:before {content: '.'; display: inline-block; width: 0; visibility: hidden;}`;function f(e,t=!1,n=!1){let r,i=e.querySelector(`.${l}`),a=document.createTreeWalker(e,NodeFilter.SHOW_ALL,{acceptNode:e=>{var t,r;if(i&&n){if(null==(t=e.classList)?void 0:t.contains(l))return NodeFilter.FILTER_ACCEPT;if(i.contains(e))return NodeFilter.FILTER_REJECT}return(null==(r=e.classList)?void 0:r.contains(l))?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),o=[];for(;r=a.nextNode();)r.originalParent||(r.originalParent=r.parentNode),o.push(r);return t?o.reverse():o}function h(e,t=!0){return t?f(o(e)):r(e).map(i)}const p=e=>document.createElement(e),y=(e,t="")=>{let n=p("style");n.id=t,n.appendChild(i(e)),document.head.appendChild(n)},m=e=>(t(e)||(e=[e/2,e/2]),e),g=(e,t)=>Math.abs(Math.random()*(e+t-(e-t))+(e-t));let b=e=>e/2;const v=e=>"value"in e;let w=e=>"function"==typeof e?e():e;const T=e=>Number.isInteger(e);let E=(e,t=document,n=!1)=>t["querySelector"+(n?"All":"")](e);const S=(e,t)=>Object.assign({},e,t);let P={"font-family":"","font-weight":"","font-size":"","font-style":"","line-height":"",color:"",transform:"translateX(-.125em)"};const I=(e,t)=>new Array(t).fill(e),L=({queueItems:e,selector:t,cursorPosition:n,to:r})=>{if(T(t))return-1*t;let i=new RegExp("END","i").test(r),a=t?[...e].reverse().findIndex((({char:e})=>{let n=e.parentElement,r=n.matches(t);return!(!i||!r)||r&&n.firstChild.isSameNode(e)})):-1;return a<0&&(a=i?0:e.length-1),a-n+(i?0:1)};let N=e=>new Promise((t=>{requestAnimationFrame((async()=>{t(await e())}))})),C=e=>null==e?void 0:e.getAnimations().find((t=>t.id===e.dataset.tiAnimationId)),D=({cursor:e,frames:t,options:n})=>{let r=e.animate(t,n);return r.pause(),r.id=e.dataset.tiAnimationId,N((()=>{N((()=>{r.play()}))})),r},M=e=>{var t;return null==(t=e.func)?void 0:t.call(null)},A=async({index:e,queueItems:t,wait:n,cursor:r,cursorOptions:i})=>{let a=t[e][1],o=[],s=e,l=a,u=()=>l&&!l.delay,c=a.shouldPauseCursor()&&i.autoPause;for(;u();)o.push(l),u()&&s++,l=t[s]?t[s][1]:null;if(o.length)return await N((async()=>{for(let e of o)await M(e)})),s-1;let d,f=C(r);return f&&(d={...f.effect.getComputedTiming(),delay:c?i.autoPauseDelay:0}),await n((async()=>{f&&c&&f.cancel(),await N((()=>{M(a)}))}),a.delay),await(({cursor:e,options:t,cursorOptions:n})=>{if(!e||!n)return;let r,i=C(e);i&&(t.delay=i.effect.getComputedTiming().delay,r=i.currentTime,i.cancel());let a=D({cursor:e,frames:n.animation.frames,options:t});return r&&(a.currentTime=r),a})({cursor:r,options:d,cursorOptions:i}),e};const x=function(e,t={}){let i=async(e,t,n=!1)=>{K.frozen&&await new Promise((e=>{this.unfreeze=()=>{K.frozen=!1,e()}})),n||await Y.beforeStep(this),await((e,t,n)=>new Promise((r=>{n.push(setTimeout((async()=>{await e(),r()}),t||0))})))(e,t,W),n||await Y.afterStep(this)},N=(e,t)=>A({index:e,queueItems:t,wait:i,cursor:ne,cursorOptions:Y.cursor}),C=e=>((e,t)=>{if(!e)return;let n=e.parentNode;(n.childNodes.length>1||n.isSameNode(t)?e:n).remove()})(e,J),M=()=>v(J),x=(e=0)=>function(e){let{speed:t,deleteSpeed:n,lifeLike:r}=e;return n=null!==n?n:t/3,r?[g(t,b(t)),g(n,b(n))]:[t,n]}(Y)[e],$=()=>(e=>v(e)?r(e.value):f(e,!0).filter((e=>!(e.childNodes.length>0))))(J),O=(e,t)=>(ee.add(e),((e={})=>{let t=e.delay;t&&ee.add({delay:t})})(t),this),R=()=>G??X,H=(e={})=>[{func:()=>j(e)},{func:()=>j(Y)}],F=e=>{let t=Y.nextStringDelay;ee.add([{delay:t[0]},...e,{delay:t[1]}])},k=async()=>{if(!M()&&ne&&J.appendChild(ne),te){((e,t)=>{let n=`[${s}='${e}'] .${l}`,r=getComputedStyle(t),i=Object.entries(P).reduce(((e,[t,n])=>`${e} ${t}: var(--ti-cursor-${t}, ${n||r[t]});`),"");y(`${n} { display: inline-block; width: 0; ${i} }`,e)})(Z,J),ne.dataset.tiAnimationId=Z;let{animation:e}=Y.cursor,{frames:t,options:n}=e;D({frames:t,cursor:ne,options:{duration:Y.cursorSpeed,...n}})}},q=()=>{let e=Y.strings.filter((e=>!!e));e.forEach(((t,n)=>{if(this.type(t),n+1===e.length)return;let r=Y.breakLines?[{func:()=>_(p("BR")),typeable:!0}]:I({func:Q,delay:x(1)},ee.getTypeable().length);F(r)}))},z=async(e=!0)=>{K.started=!0;let t=t=>{ee.done(t,!e)};try{let n=[...ee.getQueue()];for(let e=0;e<n.length;e++){let[r,i]=n[e];if(!i.done){if(!i.deletable||i.deletable&&$().length){let r=await N(e,n);Array(r-e).fill(e+1).map(((e,t)=>e+t)).forEach((e=>{let[r]=n[e];t(r)})),e=r}t(r)}}if(!e)return this;if(K.completed=!0,await Y.afterComplete(this),!Y.loop)throw"";let r=Y.loopDelay;i((async()=>{await(async e=>{let t=R();t&&await B({value:t});let n=$().map((e=>[Symbol(),{func:Q,delay:x(1),deletable:!0,shouldPauseCursor:()=>!0}]));for(let r=0;r<n.length;r++)await N(r,n);ee.reset(),ee.set(0,{delay:e})})(r[0]),z()}),r[1])}catch(n){}return this},B=async e=>{var t,n,r;t=e,n=X,r=$(),X=Math.min(Math.max(n+t,0),r.length),((e,t,n)=>{let r=t[n-1],i=E(`.${l}`,e);(e=(null==r?void 0:r.parentNode)||e).insertBefore(i,r||null)})(J,$(),X)},_=e=>((e,t)=>{if(v(e))return void(e.value=`${e.value}${t.textContent}`);t.innerHTML="";let n=(r=t.originalParent,/body/i.test(null==r?void 0:r.tagName)?e:t.originalParent||e);var r;n.insertBefore(t,E("."+l,n)||null)})(J,e),j=async e=>Y=S(Y,e),V=async()=>{M()?J.value="":$().forEach(C)},Q=()=>{let e=$();e.length&&(M()?J.value=J.value.slice(0,-1):C(e[X]))};this.break=function(e){return O({func:()=>_(p("BR")),typeable:!0},e)},this.delete=function(e=null,t={}){e=w(e);let n=H(t),r=e,{instant:i,to:a}=t,o=ee.getTypeable(),s=null===r?o.length:T(r)?r:L({queueItems:o,selector:r,cursorPosition:R(),to:a});return O([n[0],...I({func:Q,delay:i?0:x(1),deletable:!0},s),n[1]],t)},this.empty=function(e={}){return O({func:V},e)},this.exec=function(e,t={}){let n=H(t);return O([n[0],{func:()=>e(this)},n[1]],t)},this.move=function(e,t={}){e=w(e);let n=H(t),{instant:r,to:i}=t,a=L({queueItems:ee.getTypeable(),selector:null===e?"":e,to:i,cursorPosition:R()}),o=a<0?-1:1;return G=R()+a,O([n[0],...I({func:()=>B(o),delay:r?0:x(),cursorable:!0},Math.abs(a)),n[1]],t)},this.options=function(e,t={}){return e=w(e),j(e),O({},t)},this.pause=function(e,t={}){return O({delay:w(e)},t)},this.type=function(e,t={}){e=w(e);let{instant:n}=t,r=H(t),i=h(e,Y.html).map((e=>{return{func:()=>_(e),char:e,delay:n||(t=e,/<(.+)>(.*?)<\/(.+)>/.test(t.outerHTML))?0:x(),typeable:e.nodeType===Node.TEXT_NODE};var t})),a=[r[0],{func:async()=>await Y.beforeString(e,this)},...i,{func:async()=>await Y.afterString(e,this)},r[1]];return O(a,t)},this.is=function(e){return K[e]},this.destroy=function(e=!0){W.forEach(clearTimeout),W=[],w(e)&&ne&&C(ne),K.destroyed=!0},this.freeze=function(){K.frozen=!0},this.unfreeze=()=>{},this.reset=function(e){!this.is("destroyed")&&this.destroy(),e?(ee.wipe(),e(this)):ee.reset(),X=0;for(let t in K)K[t]=!1;return J[M()?"value":"innerHTML"]="",this},this.go=function(){return K.started?this:(k(),Y.waitUntilVisible?(((e,t)=>{new IntersectionObserver(((n,r)=>{n.forEach((n=>{n.isIntersecting&&(t(),r.unobserve(e))}))}),{threshold:1}).observe(e)})(J,z.bind(this)),this):(z(),this))},this.flush=function(e=(()=>{})){return k(),z(!1).then(e),this},this.getQueue=()=>ee,this.getOptions=()=>Y,this.updateOptions=e=>j(e),this.getElement=()=>J;let J="string"==typeof(U=e)?E(U):U;var U;let W=[],X=0,G=null,K=S({},u);t.cursor=(e=>{var t,n;if("object"==typeof e){let r={},{frames:i,options:a}=c.cursor.animation;return r.animation=e.animation||{},r.animation.frames=(null==(t=e.animation)?void 0:t.frames)||i,r.animation.options=S(a,(null==(n=e.animation)?void 0:n.options)||{}),r.autoPause=e.autoPause??c.cursor.autoPause,r.autoPauseDelay=e.autoPauseDelay||c.cursor.autoPauseDelay,r}return!0===e?c.cursor:e})(t.cursor??c.cursor);let Y=S(c,t);Y=S(Y,{html:!M()&&Y.html,nextStringDelay:m(Y.nextStringDelay),loopDelay:m(Y.loopDelay)});let Z=Math.random().toString().substring(2,9),ee=function(e){let t=function(e){return n(e).forEach((e=>{var t;return a.set(Symbol(null==(t=e.char)?void 0:t.innerText),r({...e}))})),this},r=e=>(e.shouldPauseCursor=function(){return Boolean(this.typeable||this.cursorable||this.deletable)},e),i=()=>Array.from(a.values()),a=new Map;return t(e),{add:t,set:function(e,t){let n=[...a.keys()];a.set(n[e],r(t))},wipe:function(){a=new Map,t(e)},reset:function(){a.forEach((e=>delete e.done))},destroy:e=>a.delete(e),done:(e,t=!1)=>t?a.delete(e):a.get(e).done=!0,getItems:(e=!1)=>e?i():i().filter((e=>!e.done)),getQueue:()=>a,getTypeable:()=>i().filter((e=>e.typeable))}}([{delay:Y.startDelay}]);J.dataset.typeitId=Z,y(d);let te=!!Y.cursor&&!M(),ne=(()=>{if(M())return;let e=p("span");return e.className=l,te?(e.innerHTML=o(Y.cursorChar).innerHTML,e):(e.style.visibility="hidden",e)})();Y.strings=(e=>{let t=J.innerHTML;return t?(J.innerHTML="",Y.startDelete?(J.innerHTML=t,a(J),F(I({func:Q,delay:x(1),deletable:!0},$().length)),e):t.replace(/<!--(.+?)-->/g,"").trim().split(/<br(?:\s*?)(?:\/)?>/).concat(e)):e})(n(Y.strings)),Y.strings.length&&q()},$=e.forwardRef(((t,n)=>{const{as:r}=t;return e.createElement(r,{ref:n,...t})})),O=t=>{const n=e.useRef(null),r=e.useRef(null),{options:i,children:a,getBeforeInit:o,getAfterInit:s,...l}=t,[u,c]=e.useState(!0),[d,f]=e.useState(null);return e.useEffect((()=>{!function(){const e=Object.assign({},i);a&&n.current&&(e.strings=n.current.innerHTML),f(e)}(),c(!1)}),[i]),e.useEffect((()=>{var e;d&&((null==(e=r.current)?void 0:e.updateOptions(d))||(r.current=new x(n.current,d),r.current=o(r.current),r.current.go(),r.current=s(r.current)))}),[d]),e.useEffect((()=>()=>{var e;return null==(e=r.current)?void 0:e.destroy()}),[]),e.createElement($,{ref:n,children:u?a:null,style:{opacity:u?0:1},...l})};return O.defaultProps={as:"span",options:{},getBeforeInit:e=>e,getAfterInit:e=>e},O})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).TypeIt=e(t.React)}(this,(function(t){"use strict";var e,s,i,n,r,a,o,l,h,u,c,d,f,p,m,y,g,w,b,v,S,T,P,k,E,W,C,q,L,N,I,D,M,x,A,O,$,R,H,z,F,B,j,_,V,Q,J,U,X,G,K=Object.defineProperty,Y=(t,e,s)=>(((t,e,s)=>{e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s})(t,"symbol"!=typeof e?e+"":e,s),s),Z=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},tt=(t,e,s)=>(Z(t,e,"read from private field"),s?s.call(t):e.get(t)),et=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},st=(t,e,s)=>(Z(t,e,"access private method"),s);const it=t=>Array.isArray(t),nt=t=>it(t)?t:[t];const rt="data-typeit-id",at="ti-cursor",ot={started:!1,completed:!1,frozen:!1,destroyed:!1},lt={breakLines:!0,cursor:{autoPause:!0,autoPauseDelay:500,animation:{frames:[0,0,1].map((t=>({opacity:t}))),options:{iterations:1/0,easing:"steps(2, start)",fill:"forwards"}}},cursorChar:"|",cursorSpeed:1e3,deleteSpeed:null,html:!0,lifeLike:!0,loop:!1,loopDelay:750,nextStringDelay:750,speed:100,startDelay:250,startDelete:!1,strings:[],waitUntilVisible:!1,beforeString:()=>{},afterString:()=>{},beforeStep:()=>{},afterStep:()=>{},afterComplete:()=>{}},ht=`[${rt}]:before {content: '.'; display: inline-block; width: 0; visibility: hidden;}`,ut=t=>document.createElement(t),ct=t=>document.createTextNode(t),dt=(t,e="")=>{let s=ut("style");s.id=e,s.appendChild(ct(t)),document.head.appendChild(s)},ft=t=>(it(t)||(t=[t/2,t/2]),t),pt=(t,e)=>Math.abs(Math.random()*(t+e-(t-e))+(t-e));let mt=t=>t/2;const yt=t=>Array.from(t);let gt=t=>([...t.childNodes].forEach((t=>{if(t.nodeValue)return[...t.nodeValue].forEach((e=>{t.parentNode.insertBefore(ct(e),t)})),void t.remove();gt(t)})),t);const wt=t=>{let e=document.implementation.createHTMLDocument();return e.body.innerHTML=t,gt(e.body)};function bt(t,e=!1,s=!1){let i,n=t.querySelector(`.${at}`),r=document.createTreeWalker(t,NodeFilter.SHOW_ALL,{acceptNode:t=>{var e,i;if(n&&s){if(null==(e=t.classList)?void 0:e.contains(at))return NodeFilter.FILTER_ACCEPT;if(n.contains(t))return NodeFilter.FILTER_REJECT}return(null==(i=t.classList)?void 0:i.contains(at))?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),a=[];for(;i=r.nextNode();)i.originalParent||(i.originalParent=i.parentNode),a.push(i);return e?a.reverse():a}function vt(t,e=!0){return e?bt(wt(t)):yt(t).map(ct)}const St=t=>Number.isInteger(t),Tt=({queueItems:t,selector:e,cursorPosition:s,to:i})=>{if(St(e))return-1*e;let n=new RegExp("END","i").test(i),r=e?[...t].reverse().findIndex((({char:t})=>{let s=t.parentElement,i=s.matches(e);return!(!n||!i)||i&&s.firstChild.isSameNode(t)})):-1;return r<0&&(r=n?0:t.length-1),r-s+(n?0:1)},Pt=(t,e)=>new Array(e).fill(t);let kt=t=>new Promise((e=>{requestAnimationFrame((async()=>{e(await t())}))})),Et=t=>null==t?void 0:t.getAnimations().find((e=>e.id===t.dataset.tiAnimationId)),Wt=({cursor:t,frames:e,options:s})=>{let i=t.animate(e,s);return i.pause(),i.id=t.dataset.tiAnimationId,kt((()=>{kt((()=>{i.play()}))})),i},Ct=t=>{var e;return null==(e=t.func)?void 0:e.call(null)},qt=async({index:t,queueItems:e,wait:s,cursor:i,cursorOptions:n})=>{let r=e[t][1],a=[],o=t,l=r,h=()=>l&&!l.delay,u=r.shouldPauseCursor()&&n.autoPause;for(;h();)a.push(l),h()&&o++,l=e[o]?e[o][1]:null;if(a.length)return await kt((async()=>{for(let t of a)await Ct(t)})),o-1;let c,d=Et(i);return d&&(c={...d.effect.getComputedTiming(),delay:u?n.autoPauseDelay:0}),await s((async()=>{d&&u&&d.cancel(),await kt((()=>{Ct(r)}))}),r.delay),await(({cursor:t,options:e,cursorOptions:s})=>{if(!t||!s)return;let i,n=Et(t);n&&(e.delay=n.effect.getComputedTiming().delay,i=n.currentTime,n.cancel());let r=Wt({cursor:t,frames:s.animation.frames,options:e});return i&&(r.currentTime=i),r})({cursor:i,options:c,cursorOptions:n}),t};const Lt=t=>"value"in t;let Nt=t=>"function"==typeof t?t():t,It=(t,e=document,s=!1)=>e["querySelector"+(s?"All":"")](t);const Dt=(t,e)=>Object.assign({},t,e);let Mt={"font-family":"","font-weight":"","font-size":"","font-style":"","line-height":"",color:"",transform:"translateX(-.125em)"};let xt=(G=class{constructor(t,s={}){var n;et(this,e),et(this,i),et(this,r),et(this,o),et(this,h),et(this,c),et(this,f),et(this,m),et(this,g),et(this,b),et(this,S),et(this,P),et(this,E),et(this,q),et(this,N),et(this,D),et(this,x),et(this,O),et(this,R),et(this,z),et(this,B),et(this,_),et(this,Q),et(this,U),Y(this,"element"),Y(this,"timeouts"),Y(this,"cursorPosition"),Y(this,"predictedCursorPosition"),Y(this,"statuses",{started:!1,completed:!1,frozen:!1,destroyed:!1}),Y(this,"opts"),Y(this,"id"),Y(this,"queue"),Y(this,"cursor"),Y(this,"unfreeze",(()=>{})),Y(this,"is",(function(t){return this.statuses[t]})),et(this,C,(t=>{t.cursor=(t=>{var e,s;if("object"==typeof t){let i={},{frames:n,options:r}=lt.cursor.animation;return i.animation=t.animation||{},i.animation.frames=(null==(e=t.animation)?void 0:e.frames)||n,i.animation.options=Dt(r,(null==(s=t.animation)?void 0:s.options)||{}),i.autoPause=t.autoPause??lt.cursor.autoPause,i.autoPauseDelay=t.autoPauseDelay||lt.cursor.autoPauseDelay,i}return!0===t?lt.cursor:t})(t.cursor??lt.cursor),this.opts.strings=st(this,q,L).call(this,nt(this.opts.strings)),this.opts=Dt(this.opts,{html:!tt(this,_,V)&&this.opts.html,nextStringDelay:ft(this.opts.nextStringDelay),loopDelay:ft(this.opts.loopDelay)})})),this.opts=Dt(lt,s),this.element="string"==typeof(n=t)?It(n):n,this.timeouts=[],this.cursorPosition=0,this.unfreeze=()=>{},this.predictedCursorPosition=null,this.statuses=Dt({},ot),this.id=Math.random().toString().substring(2,9),this.queue=function(t){let e=function(t){return nt(t).forEach((t=>{var e;return n.set(Symbol(null==(e=t.char)?void 0:e.innerText),s({...t}))})),this},s=t=>(t.shouldPauseCursor=function(){return Boolean(this.typeable||this.cursorable||this.deletable)},t),i=()=>Array.from(n.values()),n=new Map;return e(t),{add:e,set:function(t,e){let i=[...n.keys()];n.set(i[t],s(e))},wipe:function(){n=new Map,e(t)},done:(t,e=!1)=>e?n.delete(t):n.get(t).done=!0,reset:function(){n.forEach((t=>delete t.done))},destroy:t=>n.delete(t),getItems:(t=!1)=>t?i():i().filter((t=>!t.done)),getQueue:()=>n,getTypeable:()=>i().filter((t=>t.typeable))}}([{delay:this.opts.startDelay}]),tt(this,C).call(this,s),this.cursor=st(this,N,I).call(this),this.element.dataset.typeitId=this.id,dt(ht),this.opts.strings.length&&st(this,E,W).call(this)}go(){return this.statuses.started?this:(st(this,f,p).call(this),this.opts.waitUntilVisible?(t=this.element,e=st(this,i,n).bind(this),new IntersectionObserver(((s,i)=>{s.forEach((s=>{s.isIntersecting&&(e(),i.unobserve(t))}))}),{threshold:1}).observe(t),this):(st(this,i,n).call(this),this));var t,e}destroy(t=!0){this.timeouts=(this.timeouts.forEach(clearTimeout),[]),Nt(t)&&this.cursor&&st(this,R,H).call(this,this.cursor),this.statuses.destroyed=!0}reset(t){!this.is("destroyed")&&this.destroy(),t?(this.queue.wipe(),t(this)):this.queue.reset(),this.cursorPosition=0;for(let e in this.statuses)this.statuses[e]=!1;return this.element[st(this,m,y).call(this)?"value":"innerHTML"]="",this}type(t,e={}){t=Nt(t);let{instant:s}=e,i=st(this,S,T).call(this,e),n=vt(t,this.opts.html).map((t=>{return{func:()=>st(this,x,A).call(this,t),char:t,delay:s||(e=t,/<(.+)>(.*?)<\/(.+)>/.test(e.outerHTML))?0:st(this,z,F).call(this),typeable:t.nodeType===Node.TEXT_NODE};var e})),r=[i[0],{func:async()=>await this.opts.beforeString(t,this)},...n,{func:async()=>await this.opts.afterString(t,this)},i[1]];return st(this,g,w).call(this,r,e)}break(t={}){return st(this,g,w).call(this,{func:()=>st(this,x,A).call(this,ut("BR")),typeable:!0},t)}move(t,e={}){t=Nt(t);let s=st(this,S,T).call(this,e),{instant:i,to:n}=e,o=Tt({queueItems:this.queue.getTypeable(),selector:null===t?"":t,to:n,cursorPosition:tt(this,B,j)}),l=o<0?-1:1;return this.predictedCursorPosition=tt(this,B,j)+o,st(this,g,w).call(this,[s[0],...Pt({func:()=>st(this,r,a).call(this,l),delay:i?0:st(this,z,F).call(this),cursorable:!0},Math.abs(o)),s[1]],e)}exec(t,e={}){let s=st(this,S,T).call(this,e);return st(this,g,w).call(this,[s[0],{func:()=>t(this)},s[1]],e)}options(t,e={}){return t=Nt(t),st(this,P,k).call(this,t),st(this,g,w).call(this,{},e)}pause(t,e={}){return st(this,g,w).call(this,{delay:Nt(t)},e)}delete(t=null,e={}){t=Nt(t);let s=st(this,S,T).call(this,e),i=t,{instant:n,to:r}=e,a=this.queue.getTypeable(),o=(()=>null===i?a.length:St(i)?i:Tt({queueItems:a,selector:i,cursorPosition:tt(this,B,j),to:r}))();return st(this,g,w).call(this,[s[0],...Pt({func:st(this,O,$).bind(this),delay:n?0:st(this,z,F).call(this,1),deletable:!0},o),s[1]],e)}freeze(){this.statuses.frozen=!0}flush(t=(()=>{})){return st(this,f,p).call(this),st(this,i,n).call(this,!1).then(t),this}getQueue(){return this.queue}getOptions(){return this.opts}updateOptions(t){return st(this,P,k).call(this,t)}getElement(){return this.element}empty(t={}){return st(this,g,w).call(this,{func:st(this,e,s).bind(this)},t)}},e=new WeakSet,s=async function(){st(this,m,y).call(this)?this.element.value="":tt(this,U,X).forEach(st(this,R,H).bind(this))},i=new WeakSet,n=async function(t=!0){this.statuses.started=!0;let e=e=>{this.queue.done(e,!t)};try{let s=[...this.queue.getQueue()];for(let t=0;t<s.length;t++){let[i,n]=s[t];if(!n.done){if(!n.deletable||n.deletable&&tt(this,U,X).length){let i=await st(this,h,u).call(this,t,s);Array(i-t).fill(t+1).map(((t,e)=>t+e)).forEach((t=>{let[i]=s[t];e(i)})),t=i}e(i)}}if(!t)return this;if(this.statuses.completed=!0,await this.opts.afterComplete(this),!this.opts.loop)throw"";let r=this.opts.loopDelay;st(this,c,d).call(this,(async()=>{await st(this,o,l).call(this,r[0]),st(this,i,n).call(this)}),r[1])}catch(s){}return this},r=new WeakSet,a=async function(t){var e,s,i;this.cursorPosition=(e=t,s=this.cursorPosition,i=tt(this,U,X),Math.min(Math.max(s+e,0),i.length)),((t,e,s)=>{let i=e[s-1],n=It(`.${at}`,t);(t=(null==i?void 0:i.parentNode)||t).insertBefore(n,i||null)})(this.element,tt(this,U,X),this.cursorPosition)},o=new WeakSet,l=async function(t){let e=tt(this,B,j);e&&await st(this,r,a).call(this,{value:e});let s=tt(this,U,X).map((t=>[Symbol(),{func:st(this,O,$).bind(this),delay:st(this,z,F).call(this,1),deletable:!0,shouldPauseCursor:()=>!0}]));for(let i=0;i<s.length;i++)await st(this,h,u).call(this,i,s);this.queue.reset(),this.queue.set(0,{delay:t})},h=new WeakSet,u=function(t,e){return qt({index:t,queueItems:e,wait:st(this,c,d).bind(this),cursor:this.cursor,cursorOptions:this.opts.cursor})},c=new WeakSet,d=async function(t,e,s=!1){this.statuses.frozen&&await new Promise((t=>{this.unfreeze=()=>{this.statuses.frozen=!1,t()}})),s||await this.opts.beforeStep(this),await((t,e,s)=>new Promise((i=>{s.push(setTimeout((async()=>{await t(),i()}),e||0))})))(t,e,this.timeouts),s||await this.opts.afterStep(this)},f=new WeakSet,p=async function(){if(!st(this,m,y).call(this)&&this.cursor&&this.element.appendChild(this.cursor),tt(this,Q,J)){((t,e)=>{let s=`[${rt}='${t}'] .${at}`,i=getComputedStyle(e),n=Object.entries(Mt).reduce(((t,[e,s])=>`${t} ${e}: var(--ti-cursor-${e}, ${s||i[e]});`),"");dt(`${s} { display: inline-block; width: 0; ${n} }`,t)})(this.id,this.element),this.cursor.dataset.tiAnimationId=this.id;let{animation:t}=this.opts.cursor,{frames:e,options:s}=t;Wt({frames:e,cursor:this.cursor,options:{duration:this.opts.cursorSpeed,...s}})}},m=new WeakSet,y=function(){return Lt(this.element)},g=new WeakSet,w=function(t,e){return this.queue.add(t),st(this,b,v).call(this,e),this},b=new WeakSet,v=function(t={}){let e=t.delay;e&&this.queue.add({delay:e})},S=new WeakSet,T=function(t={}){return[{func:()=>st(this,P,k).call(this,t)},{func:()=>st(this,P,k).call(this,this.opts)}]},P=new WeakSet,k=async function(t){this.opts=Dt(this.opts,t)},E=new WeakSet,W=function(){let t=this.opts.strings.filter((t=>!!t));t.forEach(((e,s)=>{if(this.type(e),s+1===t.length)return;let i=this.opts.breakLines?[{func:()=>st(this,x,A).call(this,ut("BR")),typeable:!0}]:Pt({func:st(this,O,$).bind(this),delay:st(this,z,F).call(this,1)},this.queue.getTypeable().length);st(this,D,M).call(this,i)}))},C=new WeakMap,q=new WeakSet,L=function(t){let e=this.element.innerHTML;return e?(this.element.innerHTML="",this.opts.startDelete?(this.element.innerHTML=e,gt(this.element),st(this,D,M).call(this,Pt({func:st(this,O,$).bind(this),delay:st(this,z,F).call(this,1),deletable:!0},tt(this,U,X).length)),t):(s=e,s.replace(/<!--(.+?)-->/g,"").trim().split(/<br(?:\s*?)(?:\/)?>/)).concat(t)):t;var s},N=new WeakSet,I=function(){if(tt(this,_,V))return null;let t=ut("span");return t.className=at,tt(this,Q,J)?(t.innerHTML=wt(this.opts.cursorChar).innerHTML,t):(t.style.visibility="hidden",t)},D=new WeakSet,M=function(t){let e=this.opts.nextStringDelay;this.queue.add([{delay:e[0]},...t,{delay:e[1]}])},x=new WeakSet,A=function(t){((t,e)=>{if(Lt(t))return void(t.value=`${t.value}${e.textContent}`);e.innerHTML="";let s=(i=e.originalParent,/body/i.test(null==i?void 0:i.tagName)?t:e.originalParent||t);var i;s.insertBefore(e,It("."+at,s)||null)})(this.element,t)},O=new WeakSet,$=function(){tt(this,U,X).length&&(tt(this,_,V)?this.element.value=this.element.value.slice(0,-1):st(this,R,H).call(this,tt(this,U,X)[this.cursorPosition]))},R=new WeakSet,H=function(t){((t,e)=>{if(!t)return;let s=t.parentNode;(s.childNodes.length>1||s.isSameNode(e)?t:s).remove()})(t,this.element)},z=new WeakSet,F=function(t=0){return function(t){let{speed:e,deleteSpeed:s,lifeLike:i}=t;return s=null!==s?s:e/3,i?[pt(e,mt(e)),pt(s,mt(s))]:[e,s]}(this.opts)[t]},B=new WeakSet,j=function(){return this.predictedCursorPosition??this.cursorPosition},_=new WeakSet,V=function(){return Lt(this.element)},Q=new WeakSet,J=function(){return!!this.opts.cursor&&!tt(this,_,V)},U=new WeakSet,X=function(){return t=this.element,Lt(t)?yt(t.value):bt(t,!0).filter((t=>!(t.childNodes.length>0)));var t},G);const At=t.forwardRef(((e,s)=>{const{as:i}=e;return t.createElement(i,{ref:s,...e})})),Ot={};return({as:e="span",options:s=Ot,children:i=null,getBeforeInit:n=(t=>t),getAfterInit:r=(t=>t),...a})=>{const o=t.useRef(null),l=t.useRef(null),[h,u]=t.useState(!0),[c,d]=t.useState(null);return t.useEffect((()=>{!function(){const t=Object.assign({},s);i&&o.current&&(t.strings=o.current.innerHTML),d(t)}(),u(!1)}),[s]),t.useEffect((()=>{var t;c&&((null==(t=l.current)?void 0:t.updateOptions(c))||(l.current=new xt(o.current,c),l.current=n(l.current),l.current.go(),l.current=r(l.current)))}),[c]),t.useEffect((()=>()=>{var t;return null==(t=l.current)?void 0:t.destroy()}),[]),t.createElement(At,{ref:o,as:e,children:h?i:null,style:{opacity:h?0:1},...a})}})); |
{ | ||
"name": "typeit-react", | ||
"version": "2.6.4", | ||
"version": "2.7.0", | ||
"description": "React component for the most versatile JavaScript animated typing utility on the planet.", | ||
@@ -41,13 +41,13 @@ "homepage": "https://typeitjs.com", | ||
"dependencies": { | ||
"react": ">=17.0.0", | ||
"react-dom": ">=17.0.0", | ||
"typeit": "^8.7.1" | ||
"react": ">=18.2.0", | ||
"react-dom": ">=18.2.0", | ||
"typeit": "^8.8.0" | ||
}, | ||
"devDependencies": { | ||
"@babel/preset-typescript": "^7.18.6", | ||
"@types/react": "^18.0.26", | ||
"terser": "^5.16.1", | ||
"typescript": "^4.9.4", | ||
"vite": "^4.0.3" | ||
"@babel/preset-typescript": "^7.23.3", | ||
"@types/react": "^18.2.38", | ||
"terser": "^5.24.0", | ||
"typescript": "^5.3.2", | ||
"vite": "^5.0.2" | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
59082
1138
1
+ Addedjs-tokens@4.0.0(transitive)
+ Addedloose-envify@1.4.0(transitive)
+ Addedreact@18.3.1(transitive)
+ Addedreact-dom@18.3.1(transitive)
+ Addedscheduler@0.23.2(transitive)
- Removedreact@18.3.0(transitive)
- Removedreact-dom@18.3.0(transitive)
Updatedreact@>=18.2.0
Updatedreact-dom@>=18.2.0
Updatedtypeit@^8.8.0