當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript dom5.nodeWalk函數代碼示例

本文整理匯總了TypeScript中dom5.nodeWalk函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript nodeWalk函數的具體用法?TypeScript nodeWalk怎麽用?TypeScript nodeWalk使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了nodeWalk函數的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: processFile

  private async processFile(file: File): Promise<File> {
    if (file.path !== this.entrypoint) {
      return file;
    }
    const contents = await getFileContents(file);
    const document = parse5.parse(contents);

    const babelHelpersFragment =
        parse5.parseFragment('\n\n<script></script>\n\n');
    dom5.setTextContent(
        babelHelpersFragment.childNodes![1]!,
        await fs.readFile(
            path.join(__dirname, 'babel-helpers.min.js'), 'utf-8'));

    const firstScriptOrImport = dom5.nodeWalk(document, scriptOrImport);
    if (firstScriptOrImport) {
      dom5.insertBefore(
          firstScriptOrImport.parentNode!,
          firstScriptOrImport,
          babelHelpersFragment);
    } else {
      const head =
          dom5.query(document, dom5.predicates.hasTagName('head')) || document;
      dom5.append(head, babelHelpersFragment);
    }

    const newFile = file.clone();
    newFile.contents = new Buffer(parse5.serialize(document), 'utf-8');
    return newFile;
  }
開發者ID:chrisekelley,項目名稱:polymer-build,代碼行數:30,代碼來源:inject-babel-helpers.ts

示例2: ScannedElementReference

    const visitor = (node: ASTNode) => {
      if (node.tagName && this.matches(node)) {
        const element = new ScannedElementReference(
            node.tagName, document.sourceRangeForNode(node)!, node);

        if (node.attrs) {
          for (const attr of node.attrs) {
            element.attributes.set(attr.name, {
              name: attr.name,
              value: attr.value,
              sourceRange: document.sourceRangeForAttribute(node, attr.name)!,
              nameSourceRange:
                  document.sourceRangeForAttributeName(node, attr.name)!,
              valueSourceRange:
                  document.sourceRangeForAttributeValue(node, attr.name)
            });
          }
        }

        elements.push(element);
      }

      // Descend into templates.
      if (node.tagName === 'template') {
        const content = treeAdapters.default.getTemplateContent(node);
        if (content) {
          dom5.nodeWalk(content, (n) => {
            visitor(n);
            return false;
          });
        }
      }
    };
開發者ID:asdfg9822,項目名稱:polymer-analyzer,代碼行數:33,代碼來源:html-element-reference-scanner.ts

示例3: addCustomElementsEs5Adapter

export function addCustomElementsEs5Adapter(html: string): string {
  // Only modify this file if we find a web components polyfill. This is a
  // heuristic to identify the entry point HTML file. Ultimately we should
  // explicitly transform only the entry point by having the project config.
  if (!webcomponentsLoaderRegex.test(html)) {
    return html;
  }
  const parsed = parse5.parse(html, {locationInfo: true});
  const script = dom5.nodeWalk(parsed, webcomponentsLoaderMatcher);
  if (!script) {
    return html;
  }

  // Collect important dom references & create fragments for injection.
  const loaderScriptUrl = dom5.getAttribute(script, 'src')!;
  const adapterScriptUrl =
      url.resolve(loaderScriptUrl, 'custom-elements-es5-adapter.js');
  const es5AdapterFragment = parse5.parseFragment(`
    <script>if (!window.customElements) { document.write('<!--'); }</script>
    <script type="text/javascript" src="${adapterScriptUrl}"></script>
    <!--! do not remove -->
`);

  dom5.insertBefore(script.parentNode, script, es5AdapterFragment);
  return parse5.serialize(parsed);
}
開發者ID:chrisekelley,項目名稱:polymer-build,代碼行數:26,代碼來源:custom-elements-es5-adapter.ts

