Last active
December 13, 2015 20:48
-
-
Save bgourlie/4972747 to your computer and use it in GitHub Desktop.
Truncates texts that would otherwise be hidden due to overflow: hidden and adds an ellipses (…). This only works for multi-line text and not single-line text since any browser that Dart targets should support the text-overflow CSS property that has built-in support for single-line auto-ellipses.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void ellipses(Element el){ | |
| final tempElement = el.clone(true); | |
| if(el.getComputedStyle().overflow == 'hidden'){ | |
| tempElement.style.position = 'absolute'; | |
| tempElement.style.overflow = 'visible'; | |
| tempElement.style.width = '${el.clientWidth}px'; | |
| tempElement.style.height = 'auto'; | |
| tempElement.style.maxHeight = 'none'; | |
| el.insertAdjacentElement('afterEnd', tempElement); | |
| final desiredHeight = el.clientHeight; | |
| final allNodes = new List<Node>(); | |
| for(final node in tempElement.nodes){ | |
| addAllNodes(node, allNodes); | |
| } | |
| while(tempElement.clientHeight > desiredHeight){ | |
| for(int i = allNodes.length - 1; i >=0; i--){ | |
| final curNode = allNodes[i]; | |
| if(curNode.text.trim().isEmpty){ | |
| curNode.remove(); | |
| continue; | |
| } | |
| var curText = curNode.text.trim(); | |
| while(curText.length > 0){ | |
| final nextCutoff = curNode.text.lastIndexOf(' '); | |
| if(nextCutoff == -1){ | |
| curNode.remove(); | |
| break; | |
| } | |
| final nextCutoffText = curNode.text.substring(0, nextCutoff); | |
| curText = '${nextCutoffText}…'; | |
| curNode.text = curText; | |
| el.innerHtml = tempElement.innerHtml; | |
| if(tempElement.clientHeight <= desiredHeight){ | |
| tempElement.remove(); | |
| return; | |
| } | |
| } | |
| } | |
| } | |
| tempElement.remove(); | |
| } | |
| } | |
| void addAllNodes(Node curNode, List<Node> nodes){ | |
| nodes.add(curNode); | |
| for(final node in curNode.nodes){ | |
| addAllNodes(node, nodes); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment