What code will force a reselection in TinyMCE 4.6? - tinymce-4

I'm having a problem with TinyMCE 4.6. I've implemented a custom button that bumps the font size of selected text:
ed.addButton('finc', {
image: '/tinymce/plugins/zackel/button_images/big.png',
title: '+ font size',
id : 'finc',
onclick:function(editor,url) {
console.log("************ In finc: ", ed);
var delta;
var currentFontSize = new Number($(ed.selection.getNode()).css('font-size').replace('px',''));
console.log("************ finc: currentFontSize = " + currentFontSize);
var node = ed.selection.getNode(); // <======= LINE 565
var nodeName = node.nodeName; // for example 'DIV ' or 'P'
console.log("************ finc: node is ", node, "nodeName = " + nodeName);
if (currentFontSize >= 24) {
delta = 2;
}
else {
delta = 1;
}
currentFontSize = currentFontSize + delta;
console.log("************ finc: New font size = " + currentFontSize);
ed.formatter.register('incfont', {
inline : 'span',
styles : {'font-size' : currentFontSize + 'px'}
});
ed.formatter.apply('incfont');
console.log("********** finc: posting to val box " + currentFontSize);
$("div#px_val button").text(currentFontSize + 'px'); // show value in value box
}
});
If the text is initially in a P the button works fine but puts the text into a span inside the P when it's done. If I then just hit the button again it fails because the node it brings back on line 565 is still the P, which still has the original font size. So if he initial font size is 16, it goes to 17 but then every bump after that stays at 17. If I deselect the text after bumping it and reselect it, line 565 gets the span and the bumps work every time.
How can I force a reselection from my code, so 565 finds the span the second time instead of the P, without me deselecting and reselecting the text?
Thanks

It seems to me that I understand you problem, but i believe that the text re-selection should not happen every time you apply the formatting - just only in the case TinyMCE is adding the new SPAN.
Here is my proposal:
var delta;
var currentFontSize = new Number($(ed.selection.getNode()).css('font-size').replace('px',''));
var node = ed.selection.getNode();
var nodeName = node.nodeName; // for example 'DIV ' or 'P'
if (currentFontSize >= 24) {
delta = 2;
}
else {
delta = 1;
}
currentFontSize = currentFontSize + delta;
ed.formatter.register('incfont', {
inline : 'span',
styles : {'font-size' : currentFontSize + 'px'}
});
var cnt = ed.selection.getContent({format : 'html'});
var lenBefore = $(cnt).length;
ed.formatter.apply('incfont');
var cnt = ed.selection.getContent({format : 'html'});
var lenAfter = $(cnt).length;
if(lenAfter > lenBefore) {
var newText = ed.selection.selectedRange.startContainer;
var rng = ed.dom.createRng();
rng.setStart(newText, 0);
rng.setEnd(newText, newText.nodeValue.length);
ed.selection.setRng(rng);
ed.nodeChanged();
}
Explanation:
when you apply the formatter for the first time, TinyMCE is adding the SPAN and you will find the new selection inside the ed.selection.selectedRange.startContainer node of type text. This is the same as the first child node of type text of the newly inserted SPAN. For subsequent actions, there shall be no need to do any re-selection.
Moreover, IMHO i feel somehow unusual to change the font size in mouse click, i would prefer a standard plugin button which works only with a already existing text selection (but this is up to you):
Of course, the main question of the re-selection is solved, and the plugin will work repeatedly with subsequent mouse clicks also by using a plugin button.
Just in case, as said before, you may also check at the very top if there is any content:
var hasContent = ed.selection.getContent({format : 'text'}.length > 0);
if(!hasContent) return;
So i believe the whole stuff should do the job but anyway, i feel there is still room for some improvements, for example if you need also to reduce the font size, and thus you will also need to delete the already existing - but no longer necessary - SPAN which contain the formatting.

Related

How to measure/convert CSS text margin/padding in the Photoshop?

