TableGrid.js 21.5 KB
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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
/**
 * TableGrid.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class creates a grid out of a table element. This
 * makes it a whole lot easier to handle complex tables with
 * col/row spans.
 *
 * @class tinymce.tableplugin.TableGrid
 * @private
 */
define("tinymce/tableplugin/TableGrid", [
	"tinymce/util/Tools",
	"tinymce/Env",
	"tinymce/tableplugin/Utils",
	"tinymce/tableplugin/SplitCols"
], function(Tools, Env, Utils, SplitCols) {
	var each = Tools.each, getSpanVal = Utils.getSpanVal, setSpanVal = Utils.setSpanVal;

	return function(editor, table, selectedCell) {
		var grid, gridWidth, startPos, endPos, selection = editor.selection, dom = selection.dom;

		function removeCellSelection() {
			editor.$('td[data-mce-selected],th[data-mce-selected]').removeAttr('data-mce-selected');
		}

		function isEditorBody(node) {
			return node === editor.getBody();
		}

		function getChildrenByName(node, names) {
			if (!node) {
				return [];
			}

			names = Tools.map(names.split(','), function(name) {
				return name.toLowerCase();
			});

			return Tools.grep(node.childNodes, function(node) {
				return Tools.inArray(names, node.nodeName.toLowerCase()) !== -1;
			});
		}

		function buildGrid() {
			var startY = 0;

			grid = [];
			gridWidth = 0;

			each(['thead', 'tbody', 'tfoot'], function(part) {
				var partElm = getChildrenByName(table, part)[0];
				var rows = getChildrenByName(partElm, 'tr');

				each(rows, function(tr, y) {
					y += startY;

					each(getChildrenByName(tr, 'td,th'), function(td, x) {
						var x2, y2, rowspan, colspan;

						// Skip over existing cells produced by rowspan
						if (grid[y]) {
							while (grid[y][x]) {
								x++;
							}
						}

						// Get col/rowspan from cell
						rowspan = getSpanVal(td, 'rowspan');
						colspan = getSpanVal(td, 'colspan');

						// Fill out rowspan/colspan right and down
						for (y2 = y; y2 < y + rowspan; y2++) {
							if (!grid[y2]) {
								grid[y2] = [];
							}

							for (x2 = x; x2 < x + colspan; x2++) {
								grid[y2][x2] = {
									part: part,
									real: y2 == y && x2 == x,
									elm: td,
									rowspan: rowspan,
									colspan: colspan
								};
							}
						}

						gridWidth = Math.max(gridWidth, x + 1);
					});
				});

				startY += rows.length;
			});
		}

		function fireNewRow(node) {
			editor.fire('newrow', {
				node: node
			});

			return node;
		}

		function fireNewCell(node) {
			editor.fire('newcell', {
				node: node
			});

			return node;
		}

		function cloneNode(node, children) {
			node = node.cloneNode(children);
			node.removeAttribute('id');

			return node;
		}

		function getCell(x, y) {
			var row;

			row = grid[y];
			if (row) {
				return row[x];
			}
		}

		function getRow(grid, y) {
			return grid[y] ? grid[y] : null;
		}

		function getColumn(grid, x) {
			var out = [];

			for (var y = 0; y < grid.length; y++) {
				out.push(getCell(x, y));
			}

			return out;
		}

		function isCellSelected(cell) {
			return cell && (!!dom.getAttrib(cell.elm, 'data-mce-selected') || cell == selectedCell);
		}

		function getSelectedRows() {
			var rows = [];

			each(table.rows, function(row) {
				each(row.cells, function(cell) {
					if (dom.getAttrib(cell, 'data-mce-selected') || (selectedCell && cell == selectedCell.elm)) {
						rows.push(row);
						return false;
					}
				});
			});

			return rows;
		}

		function deleteTable() {
			var rng = dom.createRng();

			if (isEditorBody(table)) {
				return;
			}

			rng.setStartAfter(table);
			rng.setEndAfter(table);

			selection.setRng(rng);

			dom.remove(table);
		}

		function cloneCell(cell) {
			var formatNode, cloneFormats = {};

			if (editor.settings.table_clone_elements !== false) {
				cloneFormats = Tools.makeMap(
					(editor.settings.table_clone_elements || 'strong em b i span font h1 h2 h3 h4 h5 h6 p div').toUpperCase(),
					/[ ,]/
				);
			}

			// Clone formats
			Tools.walk(cell, function(node) {
				var curNode;

				if (node.nodeType == 3) {
					each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
						if (!cloneFormats[node.nodeName]) {
							return;
						}

						node = cloneNode(node, false);

						if (!formatNode) {
							formatNode = curNode = node;
						} else if (curNode) {
							curNode.appendChild(node);
						}

						curNode = node;
					});

					// Add something to the inner node
					if (curNode) {
						curNode.innerHTML = Env.ie && Env.ie < 10 ? '&nbsp;' : '<br data-mce-bogus="1" />';
					}

					return false;
				}
			}, 'childNodes');

			cell = cloneNode(cell, false);
			fireNewCell(cell);

			setSpanVal(cell, 'rowSpan', 1);
			setSpanVal(cell, 'colSpan', 1);

			if (formatNode) {
				cell.appendChild(formatNode);
			} else {
				Utils.paddCell(cell);
			}

			return cell;
		}

		function cleanup() {
			var rng = dom.createRng(), row;

			// Empty rows
			each(dom.select('tr', table), function(tr) {
				if (tr.cells.length === 0) {
					dom.remove(tr);
				}
			});

			// Empty table
			if (dom.select('tr', table).length === 0) {
				rng.setStartBefore(table);
				rng.setEndBefore(table);
				selection.setRng(rng);
				dom.remove(table);
				return;
			}

			// Empty header/body/footer
			each(dom.select('thead,tbody,tfoot', table), function(part) {
				if (part.rows.length === 0) {
					dom.remove(part);
				}
			});

			// Restore selection to start position if it still exists
			buildGrid();

			// If we have a valid startPos object
			if (startPos) {
				// Restore the selection to the closest table position
				row = grid[Math.min(grid.length - 1, startPos.y)];
				if (row) {
					selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
					selection.collapse(true);
				}
			}
		}

		function fillLeftDown(x, y, rows, cols) {
			var tr, x2, r, c, cell;

			tr = grid[y][x].elm.parentNode;
			for (r = 1; r <= rows; r++) {
				tr = dom.getNext(tr, 'tr');

				if (tr) {
					// Loop left to find real cell
					for (x2 = x; x2 >= 0; x2--) {
						cell = grid[y + r][x2].elm;

						if (cell.parentNode == tr) {
							// Append clones after
							for (c = 1; c <= cols; c++) {
								dom.insertAfter(cloneCell(cell), cell);
							}

							break;
						}
					}

					if (x2 == -1) {
						// Insert nodes before first cell
						for (c = 1; c <= cols; c++) {
							tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
						}
					}
				}
			}
		}

		function split() {
			each(grid, function(row, y) {
				each(row, function(cell, x) {
					var colSpan, rowSpan, i;

					if (isCellSelected(cell)) {
						cell = cell.elm;
						colSpan = getSpanVal(cell, 'colspan');
						rowSpan = getSpanVal(cell, 'rowspan');

						if (colSpan > 1 || rowSpan > 1) {
							setSpanVal(cell, 'rowSpan', 1);
							setSpanVal(cell, 'colSpan', 1);

							// Insert cells right
							for (i = 0; i < colSpan - 1; i++) {
								dom.insertAfter(cloneCell(cell), cell);
							}

							fillLeftDown(x, y, rowSpan - 1, colSpan);
						}
					}
				});
			});
		}

		function findItemsOutsideOfRange(items, start, end) {
			var out = [];

			for (var i = 0; i < items.length; i++) {
				if (i < start || i > end) {
					out.push(items[i]);
				}
			}

			return out;
		}

		function getFakeCells(cells) {
			return Tools.grep(cells, function (cell) {
				return cell.real === false;
			});
		}

		function getUniqueElms(cells) {
			var elms = [];

			for (var i = 0; i < cells.length; i++) {
				var elm = cells[i].elm;
				if (elms[elms.length - 1] !== elm) {
					elms.push(elm);
				}
			}

			return elms;
		}

		function reduceRowSpans(grid, startX, startY, endX, endY) {
			var count = 0;

			for (var y = startY; y <= endY; y++) {
				var allCells = findItemsOutsideOfRange(getRow(grid, y), startX, endX);
				var fakeCells = getFakeCells(allCells);

				if (allCells.length === fakeCells.length) {
					Tools.each(getUniqueElms(fakeCells), function (elm) {
						Utils.setRowSpan(elm, Utils.getRowSpan(elm) - 1);
					});

					count++;
				}
			}

			return count;
		}

		function reduceColSpans(grid, startX, startY, endX, endY) {
			var count = 0;

			for (var x = startX; x <= endX; x++) {
				var allCells = findItemsOutsideOfRange(getColumn(grid, x), startY, endY);
				var fakeCells = getFakeCells(allCells);

				if (allCells.length === fakeCells.length) {
					Tools.each(getUniqueElms(fakeCells), function (elm) {
						Utils.setColSpan(elm, Utils.getColSpan(elm) - 1);
					});

					count++;
				}
			}

			return count;
		}

		function merge(cell, cols, rows) {
			var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count, reducedRows, reducedCols;

			// Use specified cell and cols/rows
			if (cell) {
				pos = getPos(cell);
				startX = pos.x;
				startY = pos.y;
				endX = startX + (cols - 1);
				endY = startY + (rows - 1);
			} else {
				startPos = endPos = null;

				// Calculate start/end pos by checking for selected cells in grid works better with context menu
				each(grid, function(row, y) {
					each(row, function(cell, x) {
						if (isCellSelected(cell)) {
							if (!startPos) {
								startPos = {x: x, y: y};
							}

							endPos = {x: x, y: y};
						}
					});
				});

				// Use selection, but make sure startPos is valid before accessing
				if (startPos) {
					startX = startPos.x;
					startY = startPos.y;
					endX = endPos.x;
					endY = endPos.y;
				}
			}

			// Find start/end cells
			startCell = getCell(startX, startY);
			endCell = getCell(endX, endY);

			// Check if the cells exists and if they are of the same part for example tbody = tbody
			if (startCell && endCell && startCell.part == endCell.part) {
				// Split and rebuild grid
				split();
				buildGrid();

				reducedRows = reduceRowSpans(grid, startX, startY, endX, endY);
				reducedCols = reduceColSpans(grid, startX, startY, endX, endY);

				// Set row/col span to start cell
				startCell = getCell(startX, startY).elm;
				var colSpan = (endX - startX - reducedCols) + 1;
				var rowSpan = (endY - startY - reducedRows) + 1;

				// All cells in table selected then just make it a table with one cell
				if (colSpan === gridWidth && rowSpan === grid.length) {
					colSpan = 1;
					rowSpan = 1;
				}

				// Multiple whole rows selected then just make it one rowSpan
				if (colSpan === gridWidth && rowSpan > 1) {
					rowSpan = 1;
				}

				setSpanVal(startCell, 'colSpan', colSpan);
				setSpanVal(startCell, 'rowSpan', rowSpan);

				// Remove other cells and add it's contents to the start cell
				for (y = startY; y <= endY; y++) {
					for (x = startX; x <= endX; x++) {
						if (!grid[y] || !grid[y][x]) {
							continue;
						}

						cell = grid[y][x].elm;

						/*jshint loopfunc:true */
						/*eslint no-loop-func:0 */
						if (cell != startCell) {
							// Move children to startCell
							children = Tools.grep(cell.childNodes);
							each(children, function(node) {
								startCell.appendChild(node);
							});

							// Remove bogus nodes if there is children in the target cell
							if (children.length) {
								children = Tools.grep(startCell.childNodes);
								count = 0;
								each(children, function(node) {
									if (node.nodeName == 'BR' && count++ < children.length - 1) {
										startCell.removeChild(node);
									}
								});
							}

							dom.remove(cell);
						}
					}
				}

				// Remove empty rows etc and restore caret location
				cleanup();
			}
		}

		function insertRow(before) {
			var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan, spanValue;

			// Find first/last row
			each(grid, function(row, y) {
				each(row, function(cell) {
					if (isCellSelected(cell)) {
						cell = cell.elm;
						rowElm = cell.parentNode;
						newRow = fireNewRow(cloneNode(rowElm, false));
						posY = y;

						if (before) {
							return false;
						}
					}
				});

				if (before) {
					return !posY;
				}
			});

			// If posY is undefined there is nothing for us to do here...just return to avoid crashing below
			if (posY === undefined) {
				return;
			}

			for (x = 0, spanValue = 0; x < grid[0].length; x += spanValue) {
				// Cell not found could be because of an invalid table structure
				if (!grid[posY][x]) {
					continue;
				}

				cell = grid[posY][x].elm;
				spanValue = getSpanVal(cell, 'colspan');

				if (cell != lastCell) {
					if (!before) {
						rowSpan = getSpanVal(cell, 'rowspan');
						if (rowSpan > 1) {
							setSpanVal(cell, 'rowSpan', rowSpan + 1);
							continue;
						}
					} else {
						// Check if cell above can be expanded
						if (posY > 0 && grid[posY - 1][x]) {
							otherCell = grid[posY - 1][x].elm;
							rowSpan = getSpanVal(otherCell, 'rowSpan');
							if (rowSpan > 1) {
								setSpanVal(otherCell, 'rowSpan', rowSpan + 1);
								continue;
							}
						}
					}

					// Insert new cell into new row
					newCell = cloneCell(cell);
					setSpanVal(newCell, 'colSpan', cell.colSpan);

					newRow.appendChild(newCell);

					lastCell = cell;
				}
			}

			if (newRow.hasChildNodes()) {
				if (!before) {
					dom.insertAfter(newRow, rowElm);
				} else {
					rowElm.parentNode.insertBefore(newRow, rowElm);
				}
			}
		}

		function insertCol(before) {
			var posX, lastCell;

			// Find first/last column
			each(grid, function(row) {
				each(row, function(cell, x) {
					if (isCellSelected(cell)) {
						posX = x;

						if (before) {
							return false;
						}
					}
				});

				if (before) {
					return !posX;
				}
			});

			each(grid, function(row, y) {
				var cell, rowSpan, colSpan;

				if (!row[posX]) {
					return;
				}

				cell = row[posX].elm;
				if (cell != lastCell) {
					colSpan = getSpanVal(cell, 'colspan');
					rowSpan = getSpanVal(cell, 'rowspan');

					if (colSpan == 1) {
						if (!before) {
							dom.insertAfter(cloneCell(cell), cell);
							fillLeftDown(posX, y, rowSpan - 1, colSpan);
						} else {
							cell.parentNode.insertBefore(cloneCell(cell), cell);
							fillLeftDown(posX, y, rowSpan - 1, colSpan);
						}
					} else {
						setSpanVal(cell, 'colSpan', cell.colSpan + 1);
					}

					lastCell = cell;
				}
			});
		}

		function getSelectedCells(grid) {
			return Tools.grep(getAllCells(grid), isCellSelected);
		}

		function getAllCells(grid) {
			var cells = [];

			each(grid, function(row) {
				each(row, function(cell) {
					cells.push(cell);
				});
			});

			return cells;
		}

		function deleteCols() {
			var cols = [];

			if (isEditorBody(table)) {
				if (grid[0].length == 1) {
					return;
				}

				if (getSelectedCells(grid).length == getAllCells(grid).length) {
					return;
				}
			}

			// Get selected column indexes
			each(grid, function(row) {
				each(row, function(cell, x) {
					if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) {
						each(grid, function(row) {
							var cell = row[x].elm, colSpan;

							colSpan = getSpanVal(cell, 'colSpan');

							if (colSpan > 1) {
								setSpanVal(cell, 'colSpan', colSpan - 1);
							} else {
								dom.remove(cell);
							}
						});

						cols.push(x);
					}
				});
			});

			cleanup();
		}

		function deleteRows() {
			var rows;

			function deleteRow(tr) {
				var pos, lastCell;

				// Move down row spanned cells
				each(tr.cells, function(cell) {
					var rowSpan = getSpanVal(cell, 'rowSpan');

					if (rowSpan > 1) {
						setSpanVal(cell, 'rowSpan', rowSpan - 1);
						pos = getPos(cell);
						fillLeftDown(pos.x, pos.y, 1, 1);
					}
				});

				// Delete cells
				pos = getPos(tr.cells[0]);
				each(grid[pos.y], function(cell) {
					var rowSpan;

					cell = cell.elm;

					if (cell != lastCell) {
						rowSpan = getSpanVal(cell, 'rowSpan');

						if (rowSpan <= 1) {
							dom.remove(cell);
						} else {
							setSpanVal(cell, 'rowSpan', rowSpan - 1);
						}

						lastCell = cell;
					}
				});
			}

			// Get selected rows and move selection out of scope
			rows = getSelectedRows();

			if (isEditorBody(table) && rows.length == table.rows.length) {
				return;
			}

			// Delete all selected rows
			each(rows.reverse(), function(tr) {
				deleteRow(tr);
			});

			cleanup();
		}

		function cutRows() {
			var rows = getSelectedRows();

			if (isEditorBody(table) && rows.length == table.rows.length) {
				return;
			}

			dom.remove(rows);
			cleanup();

			return rows;
		}

		function copyRows() {
			var rows = getSelectedRows();

			each(rows, function(row, i) {
				rows[i] = cloneNode(row, true);
			});

			return rows;
		}

		function pasteRows(rows, before) {
			var splitResult, targetRow, newRows;

			// Nothing to paste
			if (!rows) {
				return;
			}

			splitResult = SplitCols.splitAt(grid, startPos.x, startPos.y, before);
			targetRow = splitResult.row;
			Tools.each(splitResult.cells, fireNewCell);

			newRows = Tools.map(rows, function (row) {
				return row.cloneNode(true);
			});

			if (!before) {
				newRows.reverse();
			}

			each(newRows, function(row) {
				var i, cellCount = row.cells.length, cell;

				fireNewRow(row);

				// Remove col/rowspans
				for (i = 0; i < cellCount; i++) {
					cell = row.cells[i];

					fireNewCell(cell);
					setSpanVal(cell, 'colSpan', 1);
					setSpanVal(cell, 'rowSpan', 1);
				}

				// Needs more cells
				for (i = cellCount; i < gridWidth; i++) {
					row.appendChild(fireNewCell(cloneCell(row.cells[cellCount - 1])));
				}

				// Needs less cells
				for (i = gridWidth; i < cellCount; i++) {
					dom.remove(row.cells[i]);
				}

				// Add before/after
				if (before) {
					targetRow.parentNode.insertBefore(row, targetRow);
				} else {
					dom.insertAfter(row, targetRow);
				}
			});

			removeCellSelection();
		}

		function getPos(target) {
			var pos;

			each(grid, function(row, y) {
				each(row, function(cell, x) {
					if (cell.elm == target) {
						pos = {x: x, y: y};
						return false;
					}
				});

				return !pos;
			});

			return pos;
		}

		function setStartCell(cell) {
			startPos = getPos(cell);
		}

		function findEndPos() {
			var maxX, maxY;

			maxX = maxY = 0;

			each(grid, function(row, y) {
				each(row, function(cell, x) {
					var colSpan, rowSpan;

					if (isCellSelected(cell)) {
						cell = grid[y][x];

						if (x > maxX) {
							maxX = x;
						}

						if (y > maxY) {
							maxY = y;
						}

						if (cell.real) {
							colSpan = cell.colspan - 1;
							rowSpan = cell.rowspan - 1;

							if (colSpan) {
								if (x + colSpan > maxX) {
									maxX = x + colSpan;
								}
							}

							if (rowSpan) {
								if (y + rowSpan > maxY) {
									maxY = y + rowSpan;
								}
							}
						}
					}
				});
			});

			return {x: maxX, y: maxY};
		}

		function setEndCell(cell) {
			var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y;

			endPos = getPos(cell);

			if (startPos && endPos) {
				// Get start/end positions
				startX = Math.min(startPos.x, endPos.x);
				startY = Math.min(startPos.y, endPos.y);
				endX = Math.max(startPos.x, endPos.x);
				endY = Math.max(startPos.y, endPos.y);

				// Expand end position to include spans
				maxX = endX;
				maxY = endY;

				// This logic tried to expand the selection to always be a rectangle
				// Expand startX
				/*for (y = startY; y <= maxY; y++) {
					cell = grid[y][startX];

					if (!cell.real) {
						newX = startX - (cell.colspan - 1);
						if (newX < startX && newX >= 0) {
							startX = newX;
						}
					}
				}

				// Expand startY
				for (x = startX; x <= maxX; x++) {
					cell = grid[startY][x];

					if (!cell.real) {
						newY = startY - (cell.rowspan - 1);
						if (newY < startY && newY >= 0) {
							startY = newY;
						}
					}
				}*/

				// Find max X, Y
				for (y = startY; y <= endY; y++) {
					for (x = startX; x <= endX; x++) {
						cell = grid[y][x];

						if (cell.real) {
							colSpan = cell.colspan - 1;
							rowSpan = cell.rowspan - 1;

							if (colSpan) {
								if (x + colSpan > maxX) {
									maxX = x + colSpan;
								}
							}

							if (rowSpan) {
								if (y + rowSpan > maxY) {
									maxY = y + rowSpan;
								}
							}
						}
					}
				}

				removeCellSelection();

				// Add new selection
				for (y = startY; y <= maxY; y++) {
					for (x = startX; x <= maxX; x++) {
						if (grid[y][x]) {
							dom.setAttrib(grid[y][x].elm, 'data-mce-selected', '1');
						}
					}
				}
			}
		}

		function moveRelIdx(cellElm, delta) {
			var pos, index, cell;

			pos = getPos(cellElm);
			index = pos.y * gridWidth + pos.x;

			do {
				index += delta;
				cell = getCell(index % gridWidth, Math.floor(index / gridWidth));

				if (!cell) {
					break;
				}

				if (cell.elm != cellElm) {
					selection.select(cell.elm, true);

					if (dom.isEmpty(cell.elm)) {
						selection.collapse(true);
					}

					return true;
				}
			} while (cell.elm == cellElm);

			return false;
		}

		function splitCols(before) {
			if (startPos) {
				var splitResult = SplitCols.splitAt(grid, startPos.x, startPos.y, before);
				Tools.each(splitResult.cells, fireNewCell);
			}
		}

		table = table || dom.getParent(selection.getStart(true), 'table');

		buildGrid();

		selectedCell = selectedCell || dom.getParent(selection.getStart(true), 'th,td');

		if (selectedCell) {
			startPos = getPos(selectedCell);
			endPos = findEndPos();
			selectedCell = getCell(startPos.x, startPos.y);
		}

		Tools.extend(this, {
			deleteTable: deleteTable,
			split: split,
			merge: merge,
			insertRow: insertRow,
			insertCol: insertCol,
			splitCols: splitCols,
			deleteCols: deleteCols,
			deleteRows: deleteRows,
			cutRows: cutRows,
			copyRows: copyRows,
			pasteRows: pasteRows,
			getPos: getPos,
			setStartCell: setStartCell,
			setEndCell: setEndCell,
			moveRelIdx: moveRelIdx,
			refresh: buildGrid
		});
	};
});