Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript refactoring #14

Open
ramblehead opened this issue Jan 31, 2023 · 0 comments
Open

Typescript refactoring #14

ramblehead opened this issue Jan 31, 2023 · 0 comments

Comments

@ramblehead
Copy link

Thank you for sharing rehype-img-size!

I needed to do some additional transformations to src attribute of img tags and I am using typescript, so I have done a bit of refactoring to rehype-img-size plugin:

import path from 'path';
import { visit } from 'unist-util-visit';
import sizeOf from 'image-size';

import type { Plugin } from 'unified';
import type { Node } from 'unist';

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const getImageSize = (src: string, dir: string) => {
  // Handles "//" such as "http://" "https://" "ftp://"
  if (src.match(/^(?:[a-z]+:)?\/\//)) {
    return undefined;
  }

  // Treat `/` as a relative path, according to the server
  const shouldJoin = !path.isAbsolute(src) || src.startsWith('/');

  let srcPath = src;

  if (dir && shouldJoin) {
    srcPath = path.join(dir, src);
  }

  return sizeOf(srcPath);
};

interface TagNode extends Node {
  tagName: '';
}

interface ImgNode extends Node {
  tagName: 'img';
  properties: {
    src: string;
    width: number;
    height: number;
  };
}

type ElementNode = TagNode | ImgNode;

type PluginParameters = [
  {
    dir: string;
  },
];

const rehypeImgSize: Plugin<PluginParameters> = ({ dir }) => {
  return (tree, _file) => {
    visit(tree, 'element', (node: ElementNode) => {
      if (node.tagName === 'img') {
        const { src } = node.properties;
        const dimensions = getImageSize(src, dir);
        node.properties.width = dimensions?.width ?? 0;
        node.properties.height = dimensions?.height ?? 0;
      }
    });
  };
};

export default rehypeImgSize;

I wonder if there is an interest in updating this project to typescript either as the code above or in jsdoc syntax flavour? In either syntax typescript can automatically generate typings and replace some unit testes by compile-time checks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant