wmakeev
10/23/2017 - 1:09 PM

MAM libs

MAM libs

/// <reference path="../../node_modules/mutation-summary/src/mutation-summary.ts" />

namespace $ {
	export interface $tools_dom_mutation_options {
		query: () => $tools_dom_mutation_query
		root_node?: () => Node
		old_previous_sibling?: () => boolean
		observe_own_changes?: () => boolean
	}

	export class $tools_dom_mutation_query {
		element?: string
	}

	export class $tools_dom_mutation extends $mol_object {
		@$mol_mem_key
		static item (options: {
			query: $tools_dom_mutation_query
			root_node?: Node
			old_previous_sibling?: boolean
			observe_own_changes?: boolean
		}) {
			return $tools_dom_mutation.make({
				query: $mol_const(options.query),
				root_node: $mol_const(options.root_node),
				old_previous_sibling: $mol_const(options.old_previous_sibling),
				observe_own_changes: $mol_const(options.observe_own_changes)
			})
		}

		query () { return null as $tools_dom_mutation_query }

		root_node () { return null as Node }

		old_previous_sibling () { return false }

		observe_own_changes () { return false }

		'observer()': MutationSummary
		observer () {
			if (this['observer()']) return this['observer()']

			let next = this['observer()'] = new MutationSummary({
				queries: [{ element: this.query().element }],
				rootNode: this.root_node(),
				oldPreviousSibling: this.old_previous_sibling(),
				observeOwnChanges: this.observe_own_changes(),
				callback: (summaries: Summary[]) => {
					summaries.forEach(summary => {
						summary.added.forEach(node => this.node_added(node, $mol_atom_force))
					})

					summaries.forEach(summary => {
						summary.removed.forEach(node => this.node_removed(node, $mol_atom_force))
					})
				}
			})

			return next
		}

		@$mol_mem
		node_added (next: Node, force?: $mol_atom_force) {
			return next || null
		}

		@$mol_mem
		node_removed (next: Node, force?: $mol_atom_force) {
			return next || null
		}

		destructor () {
			const observer = this['observer()']
			if (observer) observer.disconnect()
		}
	}
}