Text-wrapping routine.
It might be useful to expose this as d3.svg.textWrap?
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
Live example: http://bl.ocks.org/mbostock/7555321
cool, +1
Seems very useful, +1.
On Wed, Nov 20, 2013 at 3:49 AM, Sumh [email protected] wrote:
cool, +1
— Reply to this email directly or view it on GitHubhttps://github.com/mbostock/d3/issues/1642#issuecomment-28857386 .
:+1:
so cool!
Just a slight variation: There could be a routine that wraps text within a circle. It would find its application in labeled circle packs, and implementation of various diagrams (UML or similar). I guess many developers would love to have it. I could write it and post it here. Its interface could be:
function wrapWithinCircle(text, radius)
However, I am not really clear with original function wrap(text, width). How does font size affect the result? How does a caller specify what font size and what font he/she wants for the text? Should font and font size be arguments of a new function? Or maybe I am missing something entirely, its possible?
If this does get added, there is a bug that I noticed when I used this recently. If the first word is wider than the specified width, a blank line is produced instead. Just making sure you don't pop when there is only one word in the line solves the problem.
if(line.length > 1) line.pop();
One detail I would like to add is the assumption that the x attribute is 0. I explain the potential problem with that assumption here.
+1
+1. Would love to see this, or something similar, at least until SVG adds native support (which will be a while).
+1.
I'd only suggest to use a join to add tspans, something like http://bl.ocks.org/mindrones/10359683.
It'd be useful to have the tspan's text in its own __data__.
+1
+1
+1
I've written a plugin to help with this problem.
I showed it to @mbostock and @jasondavies a while back and they had some insightful suggestions which culminated in a pending pull request.
The differences between the two versions of this code are as follows; the plugin documentation is pretty extensive, so if this issue is of particular interest to you then I'd suggest reading over that as well.
| Issue | Plugin | Core |
|---|---|---|
| API | simple method called on text node | configurable function used via .call() |
| boundaries | coordinates or d3 rect selection | integer, coordinates, or any d3 selection |
| wrapping technique | tspans or foreignObject | tspans only |
API
The plugin has simpler syntax, because it extends the prototype and then you can just call it on the text selection directly:
var bounds = d3.select('rect#bounds');
var padding = 10;
var text_node = d3.select('text#wrap-me');
text_node.textwrap(bounds, padding);
Unfortunately this will be less stable in the future because the new method takes the arguments directly, so we'll have to change them if we need to add arguments later. For this reason, the version submitted to the core uses a configurable function which can be invoked using call(), like this:
var bounds = d3.select('rect#bounds');
var padding = 10;
var text_node = d3.select('text#wrap-me');
var configured_wrap = d3.svg.textWrap().bounds(bounds).padding(padding);
text_node.call(configured_wrap);
In the latter scenario, you can also call bounds() and padding() with no arguments to retrieve the values previously applied.
BOUNDARIES
The plugin can wrap to boundaries which are provided either as a set of coordinates or as a rect selection. The version submitted to the core defaults to 960px by 500px (the same size as a bl.ocks demo) and you can provide the boundaries either as a simple integer for the width (in which case the height stays at the 500px default), or a set of coordinates, or any D3 selection you pass to it. (In theory, at least – hope you guys can help me test, find ways to break it, and submit bug reports.) Note that the core version calculates getBBox() for anything you pass to it, so it will wrap text to the bounding rectangle around an unusual shape rather than to the shape itself. It may be possible to add the latter in the future.
WRAPPING TECHNIQUE
The plugin wraps with foreignObjects when they are supported by the browser, and uses tspans for Internet Explorer and anything else that doesn't support foreignObjects. The version submitted to the core always wraps with tspans, which is more predictable. The main reason I've retained the older plugin instead of simply overwriting it with the new configurable function/tspan-only version is because the plugin still allows scrollable text through the use of the CSS overflow property, which would be very complicated to implement using tspans alone.
One remaining quirk is that padding() works by modifying the bounds object (and is actually just appended to it internally), so successive uses of padding() will compound instead of reset. If this is a major concern, I think the best fix would be to use padding() only to store the value, and then actually modify the boundaries as part of the main textWrap() method. This would mean that the padding() method won't actually contain the code that applies the padding, but the tradeoff is that the API becomes more predictable.
Any other ideas, bugs, or catastrophic failures?
A follow up on bunkat's comment, indeed first words that are longer than the provided width generate an empty tspan . An extra condition must be added to prevent this, from:
if (tspan.node().getComputedTextLength() > width) { ... }
to:
if (tspan.node().getComputedTextLength() > width && line.length > 1) {...}
This doesn't work in pack layout while zooming. I implemented above wrapping method in http://mbostock.github.io/d3/talk/20111116/pack-hierarchy.html. It worked fine on load. But once I clicked on any of the circle to zoom, the wrapping didn't get applied. The labels were shown in single line.
Any ideas guys?
In order to prevent cutting through non-breaking spaces, you should replace
words = text.text().split(/\s+/).reverse()
by
words = text.text().split(/[ \f\n\r\t\v]+/).reverse()
which left out non-breaking space \xA0, as well as the unicode characters \u00A0, \u2028 and \u2029.
You could also check if x, y and dy are null or undefined and set them to a default value otherwise you get some errors if the <text> has no y defined for instance.
So, is this planned to be integrated anytime soon as d3.svg.textWrap ?
By the way I upgraded the function to accept right/left and top/bottom padding, and to return the number of lines created for each text element :
/**
* Function allowing to 'wrap' the text from an SVG <text> element with <tspan>.
* Based on https://github.com/mbostock/d3/issues/1642
* @exemple svg.append("g")
* .attr("class", "x axis")
* .attr("transform", "translate(0," + height + ")")
* .call(xAxis)
* .selectAll(".tick text")
* .call(d3TextWrap, x.rangeBand());
*
* @param text d3 selection for one or more <text> object
* @param width number - global width in which the text will be word-wrapped.
* @param paddingRightLeft integer - Padding right and left between the wrapped text and the 'invisible bax' of 'width' width
* @param paddingTopBottom integer - Padding top and bottom between the wrapped text and the 'invisible bax' of 'width' width
* @returns Array[number] - Number of lines created by the function, stored in a Array in case multiple <text> element are passed to the function
*/
function d3TextWrap(text, width, paddingRightLeft, paddingTopBottom) {
paddingRightLeft = paddingRightLeft || 5; //Default padding (5px)
width = width - (paddingRightLeft * 2); //Take the padding into account
paddingTopBottom = (paddingTopBottom || 5) - 2; //Default padding (5px), remove 2 pixels because of the borders
var textAlign = text.attr('text-anchor') || 'left';
var arrLineCreatedCount = [];
text.each(function() {
var text = d3.select(this),
words = text.text().split(/[ \f\n\r\t\v]+/).reverse(), //Don't cut non-breaking space (\xA0), as well as the Unicode characters \u00A0 \u2028 \u2029)
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, //Ems
x = text.attr("x"),
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
createdLineCount = 1; //Total line created count
//Clean the data in case <text> does not define those values
if (isNaN(dy)) dy = 1; //Default padding (1em)
var dx;
if (textAlign === 'middle') { //Offset the text according to the anchor
dx = width / 2;
}
else { //'left' and 'right' //FIXME text-anchor 'right' does not have any effect on tspans, only 'left' and 'middle' -> bug ?
dx = 0;
}
x = ((null === x)?paddingRightLeft:x) + dx; //Default padding (5px)
y = (null === y)?paddingTopBottom:y; //Default padding (5px)
var tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
//noinspection JSHint
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width && line.length > 1) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
++createdLineCount;
}
}
arrLineCreatedCount.push(createdLineCount); //Store the line count in the array
});
return arrLineCreatedCount;
}
Here's an interesting post which points out that pinging the DOM to check the width of the tspan after each word is pretty inefficient. That is an argument in favor of retaining foreignObject as the preferred method and using tspans only as a fallback; letting HTML do it works in most browsers and doesn't have any overhead.
On the other hand, Mike has astutely pointed out that styling becomes a bit more unpredictable (or at least requires a redundant rule) if you can't be certain which tag the text content lives in.
Are you trying to say pinging the DOM creates unhandledExceptions when sending requests to physical address of the domain or IP?