示例4: getDomModules

 analyzer.elements.forEach(function(element){
   // Ignore Polymer.Base since it's special.
   if (element.is == "Polymer.Base") return;
   var domModules = getDomModules(analyzer, element.is);
   if (!domModules[0]) {
     return;
   }
   if (domModules.length > 1) {
     domModules.forEach(function(domModule) {
       unorderedModules.push(lintErrorFromNode(domModule, "dom-module " +
         "has a repeated value for id " + element.is + "."));
     });
     return;
   }
   var scriptContent = dom5.getTextContent(element.scriptElement);
   var scriptFinderPredicate = p.hasTextValue(scriptContent);
   var script = dom5.nodeWalk(loadedDoc, scriptFinderPredicate);
   var otherDomModule = dom5.nodeWalkPrior(script, domModuleForId(element.is));
   if (!otherDomModule) {
     var originalDomModule = domModules[0];
     unorderedModules.push(lintErrorFromNode(originalDomModule, "dom-module " +
       "for " + element.is +
       " should be a parent of it or earlier in the document."));
   }
 });
開發者ID:PolymerLabs,項目名稱:polylint,代碼行數:25,代碼來源:linters.ts

示例5: async

 const visitor = async (node: ASTNode) => {
   if (isStyleNode(node)) {
     const tagName = node.nodeName;
     if (tagName === 'link') {
       const href = dom5.getAttribute(node, 'href')! as FileRelativeUrl;
       features.push(new ScannedImport(
           'html-style',
           href,
           document.sourceRangeForNode(node)!,
           document.sourceRangeForAttributeValue(node, 'href')!,
           node,
           true));
     } else {
       const contents = dom5.getTextContent(node);
       const locationOffset = getLocationOffsetOfStartOfTextContent(node);
       const commentText = getAttachedCommentText(node) || '';
       features.push(new ScannedInlineDocument(
           'css',
           contents,
           locationOffset,
           commentText,
           document.sourceRangeForNode(node)!,
           node));
     }
   }
   // Descend into templates.
   if (node.tagName === 'template') {
     const content = treeAdapters.default.getTemplateContent(node);
     if (content) {
       dom5.nodeWalk(content, (n) => {
         visitor(n);
         return false;
       });
     }
   }
 };
開發者ID:asdfg9822,項目名稱:polymer-analyzer,代碼行數:36,代碼來源:html-style-scanner.ts

示例6: convertStylesToScriptsThatInsertThem

  private *
      convertStylesToScriptsThatInsertThem(htmlDocument: ParsedHtmlDocument):
          Iterable<Edit> {
    const p = dom5.predicates;
    const head = dom5.nodeWalk(htmlDocument.ast, p.hasTagName('head'));
    const body = dom5.nodeWalk(htmlDocument.ast, p.hasTagName('body'));
    if (head === null || body === null) {
      throw new Error(`HTML Parser error, got a document without a head/body?`);
    }

    const tagsToInsertImperatively = [
      ...dom5.nodeWalkAll(
          head,
          p.OR(
              p.hasTagName('custom-style'),
              p.AND(
                  p.hasTagName('style'),
                  p.NOT(p.parentMatches(p.hasTagName('custom-style')))))),
    ];

    const apology = `<!-- FIXME(polymer-modulizer):
        These imperative modules that innerHTML your HTML are
        a hacky way to be sure that any mixins in included style
        modules are ready before any elements that reference them are
        instantiated, otherwise the CSS @apply mixin polyfill won't be
        able to expand the underlying CSS custom properties.
        See: https://github.com/Polymer/polymer-modulizer/issues/154
        -->
    `.split('\n').join(EOL);
    let first = true;
    for (const tag of tagsToInsertImperatively) {
      const offsets = htmlDocument.sourceRangeToOffsets(
          htmlDocument.sourceRangeForNode(tag)!);
      const scriptTag = parse5.parseFragment(`<script type="module"></script>`)
                            .childNodes![0];
      const program = jsc.program(createDomNodeInsertStatements([tag]));
      dom5.setTextContent(
          scriptTag,
          EOL +
              recast
                  .print(
                      program, {quote: 'single', wrapColumn: 80, tabWidth: 2})
                  .code +
              EOL);
      let replacementText = serializeNode(scriptTag);
      if (first) {
        replacementText = apology + replacementText;
        first = false;
      }
      yield {offsets, replacementText};
    }

    for (const bodyNode of body.childNodes || []) {
      if (bodyNode.nodeName.startsWith('#') || bodyNode.tagName === 'script') {
        continue;
      }
      const offsets = htmlDocument.sourceRangeToOffsets(
          htmlDocument.sourceRangeForNode(bodyNode)!);
      const scriptTag = parse5.parseFragment(`<script type="module"></script>`)
                            .childNodes![0];
      const program =
          jsc.program(createDomNodeInsertStatements([bodyNode], true));
      dom5.setTextContent(
          scriptTag,
          EOL +
              recast
                  .print(
                      program, {quote: 'single', wrapColumn: 80, tabWidth: 2})
                  .code +
              EOL);
      let replacementText = serializeNode(scriptTag);
      if (first) {
        replacementText = apology + replacementText;
        first = false;
      }
      yield {offsets, replacementText};
    }
  }
