JSFiddle - React, Tailwind, and code Playground
HTML
<div id="main">
<div id="top">
<div>toot length</div>
<input type="number" id="tootLength" value=500>
<div>suffix</div>
<input id="suffix" value="... (#num/#tot)">
<div>last suffix</div>
<input id="last-suffix" value=" (#num/#tot)">
</div>
<textarea id="toot" name="story"
rows="5" cols="33"
placeholder="Your toot here. Use '||' to force a new split.">
</textarea>
<div id="results">
</div>
</div>
CSS
#toot {
height: 400px;
}
#top {
display: grid;
grid-template-columns: 1fr 2fr;
text-align: right;
column-gap: 8px;
grid-column: 1 / 3;
}
#main {
display: grid;
grid-template-columns: 1fr 1fr;
}
.result div {
display: inline-block;
}
.toot {
display: block;
border: solid 1px blue;
display: block;
}
JavaScript
const tootArea = document.getElementById('toot');
function dom(tag, parent, classname, textContent) {
const el = document.createElement(tag);
if (parent) {
parent.appendChild(el);
}
if (classname) {
el.className = classname;
}
if (textContent) {
el.textContent = textContent;
}
return el;
}
function setClipboard(text) {
var type = "text/plain";
var blob = new Blob([text], { type });
var data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data);
}
function onChange() {
const tootLength = document.getElementById('tootLength').value;
let suffixTmpl = document.getElementById('suffix').value;
let lastSuffix = document.getElementById('last-suffix').value;
const content = tootArea.value;
const splitToots = [];
let lastBreakIdx = 0;
while (lastBreakIdx != -1) {
const breakIdx = content.indexOf('||', lastBreakIdx + 1);
if (breakIdx > 0) {
splitToots.push(content.substring(lastBreakIdx, breakIdx));
lastBreakIdx = breakIdx + 2;
} else {
splitToots.push(content.substring(lastBreakIdx));
break;
}
}
let tmpToots = []
for (let tootIdx in splitToots) {
// Check if the toot needs to be shortened.
let suffixLength = suffixTmpl.replace("#num", "##").replace("#tot", '##').length;
const maxLength = tootLength - suffixLength;
const toot = splitToots[tootIdx];
let remaining = toot;
let max = 0
while (remaining.length > maxLength && max < 100) {
max++;
let chunk = remaining.slice(0, maxLength);
// Got lucky, already stuck on white space.
if (!/\s/.test(chunk[chunk.length - 1])) {
const splits = chunk.split(/\s+/);
if (splits.length > 1) {
const lastSplit = splits[splits.length - 1];
chunk = chunk.substring(0, chunk.length - lastSplit.length);
}
}
let suffix = suffixTmpl.replace('#num', tmpToots.length);
tmpToots.push(chunk.trim());
remaining =...