Sync html from composer to textarea
Takes care of placeholders
@param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea
766459
function(shouldParseHtml) {
      this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue(false, false)).trim(), shouldParseHtml);
    }
84992
function processHtml(demo) {

      var allContent = demo.files.index.contents;

      var processors = [
        applyAngularAttributesToParentElement,
        insertTemplatesAsScriptTags,
        htmlEscapeAmpersand
      ];

      processors.forEach(function(processor) {
        allContent = processor(allContent, demo);
      });

      return allContent;
    }
931365
function before(element, content) {
  if (isString(content)) {
    return element.insertAdjacentHTML('beforeBegin', content);
  } else {
    return element.parentNode.insertBefore(normalizeContent(content), element);
  }
}
666359
function processHTML() {
            /**
             * Genetrate an iterator of the index where non whitespace appear
             * @param {string} text The text to set
             * @returns {number} The index
             */
            function* genWordStartIndices(text) {
                if (!text.trim()) {
                    return
                }
                const re = /\s/u
                let preIsWhitespace = true
                let i = 0
                for (const c of text) {
                    const isWhitespace = re.test(c)
                    if (preIsWhitespace && !isWhitespace) {
                        yield i
                    }
                    preIsWhitespace = isWhitespace
                    i++
                }
            }

            /**
             * Check whether the given token is a dummy element.
             * @param {Token} node The token to check.
             * @returns {boolean} `true` if the token is a dummy element.
             */
            function isDummyElement(node) {
                return (
                    !node.startTag &&
                    (node.name === "body" ||
                        node.name === "head" ||
                        node.name === "html")
                )
            }

            /**
             * Get the start token of Element
             * @param  {Node} elementNode The element node
             * @returns {Token} The start token
             */
            function getStartToken(elementNode) {
                if (!elementNode) {
                    return null
                }
                if (elementNode.type !== "HTMLElement") {
                    return null
                }
                if (isDummyElement(elementNode)) {
                    return null
                }
                return elementNode.startTag || elementNode
            }

            microTemplateService.traverseDocumentNodes({
                HTMLElement(node) {
                    if (isDummyElement(node)) {
                        return
                    }
                    const elementNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(elementNode)
                    const parentStartToken = getStartToken(elementNode.parent)
                    if (parentStartToken) {
                        // self indent
                        setOffsetToToken(
                            startToken,
                            1,
                            parentStartToken.loc.start.line
                        )
                    } else {
                        setOffsetRootToIndex(startToken.range[0])
                    }
                    if (
                        IGNORE_INDENT_ELEMENT_NAMES.find(
                            name => name === elementNode.name
                        )
                    ) {
                        ignoreRanges.push([
                            elementNode.startTag
                                ? elementNode.startTag.range[1]
                                : elementNode.range[0],
                            elementNode.endTag
                                ? elementNode.endTag.range[0]
                                : elementNode.range[1],
                        ])
                    }
                },
                HTMLStartTag(node) {
                    const attrs = node.attributes.concat(node.ignoredAttributes)
                    setOffsetToToken(
                        attrs,
                        options.attribute,
                        node.loc.start.line
                    )
                    const start = node.tagOpen
                        ? node.tagOpen.range[1]
                        : node.range[0]
                    const end = node.tagClose
                        ? node.tagClose.range[0]
                        : node.range[1]
                    const attrTemplateTokens = microTemplateService
                        .getMicroTemplateTokens()
                        .filter(token => {
                            if (
                                token.range[0] < start ||
                                end < token.range[1]
                            ) {
                                return false
                            }
                            return !attrs.some(
                                n =>
                                    token.range[0] < n.range[1] &&
                                    n.range[0] < token.range[1]
                            )
                        })
                    setOffsetToToken(
                        attrTemplateTokens,
                        options.attribute,
                        node.loc.start.line
                    )

                    if (node.tagClose) {
                        setOffsetToToken(
                            node.tagClose,
                            options.closeBracket,
                            node.loc.start.line
                        )
                    }
                },
                HTMLEndTag(node) {
                    const endTag =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(endTag.parent)
                    if (startToken) {
                        // self indent
                        setOffsetToToken(endTag, 0, startToken.loc.start.line)
                    }

                    if (endTag.tagClose) {
                        setOffsetToToken(
                            endTag.tagClose,
                            options.closeBracket,
                            endTag.loc.start.line
                        )
                    }
                },
                HTMLText(node) {
                    const textNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node

                    const textHTML = sourceCode.text.slice(
                        textNode.range[0],
                        textNode.range[1]
                    )
                    const startToken = getStartToken(textNode.parent)
                    if (startToken) {
                        // self indent
                        for (const i of genWordStartIndices(textHTML)) {
                            setOffsetToIndex(
                                textNode.range[0] + i,
                                1,
                                startToken.loc.start.line
                            )
                        }
                    } else {
                        for (const i of genWordStartIndices(textHTML)) {
                            setOffsetRootToIndex(textNode.range[0] + i)
                        }
                    }
                },
                HTMLComment(node) {
                    const commentNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(commentNode.parent)
                    if (startToken) {
                        // self indent
                        setOffsetToToken(
                            commentNode,
                            1,
                            startToken.loc.start.line
                        )
                    } else {
                        setOffsetRootToIndex(commentNode.range[0])
                    }

                    const commentStart = commentNode.range[0] + 4
                    const commentEnd = commentNode.range[1] - 3
                    const comment = sourceCode.text.slice(
                        commentStart,
                        commentEnd
                    )

                    for (const i of genWordStartIndices(comment)) {
                        setOffsetToIndex(
                            commentStart + i,
                            1,
                            commentNode.loc.start.line
                        )
                    }
                    setOffsetToIndex(commentEnd, 0, commentNode.loc.start.line)
                },
            })
        }
