Shopify / theme-tools

Everything developer experience for Shopify themes
https://shopify.dev/docs/themes
MIT License
48 stars 14 forks source link

Add working example to custom check documentation #366

Open eloyesp opened 1 month ago

eloyesp commented 1 month ago

I've been trying to add some custom checks to my theme, but I could not make it work. I found different issues while trying to make this work, mainly because how the file is being loaded.

Currently the documentation on custom checks is pretty minimal, and point to the existing checks to get ideas, but as far as I could test the syntax used is not exactly the same.

I think that a small working example, would be of great help, and it would be even better if you provide examples both in typescript and plain javascript just in case.

lukeh-shopify commented 1 month ago

👋🏻 Hi @eloyesp, thanks for the issue!

I think this is a good suggestion, and will take this back to the team to discuss. I'll update this if we have anything we can/decide to add something.

eloyesp commented 1 month ago

This is the first working version of a sample that works that I could get.

const {
  Severity,
  SourceCodeType,
} = require("@shopify/theme-check-common/dist/types")
const {
  isAttr,
  isValuedHtmlAttribute,
} = require("@shopify/theme-check-common/dist/checks/utils")

const ImgWidth = {
  meta: {
    code: "MissingImgWidth",
    aliases: ["img_width"],
    name: "Width attributes on image tags",
    docs: {
      description:
        "This check is aimed at eliminating content layout shift in themes by enforcing the use of the width and height attributes on img tags.",
      recommended: true,
      url: "https://shopify.dev/docs/themes/tools/theme-check/checks/img-width-and-height",
    },
    type: SourceCodeType.LiquidHtml,
    severity: Severity.ERROR,
    schema: {},
    targets: [],
  },

  create(context) {
    return {
      async HtmlVoidElement(node) {
        if (node.name === "img") {
          const widthAttr = node.attributes.find(
            (attr) => isValuedHtmlAttribute(attr) && isAttr(attr, "width"),
          )

          if (!widthAttr) {
            context.report({
              message: `Missing width on img tag`,
              startIndex: node.position.start,
              endIndex: node.position.end,
            })
          }
        }
      },
    }
  },
}

module.exports.checks = [ImgWidth]