All files / src/doc-listener process.ts

90.29% Statements 121/134
90.9% Branches 30/33
88.88% Functions 8/9
90.29% Lines 121/134

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1351x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 1x 1x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 9x                       9x 1x 1x 1x 9x 8x 7x 8x 1x 1x 1x 1x 1x 1x 1x 1x 4x 3x 3x 3x 1x 8x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 8x 9x 1x 1x 9x 9x 9x 3x 3x 3x 11x 3x 3x 3x 9x 9x 9x 3x 3x 3x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 15x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x  
import { isNone, isSome, some } from 'fp-ts/Option';
import { State, StateKey, update } from '../utils/state';
import * as htmlparser2 from 'htmlparser2';
import { Memento, Uri, WebviewPanel } from 'vscode';
import { join } from 'path';
import { setError, setParsedDoc } from '../utils/actions';
import { isExternal } from '../utils';
import { ListenerOpts } from './listener';
 
// TODO: this is not exhaustive
const transformTags = ['a', 'img', 'link', 'script'];
const selfClosing = ['br', 'img', 'input', 'link', 'meta'];
let buf = '';
const resetBuf = () => (buf = '<!DOCTYPE html>');
 
const pathFromRelative = (relPath: string, srcPath: string): Uri => {
  const newPath = join(srcPath, relPath);
 
  return Uri.file(newPath);
};
 
const escapeHtml = (unsafe: string) => {
  return unsafe
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
};
 
const rustDocVarAttributes = {
  dataRootPath: 'data-root-path',
  dataSearch: 'data-search-js',
  dataSearchIndex: 'data-search-index-js',
  dataSettingsCss: `data-settings-css`,
  dataSettingsJs: 'data-settings-js',
  dataStaticRootPath: 'data-static-root-path',
} as const;
const getParser = (view: WebviewPanel, srcPath: string, extensionPath: string, workspaceState: Memento) =>
  new htmlparser2.Parser({
    onopentag(name, attributes) {
      if (name === 'head') {
        const localScriptUri = view.webview.asWebviewUri(
          Uri.file(join(extensionPath, 'out', 'client', 'clientHandler.js'))
        );
        const historyStylesUri = view.webview.asWebviewUri(
          Uri.file(join(extensionPath, 'out', 'client', 'clientHandlerStyles.css'))
        );
        buf = [
          `${buf}<${name}>`,
          `<script src="${localScriptUri.toString(true)}"></script>`,
          `<link rel="stylesheet" type="text/css" href=${historyStylesUri}>`,
        ].join('');
      } else if (name === 'body') {
        let stateRaw: string = workspaceState.get('rustDocViewer', '{}');
        buf = [`${buf}<${name}>`, `<div id="doc-viewer-state" data-state=${stateRaw}></div>`].join('');
        // search depends on a div containing path for search js, and base uri's
      } else if (
        (name === 'div' && attributes['id'] === 'rustdoc-vars') ||
        (name === 'meta' && attributes['name'] === 'rustdoc-vars')
      ) {
        const hasRootPath = Boolean(attributes[rustDocVarAttributes.dataStaticRootPath]);
        const keys = [
          rustDocVarAttributes.dataRootPath,
          hasRootPath ? false : rustDocVarAttributes.dataSearch,
          rustDocVarAttributes.dataSearchIndex,
          rustDocVarAttributes.dataStaticRootPath,
        ].filter((x) => x);
        keys.forEach((key) => {
          if (typeof key === 'string' && attributes[key]) {
            const path = pathFromRelative(attributes[key], srcPath);
            attributes[key] = view.webview.asWebviewUri(path).toString(true);
          }
        });
      } else if (transformTags.includes(name)) {
        const uriAttr = attributes['src'] ? 'src' : 'href';
        if (
          attributes[uriAttr] &&
          !isExternal(attributes[uriAttr]) &&
          !attributes[uriAttr].includes('javascript:void')
        ) {
          const uri = view.webview.asWebviewUri(pathFromRelative(attributes[uriAttr], srcPath));
          attributes[uriAttr] = uri.toString(true);
        }
      }
 
      const serializedAttrs = Object.entries(attributes).reduce((attrs, [attrName, attrVal]) => {
        if (attrVal) {
          return [...attrs, `${attrName}="${attrVal}"`];
        } else {
          return [...attrs, attrName];
        }
      }, [] as string[]);
      const newTag = serializedAttrs.length > 0 ? `<${name} ${serializedAttrs.join(' ')}>` : `<${name}>`;
      buf = `${buf}${newTag}`;
    },
 
    ontext(text) {
      buf = `${buf}${escapeHtml(text)}`;
    },
 
    onclosetag(name) {
      if (!selfClosing.includes(name)) {
        buf = `${buf}</${name}>`;
      }
    },
 
    onerror(err) {
      update(setError([err.message]));
    },
  });
 
type ProcessListenerOpts = ListenerOpts<
  Pick<State, StateKey.configuration | StateKey.pageKey | StateKey.parsedDoc | StateKey.rawDoc>
> & {
  view: WebviewPanel;
  workspaceState: Memento;
};
 
export const processListener = ({ slice, view, workspaceState }: ProcessListenerOpts) =>
  slice.subscribe(({ configuration, pageKey, parsedDoc, rawDoc }) => {
    if (isNone(parsedDoc) && isSome(rawDoc) && isSome(configuration) && isSome(configuration.value.docsPath)) {
      resetBuf();
      const parser = getParser(
        view,
        configuration.value.docsPath.value,
        configuration.value.extensionPath,
        workspaceState
      );
      parser.write(rawDoc.value);
      parser.end();
      update(setParsedDoc(some(buf)));
    }
  });