520823
function htmlToComponent(str, tags, opts) {
  var keys = objectKeys(tags);
  var props = opts.props || {};
  var preserveAttributes = opts.preserveAttributes || [];
  var tagAttributes = [];
  var reactTags={};
  var reactKeys=[];
  var key;
  for(var i = 0; i<keys.length; i++) {
    key = "AB"+Math.random().toString(36).substring(2);
    if(typeof tags[keys[i]] !== "function") {
      if(typeof tags[keys[i]].slice !== "function") continue;
      tagAttributes = tags[keys[i]].slice(0,-1);
      reactTags[key] = tags[keys[i]].slice(-1)[0];
    }
    else
      reactTags[key] = tags[keys[i]];

    reactKeys.push(key);

    str = str
      .replace(new RegExp("(<\/?)"+keys[i]+"(?:[^>\"']|\".*\"|'.*')*>", "ig"), function(match, start){
        // find/replace spell-save attributes within tag to restore capitals
        if(start !== "</")
          for(var a=0; a<tagAttributes.length; a++)
            match = replaceAttribute(match, tagAttributes[a], tagAttributes[a]);

        // replace key
        return match
          .replace(new RegExp(start+keys[i]+"(\\s|>)", "i"), start+key+"$1");
      });
  }

  // remove/disable html comments
  str = str.replace(/<!--|-->/g,"")

  // find/replace global spell-save attributes to restore capitals
  var attributes = preserveReactAttributes.concat(preserveAttributes);
  for(var i=0; i<attributes.length; i++) 
    str = replaceAttribute(str, attributes[i], attributes[i]);
 
  var jsx = htmlToJsx(str);

  // replace props variables {key} with corrected variables {props['key']}
  for(var key in props) {
    jsx = jsx
      .replace(new RegExp("(\{"+key+"\})","g"),"{props['"+key+"']}");
  }
  
  var component = ReactTransform(jsx).code;
  
  // replace component variables (ComponentName) with corrected variables (tags['ComponentName'])
  for(var i=0; i<reactKeys.length; i++) {
    component = component
      .replace(new RegExp(reactKeys[i],"g"), "reactTags['"+reactKeys[i]+"']"); 
  }

  return eval(component);
}
1186589
function updateImageSizeHTML(editor, model) {
	const pos = editor.getCursorBufferPosition();
	const src = getImageSrcHTML( getImageHTMLNode(editor, model, pos) );

	if (!src) {
		return Promise.reject(new Error('No valid image source'));
	}

	locateFile(editor, src)
	.then(getImageSize)
	.then(size => {
		// since this action is asynchronous, we have to ensure that editor wasn’t
		// changed and user didn’t moved caret outside <img> node
		const img = getImageHTMLNode(editor, model, pos);
		if (getImageSrcHTML(img) === src) {
			updateHTMLTag(editor, img, size.width, size.height);
		}
	})
	.catch(err => console.warn('Error while updating image size:', err));
}
244861
function (html) {
            var t = this;

            if (html != null) {
                t.$ta.val(html);
                t.syncCode(true);
                t.$c.trigger('tbwchange');
                return t;
            }

            return t.$ta.val();
        }
