Posted 17 days ago. Visible to the public.

Automated wordbreaks for long words

The problem:

So I had the issue that User input (coming from many different sources and users) often contains the same long word. Maybe that's a super german thing to have lots of long words I have to deal with. This long word needs to be fully visible on small screens but none of the automated word-break solutions offered by css (https://justmarkup.com/articles/2015-07-31-dealing-with-long-words-in-css/) is clever or supported enough to be a good solution. So I had to come up with my own.

The Solution:

I wrote an unpoly compiler that crawls the document and replaces all occurencies of certain word and puts a soft-hyphen (­, or \xAD) where i want the word to break. This is only done in text nodes in order to not break url's in link-tags.

Copy
up.compiler('[break-long-words]', (element) => { const wordBreaks = { 'Fahrsicherheitstraining': "Fahr\xADsicherheits\xADtraining", 'Fahrsicherheitszentrum': 'Fahr\xADsicherheits\xADzentrum', 'Kreisverkehrswacht': 'Kreis\xADverkehrswacht', 'Berufsgenossenschaft': 'Berufs\xADgenossenschaft', } const keys = Object.keys(wordBreaks) function textNodes(node){ let textNodes = [] let walk = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false) let nextNode while (nextNode = walk.nextNode()) { textNodes.push(nextNode) } return textNodes } keys.forEach((key) => { let nodes = textNodes(element) nodes.forEach((node) => { node.textContent = node.textContent.replace(new RegExp(key, 'gi'), wordBreaks[key]) }) }) })

This might not be a clever idea on sites with a lot of text, because crawling long texts can get rather expensive and doing it for every long word does not make it better, but in my case the pages are not very content-heavy and there is no remarkable jump during page-build.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Jakob Scholz
Last edit:
16 days ago
by Jakob Scholz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Jakob Scholz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more