Repositioning after changing font size in UIWebView - javascript

I have an UIWebView with a huge book in it. I'm changing it's font size via javascript, using "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='150%';
Html-page gets larger, but the scroll position remains the same, causing text to shift out of a users sight.
The only idea that I have, is really weird and inefficient:
Wrap every word in <span> tags;
find the first onscreen <span> and remember it's id;
resize font;
scroll to span, that I've found in step 2.
Is there a better way to preserve the position, that user was reading?

Finally I've found an acceptable way:
Before changing font size I use a little javascript to find and store a position of a first letter on a page:
var range = document.caretRangeFromPoint(0,0); // get a range of a first onscreen letter
var textContainer = range.startContainer.parentNode;// get an element to which it belongs
var path = getElementXPath(textContainer); // get an XPath for that element (this function is not biult in, but you can find it in some other question)
path+='|'+range.startOffset; // stick XPath and index of the letter together
After that I change the font size, find needed element by XPath, insert invisible <a> right before my letter, scroll to that invisible <a>, don't forget to remove it.
Done. That is not a stragihtforward idea, but at least it works and does not consume to much of CPU or RAM, like the idea that I'have explained in original question.
Here is the place to get getElementXPath() function

Related

Retain cursor position in contenteditable

I am trying to create a richtext area using contenteditable. The parser for the highlighting returns a html string which I replace the content of the element with (perhaps ineffective, thats the way it has to be for now).
The problem with contenteditable is that the cursor position is not retained after something like this, which I can understand.
Is there a way to retain this position? I could make the parser return a element representing where the caret should be (given the cursors offset in the text) if this would aid in a solution.
Thanks in advance.
I could make the parser return a element representing where the caret should be
That would be enough. Suppose you parse the generated HTML and now you have a reference to the caret-should-be-here element in sentinel.
Use document.createRange() to create a DOM range. Let here be the new range. Call here.selectNode(sentinel) to have the range surround the element.
Call here.deleteContents() to remove the dummy element.
Call window.getSelection().removeAllRanges() to clear the current selection, which has gotten messed up by the HTML change.
Call window.getSelection().addRange(here) to put the cursor where the element used to be.
is sentinel my anchor element?
Yeah, I guess.
How do I fetch the cursor position in the string? ... I want the offset from the start of the string.
Let's start with the cursor position. The zeroth range of the window's selection should be the cursor's position. That is, the range's start and end are in the same place, at the cursor. However, these locations are expressed in a way that's geared toward DOM trees, rather than for string and offsets. They have a (start|end)Container and a (start|end)Offset. Check the DOM spec for what these mean.
You're interested in some sort of string offset. As I interpret it, this would be like, if you took a plaintext-only version of the subtree, what index corresponds to the range? There are multiple ways to define a plaintext version of a subtree. One is what the textContent property returns, where foo<br>bar gives "foobar". Some browsers define innerText, where foo<br>bar gives "foor\nbar". You've probably picked the one that you'll be using, but it's not stated in the question.
Anyway, here's an idea, but it might not be the right kind of offset for your app.
Set the window selection to a single range going from the beginning (wherever index 0 should be) to the cursor position.
Read window.getSelection().toString().length. In the browsers I've developed for, toString on a selection object gives results comparable to innerText.

Calculating xy-position of text selection

I am trying to create my own text selection with DOM-elements. Yes, I mean the blue background you see behind the text when you select it in this element. The idea is to halt the default behavior (the blue color) and use my own elements to do the job by finding the xy-position of the selection and then placing absolute positioned elements. I want to be able to do this with a regular div.
I'm thinking I need 3 elements. One for the top row (which may be incomplete), one for the middle chunk, one for the last (same as top). Here's an image that helps you understand:
I've been thinking of catching mouseup/down and then mousemove and then check window.getSelection() but so far I'm having trouble getting anywhere.
Using the CSS ::selection will not work because the element will not have focus.
I appreciate all help I can get! Thanks in advance.
Edit:
Stumbled upon https://code.google.com/p/rangy/ which might be of help? Anyone with experience with this plugin?
Edit2:
Cross-browser support is required.
You can use getClientRnge:
var element = document.getElementById('element')
element.onmouseup = function(){
var selection = document.getSelection(),
range = selection.getRangeAt(0),
clientRects = range.getClientRects()
console.log(clientRects)
}
http://jsfiddle.net/XjHtG/
This will return the left, right, top, bottom, width and height of all selections made.