71901
function (node) {
    var tagName = jsxTagName(node.tagName);
    var attributes = [];
    for (var i = 0, count = node.attributes.length; i < count; i++) {
      attributes.push(this._getElementAttribute(node, node.attributes[i]));
    }

    if (tagName === 'textarea') {
      // Hax: textareas need their inner text moved to a "defaultValue" attribute.
      attributes.push('defaultValue={' + JSON.stringify(node.value) + '}');
    }
    if (tagName === 'style') {
      // Hax: style tag contents need to be dangerously set due to liberal curly brace usage
      attributes.push('dangerouslySetInnerHTML={{__html: ' + JSON.stringify(node.textContent) + ' }}');
    }
    if (tagName === 'pre') {
      this._inPreTag = true;
    }

    this.output += '<' + tagName;
    if (attributes.length > 0) {
      this.output += ' ' + attributes.join(' ');
    }
    if (!this._isSelfClosing(node)) {
      this.output += '>';
    }
  }
1241717
function prepareHtml() {
        // remove all tabs and new lines - as they mean nothing in HTML
        $this->html = trim(preg_replace('/\t\n/', '', $this->html));

        // normalize multiple spaces to one space
        $this->html = preg_replace('/\s+/', ' ', $this->html);

        // replace special characters like &nbsp;
        $this->html = $this->replaceSpecialCharacters($this->html);

//        $charset = 'UTF-8';
//        if (function_exists('mb_convert_encoding') && in_array(strtolower($charset), array_map('strtolower', mb_list_encodings()))) {
//            $this->html = mb_convert_encoding($this->html, 'HTML-ENTITIES', $charset);
//        }

    }
618096
function TodosOfENML(text){

    var todos = [];


    var parser = new SaxParser(function(cb) {

      var onTodo = false;
      var text = null;
      var checked = false;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {
        var m = elem.match(/b|u|i|font|strong/);
        if(m && elem == m[0]){

        }
        else if(elem == 'en-todo'){

          checked = false;
          text = "";
          onTodo = true;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'checked' && attr[1] == 'true') checked = true;
          });

        } else {
          if(onTodo){
            todos.push({text: text, checked: checked});
          }
          onTodo = false;
        }

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

      });
      cb.onCharacters(function(chars) {
        if(onTodo){
          text += chars;
        }
      });

      cb.onEndDocument(function(){
        if (onTodo) {
          todos.push({text: text, checked: checked});
        }
      });
    });

    parser.parseString(text);
    return todos;
  }
361252
function onParsingComplete ()
  {
    // Validate defaultParam's value.
    $def = isset($this->props->defaultParam) ? $this->props->defaultParam : null;
    if (!empty($def)) {
      if (!$this->props->defines ($def))
        throw new ComponentException($this,
          "Invalid value for <kbd>defaultParam</kbd> on <b>&lt;{$this->getTagName()}></b>; parameter <kbd>$def</kbd> does not exist");

      // Move children to default parameter.
      if ($this->hasChildren ()) {
        $type = $this->props->getTypeOf ($def);
        if ($type != type::content && $type != type::metadata)
          throw new ComponentException($this, sprintf (
            "The macro's default parameter <kbd>$def</kbd> can't hold content because its type is <kbd>%s</kbd>.",
            type::getNameOf ($type)));

        $param = new Metadata($this->context, ucfirst ($def), $type);
        $this->props->set ($def, $param);
        $param->attachTo ($this);
        $param->setChildren ($this->getChildren ());
      }
    }
    elseif ($this->hasChildren ())
      throw new ComponentException ($this,
        'You may not specify content for this tag because it has no default property');
  }
321083
function(editor) {
			var info = editorUtils.outputInfo(editor);
			var caretPos = editor.getCaretPos();
			var nl = '\n';
			var pad = '\t';
			
			if (~xmlSyntaxes.indexOf(info.syntax)) {
				// let's see if we're breaking newly created tag
				var tag = htmlMatcher.tag(info.content, caretPos);
				if (tag && !tag.innerRange.length()) {
					editor.replaceContent(nl + pad + utils.getCaretPlaceholder() + nl, caretPos);
					return true;
				}
			} else if (info.syntax == 'css') {
				/** @type String */
				var content = info.content;
				if (caretPos && content.charAt(caretPos - 1) == '{') {
					var append = prefs.get('css.closeBraceIndentation');
					
					var hasCloseBrace = content.charAt(caretPos) == '}';
					if (!hasCloseBrace) {
						// do we really need special formatting here?
						// check if this is really a newly created rule,
						// look ahead for a closing brace
						for (var i = caretPos, il = content.length, ch; i < il; i++) {
							ch = content.charAt(i);
							if (ch == '{') {
								// ok, this is a new rule without closing brace
								break;
							}
							
							if (ch == '}') {
								// not a new rule, just add indentation
								append = '';
								hasCloseBrace = true;
								break;
							}
						}
					}
					
					if (!hasCloseBrace) {
						append += '}';
					}
					
					// defining rule set
					var insValue = nl + pad + utils.getCaretPlaceholder() + append;
					editor.replaceContent(insValue, caretPos);
					return true;
				}
			}
				
			return false;
		}
