aboutsummaryrefslogtreecommitdiff
path: root/editor.js
blob: 168c86c8338a7e114629d41737e998acdb1f966b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

/*

  Copyright (c) 2010 Samuel Lidén Borell <samuel@slbdata.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

// Misc. functions
function emptyIfNull(s) { return (s != null ? s : ""); }

Array.prototype.contains = function(elem) { return this.indexOf(elem) != -1; };


// Remove event handlers
// TODO

// Make marked sections editable
var editableElements = [];

function makeNodeEditable(node, marker) {
    node.contentEditable = true;
    if (marker != null) {
        node.setAttribute("wwweditor:marker", marker);
    }
    editableElements.push(node);
}

function isMarkerComment(node) {
    return (node.nodeType == Node.COMMENT_NODE &&
            node.nodeValue.search(/^\s*@\s*/) == 0);
}

function isEmptyTextNode(node) {
    return node.nodeType == Node.TEXT_NODE &&
           node.nodeValue.match(/^\s*$/);
}

function isTextNode(node) {
    return node.nodeType == Node.TEXT_NODE &&
           !node.nodeValue.match(/^\s*$/);
}

function makeMarkedEditable(obj) {
    var inBeginning = true;
    for (var node = obj.firstChild; node != null; node = node.nextSibling) {
        // Skip empty text nodes
        if (isEmptyTextNode(node))
            continue;
        
        // Look for special comments in the beginning
        if (inBeginning && isMarkerComment(node)) {
            var marker = node.nodeValue;
            makeNodeEditable(node.parentNode, marker);
        }
        inBeginning = false;
        
        // Process recursively
        makeMarkedEditable(node);
    }
}


function checkMarkers() {
    for (var i = 0; i < editableElements.length; i++) {
        var obj = editableElements[i];
        
        var hasMarker = false;
        for (var node = obj.firstChild; node != null; node = node.nextSibling) {
            // Skip empty text nodes
            if (isEmptyTextNode(node))
                continue;
            
            // Look for special comments in the beginning
            if (isMarkerComment(node)) {
                hasMarker = true;
            }
            
            break; // Reached a tag or a comment
        }
        
        if (!hasMarker) {
            // Marker is gone!
            var markerName = obj.getAttribute("wwweditor:marker");
            if (markerName != null) {
                var marker = document.createComment(markerName);
                obj.insertBefore(marker, obj.firstChild);
            }
        }
    }
}


if (editor.wholePageEditable) {
    makeNodeEditable(document.documentElement, null);
} else {
    makeMarkedEditable(document.documentElement);
}


function nodeIsEditable(node) {
    while (node != null && !editableElements.contains(node)) {
        node = node.parentNode;
    }
    return node != null;
}


// Function to get HTML properly
function getHTML() {
    var root = document.documentElement;
    if (editor.wholePageEditable) root.removeAttribute("contenteditable");
    
    // Put back the marker comments if they are missing
    checkMarkers();
    
    // FIXME non-standard class
    var html = new XMLSerializer().serializeToString(document);
    
    if (editor.wholePageEditable) root.contentEditable = true;
    return html;
}


var blockElems = ["blockquote", "div", "h1", "h2", "h3", "h4", "h5", "h6", "p"];
var specialElems = ["body", "form", "iframe", "td"];
var stopElems = blockElems.concat(specialElems);

function findContainingBlock(node) {
    if (node == null || !nodeIsEditable(node)) return null;
    
    // Find the containing block-level element
    while (node.parentNode != null && !editableElements.contains(node) &&
           (node.nodeType != Node.ELEMENT_NODE ||
            !stopElems.contains(node.nodeName.toLowerCase()))) {
        node = node.parentNode;
    }
    
    return node;
}

function nextInTree(node) {
    if (node.firstChild != null) {
        // Go deeper down in the tree
        return node.firstChild;
    } else if (node.nextSibling != null) {
        // Go to next node
        return node.nextSibling;
    } else if (node.parentNode != null) {
        // Go up to the node after the parent
        return node.parentNode.nextSibling;
    } else {
        // Error!
        return null;
    }
}

// Returns the selected blocks level elements, or the block where the
// cursor is if there's no selection.
function getSelectedBlocks() {
    var blocks = [];
    var selection = window.getSelection();
    for (var i = 0; i < selection.rangeCount; i++) {
        var range = selection.getRangeAt(i);
        
        // Starting point in the tree
        var node = range.startContainer;
        // we ignore the start/endOffsets because we're not interested
        // in specific text segments, but only the paragraph as a whole.
        
        for (;;) {
            // Ignore space and comments
            if (!isEmptyTextNode(node) && node.nodeType != Node.NODE_COMMENT) {
                var block = findContainingBlock(node);
                if (!blocks.contains(block)) {
                    blocks.push(block);
                }
            }
            
            // Check for end of selection
            if (node == range.endContainer) break;
            
            node = nextInTree(node);
        }
    }
    
    return blocks;
}


function getNextNonSpace(node) {
    do {
        node = node.nextSibling;
    } while (node != null &&
             node.nodeType == Node.TEXT_NODE &&
             node.nodeValue.match(/^\s*$/));
    
    return node;
}