How to get CSS text margin/padding from the Photoshop?
or
How to convert the distance from/to the text in Photoshop into CSS margin/padding?
Distances from text elements (paragraphs) in Photoshop do not correspond to margins/paddings in the CSS. Distances are measured, for example, using smart guides:
All because the line height is not used in the distances calculation. Therefore, the first recommendation I found is to use the formula:
margin_in_CSS = distance_in_PS - (line-height - font-size) / 2
or shorter:
CSS = PS - (line-height - font-size) / 2
This is the distance from some obvious border (line) to the text element. For the distance between two paragraphs we use, respectively:
CSS = PS - (line-height_1 - font-size_1) / 2 - (line-height_2 - font-size_2) / 2
As the font size increases, it becomes clear that this formula is not enough. The actual height of the line (obtained with the selection tool) in Photoshop is even less than the font size!
Although the photoshop still considers the height of the element to be approximately equal to the font size, which does not affect the distance to it :(. For example, on the Properties tab:
I calculated that the difference between the real height of the line and the font size is about 30% or 15% at the top and bottom of the text (I'm not saying this is 100% true!). And now I use the formula:
CSS = PS - (0.15 * font-size + (line-height - font-size) / 2)
Or between two paragraphs:
CSS = PS - (0.15 * font-size_1 + (line-height_1 - font-size_1) / 2)
- (0.15 * font-size_2 + (line-height_2 - font-size_2) / 2)
Similarly, we can not rely on the correct definition of the height of a paragraph in several lines by Photoshop. But here the situation is simpler, the real height of the paragraph in the CSS will be:
height = line-height * num_of_lines
The question is, is there a simpler way? О_о
Sorry for my English ^_^
UPDATE, shorter formulas:
text <> border
CSS = PS - (line-height - 0.7 * font-size) / 2
text <> text
CSS = PS - (line-height_1 - 0.7 * font-size_1) / 2
- (line-height_2 - 0.7 * font-size_2) / 2
UPDATE:
Now a script is being developed for the correct calculation of distances on the Adobe forum (link). At the moment, the script can calculate the distance from the bounding box of the text line with a standard (auto) line-height of 120%.
UPDATE:
It does not matter if you use a pointed text or a paragraph text, the result bounding box height is not equal to the text line-height (leading)
How to convert the distance from/to the text in Photoshop into CSS margin/padding?
The actual resulting glyph(s) (pink border in your image) of your text will have different height with the following contents:
"
[empty space] = no glyph at all
...
a
A
Qq
q
Margins and paddings should not be measured from the text itself, but from the boundaries of text line (or line-height in CSS).
In the above example:
65px is the actual height of text line (or line-height in CSS), (the distance from two text baselines when the text wraps) and what is used when calculating margin/padding. The end result being that no matter the contents of your text element, the distance from its baseline to the element following it should remain the same, based on line-height, (bottom) margin and (bottom) padding (and, of course, on the top margin and padding of next element).
To answer your question in a nutshell, PS does not apply a reduction to margins. It's just they are not calculated from the bounding box of the text glyphs (which might vary depending on contents), but from the bounding box of text line.
Another thing to consider when converting from .psd to HTML is that in HTML you have collapsing margins. In short, from two vertical adjacent margins only the largest one will be kept. If the other one is negative, it will be deducted from the positive one and if both are negative, the one with the largest value will be applied.
Finally, the script for measuring vertical distance is finished!
It can correctly calculate the vertical distance for CSS between layers, one of which or both are text layers.
Here's the link on Adobe Forums - A script for measuring the distance between two elements?
// version no CS6 or no effects
var old_units = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
try { app.activeDocument.suspendHistory("Get Text Bounds", "var bounds = get_selected_layers_bounds()") } catch(e) { alert(e); }
try { executeAction( charIDToTypeID( "undo" ), undefined, DialogModes.NO ); } catch(e) { alert(e); }
app.preferences.rulerUnits = old_units;
if (bounds)
{
if (bounds.length == 2)
{
var distance = 0;
if (bounds[0].bottom <= bounds[1].top) distance = bounds[1].top - bounds[0].bottom;
else if (bounds[1].bottom <= bounds[0].top) distance = bounds[0].top - bounds[1].bottom;
else alert("Intersecting layers")
var distance_in_css = distance - (bounds[0].leading - 1.2*bounds[0].size)/2 - (bounds[1].leading - 1.2*bounds[1].size)/2;
alert("distance = " + distance + "\ndistance_in_css = " + distance_in_css);
}
else
alert("More then 2 selected layers")
}
else
alert("There is no selected layers")
/////////////////////////////////////////////////////////////////////////////////////////////////
function get_selected_layers_bounds()
{
try {
var ref = new ActionReference();
ref.putProperty( charIDToTypeID( "Prpr" ), stringIDToTypeID( "targetLayers" ) );
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var desc = executeActionGet(ref);
if (!desc.hasKey( stringIDToTypeID("targetLayers") ) ) return null;
var n = 0;
try { activeDocument.backgroundLayer } catch (e) { n = 1; }
desc = desc.getList( stringIDToTypeID("targetLayers"));
var len = desc.count;
var selected_bounds = new Array();
for (var i = 0; i < len; i++)
{
try
{
var r = new ActionReference();
r.putIndex( charIDToTypeID( "Lyr " ), desc.getReference(i).getIndex() + n);
var ret = executeActionGet(r);
var size = 0;
var leading = 0;
if (ret.hasKey(stringIDToTypeID("textKey")))
{
var textStyleRangeList = ret.getObjectValue(stringIDToTypeID("textKey")).getList(charIDToTypeID("Txtt" ));
if (textStyleRangeList.count > 1) { alert("More than one textStyleRange in layer", "Oops!!"); }
var textStyle = textStyleRangeList.getObjectValue(0).getObjectValue(charIDToTypeID("TxtS" ));
var auto_leading = textStyle.getBoolean(stringIDToTypeID("autoLeading"));
size = textStyle.getUnitDoubleValue(stringIDToTypeID("size"));
leading = auto_leading?size*1.2:textStyle.getUnitDoubleValue(stringIDToTypeID("leading"));
var s = ret.getObjectValue(stringIDToTypeID("textKey")).getString(charIDToTypeID("Txt " ));
s = s.replace(/^./gm, String.fromCharCode(0x2588));
var d1 = new ActionDescriptor();
d1.putReference( charIDToTypeID( "null" ), r );
var d2 = new ActionDescriptor();
d2.putString( charIDToTypeID( "Txt " ), s);
d1.putObject( charIDToTypeID( "T " ), charIDToTypeID( "TxLr" ), d2 );
executeAction( charIDToTypeID( "setd" ), d1, DialogModes.NO );
ret = executeActionGet(r);
}
// var bounds = ret.getObjectValue(stringIDToTypeID("bounds")); // use this in CS6 or when you want to take into account the effects
var bounds = ret.getObjectValue(stringIDToTypeID("boundsNoEffects")); // in CS6 does not work
var obj = {
left : bounds.getUnitDoubleValue(stringIDToTypeID("left")),
top : bounds.getUnitDoubleValue(stringIDToTypeID("top")),
right : bounds.getUnitDoubleValue(stringIDToTypeID("right")),
bottom : bounds.getUnitDoubleValue(stringIDToTypeID("bottom")),
size : size,
leading: leading,
};
selected_bounds.push(obj);
}
catch (e) { alert(e); return null; }
}
return selected_bounds;
}
catch (e) { alert(e); return null; }
}
The script should be saved as a *.js or *.jsx file (for example, distance.js) in the Photoshop folder - C:\Program Files\Adobe\Adobe Photoshop CC 2017\Presets\Scripts
It will be available in the Photoshop menu - File > Scripts > Distance
it does not matter , psd is for showing how the website looks on completion you have to take in consideration the font size , for e.g. for paragraph text if the font size is 14 pt in psd and the grid is 1200px (bootstrap) than you have to convert the font in aspect ratio of browser ( default 16px now in bootstrap ) and calculate accordingly like 14pt in psd is equals to 14px + (14 * 0.16%)px in browser and everything else accordingly , similar for line height.
also if you want to set font size same as psd its up to you select 14px for html if our psd font size is 14pt for paragraph.

CSS hover "through" element without blocking click

note: I do not have access to the HTML or javascript code
I am using the excellent Chrome plugin, Web Override, to improve usability on a vendor site my company uses. I am only looking for CSS solutions (or possibly js/jq scripts I can sideload).
I'm trying to set table rows to highlight on hover, which is easy enough:
#task-list-main-table tr:hover {
background-color: lightyellow;
}
The problem is that there is a little button that appears on each row when you hover over it. This means if I hover over the button, the corresponding row is not highlighted.
Good:
Bad:
I know I could use pointer-events:none but then I can no longer click on the button, which I need to be able to do.
So, is there any way in CSS to "pass through" hover events without affecting click events?
This is a pretty convoluted method, but if you have the ability to inject javascript, this function will check if your mouse is overlapping whatever element you supply as the selector.
https://jsfiddle.net/tr_santi/aegybp6n/8/
//Change this value to desired element
var hoverElement = "td";
//Change this value to the class you'd like to add when hovering
var addClass = "hover";
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function overlapListener(element, x, y, classToAdd) {
var eTop = getOffset(element).top;
var eLeft = getOffset(element).left;
var eBottom = eTop + element.clientHeight;
var eRight = eLeft + element.clientWidth;
if (x <= eRight && x >= eLeft && y <= eBottom && y >= eTop) {
if (!hasClass(element, classToAdd)) {
element.className = classToAdd;
}
} else {
if (hasClass(element, classToAdd)) {
element.className = "";
}
}
}
var elementList = document.querySelectorAll(hoverElement);
document.onmousemove=function(e){
[].forEach.call(elementList, function(b) {
overlapListener(b, e.clientX, e.clientY, addClass)
});
};
I'm sure there are some JS gurus around here that could write you something a bit less obfuscated, however I found this to be a good practice exercise for myself. I chose to write it in vanilla JS as I'm unsure of what your limitations are, although JQuery could substantially reduce the amount of needed code.

tinyMCE move cursor out of tag on double space

SOLVED!
I am adding SPAN tags to the tinyMCE visual editor to display highlighted text.
while typing within a highlighted span, there may be instances where the cursor becomes trapped... with no way to type out side of the span.
I have created some javascript that fires on a "double space"
the following code...
1.) checks the current cursor position is within my highlighted SPAN
2.) checks the current cursor position is at the end of that SPAN (just before the closing /SPAN)
3.) moves the current cursor from the left of the closing /SPAN to the right of the closing /SPAN
help with any or all will be appreciated.
the correct code!
while typing, if you find your self at the end of a SPAN element, pressing the spacebar twice to break out of the current SPAN
var mycc = ''
ed.onKeyDown.add(function(ed, e){
evt = e || window.event;
var charCode = evt.keyCode || evt.which;
// if dbl space
if(mycc == charCode && charCode==32){
var curElm = ed.selection.getRng().startContainer;
var caretPos = ed.selection.getBookmark(curElm.textContent).rng.startOffset;
// if end of element
if(caretPos==curElm.textContent.length){
var mkr = '<span class="marker">!</span>'
// add marker for cursor positioning
ed.selection.setContent(mkr)
var newstr = ''
// split content at marker (plus ending span for my case)
var c = ed.getContent({format : 'raw'}).split(" "+mkr+"</span>")
if(!c[1]){
c = ed.getContent({format : 'raw'}).split(" "+mkr+"<br></span>")
}
// if the conent was split, adjust as needed
if(c[0]&&c[1]){
// add closing span back plus marker after
newstr = c[0]+'</span>'+mkr+c[1]
// update content
ed.setContent(newstr)
}
// find the marker
var marker = jQuery(ed.getBody()).find('.marker');
// set selection
ed.selection.select(marker.get(0));
// remove marker
marker.remove();
}
}
mycc = charCode
})
ed.onMouseDown.add(function(ed, e){
mycc = ''
})
above still works, but i went with the code below. this code breaks out of the end position of a span when pressing the right arow instead of dbl space
enjoy
var mycc = ''
ed.onKeyDown.add(function(ed, e){
evt = e || window.event;
var charCode = evt.keyCode || evt.which;
// if dbl space
//if(mycc == charCode && charCode==32){
if(charCode==39){
var curElm = ed.selection.getRng().startContainer;
var caretPos = ed.selection.getBookmark(curElm.textContent).rng.startOffset;
// if end of element
if(caretPos==curElm.textContent.length){
var mkr = '<span class="marker">!</span>'
ed.selection.setContent(mkr)
var newstr = ''
var c = ed.getContent({format : 'raw'}).split(mkr+"</span>")
if(!c[1]){
c = ed.getContent({format : 'raw'}).split(mkr+"<br></span>")
}
if(c[0]&&c[1]){
newstr = c[0].replace(/^\s\s*/, '').replace(/\s\s*$/, '')+'</span> '+mkr+c[1].replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/^[\s( ]+/g,'')
ed.setContent(newstr)
e.preventDefault()
}
var marker = jQuery(ed.getBody()).find('.marker');
ed.selection.select(marker.get(0));
marker.remove();
}
}
mycc = charCode
})
1.) to see if the current cursor position is within my highlighted SPAN
This is possible
var ed = tinymce.get('your_editor_id')
var node = ed.getSelection.getNode(); // in case of complex nestings you will need to loop along the parentNode till you find a span-node
if ($(node).hasClass('highlight')) {...whatever you like..}
I updated my question with the correct code.

