DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on

VSCode custom code snippets in Inbox Zero codebase.

In this article, we review the custom code snippets defined in the Inbox Zero codebase. We will look at:

  1. Code snippets in VSCode

  2. Inbox Zero custom code snippets

Code snippets in VSCode

Code snippets are templates that make it easier to enter repeating code patterns, such as loops or conditional-statements.

In Visual Studio Code, snippets appear in IntelliSense (⌃Space) mixed with other suggestions, as well as in a dedicated snippet picker (Insert Snippet in the Command Palette). There is also support for tab-completion: Enable it with "editor.tabCompletion": "on", type a snippet prefix (trigger text), and press Tab to insert a snippet.

The snippet syntax follows the TextMate snippet syntax with the exceptions of ‘interpolated shell code’ and the use of \u; both are not supported.

I checked out the VSCode documentation about creating your own snippets. You can easily define your own snippets without any extension. To create or edit your own snippets, select Configure Snippets under Code > Settings, and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages. VS Code manages the creation and refreshing of the underlying snippets file(s) for you.

Obviously there is a lot of information in the documentation, but we want to focus on Project snippet scope since this is used in the Inbox Zero codebase.

Project snippet scope

You can also have a global snippets file (JSON with file suffix .code-snippets) scoped to your project. Project-folder snippets are created with the New Snippets file for ''... option in the Snippets: Configure Snippets dropdown menu and are located at the root of the project in a .vscode folder. Project snippet files are useful for sharing snippets with all users working in that project. Project-folder snippets are similar to global snippets and can be scoped to specific languages through the scope property.

Below is a snippet syntax example:

{
  "hello": {
    "scope": "javascript,html",
    "prefix": "hello",
    "body": "$BLOCK_COMMENT_START Hello World $BLOCK_COMMENT_END"
  }
}
Enter fullscreen mode Exit fullscreen mode

Learn more about Project snippet scope.

Inbox Zero custom code snippets

inbox-zero/.vscode/typescriptreact.code-snippets has about 404 LOC at the time of writing this article. 

Based on what we just learnt above, these are project snippet scopes define, with the extention, .code-snippets I picked about two examples from this inbox-zero file, but be sure to look at the other code snippets defined.

The examples I chose are:

  1. React Hook Form

  2. Next API Post Route

React Hook Form

"React Hook Form": {
    "prefix": "rhf",
    "body": [
      "import { useCallback } from 'react';",
      "import { SubmitHandler, useForm } from 'react-hook-form';",
      "import { Button } from '@/components/Button';",
      "import { Input } from '@/components/Input';",
      "import { toastSuccess, toastError } from '@/components/Toast';",
      "import { isErrorMessage } from '@/utils/error';",
      "",
      "type Inputs = { address: string };",
      "",
      "const ${1:${TM_FILENAME_BASE/(^[a-zA-Z])(.*)/${1:/upcase}${2}/}}Form = () => {",
      "  const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<Inputs>();",
      "",
      "  const onSubmit: SubmitHandler<Inputs> = useCallback(",
      "    async data => {",
      "      const res = await updateProfile(data)",
      "      if (isErrorMessage(res)) toastError({ description: `` });",
      "      else toastSuccess({ description: `` });",
      "    },",
      "    []",
      "  );",
      "",
      "  return (",
      "    <form onSubmit={handleSubmit(onSubmit)} className=\"space-y-4\">",
      "      <Input",
      "        type=\"text\"",
      "        name=\"address\"",
      "        label=\"Address\"",
      "        registerProps={register('address', { required: true })}",
      "        error={errors.address}",
      "      />",
      "      <Button type=\"submit\" loading={isSubmitting}>",
      "        Add",
      "      </Button>",
      "    </form>",
      "  );",
      "}"
    ]
  },
Enter fullscreen mode Exit fullscreen mode

Next API Post Route

 "Next API POST Route": {
    "prefix": "napip",
    "body": [
      "import { z } from \"zod\";",
      "import { NextResponse } from \"next/server\";",
      "import { auth } from \"@/app/api/auth/[...nextauth]/auth\";",
      "import prisma from \"@/utils/prisma\";",
      "import { withAuth } from \"@/utils/middleware\";",
      "",
      "const ${1:ApiName}Body = z.object({ id: z.string(), message: z.string() });",
      "export type ${1/(.*)/${1:/downcase}/}Body = z.infer<typeof ${1:ApiName}Body>;",
      "export type update${1:ApiName}Response = Awaited<ReturnType<typeof update${1:ApiName}>>;",
      "",
      "async function update${1:ApiName}(body: ${1/(.*)/${1:/downcase}/}Body, options: { email: string }) {",
      "  const { email } = options;",
      "  const result = await prisma.${2:table}.update({",
      "    where: {",
      "      id: body.id,",
      "      email,",
      "    },",
      "    data: body",
      "  })",
      "",
      "  return { result };",
      "};",
      "",
      "export const POST = withAuth(async (request: Request) => {",
      "  const json = await request.json();",
      "  const body = ${1/(.*)/${1:/downcase}/}Body.parse(json);",
      "",
      "  const result = await update${1:ApiName}(body, { email: session.user.email });",
      "",
      "  return NextResponse.json(result);",
      "});",
      ""
    ],
    "description": "Next API POST Route"
  },
  //#endregion  //*======== Nextjs ===========
Enter fullscreen mode Exit fullscreen mode

Oh btw, Elie commented this at the top of this file

// based on: 
// https://github.com/theodorusclarence/ts-nextjs-tailwind-starter/blob/main/.vscode/typescriptreact.code-snippets
Enter fullscreen mode Exit fullscreen mode

This is a common practice I found in OSS, to leave a reference to other OSS projects when they are used as an inspiration.

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

I spent 200+ hours analyzing Supabase, shadcn/ui, LobeChat. Found the patterns that separate AI slop from production code. Stop refactoring AI slop. Start with proven patterns. Check out production-grade projects at thinkthroo.com

References:

  1. https://code.visualstudio.com/../userdefinedsnippets#_create-your-own-snippets

  2. https://code.visualstudio.com/../userdefinedsnippets#_project-snippet-scope

  3. elie222/inbox-zero/../.vscode/typescriptreact.code-snippets

Top comments (0)