function selectElements(elems) {
    // Clear selection
    var selection = document.getSelection();
    selection.removeAllRanges();
    
    // Place cursor in element if only one element is to be selected
    if (elems.length == 1) {
        var range = document.createRange();
        range.setStart(elems[0], 0);
        selection.addRange(range);
        return;
    }
    
    // More than one element is to be selected
    for (var i = 0; i < elems.length; i++) {
        var range = document.createRange();
        
        // Look ahead if this is a contiguous selection
        var j = i+1;
        for (; j < elems.length; j++) {
            var next = getNextNonSpace(elems[j-1]);
            if (getNextNonSpace(elems[j-1]) != elems[j]) break;
        }
        j--;
        
        if (j != i) {
            // Contiguous selection
            range.setStart(elems[i], 0);
            range.setEndAfter(elems[j]);
            i = j;
        } else {
            // Single block
            range.selectNode(elems[i]);
        }
        selection.addRange(range);
    }
}


// Cursor move detection
var lastNode = null;
var i = 0;
function cursorMoved(e) {
    var curNode = window.getSelection().anchorNode;
    
    // Only show options for editable nodes
    if (!nodeIsEditable(curNode)) curNode = null;
    
    // Find the containing element
    while (curNode != null && curNode.nodeType != Node.ELEMENT_NODE) {
        curNode = curNode.parentNode;
    }
    
    // Ignore repeated events
    if (curNode == lastNode) return;
    lastNode = curNode;
    
    if (curNode == null) {
        window.status = "";
        return;
    }
    
    // Find out element type of the block
    var block = findContainingBlock(curNode);
    
    // Build info message
    var msg =
        block.tagName.toLowerCase()+"\n"+
        emptyIfNull(curNode.getAttribute("class"))+"\n"+
        emptyIfNull(curNode.getAttribute("href"))+"\n"+
        emptyIfNull(curNode.getAttribute("title"));
    
    window.status = msg;
}

// Handle selection DOM events
document.documentElement.addEventListener("focus", cursorMoved, true);
document.documentElement.addEventListener("mousedown", cursorMoved, true);
document.documentElement.addEventListener("mouseup", cursorMoved, true);
document.documentElement.addEventListener("keypress", cursorMoved, true);
document.documentElement.addEventListener("keydown", cursorMoved, true);
document.documentElement.addEventListener("keyup", cursorMoved, true);

// Handle selection with non-standard events for faster response
document.documentElement.addEventListener("selectstart", cursorMoved, true);


// Sets the tag name of the current block-level element
function setElementType(elementName) {
    
    var blocks = getSelectedBlocks();
    var newBlocks = [];
    
    for (var i = 0; i < blocks.length; i++) {
        var block = blocks[i];
        
        // Don't replace elements with special meaning or the root element
        var wrap = !block.parentNode ||
                   specialElems.contains(block.nodeName.toLowerCase()) ||
                   editableElements.contains(block);
        
        // Create an element of the new type
        var newElem = document.createElement(elementName);
        
        if (!wrap) {
            // Copy attributes
            var oldAttrs = block.attributes;
            for (var j = 0; j < oldAttrs.length; j++) {
                newElem.setAttribute(oldAttrs[j].nodeName, oldAttrs[j].nodeValue);
            }
        }
        
        // Move child nodes
        while (block.firstChild != null) {
            newElem.appendChild(block.firstChild);
        }
        
        if (!wrap) {
            // Delete the old element
            block.parentNode.replaceChild(newElem, block);
        } else {
            // Add the new node to this node
            block.appendChild(newElem);
            newElem = block;
        }
        
        // The new block should be selected
        newBlocks.push(newElem);
    }
    
    // Select the new blocks
    selectElements(newBlocks);
}


// Automatic cleanup of the HTML
var handleModifications = true;
function subtreeModified(event) {
    if (!handleModifications) return;
    handleModifications = false;
    
    for (var node = window.getSelection().anchorNode;
         node != null; node = node.parentNode) {
        if (node.nodeType == Node.ELEMENT_NODE) cleanup(node);
        var sibling = node.nextSibling;
        if (sibling != null && sibling.nodeType == Node.ELEMENT_NODE) cleanup(sibling);
    }
    
    handleModifications = true;
}

function handleBackspace(event) {
    // Workaround for WebKit
    if (event.keyCode == 8 || event.charCode == 8) {
        subtreeModified(null);
    }
}

function cleanup(elem) {
    var parent = elem.parentNode;
    if (elem.nodeName == "SPAN" && elem.className == "Apple-style-span" && parent != null) {
        // Remove <span> element and replace it with it's contents
        while (elem.firstChild != null) {
            parent.insertBefore(elem.firstChild, elem);
        }
        parent.removeChild(elem);
    }
}

document.documentElement.addEventListener("DOMSubtreeModified", subtreeModified, true);
document.documentElement.addEventListener("keypress", handleBackspace, true);
document.documentElement.addEventListener("keyup", handleBackspace, true);

if (editableElements.length > 0) {
    // Focus the editor
    var ed = editableElements[0];
    ed.focus();
    
    // Instead of selecting everything (default behavior),
    // put the cursor at the beginning
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(ed, 0);
    range.setEnd(ed, 0);
    selection.addRange(range);
    
    delete range;
    delete selection;
    delete ed;
    
    // Update the GUI
    cursorMoved(null);
}