adding tooltip to datagrid headers in dojo

I have a dojo datagrid which is poulated dynamically. I want to add tooltip to table headers of this datagrid. How can i do that?My datagrid simply has the structure of table and table headers. the fields get populated dynamically.
Thanks,
Sreenivas
Easiest Way
The easiest way, (Without overriding the template) would be to add a domNode to your layout header definition. So for example, when you are setting the "name" for your column in the layout, you can have something like ...
var layout = [
{
cells: [
{
name:"<i id="sometooltip" class='icon-large icon-edit'></i> Col",
field: "_item",
formatter: lang.hitch( this, this.formatter )
}
]
}];
What you then want to do is in your formatter, you want to check to see if "sometooltip" has be initialized as a tooltip, and do your connect.. You can use any tooltip.. not just dijit.Tooltip.
There are a few words of caution though. Because the formatter will run every time there is a redraw on your grid, you might want to think up better ways of creating your tooltip. For instance, you might want to add it to onGridRowHeaderHover, or you might want to just use CSS3 and use [title] attribute to create a CSS3 header.
Also. You can't just create the tooltip once, because the header is constantly rebuilt every redraw/change of data.
The Correct Way
The correct way would be to override the Grid template for the header, and include your tooltip in there. You would then extend the header equivalent of onStyleRow (which I can't remember), but basically the method that places the headers, and create your tooltip then.
I would definitely use the second option by overriding the template. Because otherwise you will find the grid glitchy.
For a pre-AMD Dojo version this is the monkey patch that we included in our globally scoped javascript resource. My other answer was after we switched to an AMD Dojo version.
// HeaderBuilder.generateHtml
// If showTooltips is true, the header contents will be used as the tooltip text.
var old_HeaderBuilder_generateHtml = dojox.grid._HeaderBuilder.prototype.generateHtml;
dojox.grid._HeaderBuilder.prototype.generateHtml = function(inGetValue, inValue){
var html = this.getTableArray(), cells = this.view.structure.cells;
dojox.grid.util.fire(this.view, "onBeforeRow", [-1, cells]);
for(var j=0, row; (row=cells[j]); j++){
if(row.hidden){
continue;
}
html.push(!row.invisible ? '<tr>' : '<tr class="dojoxGridInvisible">');
for(var i=0, cell, markup; (cell=row[i]); i++){
cell.customClasses = [];
cell.customStyles = [];
if(this.view.simpleStructure){
if(cell.headerClasses){
if(cell.headerClasses.indexOf('dojoDndItem') == -1){
cell.headerClasses += ' dojoDndItem';
}
}else{
cell.headerClasses = 'dojoDndItem';
}
if(cell.attrs){
if(cell.attrs.indexOf("dndType='gridColumn_") == -1){
cell.attrs += " dndType='gridColumn_" + this.grid.id + "'";
}
}else{
cell.attrs = "dndType='gridColumn_" + this.grid.id + "'";
}
}
markup = this.generateCellMarkup(cell, cell.headerStyles, cell.headerClasses, true);
// content
markup[5] = (inValue != undefined ? inValue : inGetValue(cell));
// set the tooltip for this header to the same name as the header itself
try {
markup[5] = markup[5].replace("class","title='"+cell.name+"' class");
} catch(e) {
console.debug(e);
}
// styles
markup[3] = cell.customStyles.join(';');
// classes
markup[1] = cell.customClasses.join(' '); //(cell.customClasses ? ' ' + cell.customClasses : '');
html.push(markup.join(''));
}
html.push('</tr>');
}
html.push('</table>');
return html.join('');
};
I had a similar requirement. I wanted each DataGrid column header to use the name given to the column as the tooltip since our DataGrids weren't always showing the full column name due to the columns' widths sometimes being squeezed. I added a monkey patch (below) that is done with an AMD Dojo version:
require(
[
"dojo/dom",
"dojox/grid/DataGrid",
"dijit/_Widget",
"dijit/form/FilteringSelect",
"dijit/form/MultiSelect",
"dijit/layout/ContentPane",
"dijit/layout/TabContainer",
"dojox/grid/_Grid",
"dijit/MenuItem",
"dijit/MenuSeparator",
"dojox/grid/_Builder",
"dojox/grid/cells/_base",
"dojox/grid/util",
"dojo/parser",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/ready",
"dojo/query",
"dijit/registry",
],
function(dom, dojox_grid_DataGrid, dijit__Widget, dijit_form_FilteringSelect,
dijit_form_MultiSelect, dijit_layout_ContentPane, dijit_layout_TabContainer,
dojox_grid__Grid, MenuItem, MenuSeparator, dojox_grid__Builder,
dojox_grid_cells__Base, dojox_grid_util,
parser, array, dojoLang, ready, dojoQuery, registry) {
var old_HeaderBuilder_generateHtml = dojox_grid__Builder._HeaderBuilder.prototype.generateHtml;
dojox_grid__Builder._HeaderBuilder.prototype.generateHtml = function(inGetValue, inValue){
var html = this.getTableArray(), cells = this.view.structure.cells;
dojox_grid_util.fire(this.view, "onBeforeRow", [-1, cells]);
for(var j=0, row; (row=cells[j]); j++){
if(row.hidden){
continue;
}
html.push(!row.invisible ? '<tr>' : '<tr class="dojoxGridInvisible">');
for(var i=0, cell, markup; (cell=row[i]); i++){
cell.customClasses = [];
cell.customStyles = [];
if(this.view.simpleStructure){
if(cell.headerClasses){
if(cell.headerClasses.indexOf('dojoDndItem') == -1){
cell.headerClasses += ' dojoDndItem';
}
}else{
cell.headerClasses = 'dojoDndItem';
}
if(cell.attrs){
if(cell.attrs.indexOf("dndType='gridColumn_") == -1){
cell.attrs += " dndType='gridColumn_" + this.grid.id + "'";
}
}else{
cell.attrs = "dndType='gridColumn_" + this.grid.id + "'";
}
}
markup = this.generateCellMarkup(cell, cell.headerStyles, cell.headerClasses, true);
// content
markup[5] = (inValue != undefined ? inValue : inGetValue(cell));
// set the tooltip for this header to the same name as the header itself
markup[5] = markup[5].replace("class","title='"+cell.name+"' class");
// styles
markup[3] = cell.customStyles.join(';');
// classes
markup[1] = cell.customClasses.join(' '); //(cell.customClasses ? ' ' + cell.customClasses : '');
html.push(markup.join(''));
}
html.push('</tr>');
}
html.push('</table>');
return html.join('');
};
}
);
Note that if there's any chance that any markup may be added to the cell.name then you'll need to add a condition that will somehow extract just the text from it to be the tooltip, or somehow generate a tooltip that won't throw a rendering error, or avoid setting a tooltip altogether for that column.

Styling UITextField

I've been playing around with different methods of determining at runtime the width of a "label" so that I can resize the "label" because I don't want it to truncate. I've finally found an easy solution through UITextField which allows me to set the .autoSize which is great! However, now I'm trying to "style" (simply adjust font and font size) of the UITextField but it seems that I have to do it manually with '.htmlText' (which I'll gladly accept if that is the ONLY way).
I'm using the .text to set the value of the label.
My test case involves a HBox (I'm actually using a Grid but they should be the same and I've done testing on both):
I style the HBox and the style carries through to the UITextField. I don't believe this will work for me because I have other components inside that I need to style differently.
I've tried: UITextFormat and TextFormat (I see that the .htmlText being updated accordingly but the output doesn't update. Then I noticed that whenever I called hbox.addChild(myUITextField) it would override the .htmlText
I've tried setting the style with myUITextField.setStyle("fontSize", 20) before and/or after the call to addChild neither of which made an impact on the display as per what I noted above.
Changes are being made but they seem to be overrided when I add it to the display.
So what do I need to do in order to style the UITextField aside from manually setting it along with my contents in .htmlText? Solutions not using UITextField is fine as long as there is some easy way of not truncating the text.
EDIT: I want to just do textField.setStyle('fontSize', 20) and expect that every time I change the text, I wouldn't need to use HTML to go with it (so I can just do textField.text = 'something else' and expect that it will still have a font size of 20). This is what I meant by not using .htmlText (sorry if I wasn't clear before).
2nd EDIT: I guess I should present the whole issue and maybe that'll clarify what I did wrong or couldn't achieve.
My intent is to have a Grid and add text into it. I do not want it to wrap or scroll so I add it to the next row in the Grid when the current row's children total width exceeds some number. In order to add it to the next row, I need to be able to calculate the width of the text. I would like to be able to style that text individually based on cases and there might be other components (like a TextInput). Essentially what I'm trying to accomplish is "Fill in the Blank".
I've included code to show what I'm currently doing and it works somewhat. It might be un-related to the original issue of styling but I can't figure out how to adjust the distance between each UITextField but aside from that this fits what I would like to accomplish. Relevant to the question is: I would like to change the way I style each UITextField (currently setting .htmlText) into something a bit straightforward though like I previously mentioned I'll gladly accept using .htmlText if that's the only solution.
So I have a Grid with x Rows in it and in each row, I have exactly one GridItem. Based on the input, I add UITextField and TextInput into the GridItem going on to the next GridItem when necessary. If you have a better way of doing so then that would be better but I guess what I really want is to find a different way of styling.
Also another problem, I'm not sure of the exact way to add a TextField into the display. I tried:
var t : TextField = new TextField();
t.text = "I'm a TextField";
hBox.addChild(t); // doesn't work
//this.addChild(t); // doesn't work either
But I get the following error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.text::TextField#172c8f9 to mx.core.IUIComponent.
Here's what I have that's working.
private function styleQuestionString(str : String) : String {
return '<FONT leading="1" face="verdana" size="20">' + str + '</FONT>';
}
private function loadQuestion(str : String) : void {
/* Split the string */
var tmp : Array = str.split("_");
/* Track the current width of the GridItem */
var curWidth : int = 0;
/* Display components that we will add */
var txtField : UITextField = null;
var txtInput : TextInput = null;
/* Track the current GridItem */
var curGridItem : GridItem = null;
/* Track the GridItem we can use */
var gridItemAC : ArrayCollection = new ArrayCollection();
var i : int = 0;
/* Grab the first GridItem from each GridRow of Grid */
var tmpChildArray : Array = questionGrid.getChildren();
for (i = 0; i < tmpChildArray.length; i++) {
gridItemAC.addItem((tmpChildArray[i] as GridRow).getChildAt(0));
}
curGridItem = gridItemAC[0];
gridItemAC.removeItemAt(0);
/* Used to set the tab index of the TextInput */
var txtInputCounter : int = 1;
var txtFieldFormat : UITextFormat = new UITextFormat(this.systemManager);
txtFieldFormat.leading = "1";
//var txtFieldFormat : TextFormat = new TextFormat();
//txtFieldFormat.size = 20;
/* Proper Order
txtField = new UITextField();
txtField.text = tmp[curItem];
txtField.autoSize = TextFieldAutoSize.LEFT;
txtField.setTextFormat(txtFieldFormat);
*/
var txtLineMetrics : TextLineMetrics = null;
var tmpArray : Array = null;
curGridItem.setStyle("leading", "1");
var displayObj : DisplayObject = null;
for (var curItem : int= 0; curItem < tmp.length; curItem++) {
/* Using UITextField because it can be auto-sized! */
/** CORRECT BLOCK (ver 1)
txtField = new UITextField();
txtField.text = tmp[curItem];
txtField.autoSize = TextFieldAutoSize.LEFT;
txtField.setTextFormat(txtFieldFormat);
***/
tmpArray = (tmp[curItem] as String).split(" ");
for (i = 0; i < tmpArray.length; i++) {
if (tmpArray[i] as String != "") {
txtField = new UITextField();
txtField.htmlText = styleQuestionString(tmpArray[i] as String);
//txtField.setTextFormat(txtFieldFormat); // No impact on output
txtLineMetrics = curGridItem.measureHTMLText(txtField.htmlText);
curWidth += txtLineMetrics.width + 2;
if (curWidth >= 670) {
curGridItem = gridItemAC[0];
curGridItem.setStyle("leading", "1");
if (gridItemAC.length != 1) {
gridItemAC.removeItemAt(0);
}
// TODO Configure the proper gap distance
curWidth = txtLineMetrics.width + 2;
}
displayObj = curGridItem.addChild(txtField);
}
}
//txtField.setColor(0xFF0000); // WORKS
if (curItem != tmp.length - 1) {
txtInput = new TextInput();
txtInput.tabIndex = txtInputCounter;
txtInput.setStyle("fontSize", 12);
txtInputCounter++;
txtInput.setStyle("textAlign", "center");
txtInput.width = TEXT_INPUT_WIDTH;
curWidth += TEXT_INPUT_WIDTH;
if (curWidth >= 670) {
curGridItem = gridItemAC[0];
if (gridItemAC.length != 1) {
gridItemAC.removeItemAt(0);
}
// TODO Decide if we need to add a buffer
curWidth = TEXT_INPUT_WIDTH + 2;
}
curGridItem.addChild(txtInput);
txtInputAC.addItem(txtInput);
/* Adds event listener so that we can perform dragging into the TextInput */
txtInput.addEventListener(DragEvent.DRAG_ENTER, dragEnterHandler);
txtInput.addEventListener(DragEvent.DRAG_DROP, dragDropHandler);
txtInput.addEventListener(DragEvent.DRAG_EXIT, dragExitHandler);
}
/* Add event so that this label can be dragged */
//txtField.addEventListener(MouseEvent.MOUSE_MOVE, dragThisLabel(event, txtField.text));
}
}
After about 8 hours of searching for a solution to what would seem to be such a simple issue I FINALLY stumbled on your posts here... Thankyou!!!
I have been stumbling around trying to get TextField to work and had no Joy, Label was fine, but limited formatting, and I need to be able to use embedded fonts and rotate. After reading the above this finally worked for me:
var myFormat:TextFormat = new TextFormat();
myFormat.align = "center";
myFormat.font = "myFont";
myFormat.size = 14;
myFormat.color = 0xFFFFFF;
var newTxt:UITextField = new UITextField();
newTxt.text = "HELLO";
addChild(newTxt);
newTxt.validateNow();
newTxt.setTextFormat(myFormat);
The order of addChild before the final 2 steps was critical! (myFont is an embedded font I am using).
One again... a thousand thankyou's...
John
EDIT BASED ON THE ASKERS FEEDBACK:
I didn't realize you wanted to just apply one style to the whole textfield, I thought you wanted to style individual parts. This is even simpler for you, won't give you any trouble at all :)
var textFormat: TextFormat = new TextFormat("Arial", 12, 0xFF0000);
myText.setTextFormat(textFormat);
Be aware that this sets the style to the text that is in the TextField, not necessarily future text you put in. So have your text in the field before you call setTextFormat, and set it again every time you change it just to be sure it stays.
It's probably best if you use a normal TextField as opposed to the component. If you still want the component you may need to call textArea.validateNow() to get it to update with the new style (not 100% sure on that one though) Adobe components are notoriously bad, and should be avoided. :(
To see all available options on the TextFormat object see here
END EDIT ---------
This is easy enough to just do with CSS in a normal old TextField.
var myCSS: String = "Have some CSS here, probably from a loaded file";
var myHTML: String = "Have your HTML text here, and have it use the CSS styles";
// assuming your textfield's name is myText
var styleSheet: StyleSheet = new StyleSheet();
styleSheet.parseCSS(myCSS);
myText.autoSize = TextFieldAutoSize.LEFT;
myText.styleSheet = styleSheet;
myText.htmlText = myHTML;
Supported HTML tags can be found here
Supported CSS can be found here
The reason you have a problem adding Textfield to containers is that it doesn't implement the IUIComponent interface. You need to use UITextField if you want to add it. However, that's presenting me with my own styling issues that brought me to this question.
A few things I know:
TextField is styled using the TextFormat definition, and applying it to the textfield. As Bryan said, order matters.
setStyle does nothing on IUITextField, and the TextFormat method doesn't seem to work the same as in normal TextFields. (Edit #2: Ahah. You need to override the "validateNow" function on UITextFields to use the setTextFormat function)
To autosize a TextArea, you need to do something like this (inheriting from TextArea):
import mx.core.mx_internal;
use namespace mx_internal;
...
super.mx_internal::getTextField().autoSize = TextFieldAutoSize.LEFT;
this.height = super.mx_internal::getTextField().height;
Found this code on, I think, on StackOverflow a while back. Apologies to the original author. But the idea is that you need to access the "mx_internal" raw textfield.
Text and TextArea have wrapping options. (Label does not). So if you set the explicit width of a Text object, you might be able to size using the measuredHeight option and avoid truncation.
(edit: That was #4, but stackoverflow parsed it into a 1...)

Resources