I am working with a JS charting library that I did not write and I would like to add some functionality to insert HTML content in the element of an SVG graphic. The reason is that it contains a mix of RTL and LTR text:
<text class="tc-data-layout-2 tc-data-text tc-data-text-1 tc-price-chart-text-color tc-price-chart-font-size" transform="translate(13,0)" opacity="1" y="15.6875" x="5" text-anchor="start">صعود, 58 %</text>
Notice that the % symbol is at the wrong end of the string. To fix this, I'd like to add a tspan element with the LTR content:
<text class="tc-data-layout-2 tc-data-text tc-data-text-1 tc-price-chart-text-color tc-price-chart-font-size" transform="translate(13,0)" opacity="1" y="15.6875" x="5" text-anchor="start"><tspan direction="ltr" unicode-bidi="embed" xml:lang="en">% 58 </tspan>,صعود</text>
I have located the code that adds the text element:
var textElement = document.createElementNS("http://www.w3.org/2000/svg", "text");
svgElement.appendChild(textElement);
if (classStr) {
textElement.setAttribute("class", classStr);
}
textElement.textContent = text;
EDIT: One of my goals is to keep the percentage figure as one unit so that it's expressed as "99 %" or "% 99" in the markup itself.
Thanks!
Rob
The following was once explained to me by a translator, so it is not really language knowledge. Please, before publishing this, if you don't speak Persian yourself, check with a translator whether the rendering is correct.
The error occurs because in the course of the text run, the automatic identification of text direction fails. In byte order, the arabic letters have the order they are spoken in. Every program that knows RTL scripts and their Unicode encoding will render this correctly, showing the first letter in byte order to the right.
The bytes representing the comma and latin numbers are considered "direction-neutral", so if they show up next to arabic script, the RTL direction is used further on. In case you are wondering, in arabic script the lower-value digit is written to the right of the higher-level value, so for people only knowing latin script it looks as if it was written left-to-right, but that is just our ignorance. At the end of the numbers the program still thinks it is processing arabic script.
But it seems the percentage sign is interpreted as definitely LTR, and so the rendering falsely goes on on the right side.
SVG supports a inheritable
directionproperty to force the right text run direction in cases where the mix of latin and arabic letters makes it ambiguous. The following example sets the property on the<text>element. I copied your string into the tag the way you provided it, but separated the numeric part into a separate<tspan>element. Now the percentage sign renders on the left. The result remains the same whether you divide the content or not.