開發者ID:,項目名稱:,代碼行數:78,代碼來源:

示例7: convertTopLevelHtmlDocument

  /**
   * Convert a document to a top-level HTML document.
   */
  convertTopLevelHtmlDocument(namespacedExports: Map<string, JsExport>):
      ConversionResult {
    const htmlDocument = this.document.parsedDocument as ParsedHtmlDocument;
    const p = dom5.predicates;

    const edits: Array<Edit> = [];
    for (const script of this.document.getFeatures({kind: 'js-document'})) {
      if (!script.astNode ||
          !isLegacyJavaScriptTag(script.astNode.node as parse5.ASTNode)) {
        continue;  // ignore unknown script tags and preexisting modules
      }
      const astNode = script.astNode.node as parse5.ASTNode;
      const sourceRange =
          script.astNode ? htmlDocument.sourceRangeForNode(astNode) : undefined;
      if (!sourceRange) {
        continue;  // nothing we can do about scripts without known positions
      }
      const offsets = htmlDocument.sourceRangeToOffsets(sourceRange);

      const file = recast.parse(script.parsedDocument.contents);
      const program = this.rewriteInlineScript(file.program, namespacedExports);

      if (program === undefined) {
        continue;
      }

      const newScriptTag =
          parse5.treeAdapters.default.createElement('script', '', []);
      dom5.setAttribute(newScriptTag, 'type', 'module');
      dom5.setTextContent(
          newScriptTag,
          EOL +
              recast
                  .print(
                      program, {quote: 'single', wrapColumn: 80, tabWidth: 2})
                  .code +
              EOL);
      const replacementText = serializeNode(newScriptTag);
      edits.push({offsets, replacementText});
    }

    const demoSnippetTemplates = dom5.nodeWalkAll(
        htmlDocument.ast,
        p.AND(
            p.hasTagName('template'),
            p.parentMatches(p.hasTagName('demo-snippet'))));
    const scriptsToConvert = [];
    for (const demoSnippetTemplate of demoSnippetTemplates) {
      scriptsToConvert.push(...dom5.nodeWalkAll(
          demoSnippetTemplate,
          p.hasTagName('script'),
          [],
          dom5.childNodesIncludeTemplate));
    }

    for (const astNode of scriptsToConvert) {
      if (!isLegacyJavaScriptTag(astNode)) {
        continue;
      }
      const sourceRange =
          astNode ? htmlDocument.sourceRangeForNode(astNode) : undefined;
      if (!sourceRange) {
        continue;  // nothing we can do about scripts without known positions
      }
      const offsets = htmlDocument.sourceRangeToOffsets(sourceRange);

      const file = recast.parse(dom5.getTextContent(astNode));
      const program = this.rewriteInlineScript(file.program, namespacedExports);

      if (program === undefined) {
        continue;
      }

      const newScriptTag =
          parse5.treeAdapters.default.createElement('script', '', []);
      dom5.setAttribute(newScriptTag, 'type', 'module');
      dom5.setTextContent(
          newScriptTag,
          EOL +
              recast
                  .print(
                      program, {quote: 'single', wrapColumn: 80, tabWidth: 2})
                  .code +
              EOL);
      const replacementText = serializeNode(newScriptTag);
      edits.push({offsets, replacementText});
    }

    for (const htmlImport of this.getHtmlImports()) {
      // Only replace imports that are actually in the document.
      if (!htmlImport.sourceRange) {
        continue;
      }
      const offsets = htmlDocument.sourceRangeToOffsets(htmlImport.sourceRange);

      const htmlDocumentUrl =
          this.urlHandler.getDocumentUrl(htmlImport.document);
//.........這裏部分代碼省略.........
開發者ID:,項目名稱:,代碼行數:101,代碼來源:


注:本文中的dom5.nodeWalk函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。