We use cookies to make our website more effective. By using our website you agree to our privacy policy.

Source: paths.js

/**
 * paths.js is part of Aloha Editor project http://www.alohaeditor.org
 *
 * Aloha Editor ● JavaScript Content Editing Library
 * Copyright (c) 2010-2015 Gentics Software GmbH, Vienna, Austria.
 * Contributors http://www.alohaeditor.org/docs/contributing.html
 * @namespace paths
 */
define([
	'dom',
	'arrays',
	'boundaries'
], function (
	Dom,
	Arrays,
	Boundaries
) {
	'use strict';

	/**
	 * Returns a "path" from the given boundary position, up to the specified
	 * node. The `limit` node must contain the given boundary position.
	 *
	 * @param  {!Node}     limit
	 * @param  {!Boundary} boundary
	 * @return {Array.<number>}
	 * @memberOf paths
	 */
	function fromBoundary(limit, boundary) {
		var offset = Boundaries.offset(boundary);
		var container = Boundaries.container(boundary);
		if (container === limit) {
			return [offset];
		}
		var chain = Dom.childAndParentsUntilNode(container, limit);
		var path = chain.reduce(function (path, node) {
			return path.concat(Dom.nodeIndex(node));
		}, [offset]);
		path.reverse();
		return path;
	}

	/**
	 * Resolves the given path to a boundary positioned inside DOM tree whose
	 * root is `container`.
	 *
	 * @param  {!Node}          container
	 * @param  {Array.<number>} path
	 * @return {Boundary}
	 * @memberOf paths
	 */
	function toBoundary(container, path) {
		var node = path.slice(0, -1).reduce(function (node, offset) {
			return node.childNodes[offset] || node;
		}, container);
		return Boundaries.raw(node, Arrays.last(path) || 0);
	}

	/**
	 * Checkes whether the given paths are equal.
	 *
	 * @param  {!Path} a
	 * @param  {!Path} b
	 * @return {boolean}
	 */
	function equals(a, b) {
		if (a.length !== b.length) {
			return false;
		}
		for (var i = 0; i < a.length; i++) {
			if (b[i] !== a[i]) {
				return false;
			}
		}
		return true;
	}

	return {
		equals       : equals,
		toBoundary   : toBoundary,
		fromBoundary : fromBoundary
	};
});
comments powered by Disqus