Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | import * as dom from '../dom/dom';
import {DomWatcher} from './dom-watcher';
export interface textSplit2Config {
element: HTMLElement;
splitByCharacter?: boolean;
}
/**
* This is a slightly improved version of text-split.ts. It automatically
* assumes you want a word by word split but also adds sentence row indexes
* so you can add effects per sentence row.
*
* Splits the textContent of a given htmlElement and provides css variables
* that can be used to add various text effects.
*
*
* Here is a basic example.
*
* ```ts
*
* <div id="myElement">New York <br/>City</div>
*
* let splitter = new TextSplit({
* element: document.getElementById('myElement'),
* });
*
* // Break up the text and wrap spans around it.
* splitter.split();
* ```
*
* This results in:
*
* ```ts
* .only-screenreaders
* height: 1px
* width: 1px
* margin: -1px
* overflow: hidden
* padding: 0
* position: absolute
*
* <div class="only-screenreaders">New York City</div>
* <div id="myElement" class="text-split-set" style="--item-total-count:3"
* >
* <span aria-hidden="true" style="--item-index:0">New </span>
* <span aria-hidden="true" style="--item-index:1">York </span><br/>
* <span aria-hidden="true" style="--item-index:2">City</span>
* </div>
*
* ```
*
*
* Additionally, each item can received the follow:
*
* ```ts
*
* <span start="1" row="1" end="1" item="1">xxx</div>
*
* ```
*
* row: This is the row sentence number that this span resides on.
* start: If this is the first word in the sentence.
* end: If this is the last word in the sentence.
* item: The overall item index of this word.
*
*
* Notice that on the root element, you get the total number of items,
* and also on each element, you get an index.
*
* Now you can use css variables to add various effect.
*
* ```ts
* @keyframes textIn
* from
* opacity: 0;
* to
* opacity: 1;
*
* // Help fight FOUC
* #myElement
* visiblity: hidden
* #myElement.text-split-set
* visibility: visible
*
* #myElement span,
* position: relative
* font-size: 20px
* opacity: 0
* animation: textIn 1.3s ease-in-out 0s 1 forwards
*
* // Create a 0.2s stagger between each item.
* animation-delay: calc(var(--item-index) * 0.2s
*
* // More advanced. You may not know how many words or character there are
* // but you want to the animation to finish in Xs seconds.
* // Using item-total-count, you can break the subdivisions.
* // Here no matter how many words/characters there are, set it so that the
* // stagger animation always completes in 1s.
* animation-delay: calc(var(--item-index) * (1s / var(--item-total-count)))
* ```
*/
export class TextSplit2 {
private element: HTMLElement;
public originalHTML: string;
private splitByCharacter = false;
private domWatcher: DomWatcher;
private words: Array<HTMLElement> = [];
constructor(private config: textSplit2Config) {
this.element = config.element;
this.splitByCharacter = !!config.splitByCharacter;
this.originalHTML = this.element.innerHTML;
this.domWatcher = new DomWatcher();
this.domWatcher.add({
element: window,
on: 'smartResize',
callback: () => requestAnimationFrame(this.onSmartResize.bind(this)),
});
}
/**
* Splits the text and wraps <span> around each sub item.
*/
split() {
const nodes = dom.getAllTextNodes(this.element);
this.words = [];
let index = 0;
nodes.forEach((node) => {
let first = true;
let previousElement = node;
// Split this text node by space.
let texts;
if (this.splitByCharacter) {
texts = node.textContent!.trim().split('');
} else {
texts = node.textContent!.trim().split(' ');
}
texts.forEach((text) => {
const element = dom.createElementFromString(
'<span aria-hidden="true"></span>'
);
// if (i !== texts.length - 1) {
// element.innerHTML = text + ' ';
// } else {
// element.innerHTML = text + ' ';
// }
if (this.splitByCharacter) {
element.textContent = text === ' ' ? '\u00A0' : text;
} else {
element.textContent = `${text}\u00A0`;
}
element.classList.add('text-split__text');
element.setAttribute('item', index + '');
dom.setCssVariable(element, '--item-index', index + '');
this.words.push(element);
if (first) {
node.parentElement!.replaceChild(element, node);
first = false;
} else {
dom.appendAfter(element, previousElement as HTMLElement);
}
previousElement = element;
index++;
});
});
this.onSmartResize();
dom.setCssVariable(
this.config.element,
'--item-total-count',
this.words.length + ''
);
this.config.element.classList.add('text-split-set');
}
/**
* On each resize, check the position of each span and mark down which
* row it resides on.
*/
private onSmartResize() {
let sentenceNumber = 0;
let y = dom.getScrollTopWithoutTransforms(this.words[0]);
// Clean up
this.words.forEach((word) => {
word.removeAttribute('start');
word.removeAttribute('end');
word.removeAttribute('row');
});
const wordHeight = this.words[0].offsetHeight;
this.words[0].setAttribute('start', sentenceNumber + '');
this.words.forEach((word, i) => {
const wordY = dom.getScrollTopWithoutTransforms(word);
word.className.replace(/\bbg.*?\b/g, '');
const delta = Math.abs(wordY - y);
// In a simple implementation, we would just check the Y position
// of each word in the sentance and if the Y position of a given
// word doesn't match the previous word, we know we are a new sentance.
// However, there are more complicated cases. A sentence such as
// "Hello there <sup>3</sup>" is one of such cases. In this case,
// the <sup> y position is slightly off and doesn't match. With a
// simple implementation, the <sup> would get counted as a new sentance.
// To avoid this, we take the very first word and cache the height.
// If the next word is more than half the height of the wordHeight,
// then we are on a new sentance. This gives a little wiggle room
// to the logic.
const isNewRow = delta >= wordHeight * 0.5;
if (isNewRow) {
y = wordY;
if (this.words[i - 1]) {
this.words[i - 1].setAttribute('end', sentenceNumber + '');
}
sentenceNumber++;
word.setAttribute('start', sentenceNumber + '');
}
word.setAttribute('row', sentenceNumber + '');
// Last item.
if (i === this.words.length - 1) {
this.words[i].setAttribute('end', sentenceNumber + '');
}
});
}
/**
* Reverts and undoes the effects of text-split.
*/
revert() {
this.element.innerHTML = this.originalHTML;
}
dispose() {
this.domWatcher.dispose();
}
}
|