Get exact caret position

How can I get the current caret position in tinyMCE? Referring to this question "Get cursor position or number of line on which the cursor is in TinyMCE" there is mentioned how to get the line number in tinyMCE, however I can't find no reference on how to get the actual caret position? I need this since I am using tinyMCE as a document for real-time collaboration therefore I need to know the position of the caret for clients writing in the same document so that I broadcast the position on some events (keystroke, click, etc..) and paint custom carets on the position for one client to know where the other client is writing or editing.
The only solution I found was to add a span after the content, select it and remove it as follows:
<span id="caret_pos_holder"></span>
Then once inserted, do this...
ed.selection.select(ed.dom.select('span#caret_pos_holder')[0]); //select the span
ed.dom.remove(ed.dom.select('span#caret_pos_holder')[0]); //remove the span
Is this the only way around it?
EDIT: Actually the above only sets the position of the cursor to the end of the content, something which I already took care of using bookmarks.
Is it possible that there is nothing that can get the cursor's position?
var sel = ed.selection.getSel();
will return the current selection as a selection object. You can then query sel.anchorNode and sel.anchorOffset to get current caret position.
Broadcasting this data to the other client(s) would be easier than trying to extract the position as a number, but if that's really necessary, you could climb the DOM from the position given above.

Automatic Textarea cursor movement

My question is almost similar to Automatic newline in textarea in textarea but my context is more complex. I have multiple textareas which have a 1 row attribute thus giving an impression of writing on air(just meaning empty area on the website with no borders since the textarea border i have set in css as >>> border: 0;).
I would like to use JQuery or Javascript to calculate when the text entered by the user if he/she has reached the end of the row of the textarea so as to automatically move to the next textarea below. One way to solve this would be to try and count the characters but different characters have different widths.
I'm thinking of inserting a hidden element at the edge of the textareas to act as a trigger for the nexttextarea.focus() event but i have no idea of how i can achieve this.
I have tried goofing around and thinking of different hacks but only one seems to be the solution... Try to store each character in an array and give them their default space taking value in px...like 'a'=>0.7px,'b'=>0.9px or something of the sort if their is a list somewhere (although it looks like it would take a lot of overhead in terms of memory as i would have to store both capital, small letters and many other characters.) Then do some calculations depending on the width of the browser if it has been re-sized or if not the full size to determine when the textarea row width becomes full at the browser width edge. (For the time being the textarea width is 100% and has no parent therefore fills the whole browser width).
If anybody has an idea of a complex or simple way i can accomplish this, help me. A big problem is that IE and Mozilla introduce scroll-bars if the browser window is re-sized, and scroll-bars is what i never want the user to see(remember impression of typing into thin air).
Forgive me for being so verbose..just wanted to be accurate and detailed.
This is harder than it looks. Try checking the scrollHeight and scrollWidth of the textarea; if they changed, the text overflowed. At that point, you can move text from the end of the current textarea to the beginning of the next textarea until the scroll height/width goes away.
Here's an example:
document.onkeyup = function(evt) {
var event = evt || window.event;
var target = event.target;
var nextArea = target.nextSibling; // assumes no whitespace between textareas.
var chars;
if (target.tagName == 'TEXTAREA' && (target.scrollLeft || target.scrollTop)) {
chars = 0;
while (target.scrollLeft || target.scrollTop) {
target.value = target.value.replace(/.$/, function(m0) {
nextArea.value = m0 + nextArea.value;
return '';
})
++chars;
target.selectionStart = target.value.length;
}
nextArea.focus();
nextArea.selectionStart = chars;
}
}​
http://jsfiddle.net/L73RG/3/
Note that a fully-working solution will need to bind this to more than just keyup events, because the user can paste with the context menu, for example. You may want to bind it to some mouse events or even run it occasionally on a timer if you find the box can be modified without triggering events (e.g. through a top level "edit" menu).
Check on every keypress if the content of your textarea is overflowing with the answer provided to this question: Determine if an HTML element's content overflows
You'll then have to remove the extra characters and put them into the next textarea. Probably one by one, using your check overflow function after each character is moved to see if the text area is still overflowing.
A possible solution is to measure the size of the text. Ext-JS does it by creating an offscreen absolutely positioned div, giving it style properties for the font you want to measure, and them measuring the div itself.
You can use Ext-JS's code as inspiration http://docs.sencha.com/ext-js/4-1/#!/api/Ext.util.TextMetrics

