unified#Plugin TypeScript Examples

The following examples show how to use unified#Plugin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: wikiLinks.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
plugin: Plugin<[CompilerOpts?]> = function (
  this: Unified.Processor,
  opts?: PluginOpts
) {
  attachParser(this);
  if (this.Compiler != null) {
    attachCompiler(this, opts);
  }
}
Example #2
Source File: index.ts    From uniorg with GNU General Public License v3.0 6 votes vote down vote up
uniorgSlug: Plugin<[Options?]> = (options: Options = {}) => {
  return transformer;

  function transformer(tree: Node, _file: VFile) {
    const slugger = new GithubSlugger();

    visit(tree, 'section', (section: Section) => {
      const headline = section.children[0] as Headline;
      const data: any = (headline.data = headline.data || {});
      const props = (data.hProperties = data.hProperties || {});

      if (!props.id) {
        const id = customId(section) ?? slugger.slug(toString(headline));
        props.id = id;
      }
    });
  }
}
Example #3
Source File: index.ts    From uniorg with GNU General Public License v3.0 6 votes vote down vote up
extractKeywords: Plugin<[Options?]> = (options: Options = {}) => {
  return transformer;

  function transformer(tree: Node, file: VFile) {
    visit(tree, 'keyword', (kw: Keyword) => {
      let data: any = (file.data = file.data || {});
      if (options.name) {
        data = data[options.name] = data[options.name] || {};
      }

      let key = kw.key;
      if (!options.preserveCase) {
        key = key.toLowerCase();
      }

      data[key] = kw.value;
    });
  }
}
Example #4
Source File: index.ts    From uniorg with GNU General Public License v3.0 6 votes vote down vote up
uniorgAttach: Plugin<[Partial<Options>?]> = (
  options: Partial<Options> = {}
) => {
  const opts = { ...defaultOptions, ...options };
  return transformer;

  function transformer(tree: Node, file: VFile) {
    visitParents(tree, 'link', (link: Link, ancestors) => {
      if (link.linkType === 'attachment') {
        const path = resolveAttachmentPath(link, ancestors, file, opts);
        link.linkType = 'file';
        link.path = path;
        link.rawLink = link.linkType + ':' + link.path;
      }
    });
  }
}
Example #5
Source File: slate0.47-to-remark.ts    From remark-slate-transformer with MIT License 6 votes vote down vote up
plugin: Plugin<[]> = function () {
  return function (node) {
    return slateToMdast(
      {
        type: "root",
        children: slate047ToSlate((node as any).children),
      },
      {}
    );
  };
}
Example #6
Source File: userTags.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
plugin: Plugin<[PluginOpts?]> = function plugin(
  this: Unified.Processor,
  opts?: PluginOpts
) {
  attachParser(this);
  if (this.Compiler != null) {
    attachCompiler(this, opts);
  }
}
Example #7
Source File: hashtag.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
plugin: Plugin<[PluginOpts?]> = function plugin(
  this: Unified.Processor,
  opts?: PluginOpts
) {
  attachParser(this);
  if (this.Compiler != null) {
    attachCompiler(this, opts);
  }
}
Example #8
Source File: extendedImage.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
plugin: Plugin<[PluginOpts?]> = function (
  this: Unified.Processor,
  opts?: PluginOpts
) {
  attachParser(this);
  if (this.Compiler != null) {
    attachCompiler(this, opts);
  }
}
Example #9
Source File: blockAnchors.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
plugin: Plugin<[PluginOpts?]> = function (
  this: Unified.Processor,
  opts?: PluginOpts
) {
  attachParser(this);
  if (this.Compiler != null) {
    attachCompiler(this, opts);
  }
}
Example #10
Source File: noteRefsV2.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
plugin: Plugin = function (this: Unified.Processor, opts?: PluginOpts) {
  const procOptsV5 = MDUtilsV5.getProcOpts(this);

  attachParser(this);
  if (this.Compiler != null && !procOptsV5.parseOnly) {
    attachCompiler(this, opts);
  }
}
Example #11
Source File: remark.ts    From vite-plugin-md-preview with MIT License 5 votes vote down vote up
export function remarkVue(options: RemarkVueOptions): Plugin {
  const { file, root, highlighter, remove, update } = options

  const resolve = (...args: string[]) => {
    let ret = path.resolve(path.dirname(file), ...args)
    ret = path.relative(root, ret)
    return `/${ret}`
  }
  function transformer(tree): Transformer {
    const oldBlocks = fileCodeMap.get(file) || []
    const blocks: CodeBlock[] = []
    visit(tree, 'code', (node: Code, i: number, parent: Parent) => {
      const attrs = (node.meta || '').split(' ').reduce((prev, curr) => {
        const [key, value] = curr.split('=')
        if (typeof value === 'undefined') {
          prev[key] = true
        } else {
          prev[key] = value
        }
        return prev
      }, {} as Record<string, string | boolean>)

      if (node.lang === 'vue' && attrs['preview']) {
        const name = `VueCode${md5(file).substr(0, 8)}I${i}`
        const component = typeof attrs['preview'] === 'string' ? attrs['preview'] : 'VueCode'
        const code = highlighter(node.value)
        blocks.push({ name, path: resolve(`./${name}.vue`), code: node.value })
        const demoNode: HTML = {
          type: 'html',
          value: `<${component} source="${encodeURIComponent(code)}">
  <${name} />
</${component}>`,
        }
        parent.children.splice(i, 1, demoNode)
      }
    })
    const names = blocks.map(i => i.name)
    remove(oldBlocks)
    fileCodeMap.set(file, names)
    update(blocks)

    const imports = names.reduce((prev, curr) => {
      return `${prev}import ${curr} from "${resolve(`./${curr}.vue`)}"\n`
    }, '')
    const script = `<script setup>\n${imports}</script>`
    tree.children.splice(0, 0, { type: 'html', value: script })
    return tree
  }

  return transformer
}
Example #12
Source File: remark-to-slate.ts    From remark-slate-transformer with MIT License 5 votes vote down vote up
plugin: Plugin<[Options?]> = function ({ overrides = {} } = {}) {
  this.Compiler = function (node) {
    return mdastToSlate(node as any, overrides);
  };
}
Example #13
Source File: remark-to-slate0.47.ts    From remark-slate-transformer with MIT License 5 votes vote down vote up
plugin: Plugin<[]> = function () {
  this.Compiler = function (node) {
    return slateToSlate047(mdastToSlate(node as any, {}) as SlateNode[]);
  };
}
Example #14
Source File: slate-to-remark.ts    From remark-slate-transformer with MIT License 5 votes vote down vote up
plugin: Plugin<[Options?]> = ({ overrides = {} } = {}) => {
  return function (node) {
    return slateToMdast(node as any, overrides);
  };
}
Example #15
Source File: unified-org-rehype.ts    From uniorg with GNU General Public License v3.0 5 votes vote down vote up
org2rehype: Plugin<[Options?], OrgData, Root> = function org2rehype(
  options: Options = {}
) {
  return (node, _file) => {
    return orgToHast(node, options) as Root;
  };
}
Example #16
Source File: hierarchies.ts    From dendron with GNU Affero General Public License v3.0 4 votes vote down vote up
plugin: Plugin = function (this: Unified.Processor, _opts?: PluginOpts) {
  const proc = this;
  const { config } = MDUtilsV5.getProcData(this);
  let hierarchyDisplayTitle = config?.hierarchyDisplayTitle || "Children";
  let hierarchyDisplay = config?.hierarchyDisplay;

  if (MDUtilsV5.shouldApplyPublishingRules(proc)) {
    const hierarchyConfigForPublishing =
      ConfigUtils.getHierarchyDisplayConfigForPublishing(config);
    hierarchyDisplay = hierarchyConfigForPublishing.hierarchyDisplay;
    if (!_.isUndefined(hierarchyConfigForPublishing.hierarchyDisplayTitle)) {
      hierarchyDisplayTitle =
        hierarchyConfigForPublishing.hierarchyDisplayTitle;
    }
  }

  if (hierarchyDisplay === undefined) hierarchyDisplay = true;

  function transformer(tree: Node): void {
    const root = tree as Root;
    const { fname, vault, dest, config, insideNoteRef } =
      MDUtilsV4.getDendronData(proc);
    let addedBreak = false;

    if (dest !== DendronASTDest.HTML) {
      return;
    }
    // TODO: remove
    if (!hierarchyDisplay) {
      return;
    }

    function addBreak() {
      if (addedBreak) return;
      root.children.push({
        type: "thematicBreak",
      });
      addedBreak = true;
    }

    function addFootnotes() {
      /** Maps footnote identifiers to their definitions. */
      const footnotes = new Map(
        RemarkUtils.extractFootnoteDefs(root).map((definition) => [
          definition.identifier,
          definition,
        ])
      );
      /** All footnote definitions that have been referenced in this document. */
      const usedFootnotes = new Set<FootnoteDefinition>();
      visit(
        root,
        [DendronASTTypes.FOOTNOTE_REFERENCE],
        (reference: FootnoteReference, index, parent) => {
          const definition = footnotes.get(reference.identifier);
          if (definition && parent) {
            parent.children[index] = footnote2html(reference);
            usedFootnotes.add(definition);
          }
        }
      );
      if (usedFootnotes.size > 0) {
        addBreak();
        root.children.push(heading(2, text("Footnotes")) as Content);
        const footnoteItems: Node[] = [];
        for (const definition of usedFootnotes) {
          footnoteItems.push(listItem(footnoteDef2html(definition)));
        }
        root.children.push(list("ordered", footnoteItems) as Content);
      }
    }

    if (!fname || insideNoteRef) {
      // Even inside a note ref, render footnotes because we want them in there too
      addFootnotes();
      return;
    }

    const { engine } = MDUtilsV4.getEngineFromProc(proc);
    const note = NoteUtils.getNoteByFnameFromEngine({
      fname,
      engine,
      vault: vault!,
    });

    // check if v5 is active
    if (MDUtilsV5.isV5Active(proc)) {
      const resp = MDUtilsV5.getProcData(proc);
      hierarchyDisplay = ConfigUtils.getEnableChildLinks(resp.config, { note });
    }

    /** Add frontmatter tags, if any, ahead of time. This way wikilink compiler will pick them up and render them. */
    function addTags() {
      const shouldApplyPublishRules =
        MDUtilsV5.shouldApplyPublishingRules(proc);
      const enableFrontmatterTags = ConfigUtils.getEnableFrontmatterTags({
        config,
        shouldApplyPublishRules,
      });
      const enableHashesForFMTags = ConfigUtils.getEnableHashesForFMTags({
        config,
        shouldApplyPublishRules,
      });
      if (
        enableFrontmatterTags !== false &&
        note?.tags &&
        note.tags.length > 0
      ) {
        addBreak();
        root.children.push(heading(2, text("Tags")) as Content);
        const tags = _.isString(note.tags) ? [note.tags] : note.tags;
        const tagLinks = _.sortBy(
          _.map(tags, (tag) =>
            listItem(
              paragraph(
                frontmatterTag2WikiLinkNoteV4(tag, enableHashesForFMTags)
              )
            )
          ),
          ["custom.nav_order", "title"]
        );
        root.children.push(list("ordered", tagLinks) as Content);
      }
    }

    function addChildren() {
      // don't include if collection present
      if (!note || note.children.length <= 0 || note?.custom?.has_collection) {
        return;
      }
      if (
        _.isBoolean(note.custom?.hierarchyDisplay) &&
        !note.custom.hierarchyDisplay
      ) {
        return;
      }
      const children = HierarchyUtils.getChildren({
        skipLevels: note.custom?.skipLevels || 0,
        note,
        notes: engine.notes,
      })
        .filter((note) => SiteUtils.canPublish({ note, engine, config }))
        .filter(
          (note) =>
            _.isUndefined(note.custom?.nav_exclude) || !note.custom?.nav_exclude
        );

      if (!_.isEmpty(children)) {
        addBreak();
        root.children.push(
          u("strong", [{ type: "text", value: hierarchyDisplayTitle }])
        );
        root.children.push(
          list(
            "ordered",
            _.sortBy(children, ["custom.nav_order", "title"]).map((note) => {
              return listItem(
                paragraph({
                  type: DendronASTTypes.WIKI_LINK,
                  value: note.fname,
                  data: {
                    alias: note.title,
                    vaultName: VaultUtils.getName(note.vault),
                  },
                  children: [],
                } as WikiLinkNoteV4)
              );
            })
          ) as Content
        );
      }
    }

    // Will appear on page in this order
    if (hierarchyDisplay) {
      addChildren();
    }
    addTags();
    addFootnotes();

    // end transformer
  }
  return transformer;
}
Example #17
Source File: backlinks.ts    From dendron with GNU Affero General Public License v3.0 4 votes vote down vote up
plugin: Plugin = function (this: Unified.Processor) {
  const proc = this;
  function transformer(tree: Node): void {
    const root = tree as Root;
    let fname: string;
    let vault: DVault;
    let dest: DendronASTDest;
    let insideNoteRef: boolean | undefined;
    let config: IntermediateDendronConfig;
    let engine: DEngineClient;

    if (MDUtilsV5.isV5Active(proc)) {
      ({ fname, vault, dest, insideNoteRef, config, engine } =
        MDUtilsV5.getProcData(proc));
    } else {
      ({ fname, vault, dest, insideNoteRef, config } =
        MDUtilsV4.getDendronData(proc));
      engine = MDUtilsV4.getEngineFromProc(proc).engine;
    }

    // Don't show backlinks for the following cases:
    // - we are inside a note ref
    // - the destination isn't HTML
    // - the note can't be found
    // - neableChild links is toggled off
    // enableBackLinks is set to false
    if (!fname || insideNoteRef) {
      return;
    }
    if (dest !== DendronASTDest.HTML) {
      return;
    }

    const note = NoteUtils.getNoteByFnameFromEngine({ fname, vault, engine });
    if (_.isUndefined(note)) {
      return;
    }

    if (
      ConfigUtils.getEnableBackLinks(config, {
        note,
        shouldApplyPublishingRules: MDUtilsV5.shouldApplyPublishingRules(proc),
      }) === false
    ) {
      return;
    }

    const backlinks = _.uniqBy(
      (note?.links || []).filter((ent) => ent.type === "backlink"),
      (ent) => ent.from.fname + (ent.from.vaultName || "")
    );

    const backlinksToPublish = _.filter(backlinks, (backlink) => {
      const vaultName = backlink.from.vaultName!;
      const vault = VaultUtils.getVaultByName({
        vaults: engine.vaults,
        vname: vaultName,
      })!;
      const note = NoteUtils.getNoteByFnameFromEngine({
        fname: backlink.from.fname!,
        engine,
        vault,
      });

      if (!note) {
        return false;
      }
      const out = SiteUtils.canPublish({
        note,
        engine,
        config: engine.config,
      });
      return out;
    });

    if (!_.isEmpty(backlinksToPublish)) {
      root.children.push({
        type: "thematicBreak",
      });
      root.children.push(u("strong", [{ type: "text", value: "Backlinks" }]));
      root.children.push(
        list(
          "unordered",
          backlinksToPublish.map((mdLink) => {
            let alias;
            const note = NoteUtils.getNoteByFnameFromEngine({
              fname: mdLink.from.fname!,
              vault: VaultUtils.getVaultByName({
                vaults: engine.vaults,
                vname: mdLink.from.vaultName!,
              })!,
              engine,
            });

            if (note) {
              alias =
                note.title +
                (engine.vaults.length > 1
                  ? ` (${mdLink.from.vaultName!})`
                  : "");
            } else {
              alias = `Unable to find backlinked note ${mdLink.from.fname!}.`;
            }
            return listItem(
              paragraph({
                type: DendronASTTypes.WIKI_LINK,
                value: mdLink.from.fname,
                data: {
                  alias,
                  vaultName: mdLink.from.vaultName!,
                },
                children: [],
              } as WikiLinkNoteV4)
            );
          })
        ) as Content
      );
    }

    // end transformer
  }
  return transformer;
}