How can i determine the number of lines in a <textarea> based on line wrapping ?
( There are no new line characters to be detected. )
Basically, I need a way to programmatically determine the average width of characters in the text area, so I can determine where it wraps (and determine the number of lines in this <textarea>).
This is for an application using Appcelerator
SimpleCoder, a SO member, developed a plugin that tackles this same issue. You can find a description of it as well as a link to the plugin at the article below:
Textarea Line Count
Usage:
var result = $.countLines("#yourTextArea");
Related
I use a CodeMirror for displaying code on the HTML page. I have a version of the code which was saved in BD and when a user edits it in CodeMirror, I want to highlight unsaved changes like Visual Studio Code does:
I know that I can use method: codeMirror.removeLineClass(line, 'gutter', 'my_class'); to add a border that shows that changes were done at the specific line. My problem is in the calculation of the changed lines. I tried to use diff and diff2html packages and calculates changes like this:
var diff = Diff.createTwoFilesPatch('some name', 'some name', cm.state.savedText, cm.getValue());
var diffInfo = Diff2Html.getJsonFromDiff(diff, options);
This approach gives me a diff and I can get changed lines from it:
But this solution has a performance problem - it works slowly if a text contains more than 40 lines, and I will have large texts in CodeMirror.
I also tried to use history (the structure that codeMirror.getDoc().getHistory() returns) and highlight lines that are stored in 'changes' array, but it works only for new lines which were added. This approach doesn't work if the user removes the line.
What is the right way of calculation for such changes?
I was thinking of using the change event and tracking a specific change("+delete",
"+input"), then collect changed lines in special array. But this solution looks painful because in this case, I need to update this array manually if lines were added/deleted in the next iteration.
Is there a simpler way of how to do it?
After some research I've realized that even for big texts (~12 000 lines) approach with calculating the diff still works:
var diff = Diff.createTwoFilesPatch('some name', 'some name', cm.state.savedText, cm.getValue());
var diffInfo = Diff2Html.getJsonFromDiff(diff, options)
It takes ~30ms to calculate the diff for big text, and 5-6ms for small ones (~100lines). So for now it seems the most simple way for highlighting updated lines.
I am trying to truncate complex html by lines in order to be able to display a show more link after a certain number of lines has been reached. I found a great library trunk8.js which truncates by lines..but if falls short when it comes to truncating complex html. So for my particular case I overrode the truncate function so that I can handle complex the using another truncation function which gracefully leaves complex html tags intact. Truncation will work great with html but I am stuck on how to accurately calculate where to put show more more based on the number of lines
As seen in the image above I am trying to truncate to 7 lines but if the user input contains white spaces shown in yellow my calculations will be wrong because I am not accounting for the white spaces. My initial line of thought was that if I can calculate the length of the spaces in yellow for each line and convert it to characters, I can add this offset to the maximum number number of characters, then I can know where to put approximately the show more link. Is this the best approach to this problem and if not ,any suggestions to make my life easier.
This is a plunker of what I have tried so far and I am stuck in my truncateHTML() function in the trunk8.js where I am only now truncating based on the maximum length of the string.
Eureka!! After a couple of google searches and heavy debugging sprints, I stumbled upon a library truncate.js which I customized the truncatedNestednode() function for my needs.
element.appendChild(child);
/** Customized--here **/
var clonedNode = {};
if ($clipNode.length) {
if ($.inArray(element.tagName.toLowerCase(), BLOCK_TAGS) >= 0) {
// Certain elements like <li> should not be appended to.
$element.after($clipNode);
}
else
{ //Removed the commented line to put showmore next to the last line of text
$element.prev().append($clipNode);
//$element.append($clipNode);
}
}
In case someone faced this problem in the past, I have posted my revised plunker here
I'm using ExtendScript to work on JavaScript for Adobe Illustrator 2015. Is there any way I could get RGB values from a coordinate in the code below?
// declares a document
var doc = app.activeDocument;
// sets x and y coordinates to get color from
var xPosition = 70.0;
var yPosition = 64.0;
This is what needs work:
// gets rgb values
double redValue = doc.getRGBColor(xPosition, yPosition).red;
double greenValue = doc.getRGBColor(xPosition, yPosition).red;
double blueValue = doc.getRGBColor(xPosition, yPosition).red;
I've googled quite a bit and found this.
It doesn't work, though, either because it was posted in 2009, or because it was meant to be in photoshop.
A solution to the problem or translation of that post would be greatly appreciated.
[EDIT: My apologies for giving essentially an AppleScript answer to your ExtendScript question. I was just looking over AS questions and forgot I went to a different section. I can only hope that you are on a Mac. If not, I guess I'll just eat my downvotes and weep.]
There is a workaround. The advantage of it (and part of the workaround nature of it) is that it works in all apps. The downside is that it requires python (which should be on your Mac anyway - fairly easy to install if not), and two pieces of third party software (both free), "checkModifierKeys" and "cliclick". I've been using a script that appears in my script menu for years.
The python part is described here: http://thechrisgreen.blogspot.com/2013/04/python-script-for-getting-pixel-color.html
This script can be saved, made executable and invoked using the AS do shell script command.
and the rest of it, for selecting a point on the screen and for waiting for the control key to be pressed (that's how mine works) is pretty simple.
The basic checkModifierKeys part (which waits until the Control key is pressed) is:
set controlIsDown to false
repeat until (controlIsDown)
set initialCheck to ((do shell script "/usr/local/bin/checkModifierKeys control"))
if initialCheck = "1" then set controlIsDown to true
end repeat
The cliclick part (which gets the coordinates) is:
set xyGrabbed to do shell script "/usr/local/bin/cliclick p"
It may seem like a long way to go for it, but it works great. My version converts the rgb value to hex with this handler, which is useful for my purposes:
to makeHex(theNumber) --was anInteger
--Converts an unsigned integer to a two-digit hexadecimal value
set theResult to ""
repeat with theIndex from 1 to 0 by -1
set theBase to (16 ^ theIndex) as integer
if theNumber is greater than or equal to theBase then
set theMultiplier to ((theNumber - (theNumber mod theBase)) / theBase) as integer
set theResult to theResult & item theMultiplier of ¬
{1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"}
set theNumber to (theNumber - theBase * theMultiplier)
else
set theResult to (theResult & "0")
end if
end repeat
theResult
end makeHex
Yes, this solution doesn't work, because in vector editors such as Illustrator, color is applied to vector item (path) on the whole not to separate pixels. Even if you work with pixel image in illistrator there are no scripting functions to get pixel color.
I think it could be achieved via the rather monstrous solution:
Rasterize the artrboard.
Create Object Mosaic (where one tile ~> one pixel).
Figure out which one of the tiles lies underneath the given coordinates and pick its color.
I am using the cytoscape js library for displaying a hierarchy of images. I followed the example on http://jsbin.com/gist/aedff159b0df05ccfaa5?js,output and found that the breadthfirst layout is what I need.
However, I find the rendered result unsatisfactory due to too much unused space. The arrows are too long. Even the example (http://jsbin.com/gist/aedff159b0df05ccfaa5?js,output) has this issue. For this example, I tried the following
Increase the "height/width" in .selector('node') .css({
Muck around with the distanceX and distanceY (node spacing) variables in layout.breadthfirst.js (line 352).
I am unable to reduce the unused space or reduce the length of the arrows.
Ticket to follow: https://github.com/cytoscape/cytoscape.js/issues/737
If you want a new feature in future, please file a ticket.
For rushing Devs, try this layout option:
spacingFactor: 0
The manual says :
spacingFactor: 1.75, // positive spacing factor,
// larger => more space between nodes (N.B. n/a if causes overlap)
That's the result of the ticket https://github.com/cytoscape/cytoscape.js/issues/737 reported by maxkfranz.
I've got a basic Space Invaders type game going, and I can't get it to recognise when the shot from the player hits the alien. (I'm only checking Alien2 atm, the one second from the left). Since they're both moving, I've decided the only way to check for collisions is with either a range-based if statement (with 2 top coordinates and one left coordinate), or directly comparing the positions along the Y axis with Jquery.
I'm using the range-based solution at the moment, but so far it hasn't worked (not sure why).
My code so far:
if (key == "87"/*&& document.getElementById('BarrelOne').id=='BarrelOne'*/){
var Invader2 = document.getElementById('Alien2');
var Shot1 = document.getElementById('ShortShot');
Shot1.style.webkitAnimationPlayState="running";
setTimeout(function(){
Shot1.style.webkitAnimationPlayState="paused";
}, 1200);
if(document.elementFromPoint(625.5, 265.5) == Shot1){
Invader2.style.visibility="hidden";
}
};
Jsfiddle:
http://jsfiddle.net/ZJxgT/2/
I did something similar, and i found that it was much easier to achieve using gameQuery.
to test for collisions:
var collided = $("#div1").collision("#div2");
you can see full working example here
EDIT
If you're having trouble check out the API. For example, to find out how to use collisions check this part of the API.
the collision works in the following way:
This method returns the list of elements collisioning with the selected one but only those that match with the filter given as parameter. It takes two optional arguments (their order is not important). The filter is a string filtering element used to detect collision, it should contain all the elements the function should search collision into. For example if you look for collision with element of the class ‘foo’ that may be contained in a group you will use the filter ".group,.foo".
So, write something like this:
$("#ShortShot").collision("#Alien2").hide();
// will return the alien if it collides with ShortShot
or, to hide them both:
if (($("#ShortShot").collision("#Alien2")).length) {
$("#ShortShot").remove();
$("#Alien2").remove();
}
Instead of losing hours reinventing the wheel, I would suggest to switch (if still possible, depending on your time deadline) to a real 2D game engine for Javascript, with easy collision detection.
Check as well: 2D Engines for Javascript