@chayns-components/typewriter 5.0.53-alpha.0 → 5.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/components/typewriter/{typewrite-view/animated-typewriter-text/AnimatedTypewriterText.js → AnimatedTypewriterText.js} +2 -2
- package/lib/cjs/components/typewriter/AnimatedTypewriterText.js.map +1 -0
- package/lib/cjs/components/typewriter/Typewriter.js +216 -66
- package/lib/cjs/components/typewriter/Typewriter.js.map +1 -1
- package/lib/cjs/components/typewriter/{typewrite-view/TypewriterView.styles.js → Typewriter.styles.js} +2 -2
- package/lib/cjs/components/typewriter/Typewriter.styles.js.map +1 -0
- package/lib/cjs/{utils → components/typewriter}/utils.js +24 -7
- package/lib/cjs/components/typewriter/utils.js.map +1 -0
- package/lib/esm/components/typewriter/{typewrite-view/animated-typewriter-text/AnimatedTypewriterText.js → AnimatedTypewriterText.js} +1 -1
- package/lib/esm/components/typewriter/AnimatedTypewriterText.js.map +1 -0
- package/lib/esm/components/typewriter/Typewriter.js +219 -69
- package/lib/esm/components/typewriter/Typewriter.js.map +1 -1
- package/lib/esm/components/typewriter/{typewrite-view/TypewriterView.styles.js → Typewriter.styles.js} +2 -2
- package/lib/esm/components/typewriter/Typewriter.styles.js.map +1 -0
- package/lib/esm/{utils → components/typewriter}/utils.js +22 -5
- package/lib/esm/components/typewriter/utils.js.map +1 -0
- package/lib/types/components/typewriter/{typewrite-view/TypewriterView.styles.d.ts → Typewriter.styles.d.ts} +1 -1
- package/lib/types/{utils → components/typewriter}/utils.d.ts +4 -1
- package/package.json +3 -3
- package/lib/cjs/components/typewriter/typewrite-view/TypewriterView.js +0 -55
- package/lib/cjs/components/typewriter/typewrite-view/TypewriterView.js.map +0 -1
- package/lib/cjs/components/typewriter/typewrite-view/TypewriterView.styles.js.map +0 -1
- package/lib/cjs/components/typewriter/typewrite-view/animated-typewriter-text/AnimatedTypewriterText.js.map +0 -1
- package/lib/cjs/hooks/useChunkStreamingSpeed.js +0 -36
- package/lib/cjs/hooks/useChunkStreamingSpeed.js.map +0 -1
- package/lib/cjs/hooks/useTypewriterAnimation.js +0 -185
- package/lib/cjs/hooks/useTypewriterAnimation.js.map +0 -1
- package/lib/cjs/utils/utils.js.map +0 -1
- package/lib/esm/components/typewriter/typewrite-view/TypewriterView.js +0 -48
- package/lib/esm/components/typewriter/typewrite-view/TypewriterView.js.map +0 -1
- package/lib/esm/components/typewriter/typewrite-view/TypewriterView.styles.js.map +0 -1
- package/lib/esm/components/typewriter/typewrite-view/animated-typewriter-text/AnimatedTypewriterText.js.map +0 -1
- package/lib/esm/hooks/useChunkStreamingSpeed.js +0 -30
- package/lib/esm/hooks/useChunkStreamingSpeed.js.map +0 -1
- package/lib/esm/hooks/useTypewriterAnimation.js +0 -178
- package/lib/esm/hooks/useTypewriterAnimation.js.map +0 -1
- package/lib/esm/utils/utils.js.map +0 -1
- package/lib/types/components/typewriter/typewrite-view/TypewriterView.d.ts +0 -19
- package/lib/types/hooks/useChunkStreamingSpeed.d.ts +0 -7
- package/lib/types/hooks/useTypewriterAnimation.d.ts +0 -35
- /package/lib/types/components/typewriter/{typewrite-view/animated-typewriter-text/AnimatedTypewriterText.d.ts → AnimatedTypewriterText.d.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":["_speed","require","getSubTextFromHTML","html","length","div","document","createElement","innerHTML","text","currLength","escapeText","value","replace","escapeAttr","String","VOID_ELEMENTS","Set","traverse","node","nodeType","textContent","nodeText","remaining","substring","element","nodeName","toLowerCase","attributes","attribute","name","isVoid","has","i","childNodes","childNode","exports","getCharactersCount","count","trim","Array","from","forEach","shuffleArray","array","result","j","Math","floor","random","calculateAutoSpeed","ema","MINIMUM_TIMEOUT","speed","TypewriterSpeed","ExtraSlow","steps","msPerChar","min","max","calculateEMA","currentEMA","newValue","alpha","updateChunkStreamingSpeedEMA","currentLength","state","now","Date","deltaTime","lastTimestamp","deltaLength","lastLength","charsPerSecond","newEMA"],"sources":["../../../../src/components/typewriter/utils.ts"],"sourcesContent":["import { TypewriterSpeed } from '../../types/speed';\n\n/**\n * Returns a substring of an HTML string while preserving HTML structure.\n *\n * Core rules:\n * - Element nodes are re-serialized as tags (start/end) to keep structure.\n * - Text nodes are always HTML-escaped on output. This prevents that previously\n * escaped text (like \"<div>\") turns into real tags during the DOM round trip.\n * - Attribute values are HTML-escaped on output.\n * - Void elements are serialized without closing tags.\n * - For TWIGNORE/TW-IGNORE elements, the innerHTML is passed through so that\n * their content (including real HTML) remains untouched.\n * - On early cutoff (once the length limit is reached), already opened tags are\n * properly closed to keep the result valid HTML.\n *\n * Note on length counting:\n * - The length is based on the decoded textContent length (as the DOM provides),\n * not on byte length nor escaped entity length. This mirrors how the text is perceived.\n *\n * @param html The input HTML string; may contain a mix of real HTML and already escaped HTML.\n * @param length The maximum number of text characters (based on textContent) to include.\n * @returns A valid HTML string containing up to the specified number of text characters,\n * preserving HTML tags and keeping escaped text escaped.\n */\nexport const getSubTextFromHTML = (html: string, length: number): string => {\n const div = document.createElement('div');\n\n div.innerHTML = html;\n\n let text = '';\n let currLength = 0;\n\n // Escape text node content to ensure that decoded \"<\" and \">\" do not become real tags.\n const escapeText = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\n // Escape attribute values safely.\n const escapeAttr = (value: string): string =>\n String(value)\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n\n // HTML void elements (must not have closing tags)\n const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n ]);\n\n // Traverses nodes and appends to \"text\".\n // Returns false to signal \"stop traversal\" once the length limit is reached.\n const traverse = (node: Node): boolean => {\n // Text node\n if (node.nodeType === 3 && typeof node.textContent === 'string') {\n const nodeText = node.textContent;\n const remaining = length - currLength;\n\n if (remaining <= 0) {\n return false;\n }\n\n if (nodeText.length <= remaining) {\n // Always escape text before writing to output\n text += escapeText(nodeText);\n currLength += nodeText.length;\n } else {\n // Cut the text and stop traversal\n text += escapeText(nodeText.substring(0, remaining));\n currLength += remaining;\n return false;\n }\n\n return true;\n }\n\n // Element node\n if (node.nodeType === 1) {\n const element = node as Element;\n\n // Pass-through for TWIGNORE/TW-IGNORE: keep their HTML as-is.\n if (element.nodeName === 'TWIGNORE' || element.nodeName === 'TW-IGNORE') {\n // element.innerHTML serializes children; escaped text stays escaped,\n // real HTML stays HTML — exactly what we want here.\n text += element.innerHTML;\n return true;\n }\n\n const nodeName = element.nodeName.toLowerCase();\n\n // Serialize attributes safely\n let attributes = '';\n // @ts-expect-error: attributes is a NodeListOf<Attr>\n // eslint-disable-next-line no-restricted-syntax\n for (const attribute of element.attributes) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-argument\n attributes += ` ${attribute.name}=\"${escapeAttr(attribute.value)}\"`;\n }\n\n // Open tag\n text += `<${nodeName}${attributes}>`;\n\n // Void elements: do not recurse children and do not emit a closing tag\n const isVoid = VOID_ELEMENTS.has(nodeName);\n if (!isVoid) {\n // Recurse through children until limit is reached\n for (let i = 0; i < element.childNodes.length; i++) {\n const childNode = element.childNodes[i];\n if (childNode && !traverse(childNode)) {\n // On early stop: close this tag to keep valid HTML, then bubble stop.\n text += `</${nodeName}>`;\n return false;\n }\n }\n\n // Close tag after all children\n text += `</${nodeName}>`;\n }\n\n return true;\n }\n\n // Other node types (comments, etc.) are ignored for text length\n return true;\n };\n\n // Traverse top-level children\n for (let i = 0; i < div.childNodes.length; i++) {\n const childNode = div.childNodes[i];\n if (childNode && !traverse(childNode)) {\n return text;\n }\n }\n\n return text;\n};\n\nexport const getCharactersCount = (html: string): number => {\n const div = document.createElement('div');\n\n div.innerHTML = html;\n\n let count = 0;\n\n const traverse = (node: Node): void => {\n if (node.nodeName === 'TWIGNORE') {\n count += 1;\n } else if (node.nodeType === 3 && typeof node.textContent === 'string') {\n count += node.textContent.trim().length;\n } else if (node.nodeType === 1) {\n if (node.nodeName === 'CODE' && node.textContent !== null) {\n count += node.textContent.length;\n\n return;\n }\n\n Array.from(node.childNodes).forEach(traverse);\n }\n };\n\n Array.from(div.childNodes).forEach(traverse);\n\n return count;\n};\n\nexport const shuffleArray = <T>(array: T[]): T[] => {\n const result = Array.from(array);\n\n for (let i = result.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n [result[i], result[j]] = [result[j]!, result[i]!];\n }\n\n return result;\n};\n\nexport const calculateAutoSpeed = (ema: number): { speed: number; steps: number } => {\n // nested timer calls are clamped to a 4ms minimum\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#reasons_for_longer_delays_than_specified\n const MINIMUM_TIMEOUT = 4;\n\n if (ema <= 0) {\n return { speed: TypewriterSpeed.ExtraSlow, steps: 1 };\n }\n\n const msPerChar = Math.min(1000 / ema, TypewriterSpeed.ExtraSlow);\n\n if (msPerChar >= MINIMUM_TIMEOUT) {\n return { speed: msPerChar, steps: 1 };\n }\n\n const steps = Math.max(1, MINIMUM_TIMEOUT / msPerChar);\n return { speed: MINIMUM_TIMEOUT, steps };\n};\n\ninterface CalculateEMAProps {\n currentEMA: number;\n newValue: number;\n alpha?: number;\n}\n\nexport const calculateEMA = ({ currentEMA, newValue, alpha = 0.25 }: CalculateEMAProps): number =>\n alpha * newValue + (1 - alpha) * currentEMA;\n\nexport interface ChunkStreamingSpeedState {\n lastTimestamp?: number;\n lastLength: number;\n ema: number;\n}\n\ninterface ChunkStreamingSpeedProps {\n currentLength: number;\n state: ChunkStreamingSpeedState;\n}\n\nexport const updateChunkStreamingSpeedEMA = ({\n currentLength,\n state,\n}: ChunkStreamingSpeedProps): ChunkStreamingSpeedState => {\n const now = Date.now();\n const deltaTime = now - (state?.lastTimestamp ?? now);\n\n if (deltaTime <= 0) return { ...state, lastTimestamp: now };\n\n const deltaLength = currentLength - state.lastLength;\n\n const charsPerSecond = Math.max(0, (deltaLength / deltaTime) * 1000);\n\n const newEMA = calculateEMA({\n currentEMA: state.ema,\n newValue: charsPerSecond,\n });\n\n return {\n lastTimestamp: now,\n lastLength: currentLength,\n ema: newEMA,\n };\n};\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,kBAAkB,GAAGA,CAACC,IAAY,EAAEC,MAAc,KAAa;EACxE,MAAMC,GAAG,GAAGC,QAAQ,CAACC,aAAa,CAAC,KAAK,CAAC;EAEzCF,GAAG,CAACG,SAAS,GAAGL,IAAI;EAEpB,IAAIM,IAAI,GAAG,EAAE;EACb,IAAIC,UAAU,GAAG,CAAC;;EAElB;EACA,MAAMC,UAAU,GAAIC,KAAa,IAC7BA,KAAK,CAACC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAACA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAACA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;;EAE5E;EACA,MAAMC,UAAU,GAAIF,KAAa,IAC7BG,MAAM,CAACH,KAAK,CAAC,CACRC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CACtBA,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CACvBA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CACrBA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;;EAE9B;EACA,MAAMG,aAAa,GAAG,IAAIC,GAAG,CAAC,CAC1B,MAAM,EACN,MAAM,EACN,IAAI,EACJ,KAAK,EACL,OAAO,EACP,IAAI,EACJ,KAAK,EACL,OAAO,EACP,MAAM,EACN,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,WAAW,GAAGN,aAAa,GAAGC,KAAK,CAACM,UAAU;EAEpD,MAAMC,cAAc,GAAG1B,IAAI,CAACY,GAAG,CAAC,CAAC,EAAGY,WAAW,GAAGF,SAAS,GAAI,IAAI,CAAC;EAEpE,MAAMK,MAAM,GAAGd,YAAY,CAAC;IACxBC,UAAU,EAAEK,KAAK,CAACf,GAAG;IACrBW,QAAQ,EAAEW;EACd,CAAC,CAAC;EAEF,OAAO;IACHH,aAAa,EAAEH,GAAG;IAClBK,UAAU,EAAEP,aAAa;IACzBd,GAAG,EAAEuB;EACT,CAAC;AACL,CAAC;AAACtC,OAAA,CAAA4B,4BAAA,GAAAA,4BAAA","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AnimatedTypewriterText.js","names":["React","useCallback","useMemo","StyledTypewriterText","AnimatedTypewriterText","shouldHideCursor","shownText","shouldRemainSingleLine","textStyle","updateTypewriterCursor","ref","traverseNodes","node","nodeType","Node","TEXT_NODE","textContent","trim","parentElement","childNodes","Array","from","i","length","result","lastParentWithContent","classList","remove","querySelectorAll","forEach","element","add","createElement","dangerouslySetInnerHTML","__html","$shouldRemainSingleLine","style","$isAnimatingText"],"sources":["../../../../src/components/typewriter/AnimatedTypewriterText.tsx"],"sourcesContent":["import React, { FC, useCallback, useMemo } from 'react';\nimport { CSSPropertiesWithVars } from 'styled-components/dist/types';\nimport { StyledTypewriterText } from './Typewriter.styles';\n\ntype AnimatedTypewriterTextProps = {\n shouldHideCursor: boolean;\n shownText: string;\n textStyle?: CSSPropertiesWithVars;\n shouldRemainSingleLine: boolean;\n};\n\nconst AnimatedTypewriterText: FC<AnimatedTypewriterTextProps> = ({\n shouldHideCursor,\n shownText,\n shouldRemainSingleLine,\n textStyle,\n}) => {\n const updateTypewriterCursor = useCallback(\n (ref: HTMLSpanElement | null) => {\n if (ref && !shouldHideCursor) {\n // Finds the last text node with content.\n const traverseNodes = (node: Node): HTMLElement | null => {\n if (node.nodeType === Node.TEXT_NODE && node.textContent?.trim()) {\n return node.parentElement;\n }\n\n const childNodes = Array.from(node.childNodes);\n for (let i = childNodes.length - 1; i >= 0; i--) {\n const result = traverseNodes(childNodes[i] as Node);\n if (result) {\n return result;\n }\n }\n\n return null;\n };\n\n const lastParentWithContent = traverseNodes(ref);\n\n // Removes lastWithContent class from all elements\n ref.classList.remove('typewriter-lastWithContent');\n ref.querySelectorAll('.lastWithContent').forEach((element) => {\n element.classList.remove('typewriter-lastWithContent');\n });\n\n // Adds lastWithContent class to the last element with content\n if (lastParentWithContent) {\n lastParentWithContent.classList.add('typewriter-lastWithContent');\n } else {\n ref.classList.add('typewriter-lastWithContent');\n }\n }\n },\n [shouldHideCursor],\n );\n\n return useMemo(\n () => (\n <StyledTypewriterText\n ref={(ref) => updateTypewriterCursor(ref)}\n dangerouslySetInnerHTML={{ __html: shownText }}\n $shouldRemainSingleLine={shouldRemainSingleLine}\n style={textStyle}\n $isAnimatingText\n />\n ),\n [shownText, shouldRemainSingleLine, textStyle, updateTypewriterCursor],\n );\n};\n\nexport default AnimatedTypewriterText;\n"],"mappings":"AAAA,OAAOA,KAAK,IAAQC,WAAW,EAAEC,OAAO,QAAQ,OAAO;AAEvD,SAASC,oBAAoB,QAAQ,qBAAqB;AAS1D,MAAMC,sBAAuD,GAAGA,CAAC;EAC7DC,gBAAgB;EAChBC,SAAS;EACTC,sBAAsB;EACtBC;AACJ,CAAC,KAAK;EACF,MAAMC,sBAAsB,GAAGR,WAAW,CACrCS,GAA2B,IAAK;IAC7B,IAAIA,GAAG,IAAI,CAACL,gBAAgB,EAAE;MAC1B;MACA,MAAMM,aAAa,GAAIC,IAAU,IAAyB;QACtD,IAAIA,IAAI,CAACC,QAAQ,KAAKC,IAAI,CAACC,SAAS,IAAIH,IAAI,CAACI,WAAW,EAAEC,IAAI,CAAC,CAAC,EAAE;UAC9D,OAAOL,IAAI,CAACM,aAAa;QAC7B;QAEA,MAAMC,UAAU,GAAGC,KAAK,CAACC,IAAI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
|
|
|
1
1
|
import { ColorSchemeProvider, useColorScheme } from '@chayns-components/core';
|
|
2
2
|
import { ChaynsProvider, useFunctions, useValues } from 'chayns-api';
|
|
3
|
-
import React, { useCallback, useMemo, useState } from 'react';
|
|
3
|
+
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
4
|
+
import { createPortal } from 'react-dom';
|
|
4
5
|
import { renderToString } from 'react-dom/server';
|
|
5
6
|
import { CursorType } from '../../types/cursor';
|
|
6
7
|
import { TypewriterDelay, TypewriterSpeed } from '../../types/speed';
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import { getCharactersCount, getSubTextFromHTML, shuffleArray } from '
|
|
8
|
+
import AnimatedTypewriterText from './AnimatedTypewriterText';
|
|
9
|
+
import { StyledTypewriter, StyledTypewriterPseudoText, StyledTypewriterText } from './Typewriter.styles';
|
|
10
|
+
import { calculateAutoSpeed, getCharactersCount, getSubTextFromHTML, shuffleArray, updateChunkStreamingSpeedEMA } from './utils';
|
|
11
|
+
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
|
|
10
12
|
const Typewriter = ({
|
|
11
13
|
children,
|
|
12
14
|
cursorType = CursorType.Default,
|
|
@@ -34,99 +36,247 @@ const Typewriter = ({
|
|
|
34
36
|
autoSpeedBaseFactor = 2000
|
|
35
37
|
}) => {
|
|
36
38
|
const [currentChildrenIndex, setCurrentChildrenIndex] = useState(0);
|
|
39
|
+
const [hasRenderedChildrenOnce, setHasRenderedChildrenOnce] = useState(false);
|
|
40
|
+
const [shouldPreventBlinkingCursor, setShouldPreventBlinkingCursor] = useState(false);
|
|
41
|
+
const [isResetAnimationActive, setIsResetAnimationActive] = useState(false);
|
|
42
|
+
const [shouldStopAnimation, setShouldStopAnimation] = useState(false);
|
|
43
|
+
const autoSpeed = useRef();
|
|
44
|
+
const autoSteps = useRef(animationSteps);
|
|
37
45
|
const functions = useFunctions();
|
|
38
46
|
const values = useValues();
|
|
39
47
|
const colorScheme = useColorScheme();
|
|
48
|
+
useIsomorphicLayoutEffect(() => {
|
|
49
|
+
if (children) {
|
|
50
|
+
setHasRenderedChildrenOnce(false);
|
|
51
|
+
}
|
|
52
|
+
}, [children]);
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
if (!hasRenderedChildrenOnce) {
|
|
55
|
+
setHasRenderedChildrenOnce(true);
|
|
56
|
+
}
|
|
57
|
+
}, [hasRenderedChildrenOnce]);
|
|
40
58
|
const sortedChildren = useMemo(() => Array.isArray(children) && shouldSortChildrenRandomly ? shuffleArray(children) : children, [children, shouldSortChildrenRandomly]);
|
|
41
59
|
const areMultipleChildrenGiven = Array.isArray(sortedChildren);
|
|
42
60
|
const childrenCount = areMultipleChildrenGiven ? sortedChildren.length : 1;
|
|
43
|
-
const renderChildToString = useCallback(child => /*#__PURE__*/React.isValidElement(child) ? renderToString(/*#__PURE__*/React.createElement(ChaynsProvider, {
|
|
44
|
-
data: values,
|
|
45
|
-
functions: functions,
|
|
46
|
-
isModule: true
|
|
47
|
-
}, /*#__PURE__*/React.createElement(ColorSchemeProvider, {
|
|
48
|
-
color: colorScheme?.designSettings?.color,
|
|
49
|
-
colorMode: colorScheme?.designSettings?.colorMode,
|
|
50
|
-
style: {
|
|
51
|
-
display: 'inline'
|
|
52
|
-
}
|
|
53
|
-
}, /*#__PURE__*/React.createElement("span", {
|
|
54
|
-
className: "notranslate"
|
|
55
|
-
}, child)))) : child, [colorScheme?.designSettings?.color, colorScheme?.designSettings?.colorMode, functions, values]);
|
|
56
|
-
const handleSetNextChildrenIndex = useCallback(() => setCurrentChildrenIndex(prevIndex => {
|
|
57
|
-
let newIndex = prevIndex + 1;
|
|
58
|
-
if (newIndex > childrenCount - 1) {
|
|
59
|
-
newIndex = 0;
|
|
60
|
-
}
|
|
61
|
-
return newIndex;
|
|
62
|
-
}), [childrenCount]);
|
|
63
61
|
const textContent = useMemo(() => {
|
|
64
62
|
if (areMultipleChildrenGiven) {
|
|
65
63
|
const currentChildren = sortedChildren[currentChildrenIndex];
|
|
66
64
|
if (currentChildren) {
|
|
67
|
-
return
|
|
65
|
+
return /*#__PURE__*/React.isValidElement(currentChildren) ? renderToString(/*#__PURE__*/React.createElement(ChaynsProvider, {
|
|
66
|
+
data: values,
|
|
67
|
+
functions: functions,
|
|
68
|
+
isModule: true
|
|
69
|
+
}, /*#__PURE__*/React.createElement(ColorSchemeProvider, {
|
|
70
|
+
color: colorScheme?.designSettings?.color,
|
|
71
|
+
colorMode: colorScheme?.designSettings?.colorMode,
|
|
72
|
+
style: {
|
|
73
|
+
display: 'inline'
|
|
74
|
+
}
|
|
75
|
+
}, /*#__PURE__*/React.createElement("span", {
|
|
76
|
+
className: "notranslate"
|
|
77
|
+
}, currentChildren)))) : currentChildren;
|
|
68
78
|
}
|
|
69
79
|
return '';
|
|
70
80
|
}
|
|
71
|
-
return
|
|
72
|
-
|
|
81
|
+
return /*#__PURE__*/React.isValidElement(sortedChildren) ? renderToString(/*#__PURE__*/React.createElement(ChaynsProvider, {
|
|
82
|
+
data: values,
|
|
83
|
+
functions: functions,
|
|
84
|
+
isModule: true
|
|
85
|
+
}, /*#__PURE__*/React.createElement(ColorSchemeProvider, {
|
|
86
|
+
color: colorScheme?.designSettings?.color,
|
|
87
|
+
colorMode: colorScheme?.designSettings?.colorMode,
|
|
88
|
+
style: {
|
|
89
|
+
display: 'inline'
|
|
90
|
+
}
|
|
91
|
+
}, /*#__PURE__*/React.createElement("span", {
|
|
92
|
+
className: "notranslate"
|
|
93
|
+
}, sortedChildren)))) : sortedChildren;
|
|
94
|
+
}, [areMultipleChildrenGiven, colorScheme?.designSettings?.color, colorScheme?.designSettings?.colorMode, currentChildrenIndex, functions, sortedChildren, values]);
|
|
73
95
|
const charactersCount = useMemo(() => getCharactersCount(textContent), [textContent]);
|
|
74
|
-
const {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
handleClick,
|
|
78
|
-
isAnimatingText,
|
|
79
|
-
isTypingAnimationActive,
|
|
80
|
-
shouldPreventBlinkingCursor
|
|
81
|
-
} = useTypewriterAnimation({
|
|
82
|
-
autoSpeedBaseFactor,
|
|
83
|
-
charactersCount,
|
|
84
|
-
childrenKey: children,
|
|
85
|
-
childrenCount,
|
|
86
|
-
currentTextLength: textContent.length,
|
|
87
|
-
cursorType,
|
|
88
|
-
nextTextDelay,
|
|
89
|
-
onAdvanceChild: handleSetNextChildrenIndex,
|
|
90
|
-
onFinish,
|
|
91
|
-
onResetAnimationEnd,
|
|
92
|
-
onResetAnimationStart,
|
|
93
|
-
onTypingAnimationEnd,
|
|
94
|
-
onTypingAnimationStart,
|
|
95
|
-
resetDelay,
|
|
96
|
-
resetSpeed,
|
|
97
|
-
shouldCalcAutoSpeed,
|
|
98
|
-
shouldForceCursorAnimation,
|
|
99
|
-
shouldUseResetAnimation,
|
|
100
|
-
shouldWaitForContent,
|
|
101
|
-
speed,
|
|
102
|
-
startDelay
|
|
96
|
+
const chunkIntervalExponentialMovingAverage = useRef({
|
|
97
|
+
lastLength: charactersCount,
|
|
98
|
+
ema: charactersCount / (autoSpeedBaseFactor / 1000)
|
|
103
99
|
});
|
|
104
|
-
const
|
|
100
|
+
const [shownCharCount, setShownCharCount] = useState(charactersCount > 0 ? 0 : textContent.length);
|
|
101
|
+
const currentPosition = useRef(0);
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
if (shouldUseResetAnimation) {
|
|
104
|
+
chunkIntervalExponentialMovingAverage.current = {
|
|
105
|
+
ema: charactersCount / (autoSpeedBaseFactor / 1000),
|
|
106
|
+
lastLength: charactersCount
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
chunkIntervalExponentialMovingAverage.current = updateChunkStreamingSpeedEMA({
|
|
110
|
+
currentLength: charactersCount,
|
|
111
|
+
state: chunkIntervalExponentialMovingAverage.current
|
|
112
|
+
});
|
|
113
|
+
}, [autoSpeedBaseFactor, charactersCount, shouldUseResetAnimation]);
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
if (!shouldCalcAutoSpeed) {
|
|
116
|
+
autoSpeed.current = undefined;
|
|
117
|
+
autoSteps.current = animationSteps;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const {
|
|
121
|
+
speed: calculatedAutoSpeed,
|
|
122
|
+
steps
|
|
123
|
+
} = calculateAutoSpeed(chunkIntervalExponentialMovingAverage.current.ema);
|
|
124
|
+
autoSpeed.current = calculatedAutoSpeed;
|
|
125
|
+
autoSteps.current = steps;
|
|
126
|
+
}, [animationSteps, charactersCount, shouldCalcAutoSpeed]);
|
|
127
|
+
const isAnimatingText = shownCharCount < textContent.length || shouldForceCursorAnimation || areMultipleChildrenGiven || textContent.length === 0;
|
|
128
|
+
const handleClick = useCallback(event => {
|
|
129
|
+
event.stopPropagation();
|
|
130
|
+
event.preventDefault();
|
|
131
|
+
setShouldStopAnimation(true);
|
|
132
|
+
}, []);
|
|
133
|
+
const handleSetNextChildrenIndex = useCallback(() => setCurrentChildrenIndex(() => {
|
|
134
|
+
let newIndex = currentChildrenIndex + 1;
|
|
135
|
+
if (newIndex > childrenCount - 1) {
|
|
136
|
+
newIndex = 0;
|
|
137
|
+
}
|
|
138
|
+
return newIndex;
|
|
139
|
+
}), [childrenCount, currentChildrenIndex]);
|
|
140
|
+
useEffect(() => {
|
|
141
|
+
let interval;
|
|
142
|
+
if (shouldStopAnimation || charactersCount === 0) {
|
|
143
|
+
setShownCharCount(textContent.length);
|
|
144
|
+
currentPosition.current = textContent.length;
|
|
145
|
+
} else if (isResetAnimationActive) {
|
|
146
|
+
if (typeof onResetAnimationStart === 'function') {
|
|
147
|
+
onResetAnimationStart();
|
|
148
|
+
}
|
|
149
|
+
interval = window.setInterval(() => {
|
|
150
|
+
setShownCharCount(prevState => {
|
|
151
|
+
const nextState = prevState - autoSteps.current;
|
|
152
|
+
currentPosition.current = nextState;
|
|
153
|
+
if (nextState === 0) {
|
|
154
|
+
window.clearInterval(interval);
|
|
155
|
+
if (typeof onResetAnimationEnd === 'function') {
|
|
156
|
+
onResetAnimationEnd();
|
|
157
|
+
}
|
|
158
|
+
if (areMultipleChildrenGiven) {
|
|
159
|
+
setTimeout(() => {
|
|
160
|
+
setIsResetAnimationActive(false);
|
|
161
|
+
handleSetNextChildrenIndex();
|
|
162
|
+
}, nextTextDelay);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return nextState;
|
|
166
|
+
});
|
|
167
|
+
}, resetSpeed);
|
|
168
|
+
} else {
|
|
169
|
+
const startTypingAnimation = () => {
|
|
170
|
+
if (cursorType === CursorType.Thin) {
|
|
171
|
+
setShouldPreventBlinkingCursor(true);
|
|
172
|
+
}
|
|
173
|
+
if (typeof onTypingAnimationStart === 'function') {
|
|
174
|
+
onTypingAnimationStart();
|
|
175
|
+
}
|
|
176
|
+
const runTypingInterval = () => {
|
|
177
|
+
setShownCharCount(prevState => {
|
|
178
|
+
let nextState = Math.min(prevState + autoSteps.current, charactersCount);
|
|
179
|
+
if (nextState >= charactersCount && !shouldWaitForContent) {
|
|
180
|
+
window.clearInterval(interval);
|
|
181
|
+
if (cursorType === CursorType.Thin) {
|
|
182
|
+
setShouldPreventBlinkingCursor(false);
|
|
183
|
+
}
|
|
184
|
+
if (typeof onTypingAnimationEnd === 'function') {
|
|
185
|
+
onTypingAnimationEnd();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* At this point, the next value for "shownCharCount" is deliberately set to
|
|
190
|
+
* the length of the textContent to correctly display HTML elements
|
|
191
|
+
* after the last letter.
|
|
192
|
+
*/
|
|
193
|
+
nextState = textContent.length;
|
|
194
|
+
if (areMultipleChildrenGiven) {
|
|
195
|
+
setTimeout(() => {
|
|
196
|
+
if (shouldUseResetAnimation) {
|
|
197
|
+
setIsResetAnimationActive(true);
|
|
198
|
+
} else {
|
|
199
|
+
setShownCharCount(0);
|
|
200
|
+
setTimeout(handleSetNextChildrenIndex, nextTextDelay);
|
|
201
|
+
}
|
|
202
|
+
}, resetDelay);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
currentPosition.current = nextState;
|
|
206
|
+
return nextState;
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
interval = window.setInterval(runTypingInterval, autoSpeed.current ?? speed);
|
|
210
|
+
};
|
|
211
|
+
if (startDelay) {
|
|
212
|
+
setTimeout(startTypingAnimation, startDelay);
|
|
213
|
+
} else {
|
|
214
|
+
startTypingAnimation();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return () => {
|
|
218
|
+
window.clearInterval(interval);
|
|
219
|
+
};
|
|
220
|
+
}, [areMultipleChildrenGiven, autoSteps, charactersCount, cursorType, handleSetNextChildrenIndex, isResetAnimationActive, nextTextDelay, onResetAnimationEnd, onResetAnimationStart, onTypingAnimationEnd, onTypingAnimationStart, resetDelay, resetSpeed, shouldStopAnimation, shouldUseResetAnimation, shouldWaitForContent, speed, startDelay, textContent.length]);
|
|
221
|
+
useEffect(() => {
|
|
222
|
+
if (!isAnimatingText && typeof onFinish === 'function') {
|
|
223
|
+
onFinish();
|
|
224
|
+
}
|
|
225
|
+
}, [isAnimatingText, onFinish]);
|
|
226
|
+
const shownText = useMemo(() => getSubTextFromHTML(textContent, shownCharCount), [shownCharCount, textContent]);
|
|
105
227
|
const pseudoTextHTML = useMemo(() => {
|
|
106
228
|
if (pseudoChildren) {
|
|
107
|
-
const pseudoText =
|
|
229
|
+
const pseudoText = /*#__PURE__*/React.isValidElement(pseudoChildren) ? renderToString(/*#__PURE__*/React.createElement(ChaynsProvider, {
|
|
230
|
+
data: values,
|
|
231
|
+
functions: functions,
|
|
232
|
+
isModule: true
|
|
233
|
+
}, /*#__PURE__*/React.createElement(ColorSchemeProvider, {
|
|
234
|
+
color: colorScheme?.designSettings?.color,
|
|
235
|
+
colorMode: colorScheme?.designSettings?.colorMode,
|
|
236
|
+
style: {
|
|
237
|
+
display: 'inline'
|
|
238
|
+
}
|
|
239
|
+
}, pseudoChildren))) : pseudoChildren;
|
|
108
240
|
if (shouldUseAnimationHeight) {
|
|
109
|
-
return getSubTextFromHTML(pseudoText,
|
|
241
|
+
return getSubTextFromHTML(pseudoText, shownCharCount);
|
|
110
242
|
}
|
|
111
243
|
return pseudoText;
|
|
112
244
|
}
|
|
113
245
|
if (shouldUseAnimationHeight && textContent) {
|
|
114
|
-
return getSubTextFromHTML(textContent,
|
|
246
|
+
return getSubTextFromHTML(textContent, shownCharCount);
|
|
115
247
|
}
|
|
116
248
|
return textContent || '​';
|
|
117
|
-
}, [
|
|
118
|
-
return /*#__PURE__*/React.createElement(
|
|
119
|
-
cursorType: cursorType,
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
249
|
+
}, [colorScheme?.designSettings?.color, colorScheme?.designSettings?.colorMode, functions, pseudoChildren, shouldUseAnimationHeight, shownCharCount, textContent, values]);
|
|
250
|
+
return useMemo(() => /*#__PURE__*/React.createElement(StyledTypewriter, {
|
|
251
|
+
$cursorType: cursorType,
|
|
252
|
+
onClick: isAnimatingText ? handleClick : undefined,
|
|
253
|
+
$isAnimatingText: isAnimatingText,
|
|
254
|
+
$shouldHideCursor: shouldHideCursor,
|
|
255
|
+
$shouldPreventBlinkAnimation: shouldPreventBlinkingCursor
|
|
256
|
+
}, isAnimatingText ? /*#__PURE__*/React.createElement(AnimatedTypewriterText, {
|
|
124
257
|
shouldHideCursor: shouldHideCursor,
|
|
125
|
-
shouldPreventBlinkingCursor: shouldPreventBlinkingCursor,
|
|
126
258
|
shouldRemainSingleLine: shouldRemainSingleLine,
|
|
127
259
|
shownText: shownText,
|
|
128
260
|
textStyle: textStyle
|
|
129
|
-
},
|
|
261
|
+
}) : /*#__PURE__*/React.createElement(StyledTypewriterText, {
|
|
262
|
+
className: "notranslate",
|
|
263
|
+
$shouldRemainSingleLine: shouldRemainSingleLine,
|
|
264
|
+
dangerouslySetInnerHTML: typeof sortedChildren === 'string' ? {
|
|
265
|
+
__html: shownText
|
|
266
|
+
} : undefined,
|
|
267
|
+
style: textStyle
|
|
268
|
+
}, typeof sortedChildren !== 'string' ? sortedChildren : undefined), isAnimatingText && /*#__PURE__*/React.createElement(StyledTypewriterPseudoText, {
|
|
269
|
+
$isAnimatingText: isAnimatingText,
|
|
270
|
+
$shouldHideCursor: shouldHideCursor,
|
|
271
|
+
dangerouslySetInnerHTML: {
|
|
272
|
+
__html: pseudoTextHTML
|
|
273
|
+
}
|
|
274
|
+
}), !hasRenderedChildrenOnce && /*#__PURE__*/createPortal(/*#__PURE__*/React.createElement("div", {
|
|
275
|
+
style: {
|
|
276
|
+
position: 'absolute',
|
|
277
|
+
visibility: 'hidden'
|
|
278
|
+
}
|
|
279
|
+
}, children), document.body)), [children, cursorType, handleClick, hasRenderedChildrenOnce, isAnimatingText, pseudoTextHTML, shouldHideCursor, shouldPreventBlinkingCursor, shouldRemainSingleLine, shownText, sortedChildren, textStyle]);
|
|
130
280
|
};
|
|
131
281
|
Typewriter.displayName = 'Typewriter';
|
|
132
282
|
export default Typewriter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Typewriter.js","names":["ColorSchemeProvider","useColorScheme","ChaynsProvider","useFunctions","useValues","React","useCallback","useMemo","useState","renderToString","CursorType","TypewriterDelay","TypewriterSpeed","TypewriterView","useTypewriterAnimation","getCharactersCount","getSubTextFromHTML","shuffleArray","Typewriter","children","cursorType","Default","nextTextDelay","Medium","onFinish","onResetAnimationEnd","animationSteps","onResetAnimationStart","onTypingAnimationEnd","onTypingAnimationStart","pseudoChildren","resetDelay","shouldForceCursorAnimation","shouldHideCursor","shouldRemainSingleLine","shouldSortChildrenRandomly","shouldUseAnimationHeight","shouldUseResetAnimation","shouldWaitForContent","speed","resetSpeed","startDelay","None","textStyle","shouldCalcAutoSpeed","autoSpeedBaseFactor","currentChildrenIndex","setCurrentChildrenIndex","functions","values","colorScheme","sortedChildren","Array","isArray","areMultipleChildrenGiven","childrenCount","length","renderChildToString","child","isValidElement","createElement","data","isModule","color","designSettings","colorMode","style","display","className","handleSetNextChildrenIndex","prevIndex","newIndex","textContent","currentChildren","charactersCount","effectiveShownCharCount","hasRenderedChildrenOnce","handleClick","isAnimatingText","isTypingAnimationActive","shouldPreventBlinkingCursor","childrenKey","currentTextLength","onAdvanceChild","shownText","pseudoTextHTML","pseudoText","undefined","displayName"],"sources":["../../../../src/components/typewriter/Typewriter.tsx"],"sourcesContent":["import { ColorSchemeProvider, useColorScheme } from '@chayns-components/core';\nimport { ChaynsProvider, useFunctions, useValues } from 'chayns-api';\nimport React, { FC, ReactElement, useCallback, useMemo, useState } from 'react';\nimport { renderToString } from 'react-dom/server';\nimport { CSSPropertiesWithVars } from 'styled-components/dist/types';\nimport { CursorType } from '../../types/cursor';\nimport { TypewriterDelay, TypewriterSpeed } from '../../types/speed';\nimport TypewriterView from './typewrite-view/TypewriterView';\nimport useTypewriterAnimation from '../../hooks/useTypewriterAnimation';\nimport { getCharactersCount, getSubTextFromHTML, shuffleArray } from '../../utils/utils';\n\nexport type TypewriterProps = {\n /**\n * The number of characters that will be animated per animation cycle.\n */\n animationSteps?: number;\n /**\n * The text to type\n */\n children: ReactElement | ReactElement[] | string | string[];\n /**\n * The type of the cursor. Use the CursorType enum for this prop.\n */\n cursorType?: CursorType;\n /**\n * The delay in milliseconds before the next text is shown.\n * This prop is only used if multiple texts are given.\n */\n nextTextDelay?: TypewriterDelay;\n /**\n * Function that is executed when the typewriter animation has finished. This function will not\n * be executed if multiple texts are used.\n */\n onFinish?: VoidFunction;\n /**\n * Function that is executed when the reset animation has finished. This function will not be\n * executed if `shouldUseResetAnimation` is not set to `true`.\n */\n onResetAnimationEnd?: VoidFunction;\n /**\n * Function that is executed when the reset animation has started. This function will not be\n * executed if `shouldUseResetAnimation` is not set to `true`.\n */\n onResetAnimationStart?: VoidFunction;\n /**\n * Function that is executed when the typing animation has finished. If multiple texts are given,\n * this function will be executed for each text.\n */\n onTypingAnimationEnd?: VoidFunction;\n /**\n * Function that is executed when the typing animation has started. If multiple texts are given,\n * this function will be executed for each text.\n */\n onTypingAnimationStart?: VoidFunction;\n /**\n * Pseudo-element to be rendered invisible during animation to define the size of the element\n * for the typewriter effect. By default, the \"children\" is used for this purpose.\n */\n pseudoChildren?: ReactElement | string;\n /**\n * Waiting time in milliseconds before the typewriter resets the text.\n * This prop is only used if multiple texts are given.\n */\n resetDelay?: TypewriterDelay;\n /**\n * The reset speed of the animation. Use the TypewriterSpeed enum for this prop.\n */\n resetSpeed?: TypewriterSpeed | number;\n /**\n * Specifies whether the cursor should be forced to animate even if no text is currently animated.\n */\n shouldForceCursorAnimation?: boolean;\n /**\n * Specifies whether the cursor should be hidden\n */\n shouldHideCursor?: boolean;\n /**\n * Whether the content should remain a single line.\n */\n shouldRemainSingleLine?: boolean;\n /**\n * Specifies whether the children should be sorted randomly if there are multiple texts.\n * This makes the typewriter start with a different text each time and also changes them\n * in a random order.\n */\n shouldSortChildrenRandomly?: boolean;\n /**\n * Specifies whether the animation should use its full height or the height of the current\n * chunk.\n */\n shouldUseAnimationHeight?: boolean;\n /**\n * Whether the animation speed should be calculated with the chunk interval.\n */\n shouldCalcAutoSpeed?: boolean;\n /**\n * Sets how long the animation should last when `shouldCalcAutoSpeed` is enabled in milliseconds.\n * When chunks are streamed, this value will only be used for the initial speed and then change to the speed characters are added at\n */\n autoSpeedBaseFactor?: number;\n /**\n * Specifies whether the reset of the text should be animated with a backspace animation for\n * multiple texts.\n */\n shouldUseResetAnimation?: boolean;\n /**\n * Whether the typewriter should wait for new content\n */\n shouldWaitForContent?: boolean;\n /**\n * The speed of the animation. Use the TypewriterSpeed enum for this prop.\n */\n speed?: TypewriterSpeed | number;\n /**\n * The delay in milliseconds before the typewriter starts typing.\n */\n startDelay?: TypewriterDelay;\n /**\n * The style of the typewriter text element\n */\n textStyle?: CSSPropertiesWithVars;\n};\n\nconst Typewriter: FC<TypewriterProps> = ({\n children,\n cursorType = CursorType.Default,\n nextTextDelay = TypewriterDelay.Medium,\n onFinish,\n onResetAnimationEnd,\n animationSteps = 1,\n onResetAnimationStart,\n onTypingAnimationEnd,\n onTypingAnimationStart,\n pseudoChildren,\n resetDelay = TypewriterDelay.Medium,\n shouldForceCursorAnimation = false,\n shouldHideCursor = false,\n shouldRemainSingleLine = false,\n shouldSortChildrenRandomly = false,\n shouldUseAnimationHeight = false,\n shouldUseResetAnimation = false,\n shouldWaitForContent,\n speed = TypewriterSpeed.Medium,\n resetSpeed = speed,\n startDelay = TypewriterDelay.None,\n textStyle,\n shouldCalcAutoSpeed = false,\n autoSpeedBaseFactor = 2000,\n}) => {\n const [currentChildrenIndex, setCurrentChildrenIndex] = useState(0);\n\n const functions = useFunctions();\n const values = useValues();\n\n const colorScheme = useColorScheme();\n\n const sortedChildren = useMemo(\n () =>\n Array.isArray(children) && shouldSortChildrenRandomly\n ? shuffleArray<ReactElement | string>(children)\n : children,\n [children, shouldSortChildrenRandomly],\n );\n\n const areMultipleChildrenGiven = Array.isArray(sortedChildren);\n const childrenCount = areMultipleChildrenGiven ? sortedChildren.length : 1;\n\n const renderChildToString = useCallback(\n (child: ReactElement | ReactElement[] | string | string[]) =>\n React.isValidElement(child)\n ? renderToString(\n <ChaynsProvider data={values} functions={functions} isModule>\n <ColorSchemeProvider\n color={colorScheme?.designSettings?.color}\n colorMode={colorScheme?.designSettings?.colorMode}\n style={{ display: 'inline' }}\n >\n <span className=\"notranslate\">{child}</span>\n </ColorSchemeProvider>\n </ChaynsProvider>,\n )\n : (child as string),\n [\n colorScheme?.designSettings?.color,\n colorScheme?.designSettings?.colorMode,\n functions,\n values,\n ],\n );\n\n const handleSetNextChildrenIndex = useCallback(\n () =>\n setCurrentChildrenIndex((prevIndex) => {\n let newIndex = prevIndex + 1;\n\n if (newIndex > childrenCount - 1) {\n newIndex = 0;\n }\n\n return newIndex;\n }),\n [childrenCount],\n );\n\n const textContent = useMemo(() => {\n if (areMultipleChildrenGiven) {\n const currentChildren = sortedChildren[currentChildrenIndex];\n\n if (currentChildren) {\n return renderChildToString(currentChildren);\n }\n\n return '';\n }\n\n return renderChildToString(sortedChildren);\n }, [areMultipleChildrenGiven, currentChildrenIndex, renderChildToString, sortedChildren]);\n\n const charactersCount = useMemo(() => getCharactersCount(textContent), [textContent]);\n\n const {\n effectiveShownCharCount,\n hasRenderedChildrenOnce,\n handleClick,\n isAnimatingText,\n isTypingAnimationActive,\n shouldPreventBlinkingCursor,\n } = useTypewriterAnimation({\n autoSpeedBaseFactor,\n charactersCount,\n childrenKey: children,\n childrenCount,\n currentTextLength: textContent.length,\n cursorType,\n nextTextDelay,\n onAdvanceChild: handleSetNextChildrenIndex,\n onFinish,\n onResetAnimationEnd,\n onResetAnimationStart,\n onTypingAnimationEnd,\n onTypingAnimationStart,\n resetDelay,\n resetSpeed,\n shouldCalcAutoSpeed,\n shouldForceCursorAnimation,\n shouldUseResetAnimation,\n shouldWaitForContent,\n speed,\n startDelay,\n });\n\n const shownText = useMemo(\n () => getSubTextFromHTML(textContent, effectiveShownCharCount) || '​',\n [effectiveShownCharCount, textContent],\n );\n\n const pseudoTextHTML = useMemo(() => {\n if (pseudoChildren) {\n const pseudoText = renderChildToString(pseudoChildren);\n\n if (shouldUseAnimationHeight) {\n return getSubTextFromHTML(pseudoText, effectiveShownCharCount);\n }\n\n return pseudoText;\n }\n\n if (shouldUseAnimationHeight && textContent) {\n return getSubTextFromHTML(textContent, effectiveShownCharCount);\n }\n\n return textContent || '​';\n }, [\n effectiveShownCharCount,\n pseudoChildren,\n renderChildToString,\n shouldUseAnimationHeight,\n textContent,\n ]);\n\n return (\n <TypewriterView\n cursorType={cursorType}\n handleClick={isTypingAnimationActive ? handleClick : undefined}\n hasRenderedChildrenOnce={hasRenderedChildrenOnce}\n isAnimatingText={isAnimatingText}\n pseudoTextHTML={pseudoTextHTML}\n shouldHideCursor={shouldHideCursor}\n shouldPreventBlinkingCursor={shouldPreventBlinkingCursor}\n shouldRemainSingleLine={shouldRemainSingleLine}\n shownText={shownText}\n textStyle={textStyle}\n >\n {sortedChildren}\n </Typewriter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kBAAkB,CAACwD,WAAW,EAAEG,uBAAuB,CAAC,IAAI,SAAS,EAC3E,CAACA,uBAAuB,EAAEH,WAAW,CACzC,CAAC;EAED,MAAMa,cAAc,GAAG9E,OAAO,CAAC,MAAM;IACjC,IAAIuB,cAAc,EAAE;MAChB,MAAMwD,UAAU,GAAG7B,mBAAmB,CAAC3B,cAAc,CAAC;MAEtD,IAAIM,wBAAwB,EAAE;QAC1B,OAAOpB,kBAAkB,CAACsE,UAAU,EAAEX,uBAAuB,CAAC;MAClE;MAEA,OAAOW,UAAU;IACrB;IAEA,IAAIlD,wBAAwB,IAAIoC,WAAW,EAAE;MACzC,OAAOxD,kBAAkB,CAACwD,WAAW,EAAEG,uBAAuB,CAAC;IACnE;IAEA,OAAOH,WAAW,IAAI,SAAS;EACnC,CAAC,EAAE,CACCG,uBAAuB,EACvB7C,cAAc,EACd2B,mBAAmB,EACnBrB,wBAAwB,EACxBoC,WAAW,CACd,CAAC;EAEF,oBACInE,KAAA,CAAAuD,aAAA,CAAC/C,cAAc;IACXO,UAAU,EAAEA,UAAW;IACvByD,WAAW,EAAEE,uBAAuB,GAAGF,WAAW,GAAGU,SAAU;IAC/DX,uBAAuB,EAAEA,uBAAwB;IACjDE,eAAe,EAAEA,eAAgB;IACjCO,cAAc,EAAEA,cAAe;IAC/BpD,gBAAgB,EAAEA,gBAAiB;IACnC+C,2BAA2B,EAAEA,2BAA4B;IACzD9C,sBAAsB,EAAEA,sBAAuB;IAC/CkD,SAAS,EAAEA,SAAU;IACrBzC,SAAS,EAAEA;EAAU,GAEpBQ,cACW,CAAC;AAEzB,CAAC;AAEDjC,UAAU,CAACsE,WAAW,GAAG,YAAY;AAErC,eAAetE,UAAU","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"Typewriter.js","names":["ColorSchemeProvider","useColorScheme","ChaynsProvider","useFunctions","useValues","React","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","createPortal","renderToString","CursorType","TypewriterDelay","TypewriterSpeed","AnimatedTypewriterText","StyledTypewriter","StyledTypewriterPseudoText","StyledTypewriterText","calculateAutoSpeed","getCharactersCount","getSubTextFromHTML","shuffleArray","updateChunkStreamingSpeedEMA","useIsomorphicLayoutEffect","window","Typewriter","children","cursorType","Default","nextTextDelay","Medium","onFinish","onResetAnimationEnd","animationSteps","onResetAnimationStart","onTypingAnimationEnd","onTypingAnimationStart","pseudoChildren","resetDelay","shouldForceCursorAnimation","shouldHideCursor","shouldRemainSingleLine","shouldSortChildrenRandomly","shouldUseAnimationHeight","shouldUseResetAnimation","shouldWaitForContent","speed","resetSpeed","startDelay","None","textStyle","shouldCalcAutoSpeed","autoSpeedBaseFactor","currentChildrenIndex","setCurrentChildrenIndex","hasRenderedChildrenOnce","setHasRenderedChildrenOnce","shouldPreventBlinkingCursor","setShouldPreventBlinkingCursor","isResetAnimationActive","setIsResetAnimationActive","shouldStopAnimation","setShouldStopAnimation","autoSpeed","autoSteps","functions","values","colorScheme","sortedChildren","Array","isArray","areMultipleChildrenGiven","childrenCount","length","textContent","currentChildren","isValidElement","createElement","data","isModule","color","designSettings","colorMode","style","display","className","charactersCount","chunkIntervalExponentialMovingAverage","lastLength","ema","shownCharCount","setShownCharCount","currentPosition","current","currentLength","state","undefined","calculatedAutoSpeed","steps","isAnimatingText","handleClick","event","stopPropagation","preventDefault","handleSetNextChildrenIndex","newIndex","interval","setInterval","prevState","nextState","clearInterval","setTimeout","startTypingAnimation","Thin","runTypingInterval","Math","min","shownText","pseudoTextHTML","pseudoText","$cursorType","onClick","$isAnimatingText","$shouldHideCursor","$shouldPreventBlinkAnimation","$shouldRemainSingleLine","dangerouslySetInnerHTML","__html","position","visibility","document","body","displayName"],"sources":["../../../../src/components/typewriter/Typewriter.tsx"],"sourcesContent":["import { ColorSchemeProvider, useColorScheme } from '@chayns-components/core';\nimport { ChaynsProvider, useFunctions, useValues } from 'chayns-api';\nimport React, {\n FC,\n ReactElement,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { renderToString } from 'react-dom/server';\nimport { CSSPropertiesWithVars } from 'styled-components/dist/types';\nimport { CursorType } from '../../types/cursor';\nimport { TypewriterDelay, TypewriterSpeed } from '../../types/speed';\nimport AnimatedTypewriterText from './AnimatedTypewriterText';\nimport {\n StyledTypewriter,\n StyledTypewriterPseudoText,\n StyledTypewriterText,\n} from './Typewriter.styles';\nimport {\n calculateAutoSpeed,\n ChunkStreamingSpeedState,\n getCharactersCount,\n getSubTextFromHTML,\n shuffleArray,\n updateChunkStreamingSpeedEMA,\n} from './utils';\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\nexport type TypewriterProps = {\n /**\n * The number of characters that will be animated per animation cycle.\n */\n animationSteps?: number;\n /**\n * The text to type\n */\n children: ReactElement | ReactElement[] | string | string[];\n /**\n * The type of the cursor. Use the CursorType enum for this prop.\n */\n cursorType?: CursorType;\n /**\n * The delay in milliseconds before the next text is shown.\n * This prop is only used if multiple texts are given.\n */\n nextTextDelay?: TypewriterDelay;\n /**\n * Function that is executed when the typewriter animation has finished. This function will not\n * be executed if multiple texts are used.\n */\n onFinish?: VoidFunction;\n /**\n * Function that is executed when the reset animation has finished. This function will not be\n * executed if `shouldUseResetAnimation` is not set to `true`.\n */\n onResetAnimationEnd?: VoidFunction;\n /**\n * Function that is executed when the reset animation has started. This function will not be\n * executed if `shouldUseResetAnimation` is not set to `true`.\n */\n onResetAnimationStart?: VoidFunction;\n /**\n * Function that is executed when the typing animation has finished. If multiple texts are given,\n * this function will be executed for each text.\n */\n onTypingAnimationEnd?: VoidFunction;\n /**\n * Function that is executed when the typing animation has started. If multiple texts are given,\n * this function will be executed for each text.\n */\n onTypingAnimationStart?: VoidFunction;\n /**\n * Pseudo-element to be rendered invisible during animation to define the size of the element\n * for the typewriter effect. By default, the \"children\" is used for this purpose.\n */\n pseudoChildren?: ReactElement | string;\n /**\n * Waiting time in milliseconds before the typewriter resets the text.\n * This prop is only used if multiple texts are given.\n */\n resetDelay?: TypewriterDelay;\n /**\n * The reset speed of the animation. Use the TypewriterSpeed enum for this prop.\n */\n resetSpeed?: TypewriterSpeed | number;\n /**\n * Specifies whether the cursor should be forced to animate even if no text is currently animated.\n */\n shouldForceCursorAnimation?: boolean;\n /**\n * Specifies whether the cursor should be hidden\n */\n shouldHideCursor?: boolean;\n /**\n * Whether the content should remain a single line.\n */\n shouldRemainSingleLine?: boolean;\n /**\n * Specifies whether the children should be sorted randomly if there are multiple texts.\n * This makes the typewriter start with a different text each time and also changes them\n * in a random order.\n */\n shouldSortChildrenRandomly?: boolean;\n /**\n * Specifies whether the animation should use its full height or the height of the current\n * chunk.\n */\n shouldUseAnimationHeight?: boolean;\n /**\n * Whether the animation speed should be calculated with the chunk interval.\n */\n shouldCalcAutoSpeed?: boolean;\n /**\n * Sets how long the animation should last when `shouldCalcAutoSpeed` is enabled in milliseconds.\n * When chunks are streamed, this value will only be used for the initial speed and then change to the speed characters are added at\n */\n autoSpeedBaseFactor?: number;\n /**\n * Specifies whether the reset of the text should be animated with a backspace animation for\n * multiple texts.\n */\n shouldUseResetAnimation?: boolean;\n /**\n * Whether the typewriter should wait for new content\n */\n shouldWaitForContent?: boolean;\n /**\n * The speed of the animation. Use the TypewriterSpeed enum for this prop.\n */\n speed?: TypewriterSpeed | number;\n /**\n * The delay in milliseconds before the typewriter starts typing.\n */\n startDelay?: TypewriterDelay;\n /**\n * The style of the typewriter text element\n */\n textStyle?: CSSPropertiesWithVars;\n};\n\nconst Typewriter: FC<TypewriterProps> = ({\n children,\n cursorType = CursorType.Default,\n nextTextDelay = TypewriterDelay.Medium,\n onFinish,\n onResetAnimationEnd,\n animationSteps = 1,\n onResetAnimationStart,\n onTypingAnimationEnd,\n onTypingAnimationStart,\n pseudoChildren,\n resetDelay = TypewriterDelay.Medium,\n shouldForceCursorAnimation = false,\n shouldHideCursor = false,\n shouldRemainSingleLine = false,\n shouldSortChildrenRandomly = false,\n shouldUseAnimationHeight = false,\n shouldUseResetAnimation = false,\n shouldWaitForContent,\n speed = TypewriterSpeed.Medium,\n resetSpeed = speed,\n startDelay = TypewriterDelay.None,\n textStyle,\n shouldCalcAutoSpeed = false,\n autoSpeedBaseFactor = 2000,\n}) => {\n const [currentChildrenIndex, setCurrentChildrenIndex] = useState(0);\n const [hasRenderedChildrenOnce, setHasRenderedChildrenOnce] = useState(false);\n const [shouldPreventBlinkingCursor, setShouldPreventBlinkingCursor] = useState(false);\n const [isResetAnimationActive, setIsResetAnimationActive] = useState(false);\n const [shouldStopAnimation, setShouldStopAnimation] = useState(false);\n const autoSpeed = useRef<number>();\n const autoSteps = useRef<number>(animationSteps);\n\n const functions = useFunctions();\n const values = useValues();\n\n const colorScheme = useColorScheme();\n\n useIsomorphicLayoutEffect(() => {\n if (children) {\n setHasRenderedChildrenOnce(false);\n }\n }, [children]);\n\n useEffect(() => {\n if (!hasRenderedChildrenOnce) {\n setHasRenderedChildrenOnce(true);\n }\n }, [hasRenderedChildrenOnce]);\n\n const sortedChildren = useMemo(\n () =>\n Array.isArray(children) && shouldSortChildrenRandomly\n ? shuffleArray<ReactElement | string>(children)\n : children,\n [children, shouldSortChildrenRandomly],\n );\n\n const areMultipleChildrenGiven = Array.isArray(sortedChildren);\n const childrenCount = areMultipleChildrenGiven ? sortedChildren.length : 1;\n\n const textContent = useMemo(() => {\n if (areMultipleChildrenGiven) {\n const currentChildren = sortedChildren[currentChildrenIndex];\n\n if (currentChildren) {\n return React.isValidElement(currentChildren)\n ? renderToString(\n <ChaynsProvider data={values} functions={functions} isModule>\n <ColorSchemeProvider\n color={colorScheme?.designSettings?.color}\n colorMode={colorScheme?.designSettings?.colorMode}\n style={{ display: 'inline' }}\n >\n <span className=\"notranslate\">{currentChildren}</span>\n </ColorSchemeProvider>\n </ChaynsProvider>,\n )\n : (currentChildren as string);\n }\n\n return '';\n }\n\n return React.isValidElement(sortedChildren)\n ? renderToString(\n <ChaynsProvider data={values} functions={functions} isModule>\n <ColorSchemeProvider\n color={colorScheme?.designSettings?.color}\n colorMode={colorScheme?.designSettings?.colorMode}\n style={{ display: 'inline' }}\n >\n <span className=\"notranslate\">{sortedChildren}</span>\n </ColorSchemeProvider>\n </ChaynsProvider>,\n )\n : (sortedChildren as string);\n }, [\n areMultipleChildrenGiven,\n colorScheme?.designSettings?.color,\n colorScheme?.designSettings?.colorMode,\n currentChildrenIndex,\n functions,\n sortedChildren,\n values,\n ]);\n\n const charactersCount = useMemo(() => getCharactersCount(textContent), [textContent]);\n const chunkIntervalExponentialMovingAverage = useRef<ChunkStreamingSpeedState>({\n lastLength: charactersCount,\n ema: charactersCount / (autoSpeedBaseFactor / 1000),\n });\n\n const [shownCharCount, setShownCharCount] = useState(\n charactersCount > 0 ? 0 : textContent.length,\n );\n\n const currentPosition = useRef(0);\n\n useEffect(() => {\n if (shouldUseResetAnimation) {\n chunkIntervalExponentialMovingAverage.current = {\n ema: charactersCount / (autoSpeedBaseFactor / 1000),\n lastLength: charactersCount,\n };\n }\n chunkIntervalExponentialMovingAverage.current = updateChunkStreamingSpeedEMA({\n currentLength: charactersCount,\n state: chunkIntervalExponentialMovingAverage.current,\n });\n }, [autoSpeedBaseFactor, charactersCount, shouldUseResetAnimation]);\n\n useEffect(() => {\n if (!shouldCalcAutoSpeed) {\n autoSpeed.current = undefined;\n autoSteps.current = animationSteps;\n return;\n }\n const { speed: calculatedAutoSpeed, steps } = calculateAutoSpeed(\n chunkIntervalExponentialMovingAverage.current.ema,\n );\n\n autoSpeed.current = calculatedAutoSpeed;\n autoSteps.current = steps;\n }, [animationSteps, charactersCount, shouldCalcAutoSpeed]);\n\n const isAnimatingText =\n shownCharCount < textContent.length ||\n shouldForceCursorAnimation ||\n areMultipleChildrenGiven ||\n textContent.length === 0;\n\n const handleClick = useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n event.preventDefault();\n\n setShouldStopAnimation(true);\n }, []);\n\n const handleSetNextChildrenIndex = useCallback(\n () =>\n setCurrentChildrenIndex(() => {\n let newIndex = currentChildrenIndex + 1;\n\n if (newIndex > childrenCount - 1) {\n newIndex = 0;\n }\n\n return newIndex;\n }),\n [childrenCount, currentChildrenIndex],\n );\n\n useEffect(() => {\n let interval: number | undefined;\n\n if (shouldStopAnimation || charactersCount === 0) {\n setShownCharCount(textContent.length);\n currentPosition.current = textContent.length;\n } else if (isResetAnimationActive) {\n if (typeof onResetAnimationStart === 'function') {\n onResetAnimationStart();\n }\n\n interval = window.setInterval(() => {\n setShownCharCount((prevState) => {\n const nextState = prevState - autoSteps.current;\n currentPosition.current = nextState;\n\n if (nextState === 0) {\n window.clearInterval(interval);\n\n if (typeof onResetAnimationEnd === 'function') {\n onResetAnimationEnd();\n }\n\n if (areMultipleChildrenGiven) {\n setTimeout(() => {\n setIsResetAnimationActive(false);\n handleSetNextChildrenIndex();\n }, nextTextDelay);\n }\n }\n\n return nextState;\n });\n }, resetSpeed);\n } else {\n const startTypingAnimation = () => {\n if (cursorType === CursorType.Thin) {\n setShouldPreventBlinkingCursor(true);\n }\n\n if (typeof onTypingAnimationStart === 'function') {\n onTypingAnimationStart();\n }\n\n const runTypingInterval = () => {\n setShownCharCount((prevState) => {\n let nextState = Math.min(prevState + autoSteps.current, charactersCount);\n\n if (nextState >= charactersCount && !shouldWaitForContent) {\n window.clearInterval(interval);\n\n if (cursorType === CursorType.Thin) {\n setShouldPreventBlinkingCursor(false);\n }\n\n if (typeof onTypingAnimationEnd === 'function') {\n onTypingAnimationEnd();\n }\n\n /**\n * At this point, the next value for \"shownCharCount\" is deliberately set to\n * the length of the textContent to correctly display HTML elements\n * after the last letter.\n */\n nextState = textContent.length;\n\n if (areMultipleChildrenGiven) {\n setTimeout(() => {\n if (shouldUseResetAnimation) {\n setIsResetAnimationActive(true);\n } else {\n setShownCharCount(0);\n setTimeout(handleSetNextChildrenIndex, nextTextDelay);\n }\n }, resetDelay);\n }\n }\n\n currentPosition.current = nextState;\n\n return nextState;\n });\n };\n interval = window.setInterval(runTypingInterval, autoSpeed.current ?? speed);\n };\n\n if (startDelay) {\n setTimeout(startTypingAnimation, startDelay);\n } else {\n startTypingAnimation();\n }\n }\n\n return () => {\n window.clearInterval(interval);\n };\n }, [\n areMultipleChildrenGiven,\n autoSteps,\n charactersCount,\n cursorType,\n handleSetNextChildrenIndex,\n isResetAnimationActive,\n nextTextDelay,\n onResetAnimationEnd,\n onResetAnimationStart,\n onTypingAnimationEnd,\n onTypingAnimationStart,\n resetDelay,\n resetSpeed,\n shouldStopAnimation,\n shouldUseResetAnimation,\n shouldWaitForContent,\n speed,\n startDelay,\n textContent.length,\n ]);\n\n useEffect(() => {\n if (!isAnimatingText && typeof onFinish === 'function') {\n onFinish();\n }\n }, [isAnimatingText, onFinish]);\n\n const shownText = useMemo(\n () => getSubTextFromHTML(textContent, shownCharCount),\n [shownCharCount, textContent],\n );\n\n const pseudoTextHTML = useMemo(() => {\n if (pseudoChildren) {\n const pseudoText = React.isValidElement(pseudoChildren)\n ? renderToString(\n <ChaynsProvider data={values} functions={functions} isModule>\n <ColorSchemeProvider\n color={colorScheme?.designSettings?.color}\n colorMode={colorScheme?.designSettings?.colorMode}\n style={{ display: 'inline' }}\n >\n {pseudoChildren}\n </ColorSchemeProvider>\n </ChaynsProvider>,\n )\n : (pseudoChildren as string);\n\n if (shouldUseAnimationHeight) {\n return getSubTextFromHTML(pseudoText, shownCharCount);\n }\n\n return pseudoText;\n }\n\n if (shouldUseAnimationHeight && textContent) {\n return getSubTextFromHTML(textContent, shownCharCount);\n }\n\n return textContent || '​';\n }, [\n colorScheme?.designSettings?.color,\n colorScheme?.designSettings?.colorMode,\n functions,\n pseudoChildren,\n shouldUseAnimationHeight,\n shownCharCount,\n textContent,\n values,\n ]);\n\n return useMemo(\n () => (\n <StyledTypewriter\n $cursorType={cursorType}\n onClick={isAnimatingText ? handleClick : undefined}\n $isAnimatingText={isAnimatingText}\n $shouldHideCursor={shouldHideCursor}\n $shouldPreventBlinkAnimation={shouldPreventBlinkingCursor}\n >\n {isAnimatingText ? (\n <AnimatedTypewriterText\n shouldHideCursor={shouldHideCursor}\n shouldRemainSingleLine={shouldRemainSingleLine}\n shownText={shownText}\n textStyle={textStyle}\n />\n ) : (\n <StyledTypewriterText\n className=\"notranslate\"\n $shouldRemainSingleLine={shouldRemainSingleLine}\n dangerouslySetInnerHTML={\n typeof sortedChildren === 'string' ? { __html: shownText } : undefined\n }\n style={textStyle}\n >\n {typeof sortedChildren !== 'string' ? sortedChildren : undefined}\n </StyledTypewriterText>\n )}\n {isAnimatingText && (\n <StyledTypewriterPseudoText\n $isAnimatingText={isAnimatingText}\n $shouldHideCursor={shouldHideCursor}\n dangerouslySetInnerHTML={{ __html: pseudoTextHTML }}\n />\n )}\n {/*\n The following is needed because some components like the CodeHighlighter will not render correct\n if the element is not rendered on a client before...\n */}\n {!hasRenderedChildrenOnce &&\n createPortal(\n <div style={{ position: 'absolute', visibility: 'hidden' }}>\n {children}\n </div>,\n document.body,\n )}\n </StyledTypewriter>\n ),\n [\n children,\n cursorType,\n handleClick,\n hasRenderedChildrenOnce,\n isAnimatingText,\n pseudoTextHTML,\n shouldHideCursor,\n shouldPreventBlinkingCursor,\n shouldRemainSingleLine,\n shownText,\n sortedChildren,\n textStyle,\n ],\n );\n};\n\nTypewriter.displayName = 'Typewriter';\n\nexport default Typewriter;\n"],"mappings":"AAAA,SAASA,mBAAmB,EAAEC,cAAc,QAAQ,yBAAyB;AAC7E,SAASC,cAAc,EAAEC,YAAY,EAAEC,SAAS,QAAQ,YAAY;AACpE,OAAOC,KAAK,IAGRC,WAAW,EACXC,SAAS,EACTC,eAAe,EACfC,OAAO,EACPC,MAAM,EACNC,QAAQ,QACL,OAAO;AACd,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,cAAc,QAAQ,kBAAkB;AAEjD,SAASC,UAAU,QAAQ,oBAAoB;AAC/C,SAASC,eAAe,EAAEC,eAAe,QAAQ,mBAAmB;AACpE,OAAOC,sBAAsB,MAAM,0B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AAsB,EAAEA,sBAAuB;IAC/C4E,SAAS,EAAEA,SAAU;IACrBnE,SAAS,EAAEA;EAAU,CACxB,CAAC,gBAEFhD,KAAA,CAAA2E,aAAA,CAAC5D,oBAAoB;IACjBoE,SAAS,EAAC,aAAa;IACvBwC,uBAAuB,EAAEpF,sBAAuB;IAChDqF,uBAAuB,EACnB,OAAO1D,cAAc,KAAK,QAAQ,GAAG;MAAE2D,MAAM,EAAEV;IAAU,CAAC,GAAGrB,SAChE;IACDb,KAAK,EAAEjC;EAAU,GAEhB,OAAOkB,cAAc,KAAK,QAAQ,GAAGA,cAAc,GAAG4B,SACrC,CACzB,EACAG,eAAe,iBACZjG,KAAA,CAAA2E,aAAA,CAAC7D,0BAA0B;IACvB0G,gBAAgB,EAAEvB,eAAgB;IAClCwB,iBAAiB,EAAEnF,gBAAiB;IACpCsF,uBAAuB,EAAE;MAAEC,MAAM,EAAET;IAAe;EAAE,CACvD,CACJ,EAKA,CAAC/D,uBAAuB,iBACrB9C,YAAY,cACRP,KAAA,CAAA2E,aAAA;IAAKM,KAAK,EAAE;MAAE6C,QAAQ,EAAE,UAAU;MAAEC,UAAU,EAAE;IAAS;EAAE,GACtDvG,QACA,CAAC,EACNwG,QAAQ,CAACC,IACb,CACU,CACrB,EACD,CACIzG,QAAQ,EACRC,UAAU,EACVyE,WAAW,EACX7C,uBAAuB,EACvB4C,eAAe,EACfmB,cAAc,EACd9E,gBAAgB,EAChBiB,2BAA2B,EAC3BhB,sBAAsB,EACtB4E,SAAS,EACTjD,cAAc,EACdlB,SAAS,CAEjB,CAAC;AACL,CAAC;AAEDzB,UAAU,CAAC2G,WAAW,GAAG,YAAY;AAErC,eAAe3G,UAAU","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import styled, { css, keyframes } from 'styled-components';
|
|
2
|
-
import { CursorType } from '
|
|
2
|
+
import { CursorType } from '../../types/cursor';
|
|
3
3
|
const typewriterCursorElement = ({
|
|
4
4
|
$cursorType,
|
|
5
5
|
$isAnimatingText,
|
|
@@ -94,4 +94,4 @@ export const StyledTypewriterText = styled.span`
|
|
|
94
94
|
width: 100%;
|
|
95
95
|
`}
|
|
96
96
|
`;
|
|
97
|
-
//# sourceMappingURL=
|
|
97
|
+
//# sourceMappingURL=Typewriter.styles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Typewriter.styles.js","names":["styled","css","keyframes","CursorType","typewriterCursorElement","$cursorType","$isAnimatingText","$shouldHideCursor","$shouldPreventBlinkAnimation","Thin","blinkAnimation","theme","text","StyledTypewriter","div","StyledTypewriterPseudoText","span","StyledTypewriterText","$shouldRemainSingleLine"],"sources":["../../../../src/components/typewriter/Typewriter.styles.ts"],"sourcesContent":["import type { WithTheme } from '@chayns-components/core';\nimport styled, { css, keyframes } from 'styled-components';\nimport { CursorType } from '../../types/cursor';\nimport type { TypewriterProps } from './Typewriter';\n\ntype StyledTypewriterProps = WithTheme<{\n $cursorType: TypewriterProps['cursorType'];\n $isAnimatingText: boolean;\n $shouldHideCursor: TypewriterProps['shouldHideCursor'];\n $shouldPreventBlinkAnimation: boolean;\n}>;\n\nconst typewriterCursorElement = ({\n $cursorType,\n $isAnimatingText,\n $shouldHideCursor,\n $shouldPreventBlinkAnimation,\n}: StyledTypewriterProps) => {\n if (!$isAnimatingText || $shouldHideCursor) {\n return '';\n }\n\n if ($cursorType === CursorType.Thin) {\n return css`\n .typewriter-lastWithContent {\n &:after {\n animation: ${$shouldPreventBlinkAnimation ? 'none' : blinkAnimation} 1s steps(2, start) infinite;\n color: inherit;\n content: '|';\n font-size: 25px;\n position: relative;\n line-height: 0;\n vertical-align: baseline;\n }\n `;\n }\n\n return css`\n .typewriter-lastWithContent {\n &:after {\n animation: ${blinkAnimation} 1s steps(2, start) infinite;\n color: ${({ theme }) => (theme as { text: string }).text};\n content: '▋';\n margin-left: 0.25rem;\n opacity: 0.85;\n position: relative;\n vertical-align: baseline;\n }\n }\n `;\n};\n\nexport const StyledTypewriter = styled.div<StyledTypewriterProps>`\n align-items: inherit;\n display: flex;\n position: relative;\n width: 100%;\n ${typewriterCursorElement}\n`;\n\nconst blinkAnimation = keyframes`\n 100% {\n visibility: hidden;\n }\n`;\n\ntype StyledTypewriterPseudoTextProps = WithTheme<{\n $isAnimatingText?: boolean;\n $shouldHideCursor: TypewriterProps['shouldHideCursor'];\n}>;\n\nexport const StyledTypewriterPseudoText = styled.span<StyledTypewriterPseudoTextProps>`\n opacity: 0;\n pointer-events: none;\n user-select: none;\n width: fit-content;\n\n ${({ $isAnimatingText, $shouldHideCursor }) =>\n $isAnimatingText &&\n !$shouldHideCursor &&\n css`\n &:after {\n animation: ${blinkAnimation} 1s steps(2, start) infinite;\n color: inherit;\n content: '|';\n font-size: 25px;\n position: relative;\n line-height: 0;\n vertical-align: baseline;\n }\n `}\n`;\n\ntype StyledTypewriterTextProps = WithTheme<{\n $isAnimatingText?: boolean;\n $shouldRemainSingleLine: boolean;\n}>;\n\nexport const StyledTypewriterText = styled.span<StyledTypewriterTextProps>`\n color: inherit;\n position: ${({ $isAnimatingText }) => ($isAnimatingText ? 'absolute' : 'relative')};\n width: fit-content;\n\n ${({ $isAnimatingText }) =>\n $isAnimatingText &&\n css`\n pointer-events: none;\n `}\n\n ${({ $shouldRemainSingleLine }) =>\n $shouldRemainSingleLine &&\n css`\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n width: 100%;\n `}\n`;\n"],"mappings":"AACA,OAAOA,MAAM,IAAIC,GAAG,EAAEC,SAAS,QAAQ,mBAAmB;AAC1D,SAASC,UAAU,QAAQ,oBAAoB;AAU/C,MAAMC,uBAAuB,GAAGA,CAAC;EAC7BC,WAAW;EACXC,gBAAgB;EAChBC,iBAAiB;EACjBC;AACmB,CAAC,KAAK;EACzB,IAAI,CAACF,gBAAgB,IAAIC,iBAAiB,EAAE;IACxC,OAAO,EAAE;EACb;EAEA,IAAIF,WAAW,KAAKF,UAAU,CAACM,IAAI,EAAE;IACjC,OAAOR,GAAG;AAClB;AACA;AACA,iCAAiCO,4BAA4B,GAAG,MAAM,GAAGE,cAAc;AACvF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;EACL;EAEA,OAAOT,GAAG;AACd;AACA;AACA,6BAA6BS,cAAc;AAC3C,yBAAyB,CAAC;IAAEC;EAAM,CAAC,KAAMA,KAAK,CAAsBC,IAAI;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,CAAC;AAED,OAAO,MAAMC,gBAAgB,GAAGb,MAAM,CAACc,GAA0B;AACjE;AACA;AACA;AACA;AACA,MAAMV,uBAAuB;AAC7B,CAAC;AAED,MAAMM,cAAc,GAAGR,SAAS;AAChC;AACA;AACA;AACA,CAAC;AAOD,OAAO,MAAMa,0BAA0B,GAAGf,MAAM,CAACgB,IAAqC;AACtF;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC;EAAEV,gBAAgB;EAAEC;AAAkB,CAAC,KACtCD,gBAAgB,IAChB,CAACC,iBAAiB,IAClBN,GAAG;AACX;AACA,6BAA6BS,cAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,CAAC;AAOD,OAAO,MAAMO,oBAAoB,GAAGjB,MAAM,CAACgB,IAA+B;AAC1E;AACA,gBAAgB,CAAC;EAAEV;AAAiB,CAAC,KAAMA,gBAAgB,GAAG,UAAU,GAAG,UAAW;AACtF;AACA;AACA,MAAM,CAAC;EAAEA;AAAiB,CAAC,KACnBA,gBAAgB,IAChBL,GAAG;AACX;AACA,SAAS;AACT;AACA,MAAM,CAAC;EAAEiB;AAAwB,CAAC,KAC1BA,uBAAuB,IACvBjB,GAAG;AACX;AACA;AACA;AACA;AACA,SAAS;AACT,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TypewriterSpeed } from '
|
|
1
|
+
import { TypewriterSpeed } from '../../types/speed';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Returns a substring of an HTML string while preserving HTML structure.
|
|
@@ -148,16 +148,33 @@ export const shuffleArray = array => {
|
|
|
148
148
|
}
|
|
149
149
|
return result;
|
|
150
150
|
};
|
|
151
|
-
export const
|
|
151
|
+
export const calculateAutoSpeed = ema => {
|
|
152
|
+
// nested timer calls are clamped to a 4ms minimum
|
|
153
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#reasons_for_longer_delays_than_specified
|
|
154
|
+
const MINIMUM_TIMEOUT = 4;
|
|
152
155
|
if (ema <= 0) {
|
|
153
|
-
return
|
|
156
|
+
return {
|
|
157
|
+
speed: TypewriterSpeed.ExtraSlow,
|
|
158
|
+
steps: 1
|
|
159
|
+
};
|
|
154
160
|
}
|
|
155
|
-
|
|
161
|
+
const msPerChar = Math.min(1000 / ema, TypewriterSpeed.ExtraSlow);
|
|
162
|
+
if (msPerChar >= MINIMUM_TIMEOUT) {
|
|
163
|
+
return {
|
|
164
|
+
speed: msPerChar,
|
|
165
|
+
steps: 1
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const steps = Math.max(1, MINIMUM_TIMEOUT / msPerChar);
|
|
169
|
+
return {
|
|
170
|
+
speed: MINIMUM_TIMEOUT,
|
|
171
|
+
steps
|
|
172
|
+
};
|
|
156
173
|
};
|
|
157
174
|
export const calculateEMA = ({
|
|
158
175
|
currentEMA,
|
|
159
176
|
newValue,
|
|
160
|
-
alpha = 0.
|
|
177
|
+
alpha = 0.25
|
|
161
178
|
}) => alpha * newValue + (1 - alpha) * currentEMA;
|
|
162
179
|
export const updateChunkStreamingSpeedEMA = ({
|
|
163
180
|
currentLength,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":["TypewriterSpeed","getSubTextFromHTML","html","length","div","document","createElement","innerHTML","text","currLength","escapeText","value","replace","escapeAttr","String","VOID_ELEMENTS","Set","traverse","node","nodeType","textContent","nodeText","remaining","substring","element","nodeName","toLowerCase","attributes","attribute","name","isVoid","has","i","childNodes","childNode","getCharactersCount","count","trim","Array","from","forEach","shuffleArray","array","result","j","Math","floor","random","calculateAutoSpeed","ema","MINIMUM_TIMEOUT","speed","ExtraSlow","steps","msPerChar","min","max","calculateEMA","currentEMA","newValue","alpha","updateChunkStreamingSpeedEMA","currentLength","state","now","Date","deltaTime","lastTimestamp","deltaLength","lastLength","charsPerSecond","newEMA"],"sources":["../../../../src/components/typewriter/utils.ts"],"sourcesContent":["import { TypewriterSpeed } from '../../types/speed';\n\n/**\n * Returns a substring of an HTML string while preserving HTML structure.\n *\n * Core rules:\n * - Element nodes are re-serialized as tags (start/end) to keep structure.\n * - Text nodes are always HTML-escaped on output. This prevents that previously\n * escaped text (like \"<div>\") turns into real tags during the DOM round trip.\n * - Attribute values are HTML-escaped on output.\n * - Void elements are serialized without closing tags.\n * - For TWIGNORE/TW-IGNORE elements, the innerHTML is passed through so that\n * their content (including real HTML) remains untouched.\n * - On early cutoff (once the length limit is reached), already opened tags are\n * properly closed to keep the result valid HTML.\n *\n * Note on length counting:\n * - The length is based on the decoded textContent length (as the DOM provides),\n * not on byte length nor escaped entity length. This mirrors how the text is perceived.\n *\n * @param html The input HTML string; may contain a mix of real HTML and already escaped HTML.\n * @param length The maximum number of text characters (based on textContent) to include.\n * @returns A valid HTML string containing up to the specified number of text characters,\n * preserving HTML tags and keeping escaped text escaped.\n */\nexport const getSubTextFromHTML = (html: string, length: number): string => {\n const div = document.createElement('div');\n\n div.innerHTML = html;\n\n let text = '';\n let currLength = 0;\n\n // Escape text node content to ensure that decoded \"<\" and \">\" do not become real tags.\n const escapeText = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\n // Escape attribute values safely.\n const escapeAttr = (value: string): string =>\n String(value)\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n\n // HTML void elements (must not have closing tags)\n const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n ]);\n\n // Traverses nodes and appends to \"text\".\n // Returns false to signal \"stop traversal\" once the length limit is reached.\n const traverse = (node: Node): boolean => {\n // Text node\n if (node.nodeType === 3 && typeof node.textContent === 'string') {\n const nodeText = node.textContent;\n const remaining = length - currLength;\n\n if (remaining <= 0) {\n return false;\n }\n\n if (nodeText.length <= remaining) {\n // Always escape text before writing to output\n text += escapeText(nodeText);\n currLength += nodeText.length;\n } else {\n // Cut the text and stop traversal\n text += escapeText(nodeText.substring(0, remaining));\n currLength += remaining;\n return false;\n }\n\n return true;\n }\n\n // Element node\n if (node.nodeType === 1) {\n const element = node as Element;\n\n // Pass-through for TWIGNORE/TW-IGNORE: keep their HTML as-is.\n if (element.nodeName === 'TWIGNORE' || element.nodeName === 'TW-IGNORE') {\n // element.innerHTML serializes children; escaped text stays escaped,\n // real HTML stays HTML — exactly what we want here.\n text += element.innerHTML;\n return true;\n }\n\n const nodeName = element.nodeName.toLowerCase();\n\n // Serialize attributes safely\n let attributes = '';\n // @ts-expect-error: attributes is a NodeListOf<Attr>\n // eslint-disable-next-line no-restricted-syntax\n for (const attribute of element.attributes) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-argument\n attributes += ` ${attribute.name}=\"${escapeAttr(attribute.value)}\"`;\n }\n\n // Open tag\n text += `<${nodeName}${attributes}>`;\n\n // Void elements: do not recurse children and do not emit a closing tag\n const isVoid = VOID_ELEMENTS.has(nodeName);\n if (!isVoid) {\n // Recurse through children until limit is reached\n for (let i = 0; i < element.childNodes.length; i++) {\n const childNode = element.childNodes[i];\n if (childNode && !traverse(childNode)) {\n // On early stop: close this tag to keep valid HTML, then bubble stop.\n text += `</${nodeName}>`;\n return false;\n }\n }\n\n // Close tag after all children\n text += `</${nodeName}>`;\n }\n\n return true;\n }\n\n // Other node types (comments, etc.) are ignored for text length\n return true;\n };\n\n // Traverse top-level children\n for (let i = 0; i < div.childNodes.length; i++) {\n const childNode = div.childNodes[i];\n if (childNode && !traverse(childNode)) {\n return text;\n }\n }\n\n return text;\n};\n\nexport const getCharactersCount = (html: string): number => {\n const div = document.createElement('div');\n\n div.innerHTML = html;\n\n let count = 0;\n\n const traverse = (node: Node): void => {\n if (node.nodeName === 'TWIGNORE') {\n count += 1;\n } else if (node.nodeType === 3 && typeof node.textContent === 'string') {\n count += node.textContent.trim().length;\n } else if (node.nodeType === 1) {\n if (node.nodeName === 'CODE' && node.textContent !== null) {\n count += node.textContent.length;\n\n return;\n }\n\n Array.from(node.childNodes).forEach(traverse);\n }\n };\n\n Array.from(div.childNodes).forEach(traverse);\n\n return count;\n};\n\nexport const shuffleArray = <T>(array: T[]): T[] => {\n const result = Array.from(array);\n\n for (let i = result.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n [result[i], result[j]] = [result[j]!, result[i]!];\n }\n\n return result;\n};\n\nexport const calculateAutoSpeed = (ema: number): { speed: number; steps: number } => {\n // nested timer calls are clamped to a 4ms minimum\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#reasons_for_longer_delays_than_specified\n const MINIMUM_TIMEOUT = 4;\n\n if (ema <= 0) {\n return { speed: TypewriterSpeed.ExtraSlow, steps: 1 };\n }\n\n const msPerChar = Math.min(1000 / ema, TypewriterSpeed.ExtraSlow);\n\n if (msPerChar >= MINIMUM_TIMEOUT) {\n return { speed: msPerChar, steps: 1 };\n }\n\n const steps = Math.max(1, MINIMUM_TIMEOUT / msPerChar);\n return { speed: MINIMUM_TIMEOUT, steps };\n};\n\ninterface CalculateEMAProps {\n currentEMA: number;\n newValue: number;\n alpha?: number;\n}\n\nexport const calculateEMA = ({ currentEMA, newValue, alpha = 0.25 }: CalculateEMAProps): number =>\n alpha * newValue + (1 - alpha) * currentEMA;\n\nexport interface ChunkStreamingSpeedState {\n lastTimestamp?: number;\n lastLength: number;\n ema: number;\n}\n\ninterface ChunkStreamingSpeedProps {\n currentLength: number;\n state: ChunkStreamingSpeedState;\n}\n\nexport const updateChunkStreamingSpeedEMA = ({\n currentLength,\n state,\n}: ChunkStreamingSpeedProps): ChunkStreamingSpeedState => {\n const now = Date.now();\n const deltaTime = now - (state?.lastTimestamp ?? now);\n\n if (deltaTime <= 0) return { ...state, lastTimestamp: now };\n\n const deltaLength = currentLength - state.lastLength;\n\n const charsPerSecond = Math.max(0, (deltaLength / deltaTime) * 1000);\n\n const newEMA = calculateEMA({\n currentEMA: state.ema,\n newValue: charsPerSecond,\n });\n\n return {\n lastTimestamp: now,\n lastLength: currentLength,\n ema: newEMA,\n };\n};\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,mBAAmB;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,kBAAkB,GAAGA,CAACC,IAAY,EAAEC,MAAc,KAAa;EACxE,MAAMC,GAAG,GAAGC,QAAQ,CAACC,aAAa,CAAC,KAAK,CAAC;EAEzCF,GAAG,CAACG,SAAS,GAAGL,IAAI;EAEpB,IAAIM,IAAI,GAAG,EAAE;EACb,IAAIC,UAAU,GAAG,CAAC;;EAElB;EACA,MAAMC,UAAU,GAAIC,KAAa,IAC7BA,KAAK,CAACC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAACA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAACA,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;;EAE5E;EACA,MAAMC,UAAU,GAAIF,KAAa,IAC7BG,MAAM,CAACH,KAAK,CAAC,CACRC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CACtBA,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CACvBA,OAAO,CAAC,IAAI,E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