How DevSnips Works
DevSnips is a static website that dynamically fetches and renders code snippets from a public GitHub repository. This approach eliminates the need for a traditional backend or database, making the platform lightweight and easy to maintain. The core functionality relies on client-side JavaScript and the GitHub API.
Fetching Snippets via the GitHub API
All snippets are stored as individual files in the DevSnips GitHub repository. When a user visits a snippet category page (e.g., "HTML Snippets"), the website's JavaScript initiates a request to the GitHub API's contents endpoint.
The API endpoint is structured as follows:
https://api.github.com/repos/developer8sarthak/DevSnips/contents/devsnips/snippets/{category}-snippetsFor example, to fetch CSS snippets, the application calls:
https://api.github.com/repos/developer8sarthak/DevSnips/contents/devsnips/snippets/css-snippetsRecursive Fetching and Response Handling
The fetchSnippets function in javascript-files/snippets.js is designed to handle the API response. Since snippets can be organized into subdirectories for better management, the function recursively traverses the directory structure.
                
Hereβs a conceptual overview of the process:
- An API call is made to the category's main directory.
- The API returns a JSON array of objects, where each object represents a file or a directory.
- The JavaScript iterates through the array. If an item is a directory, it makes another API call to that directory's URL.
- If an item is a file, it fetches the file's content from the download_urlprovided in the response.
- The content of each file (the code snippet) is then packaged into a JavaScript object along with metadata like its name, language, and ID.
Dynamic Rendering of Snippet Cards
Once the snippet data is fetched and compiled into an array of objects, the next step is to render it on the page. This is handled by the makeCard function, which dynamically creates the HTML for each snippet card.
For each snippet object, the makeCard function:
- Creates an <article>element with the classsnippet-card.
- Generates the card's header, including the title and action buttons like "Share" and "Try It."
- Constructs the code preview block, wrapping the code in <pre>and<code>tags and attaching a "Copy" button.
- Adds event listeners to the buttons for interactivity (e.g., copying code to the clipboard or opening the snippet in the playground).
- Appends the fully constructed card to the main grid on the page.
After all cards are added to the DOM, a syntax highlighting library (Prism.js) is called to style the code blocks according to their language.