How to measure word/caret position in Google Docs?

For those who haven't worked with the Google Docs editor here's a short explanation of how it works:
Google Docs has no visible editable textarea or contentEditable elements.
Google Docs listens for keydown/press/up in a separate iFrame where they place the OS cursor for event listening.
When the iFrame catches an event Google handles it by performing the equivalent operations on the visible document.
The "caret" in Google Docs is a DIV that is styled and scripted to look and act like an OS cursor.
With that out of the way, here's my request:
I'm working on a plugin that interacts with the Google Doc and I need to be able to do two things:
Highlight words with an opaque overlay DIV.
Determine cursor position inside a word.
I've been exhausting a lot of ideas about just how to handle this, but so far I've only manage to get a buggy solution for the latter problem (I perform a backspace, determine where the text changed and undo the backspace).
I'm looking for all the best ideas you can come up with to solve these problems. They don't need to be cross browser, but they do need to be able to be turned into something robust that will also handle things such as font size changed mid line.
A little bit of extra info explaining what a Google Doc looks like in HTML:
<wrapper> // Simplified wrapper containing margins, pagination and similar
<div class="kix-paragraphrenderer"> // single DIV per page wrapping all content
// Multiple paragraphs separated by linebreak created by Enter key:
<div class="kix-paragraphrendeder">...</div>
<div class="kix-paragraphrendeder">...</div>
<div class="kix-paragraphrendeder">
// Multiple wrapper divs created by Google's word wrapping:
<div class="kix-lineview">...</div>
<div class="kix-lineview">...</div>
<div class="kix-lineview">
// Single inner wrapper, still full width of first wrapper paragraph:
<div class="kix-lineview-content">
// Single wrapper SPAN containing full text of the line, but not display:block
<span class="kix-lineview-text-block">
// Multiple spans, one per new font change such as normal/bold text,
// change in font size, indentation and similar:
<span>This is normal text</span>
<span style="font-size:40px; padding-left:4px;">This larger text.</span>
<span style="font-weight:bold; padding-left:10px;">This is bold text</span>
<span style="padding-left:4px;">More normal text</span>
</span>
</div>
</div>
</div>
</div>
</wrapper>
After more tinkering I came to the conclusion that it is extremely troublesome - if not impossible - to try and programmatically determine cursor position with regard to a letter inside a <span>, simply because the <span> is the smallest element that is measurable (correct me if I am wrong).
So how to solve the problem? Here's what I ended up doing:
I create an offscreen positioned <div>
I get the text of the current paragraph (<div class="kix-paragraphrenderer">) - I could get the entire text, but wanted to limit the computational load.
I extract each single character of the paragraph by looping through its children in the following way:
Loop through linveviews of the paragraph (<div class="kix-lineview">)
Get the lineview content (<div class="kix-lineview-content">)
Loop through text blocks of the lineview content (<span class="kix-lineview-text-block">)
Loop through <span>'s of the text block
Loop through innerText of the <span>
I append each character in my offscreen <div> with the currently applied style extracted from style.cssText of the current <span>
For each character appended I measure the width of the <div> and save this in an array. I now have a position of each single character.
I measure the position of the cursor relative to my widths and voila - I know where the cursor is positioned in the text.
This is obviously a bit simplied (I left out details about margins and paddings of the different elements), but it covers the idea behind how it's possible to get the cursor position.
It works quite well, but there are many pitfalls and a lot of measuring required. On top of that it's also required to post-parse the text if you want to use it for anything, since tabs, spaces and linebreaks aren't always included in innerText (depending on where these are in the text, Google may or may not make them through positioning of new elements).
I made something like Kix two years ago Google Docs. And for any HTML design and yes, for IE6 too :-) How? All we need is to compute letter absolute position. How? Replace textNode with inline element without layout, that's important, and then use Element.getClientRects I remember I also needed wrap just letter and compute its position via fast and reliable https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
The trick how to detect lines and wraps for home and end keys was based on some vertical heuristic letter position change. Something like if base line is different, than stop caret walking. It was pretty fast and with any markup and without any caching. Holy grail :)
The only not resolvable problem was justified text, because letters were distributed randomly and spaces between them was not computable.
That project is dead http://webeena.com now. Bad management killed it (and me almost too).

Categories