541586
function () {

        $assertEveryCalled (function (blockChangeEventCalled) {

            var textarea = new ($component ({

                    $traits: [DOMReference,
                              DOMEvents,
                              $trait ({ blockChangeEvent: $on ('change', function (e) { blockChangeEventCalled (); e.stopImmediatePropagation () }) }),
                              $trait ({ shouldNotCall:    $on ('change', function (e) { $fail }) }) ],

                    init: function () { this.domReady (
                                            N.textarea.insertMeAfter (document.body.lastChild)) } })) ()

                textarea.dispatchEvent ('change')
                textarea.destroy () }) }
1229025
function(data) {
        var TTML_BODY = '',
            index = 0,
            splitText,
            captions = data;

        TTML_BODY += TTML.header.join('\n') + '\n';
        captions.forEach(function(caption) {
            if (caption.text.length > 0 && validateText(caption.text)) {
                if ((/&/.test(caption.text)) && !(/&amp;/.test(caption.text))) {
                    caption.text = caption.text.replace(/&/g, '&amp;');
                }
                if ((/</.test(caption.text)) && !(/&lt;/.test(caption.text))) {
                    caption.text = caption.text.replace(/</g, '&lt;');
                }
                if ((/>/.test(caption.text)) && !(/&gt;/.test(caption.text))) {
                    caption.text = caption.text.replace(/>/g, '&gt;');
                }
                if (/\{break\}/.test(caption.text)) {
                    splitText = caption.text.split('{break}');
                    //TODO this should count for number of breaks and add the appropriate pops where needed.
                    for (index = 0; index < splitText.length; index++) {
                        TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop' + (index + 1))
                            .replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
                            .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
                            .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(splitText[index])))) + '\n';
                    }
                } else {
                    TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop1')
                        .replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
                        .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
                        .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n';
                }
            }
        });

        return TTML_BODY + TTML.footer.join('\n') + '\n';
    }
758951
function parseGuestWlanHTML(html)
{
    $ = cheerio.load(html);
    var form = $('form');
    var settings = {};

    $('input', form).each(function(i, elem) {
        var val;
        var name = $(elem).attr('name');
        if (!name) return;

        switch ($(elem).attr('type')) {
            case 'checkbox':
                val = $(elem).attr('checked') == 'checked';
                break;
            default:
                val = $(elem).val();
        }
        settings[name] = val;
    });

    $('select option[selected=selected]', form).each(function(i, elem) {
        var val = $(elem).val();
        var name = $(elem).parent().attr('name');
        settings[name] = val;
    });

    return settings;
}
1353122
function parseHtml(html, sourceCodeStore) {
    const isFragment = !/^\s*<(!doctype|html|head|body|!--)/iu.test(html)
    const document = (isFragment ? parse5.parseFragment : parse5.parse)(html, {
        sourceCodeLocationInfo: true,
    })

    return parse5NodeToToken(document, null, html, sourceCodeStore, html.length)
}
726218
function before_html_mode(t,value,arg3,arg4) {
    var elt;
    switch(t) {
    case 1: // TEXT
      value = value.replace(LEADINGWS, ""); // Ignore spaces
      if (value.length === 0) return; // Are we done?
      break; // Handle anything non-space text below
    case 5: // DOCTYPE
      /* ignore the token */
      return;
    case 4: // COMMENT
      doc._appendChild(doc.createComment(value));
      return;
    case 2: // TAG
      if (value === "html") {
        elt = createHTMLElt(doc, value, arg3);
        stack.push(elt);
        doc.appendChild(elt);
        // XXX: handle application cache here
        parser = before_head_mode;
        return;
      }
      break;
    case 3: // ENDTAG
      switch(value) {
      case "html":
      case "head":
      case "body":
      case "br":
        break;  // fall through on these
      default:
        return; // ignore most end tags
      }
    }

    // Anything that didn't get handled above is handled like this:
    elt = createHTMLElt(doc, "html", null);
    stack.push(elt);
    doc.appendChild(elt);
    // XXX: handle application cache here
    parser = before_head_mode;
    parser(t,value,arg3,arg4);
  }