Skip to content

Commit

Permalink
add insertSpans logic to replace ellipses with spaces
Browse files Browse the repository at this point in the history
  • Loading branch information
pandringa committed Dec 3, 2024
1 parent 8bd75ff commit d5c05dd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
5 changes: 5 additions & 0 deletions components/BodyText/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ const BodyText = ({ elements, maxWidowSize = 8, extraMargin = true }) => (
regex: new RegExp(`(\\w+\\s\\w{1,${maxWidowSize}}.?)$`),
className: 'nowrap',
},
{
regex: /(|\.\s?\.\s?\.)/,
className: 'ellipses',
innerText: '. . .',
},
]);

switch (type) {
Expand Down
4 changes: 4 additions & 0 deletions components/BodyText/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@
margin: 72px auto;
}
}

.ellipses {
text-wrap: nowrap;
}
}
19 changes: 15 additions & 4 deletions util/text.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,30 @@ export function insertSpans(text, highlights, options = { p: true }) {
.map(([k, v]) => (k && v ? `${k}="${v?.replace('"', '\\"')}"` : ''))
.join(' ');

return [
// Add the start/end tags to the queue
const matchTags = [
{ tag: `<${el} ${props}>`, index: match.start },
{ tag: `</${el}>`, index: match.end },
];

// Add a special "replace" tag if necessary
if (match.innerText)
matchTags.push({
tag: match.innerText,
index: match.start,
replace: match.end - match.start,
});

return matchTags;
})
.flat()
.sort((a, b) => a.index - b.index);

// 3. Insert the HTML tags into the string
const output = tags.reduce(
({ offset, __html }, { tag, index }) => ({
offset: offset + tag.length,
__html: __html.slice(0, index + offset) + tag + __html.slice(index + offset),
({ offset, __html }, { tag, index, replace = 0 }) => ({
offset: offset + tag.length - replace,
__html: __html.slice(0, index + offset) + tag + __html.slice(index + offset + replace),
}),
{ offset: 0, __html: text }
);
Expand Down

0 comments on commit d5c05dd

Please sign in to comment.