├── .gitattributes ├── .github └── workflows │ └── build.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── snippets.code-snippets ├── .vscodeignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── icon.jpg ├── img └── Sreenshot.png ├── package-lock.json ├── package.json ├── scripts └── generateREADME.ts ├── src ├── components │ └── rnpButton.ts ├── extension.ts ├── getExistingImports.ts ├── snip.ts ├── snippets.ts └── utils.ts ├── tsconfig.json └── typings ├── nyc └── index.d.ts └── require-glob └── index.d.ts /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behavior to automatically normalize line endings. 2 | * text=auto 3 | 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy next to release 2 | on: 3 | push: 4 | branches: 5 | - next 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | with: 12 | persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal token 13 | fetch-depth: 0 # otherwise, you will failed to push refs to dest repo 14 | - name: Setup Node.js Env 15 | uses: actions/setup-node@v2 16 | with: 17 | node-version: "14" 18 | - name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built. 19 | run: | 20 | yarn 21 | yarn build 22 | - name: Create local changes 23 | run: | 24 | git add . 25 | - name: Commit files 26 | run: | 27 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" 28 | git config --local user.name "github-actions[bot]" 29 | git commit -m "New build" -a 30 | - name: Push changes 31 | uses: ad-m/github-push-action@master 32 | with: 33 | github_token: ${{ secrets.GITHUB_TOKEN }} 34 | branch: release 35 | force: true 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.vsix 3 | build/ -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "runtimeExecutable": "${execPath}", 13 | "args": [ 14 | "--extensionDevelopmentPath=${workspaceFolder}" 15 | ], 16 | "outFiles": [ 17 | "${workspaceFolder}/build/**/*.js" 18 | ], 19 | // "preLaunchTask": "npm: prebuild" 20 | }, 21 | ] 22 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "xd.lastPackage": "/home/arpit/Desktop/work/react/hehe", 3 | "xd.globalEditor": true 4 | } -------------------------------------------------------------------------------- /.vscode/snippets.code-snippets: -------------------------------------------------------------------------------- 1 | { 2 | "Snippet Template": { 3 | "prefix": "snip", 4 | "body": [ 5 | "import snip from '../snip'", 6 | "", 7 | "export const description = '$1'", 8 | "", 9 | "export const docKey = '$2'", 10 | "", 11 | "export const previewURL = '';", 12 | "", 13 | "export const body = snip`", 14 | "$0", 15 | "`" 16 | ] 17 | } 18 | } -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .github/** 3 | .vscode-test/** 4 | .gitignore 5 | src/** 6 | scripts/** 7 | typings/** 8 | tsconfig.json 9 | img/ 10 | docs/ 11 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## [1.0.7] 4 | 5 | - Added More Components 6 | 7 | ## [1.0.6] 8 | 9 | - Added More Components 10 | 11 | ## [1.0.5] 12 | 13 | - Added Automatic Imports 14 | - Added Docs Links 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Arpit Bhalla 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Native Elements Snippets 2 | 3 | ![Visual Studio Marketplace Downloads](https://img.shields.io/visual-studio-marketplace/d/arpitbhalla.rnp-snippets?color=blue&style=flat-square) ![Visual Studio Marketplace Version](https://img.shields.io/visual-studio-marketplace/v/arpitbhalla.rnp-snippets?style=flat-square) ![Visual Studio Marketplace Rating (Stars)](https://img.shields.io/visual-studio-marketplace/stars/arpitbhalla.rnp-snippets?style=flat-square) 4 | 5 | # Features 6 | 7 | - Auto Import Components `(^ Space)` on Mac or `(Ctrl Space)` on Windows, Linux 8 | - Documentation Links 9 | - Visual Preview 10 | 11 | # Snippets 12 | 13 | 14 | 15 | - [`rnpButton`](#rnpbutton) 16 | 17 | ### `rnpButton` 18 | 19 | ##### Button Component 20 | 21 | ``` 22 | 25 | ``` 26 | 27 | 28 | 29 | Thanks to https://github.com/vscodeshift/material-ui-snippets 30 | -------------------------------------------------------------------------------- /icon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arpitBhalla/react-native-paper-vs-code/2cab96655c6ef99ac5d78d91b5957246b403d76b/icon.jpg -------------------------------------------------------------------------------- /img/Sreenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arpitBhalla/react-native-paper-vs-code/2cab96655c6ef99ac5d78d91b5957246b403d76b/img/Sreenshot.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rnp-snippets", 3 | "displayName": "React Native Paper Snippets", 4 | "description": "Cross-platform Material Design for React Native.", 5 | "private": true, 6 | "version": "0.0.1", 7 | "publisher": "arpitBhalla", 8 | "keywords": [ 9 | "snippets", 10 | "react-native", 11 | "react-native-paper" 12 | ], 13 | "contributors": [ 14 | { 15 | "name": "Arpit Bhalla", 16 | "url": "https://github.com/arpitBhalla" 17 | } 18 | ], 19 | "main": "./build/extension.js", 20 | "scripts": { 21 | "build": "ts-node scripts/generateREADME.ts && prettier --write README.md ", 22 | "prerelease": "npm run build && git add . && git commit -m 'PreRelease' && release-it ", 23 | "release": "vsce publish", 24 | "prebuild": "tsc", 25 | "test-compile": "tsc -p ./" 26 | }, 27 | "license": "MIT", 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/arpitBhalla/rnp-snippets" 31 | }, 32 | "icon": "icon.jpg", 33 | "engines": { 34 | "vscode": "^0.10.5" 35 | }, 36 | "categories": [ 37 | "Snippets" 38 | ], 39 | "activationEvents": [ 40 | "onLanguage:javascript", 41 | "onLanguage:javascriptreact", 42 | "onLanguage:typescriptreact" 43 | ], 44 | "contributes": { 45 | "commands": [ 46 | { 47 | "command": "extension.rnpButton", 48 | "title": "Insert Button Component", 49 | "category": "React Native Paper Snippets" 50 | } 51 | ] 52 | }, 53 | "devDependencies": { 54 | "@types/jscodeshift": "^0.11.0", 55 | "@types/react-dom": "^17.0.3", 56 | "@types/shallowequal": "^1.1.1", 57 | "esbuild": "^0.11.18", 58 | "prettier": "^2.2.1", 59 | "release-it": "^14.6.1", 60 | "ts-node": "^9.1.1", 61 | "vsce": "^1.88.0", 62 | "vscode": "^1.1.37" 63 | }, 64 | "dependencies": { 65 | "require-glob": "^3.2.0", 66 | "jscodeshift": "^0.12.0", 67 | "jscodeshift-choose-parser": "^2.0.0", 68 | "shallowequal": "^1.1.0" 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /scripts/generateREADME.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs"; 2 | import * as path from "path"; 3 | import loadSnippets from "../src/snippets"; 4 | import { CompiledSnippet } from "../src/snip"; 5 | 6 | const table: Array = []; 7 | const markdown: Array = []; 8 | const commands: Array> = []; 9 | 10 | const root = path.resolve(__dirname, ".."); 11 | 12 | const headingUrl = (heading: string): string => 13 | "#" + 14 | heading 15 | .replace(/&[^;]+;/g, "") 16 | .replace(/\s+/g, "-") 17 | .replace(/[^-a-z0-9]/gi, "") 18 | .trim() 19 | .toLowerCase(); 20 | 21 | (async () => { 22 | await loadSnippets().then(async (e) => { 23 | for (const snippet of Object.values(e)) { 24 | const { prefix } = snippet; 25 | 26 | commands.push({ 27 | command: `extension.${prefix}`, 28 | title: 29 | "Insert " + 30 | snippet.description.replace(/^\s*React Native Paper\s*/i, "") + 31 | " Component", 32 | category: "React Native Paper Snippets", 33 | }); 34 | 35 | const description = snippet.description.replace( 36 | /^\s*React Native Paper\s*/i, 37 | "" 38 | ); 39 | const heading = `\`${prefix}\``; 40 | table.push(`- [${heading}](${headingUrl(heading)})`); 41 | markdown.push(`### ${heading}`); 42 | markdown.push(`##### ${description} Component`); 43 | if (typeof snippet.body === "function") { 44 | const { parameters } = snippet.body as CompiledSnippet; 45 | if (parameters.has("formControlMode")) { 46 | markdown.push(`#### Controlled`); 47 | markdown.push( 48 | "```\n" + 49 | snippet 50 | .body({ 51 | language: "typescriptreact", 52 | formControlMode: "controlled", 53 | }) 54 | .replace(/^\n|\n$/gm, "") + 55 | "\n```" 56 | ); 57 | markdown.push(`#### Uncontrolled`); 58 | markdown.push( 59 | "```\n" + 60 | snippet 61 | .body({ 62 | language: "typescriptreact", 63 | formControlMode: "uncontrolled", 64 | }) 65 | .replace(/^\n|\n$/gm, "") + 66 | "\n```" 67 | ); 68 | } else { 69 | markdown.push( 70 | "```\n" + 71 | snippet 72 | .body({ 73 | language: "typescriptreact", 74 | formControlMode: "controlled", 75 | }) 76 | .replace(/^\n|\n$/gm, "") + 77 | "\n```" 78 | ); 79 | } 80 | } else { 81 | markdown.push( 82 | "```\n" + snippet.body.replace(/^\n|\n$/gm, "") + "\n```" 83 | ); 84 | } 85 | } 86 | 87 | const packageJsonPath = path.join(root, "package.json"); 88 | const packageJson = require("./../package.json"); 89 | 90 | packageJson.contributes.commands = commands; 91 | fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2)); 92 | 93 | const readmePath = path.join(root, "README.md"); 94 | 95 | const oldReadme = fs.readFileSync(readmePath, "utf8"); 96 | const startComment = //.exec(oldReadme); 97 | const endComment = //.exec(oldReadme); 98 | if (startComment && endComment && endComment.index > startComment.index) { 99 | const newReadme = `${oldReadme.substring( 100 | 0, 101 | startComment.index + startComment[0].length 102 | )} 103 | ${table.join("\n")} 104 | ${markdown.join("\n\n")} 105 | ${oldReadme.substring(endComment.index)}`; 106 | 107 | if (newReadme !== oldReadme) { 108 | fs.writeFileSync(readmePath, newReadme, "utf8"); 109 | } 110 | } 111 | }); 112 | })(); 113 | -------------------------------------------------------------------------------- /src/components/rnpButton.ts: -------------------------------------------------------------------------------- 1 | import snip from "../snip"; 2 | 3 | export const mode = ["text", "outlined", "contained"]; 4 | 5 | export const rounded = [true, false]; 6 | 7 | export const description = `React Native Paper Button`; 8 | 9 | export const body = snip` 10 | 13 | `; 14 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import loadSnippets, { SnippetOptions } from "./snippets"; 3 | import shallowEqual from "shallowequal"; 4 | import getExistingImports from "./getExistingImports"; 5 | import { getSnippetImports } from "./utils"; 6 | class RNPCompletionItem extends vscode.CompletionItem { 7 | imports: string[] | undefined; 8 | } 9 | 10 | export async function activate( 11 | context: vscode.ExtensionContext 12 | ): Promise { 13 | const config = vscode.workspace.getConfiguration("rnp.snippets"); 14 | if (config.get("showNotesOnStartup")) { 15 | const message = 16 | "RNP Snippets: automatic imports for snippets have been re-enabled now that the VSCode completions API has been improved."; 17 | vscode.window.showInformationMessage(message); 18 | config.update( 19 | "showNotesOnStartup", 20 | false, 21 | vscode.ConfigurationTarget.Global 22 | ); 23 | } 24 | 25 | const snippets = await loadSnippets(); 26 | 27 | function getAdditionalTextEdits({ 28 | imports, 29 | }: { 30 | imports: string[] | undefined; 31 | }): vscode.TextEdit[] { 32 | const document = vscode.window.activeTextEditor?.document; 33 | if (!document || !imports) return []; 34 | 35 | let existingImports: Set | null; 36 | let insertPosition: vscode.Position = new vscode.Position(0, 0); 37 | let coreInsertPosition: vscode.Position | null = null; 38 | try { 39 | ({ 40 | existingImports, 41 | insertPosition, 42 | coreInsertPosition, 43 | } = getExistingImports(document)); 44 | } catch (error) { 45 | existingImports = null; 46 | } 47 | 48 | const additionalTextEdits: vscode.TextEdit[] = []; 49 | const finalExistingImports = existingImports; 50 | if (finalExistingImports) { 51 | const coreImports = imports.filter( 52 | (comp: string) => !finalExistingImports.has(comp) 53 | ); 54 | if (coreImports.length) { 55 | if (coreInsertPosition) { 56 | additionalTextEdits.push( 57 | vscode.TextEdit.insert( 58 | coreInsertPosition, 59 | ", " + coreImports.join(", ") 60 | ) 61 | ); 62 | } else { 63 | additionalTextEdits.push( 64 | vscode.TextEdit.insert( 65 | insertPosition, 66 | `import { ${coreImports.join(", ")} } from 'react-native-paper'\n` 67 | ) 68 | ); 69 | } 70 | } 71 | } 72 | return additionalTextEdits; 73 | } 74 | 75 | for (const snippet of Object.values(snippets)) { 76 | const { prefix, description } = snippet; 77 | context.subscriptions.push( 78 | vscode.commands.registerCommand(`extension.${prefix}`, async () => 79 | vscode.window.withProgress( 80 | { 81 | cancellable: true, 82 | location: vscode.ProgressLocation.Notification, 83 | title: `Inserting RNP ${description}...`, 84 | }, 85 | async ( 86 | progress: vscode.Progress<{ 87 | message?: string | undefined; 88 | increment?: number | undefined; 89 | }>, 90 | token: vscode.CancellationToken 91 | ) => { 92 | const body = (typeof snippet.body === "function" 93 | ? snippet.body({ 94 | language: vscode.window.activeTextEditor?.document 95 | .languageId as any, // eslint-disable-line @typescript-eslint/no-explicit-any 96 | formControlMode: 97 | config.get("formControlMode") || "controlled", 98 | }) 99 | : snippet.body 100 | ).replace(/^\n|\n$/gm, ""); 101 | 102 | if (token.isCancellationRequested) return; 103 | 104 | const additionalTextEdits = getAdditionalTextEdits({ 105 | imports: getSnippetImports(body), 106 | }); 107 | 108 | if (token.isCancellationRequested) return; 109 | 110 | const editor = vscode.window.activeTextEditor; 111 | if (!editor) return; 112 | await editor.insertSnippet( 113 | new vscode.SnippetString(body), 114 | editor.selection 115 | ); 116 | editor.edit((edit: vscode.TextEditorEdit) => { 117 | for (const additionalEdit of additionalTextEdits) { 118 | edit.insert(additionalEdit.range.start, additionalEdit.newText); 119 | } 120 | }); 121 | } 122 | ) 123 | ) 124 | ); 125 | } 126 | 127 | for (const language of ["javascript", "javascriptreact", "typescriptreact"]) { 128 | let lastOptions: SnippetOptions | null = null; 129 | let lastCompletionItems: RNPCompletionItem[]; 130 | 131 | const getCompletionItems = ( 132 | options: SnippetOptions 133 | ): RNPCompletionItem[] => { 134 | if (shallowEqual(options, lastOptions)) { 135 | return lastCompletionItems; 136 | } 137 | lastOptions = options; 138 | const result = []; 139 | for (const snippet of Object.values(snippets)) { 140 | const { prefix, description, docKey, previewURL } = snippet; 141 | 142 | const body = (typeof snippet.body === "function" 143 | ? snippet.body(options) 144 | : snippet.body 145 | ).replace(/^\n|\n$/gm, ""); 146 | 147 | let extendedDoc = description; 148 | extendedDoc += docKey 149 | ? `\n\n Documentation: [Click here](https://reactnativeelements.com/docs/${docKey})` 150 | : ""; 151 | extendedDoc += previewURL 152 | ? `\n\n Preview : \n\n ![${prefix}](${previewURL}) ` 153 | : ""; 154 | const completion = new RNPCompletionItem(prefix); 155 | completion.insertText = new vscode.SnippetString(body); 156 | completion.documentation = new vscode.MarkdownString(extendedDoc); 157 | completion.imports = getSnippetImports(body); 158 | result.push(completion); 159 | } 160 | return (lastCompletionItems = result); 161 | }; 162 | 163 | context.subscriptions.push( 164 | vscode.languages.registerCompletionItemProvider(language, { 165 | provideCompletionItems( 166 | /* eslint-disable @typescript-eslint/no-unused-vars */ 167 | document: vscode.TextDocument, 168 | position: vscode.Position, 169 | token: vscode.CancellationToken, 170 | context: vscode.CompletionContext 171 | /* eslint-enable @typescript-eslint/no-unused-vars */ 172 | ): vscode.ProviderResult { 173 | return getCompletionItems({ 174 | language: language as any, // eslint-disable-line @typescript-eslint/no-explicit-any 175 | formControlMode: "controlled", 176 | }); 177 | }, 178 | async resolveCompletionItem( 179 | item: RNPCompletionItem, 180 | /* eslint-disable @typescript-eslint/no-unused-vars */ 181 | token: vscode.CancellationToken 182 | /* eslint-enable @typescript-eslint/no-unused-vars */ 183 | ): Promise { 184 | item.additionalTextEdits = getAdditionalTextEdits(item); 185 | return item; 186 | }, 187 | }) 188 | ); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/getExistingImports.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import jscodeshift, { ImportDeclaration, ASTPath } from "jscodeshift"; 3 | import chooseJSCodeshiftParser from "jscodeshift-choose-parser"; 4 | 5 | export default function getExistingImports( 6 | document: vscode.TextDocument 7 | ): { 8 | existingImports: Set; 9 | insertPosition: vscode.Position; 10 | coreInsertPosition: vscode.Position | null; 11 | } { 12 | const text = document.getText(); 13 | const parser = chooseJSCodeshiftParser(document.uri.fsPath); 14 | const j = parser ? jscodeshift.withParser(parser) : jscodeshift; 15 | 16 | const result: Set = new Set(); 17 | 18 | let insertLine = 0; 19 | let coreInsertPosition: vscode.Position | null = null; 20 | 21 | let root; 22 | try { 23 | root = j(text); 24 | } catch (error) { 25 | // fall back to trying with flow parser, because it tends to be 26 | // very tolerant of errors and we might at least get the import 27 | // nodes 28 | root = j.withParser("flow")(text); 29 | } 30 | root 31 | .find(j.ImportDeclaration) 32 | .forEach(({ node }: ASTPath): void => { 33 | if (!node) return; 34 | if (node.loc) insertLine = node.loc.end.line; 35 | const source = node.source.value; 36 | if (typeof source !== "string") return; 37 | if (source === "react-native-elements") { 38 | for (const specifier of node?.specifiers) { 39 | if (specifier.type !== "ImportSpecifier") continue; 40 | const { loc } = specifier; 41 | if (loc) { 42 | const { line, column } = loc.end; 43 | coreInsertPosition = new vscode.Position(line - 1, column); 44 | } 45 | const { imported, local } = specifier; 46 | if (imported && local && imported.name === local.name) { 47 | result.add(local.name); 48 | } 49 | } 50 | } 51 | }); 52 | return { 53 | existingImports: result, 54 | insertPosition: new vscode.Position(insertLine, 0), 55 | coreInsertPosition, 56 | }; 57 | } 58 | -------------------------------------------------------------------------------- /src/snip.ts: -------------------------------------------------------------------------------- 1 | import { SnippetOptions } from "./snippets"; 2 | 3 | type Parameter = keyof SnippetOptions; 4 | 5 | const validParameters: Set = new Set(["language", "formControlMode"]); 6 | 7 | export interface CompiledSnippet { 8 | (options: SnippetOptions): string; 9 | parameters: Set; 10 | } 11 | 12 | export default function snip( 13 | strings: TemplateStringsArray, 14 | ...expressions: any[] // eslint-disable-line @typescript-eslint/no-explicit-any 15 | ): CompiledSnippet { 16 | const parts = []; 17 | for (let i = 0; i < strings.length - 1; i++) { 18 | parts.push(strings[i]); 19 | parts.push( 20 | Array.isArray(expressions[i]) 21 | ? `|${expressions[i].join(",")}|` 22 | : String(expressions[i]) 23 | ); 24 | } 25 | parts.push(...strings.slice(expressions.length)); 26 | const body = parts.join("").replace(/\s+$/gm, ""); 27 | 28 | const parameters: Set = new Set(); 29 | 30 | const ifRx = /^\s*\{\{\s*#if\s*(\S+)\s*(===\s*(\S+)\s*)\}\}([^\n]*\n)?/gm; 31 | let match; 32 | while ((match = ifRx.exec(body))) { 33 | const parameter = match[1]; 34 | if (!validParameters.has(parameter)) { 35 | throw new Error(`invalid parameter: ${parameter}`); 36 | } 37 | parameters.add(parameter as Parameter); 38 | } 39 | 40 | const makeSnippet = (options: SnippetOptions): string => { 41 | let lastIndex = 0; 42 | const parts = []; 43 | const ifRx = /^\s*\{\{\s*#if\s*(\S+)\s*(===\s*(\S+)\s*)\}\}([^\n]*\n)?/gm; 44 | const endifRx = /^\s*\{\{\s*\/if\s*\}\}([^\n]*\n)?/gm; 45 | let start, end; 46 | while ((start = ifRx.exec(body))) { 47 | endifRx.lastIndex = start.index + start[0].length; 48 | if ((end = endifRx.exec(body))) { 49 | const parameter = start[1]; 50 | let value; 51 | try { 52 | value = start[3] ? JSON.parse(start[3]) : true; 53 | } catch (error) { 54 | throw new Error(`value is not JSON: ${start[3]}`); 55 | } 56 | parts.push(body.substring(lastIndex, start.index)); 57 | if (options[parameter as Parameter] === value) { 58 | parts.push(body.substring(start.index + start[0].length, end.index)); 59 | } 60 | lastIndex = end.index + end[0].length; 61 | } 62 | } 63 | parts.push(body.substring(lastIndex)); 64 | 65 | let counter = 0; 66 | return parts 67 | .join("") 68 | .replace(/^\n|\n$/g, "") 69 | .replace(/#/g, () => String(++counter)); 70 | }; 71 | makeSnippet.parameters = parameters; 72 | return makeSnippet; 73 | } 74 | -------------------------------------------------------------------------------- /src/snippets.ts: -------------------------------------------------------------------------------- 1 | import requireGlob from "require-glob"; 2 | import path from "path"; 3 | import { CompiledSnippet } from "./snip"; 4 | 5 | export type SnippetOptions = { 6 | language: "javascriptreact" | "typescriptreact"; 7 | formControlMode: "controlled" | "uncontrolled"; 8 | }; 9 | 10 | export type SnippetBody = string | CompiledSnippet; 11 | 12 | export type Snippet = { 13 | prefix: string; 14 | description: string; 15 | body: SnippetBody; 16 | docKey?: string; 17 | previewURL?: string; 18 | }; 19 | 20 | export default async function loadSnippets(): Promise> { 21 | return await requireGlob("./components/*.{js,ts}", { 22 | reducer: ( 23 | options: Record, 24 | result: Record, 25 | file: { path: string; exports: any } 26 | ) => { 27 | if (file.path === __filename) return result; 28 | const filename = path.basename(file.path); 29 | const filenameNoExt = filename.replace(/\.[^.]+$/, ""); 30 | const { 31 | prefix = filenameNoExt, 32 | description, 33 | body, 34 | docKey, 35 | previewURL, 36 | } = file.exports; 37 | if (!prefix || typeof prefix !== "string") { 38 | throw new Error( 39 | `src/components/${filename}: prefix must be a string if exported` 40 | ); 41 | } 42 | if (!description || typeof description !== "string") { 43 | throw new Error( 44 | `src/components/${filename}: must export a string description` 45 | ); 46 | } 47 | if (!body || (typeof body !== "string" && typeof body !== "function")) { 48 | throw new Error( 49 | `src/components/${filename}: must export a function or string body` 50 | ); 51 | } 52 | result[filenameNoExt] = { 53 | prefix, 54 | description, 55 | body: body(), 56 | docKey, 57 | previewURL, 58 | }; 59 | 60 | return result; 61 | }, 62 | }); 63 | } 64 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export function once(fn: F): F { 2 | let called = false; 3 | let result: any; 4 | 5 | return function onceified(this: any) { 6 | if (!called) { 7 | result = fn.apply(this, arguments); 8 | called = true; 9 | } 10 | return result; 11 | } as any; 12 | } 13 | 14 | export function getSnippetImports(body: string): string[] { 15 | const rx = /<([A-Z][A-Za-z]+)/g; 16 | const components: Set = new Set(); 17 | let match; 18 | while ((match = rx.exec(body))) { 19 | components.add(match[1]); 20 | } 21 | return [...components].sort(); 22 | } 23 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | /* Basic Options */ 5 | // "incremental": true, /* Enable incremental compilation */ 6 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 7 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 8 | // "lib": [], /* Specify library files to be included in the compilation. */ 9 | // "allowJs": true, /* Allow javascript files to be compiled. */ 10 | // "checkJs": true, /* Report errors in .js files. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | "outDir": "./build", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | /* Strict Type-Checking Options */ 25 | // "strict": true, /* Enable all strict type-checking options. */ 26 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 27 | // "strictNullChecks": true, /* Enable strict null checks. */ 28 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 29 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 30 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 31 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 32 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 33 | /* Additional Checks */ 34 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 35 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 36 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 37 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 38 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 39 | // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ 40 | /* Module Resolution Options */ 41 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 42 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 43 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 44 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 45 | // "typeRoots": [], /* List of folders to include type definitions from. */ 46 | // "types": [], /* Type declaration files to be included in compilation. */ 47 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 48 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 49 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 50 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 51 | /* Source Map Options */ 52 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 53 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 54 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 55 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 56 | /* Experimental Options */ 57 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 58 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 59 | /* Advanced Options */ 60 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 61 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 62 | }, 63 | "include": [ 64 | "src" 65 | ] 66 | } -------------------------------------------------------------------------------- /typings/nyc/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'nyc' { 2 | export default class NYC { 3 | createTempDirectory(): Promise 4 | writeCoverageFile(): Promise 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /typings/require-glob/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'require-glob' { 2 | export default function async( 3 | path: string, 4 | options?: { 5 | reducer?: ( 6 | options: Record, 7 | result: Record, 8 | file: { path: string; exports: any } 9 | ) => Record 10 | } 11 | ): Promise> 12 | export function sync( 13 | path: string, 14 | options?: { 15 | reducer?: ( 16 | options: Record, 17 | result: Record, 18 | file: { path: string; exports: any } 19 | ) => Record 20 | } 21 | ): Record 22 | } 23 | --------------------------------------------------------------------------------