chore: publish from staged

This commit is contained in:
github-actions[bot]
2026-05-04 06:34:46 +00:00
parent b644d55e12
commit f503ffa543
536 changed files with 116819 additions and 294 deletions

View File

@@ -19,9 +19,9 @@
"repository": "https://github.com/github/awesome-copilot",
"license": "MIT",
"skills": [
"./skills/content-management-systems/",
"./skills/markdown-to-html/",
"./skills/quasi-coder/",
"./skills/web-coder/"
"./skills/content-management-systems",
"./skills/markdown-to-html",
"./skills/quasi-coder",
"./skills/web-coder"
]
}

View File

@@ -0,0 +1,106 @@
---
name: content-management-systems
description: 'Workflow for building and modifying content management systems across WordPress, Shopify, Wix, Squarespace, Drupal, WooCommerce, Joomla, HubSpot CMS Hub, Webflow, Adobe Experience Manager, and similar platforms. Use when working on CMS themes, plugins, apps, modules, admin panels, media uploads, content models, editors, markdown pipelines, or static export workflows.'
---
# Content Management Systems
Use this skill when the user is working on a content management system or on software that behaves like one.
This skill focuses on the seams that matter in CMS work:
- themes and templates
- plugins, apps, modules, and extensions
- admin and editor interfaces
- media and upload handling
- content models, taxonomy, and metadata
- render pipelines and static export flows
## When to Use This Skill
- The user mentions a CMS platform such as WordPress, Shopify, Drupal, Joomla, Webflow, Squarespace, Wix, WooCommerce, HubSpot CMS Hub, or Adobe Experience Manager.
- The task is about theme development, template changes, or design system work inside a CMS.
- The task is about plugins, modules, apps, or extension points.
- The task touches editor UX, previews, taxonomy, slugs, SEO fields, or publishing behavior.
- The task involves uploads, media libraries, authored assets, markdown rendering, or static export.
## First Pass
1. Identify the platform category: self-hosted CMS, SaaS site builder, commerce platform, or hybrid/headless system.
2. Find the owning implementation seam before editing:
- theme or template layer
- plugin, app, module, or extension layer
- admin or editor surface
- content model or storage layer
- media pipeline
- export, deploy, or rendering pipeline
3. Check platform constraints before choosing an approach:
- what is editable locally
- what is authored content versus code
- where media belongs
- whether the final site is server-rendered, static-exported, or hosted remotely
## CMS Rules
- Follow the platform's naming and folder conventions for themes, modules, template parts, or sections.
- Keep theme assets separate from user-uploaded media unless the platform explicitly combines them.
- Prefer structured content fields over storing important metadata inside presentation markup.
- Treat previews, slugs, taxonomy, excerpts, meta fields, and publish states as first-class CMS concerns.
- Prefer safe defaults and graceful fallback behavior when config, theme selection, or content input is invalid.
- When changing editor or admin behavior, trace the stored field, validation rules, preview path, and final render path together.
## Common Workflows
### Themes and Templates
- Start at the template loader or theme runtime, not at a downstream include.
- Preserve the platform's template hierarchy and partial naming conventions.
- Keep presentation changes close to templates and shared theme helpers.
### Plugins, Apps, and Modules
- Add behavior at the platform's extension seam instead of scattering logic into templates.
- Keep migrations, seed data, and configuration updates explicit and versioned.
- Document the extension's setup assumptions when the platform requires activation or registration.
### Admin and Editor UX
- Keep forms aligned with the stored content model.
- Prefer author-facing previews when content transformations are non-trivial.
- Keep validation, CSRF or equivalent safeguards, and permissions consistent with the surrounding admin code.
### Media and Uploads
- Use a dedicated upload path for authored media.
- Keep decorative or theme-owned imagery in the active theme folder.
- Default to conventional locations like `uploads/` for authored media and `img/` for theme assets unless the platform dictates a stronger convention.
- When a CMS supports configurable media directories, expose the setting with a safe fallback.
### Content Models and Migrations
- Distinguish content entities clearly: pages, posts, products, entries, collections, taxonomies, and settings.
- Prefer migration files or exportable schema definitions over ad hoc runtime mutations.
- Keep slugs, publish dates, excerpts, canonical metadata, and taxonomy relations structured.
### Markdown, HTML, and Static Export
- Decide whether markdown is authored input, intermediate content, or build output before changing the renderer.
- Pair renderer changes with preview or validation when feasible.
- For static-exported CMS systems, validate rewritten permalinks and asset paths after build changes.
## Identifying the Owning Seam
Regardless of platform, locate the owning seam before editing by mapping the codebase to these CMS roles:
- Runtime bootstrap and request routing
- Admin or editor controllers and their view templates
- Theme loading, template hierarchy, and shared template helpers
- Repositories, models, or schema/migration files for content, taxonomy, and settings
- Markdown or content transformation utilities
- Static export, deploy, or render pipeline entry points
Step to the owning seam first, then make the smallest change that preserves the CMS structure.
## Platform Notes
See `references/cms-platform-workflows.md` for a compact mapping of common CMS platforms, extension surfaces, and media conventions.

View File

@@ -0,0 +1,37 @@
# CMS Platform Workflows
This reference keeps the high-level platform map close to the skill so the agent can choose the right seam quickly.
## Platform Map
| Platform | Primary extension surfaces | Media and asset convention | Notes |
| --- | --- | --- | --- |
| WordPress | Themes, plugins, template parts, hooks | Theme assets inside the active theme; authored media under uploads-style paths | Good fit for template hierarchy, taxonomy, custom fields, and local/static export workflows |
| WooCommerce | WordPress themes and plugins plus product/catalog extensions | Same base conventions as WordPress, with product imagery as authored media | Treat it as WordPress first, then apply commerce-specific content and admin rules |
| Shopify | Themes, Liquid sections, blocks, apps, metafields | Theme assets and hosted store media are distinct concerns | Prefer app or metafield seams over theme-only hacks when data must survive redesigns |
| Wix | Site builder surfaces, apps, content collections, custom elements | Hosted media library plus editor-managed assets | Favor editor-safe changes and avoid assuming file-system level access |
| Squarespace | Templates, code injection, content collections, commerce settings | Hosted asset library managed through the platform | Expect narrower extension points and stronger hosted constraints |
| Drupal | Themes, modules, content types, views, taxonomy | Managed files and theme assets are separate | Strong fit for structured content, enterprise workflows, and migration-heavy changes |
| Joomla | Templates, modules, components, plugins | Managed media plus template-owned assets | Similar split between templates and extensions; watch routing and content component boundaries |
| HubSpot CMS Hub | Themes, modules, templates, serverless functions, CRM-linked content | Hosted file manager plus theme assets | Content, marketing, and CRM concerns are tightly coupled |
| Webflow | Designer, CMS collections, components, embeds, limited code export | Hosted assets and CMS collection media | Export constraints matter; distinguish what survives export from what depends on hosted CMS features |
| Adobe Experience Manager | Components, templates, content fragments, experience fragments, workflows | DAM-managed assets plus component resources | Enterprise governance, authoring workflows, and content fragment models drive most changes |
## Media Rule of Thumb
- Theme-owned images belong with the theme or template package.
- User-authored images belong in the platform's upload or media-library flow.
- If a project supports both, keep them distinct in config and in code paths.
## Generic CMS Responsibility Map
Most CMS codebases group behavior into the same handful of responsibilities. Use this as a checklist when locating the owning seam in any project:
- Runtime assembly and request routing
- Theme or template system and shared template helpers
- Admin and editor controllers with their view templates
- Content, taxonomy, and settings persistence (repositories, models, schema/migrations)
- Content transformation utilities (markdown, shortcodes, block renderers)
- Static export, deploy, or render pipeline entry points
Map the project to these responsibilities first, then make the smallest change that preserves the platform's structure.

View File

@@ -0,0 +1,916 @@
---
name: markdown-to-html
description: 'Convert Markdown files to HTML similar to `marked.js`, `pandoc`, `gomarkdown/markdown`, or similar tools; or writing custom script to convert markdown to html and/or working on web template systems like `jekyll/jekyll`, `gohugoio/hugo`, or similar web templating systems that utilize markdown documents, converting them to html. Use when asked to "convert markdown to html", "transform md to html", "render markdown", "generate html from markdown", or when working with .md files and/or web a templating system that converts markdown to HTML output. Supports CLI and Node.js workflows with GFM, CommonMark, and standard Markdown flavors.'
---
# Markdown to HTML Conversion
Expert skill for converting Markdown documents to HTML using the marked.js library, or writing data conversion scripts; in this case scripts similar to [markedJS/marked](https://github.com/markedjs/marked) repository. For custom scripts knowledge is not confined to `marked.js`, but data conversion methods are utilized from tools like [pandoc](https://github.com/jgm/pandoc) and [gomarkdown/markdown](https://github.com/gomarkdown/markdown) for data conversion; [jekyll/jekyll](https://github.com/jekyll/jekyll) and [gohugoio/hugo](https://github.com/gohugoio/hugo) for templating systems.
The conversion script or tool should handle single files, batch conversions, and advanced configurations.
## When to Use This Skill
- User asks to "convert markdown to html" or "transform md files"
- User wants to "render markdown" as HTML output
- User needs to generate HTML documentation from .md files
- User is building static sites from Markdown content
- User is building template system that converts markdown to html
- User is working on a tool, widget, or custom template for an existing templating system
- User wants to preview Markdown as rendered HTML
## Converting Markdown to HTML
### Essential Basic Conversions
For more see [basic-markdown-to-html.md](references/basic-markdown-to-html.md)
```text
```markdown
# Level 1
## Level 2
One sentence with a [link](https://example.com), and a HTML snippet like `<p>paragraph tag</p>`.
- `ul` list item 1
- `ul` list item 2
1. `ol` list item 1
2. `ol` list item 1
| Table Item | Description |
| One | One is the spelling of the number `1`. |
| Two | Two is the spelling of the number `2`. |
```js
var one = 1;
var two = 2;
function simpleMath(x, y) {
return x + y;
}
console.log(simpleMath(one, two));
```
```
```html
<h1>Level 1</h1>
<h2>Level 2</h2>
<p>One sentence with a <a href="https://example.com">link</a>, and a HTML snippet like <code>&lt;p&gt;paragraph tag&lt;/p&gt;</code>.</p>
<ul>
<li>`ul` list item 1</li>
<li>`ul` list item 2</li>
</ul>
<ol>
<li>`ol` list item 1</li>
<li>`ol` list item 2</li>
</ol>
<table>
<thead>
<tr>
<th>Table Item</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>One</td>
<td>One is the spelling of the number `1`.</td>
</tr>
<tr>
<td>Two</td>
<td>Two is the spelling of the number `2`.</td>
</tr>
</tbody>
</table>
<pre>
<code>var one = 1;
var two = 2;
function simpleMath(x, y) {
return x + y;
}
console.log(simpleMath(one, two));</code>
</pre>
```
```
### Code Block Conversions
For more see [code-blocks-to-html.md](references/code-blocks-to-html.md)
```text
```markdown
your code here
```
```html
<pre><code class="language-md">
your code here
</code></pre>
```
```js
console.log("Hello world");
```
```html
<pre><code class="language-js">
console.log("Hello world");
</code></pre>
```
```markdown
```
```
visible backticks
```
```
```
```html
<pre><code>
```
visible backticks
```
</code></pre>
```
```
### Collapsed Section Conversions
For more see [collapsed-sections-to-html.md](references/collapsed-sections-to-html.md)
```text
```markdown
<details>
<summary>More info</summary>
### Header inside
- Lists
- **Formatting**
- Code blocks
```js
console.log("Hello");
```
</details>
```
```html
<details>
<summary>More info</summary>
<h3>Header inside</h3>
<ul>
<li>Lists</li>
<li><strong>Formatting</strong></li>
<li>Code blocks</li>
</ul>
<pre>
<code class="language-js">console.log("Hello");</code>
</pre>
</details>
```
```
### Mathematical Expression Conversions
For more see [writing-mathematical-expressions-to-html.md](references/writing-mathematical-expressions-to-html.md)
```text
```markdown
This sentence uses `$` delimiters to show math inline: $\sqrt{3x-1}+(1+x)^2$
```
```html
<p>This sentence uses <code>$</code> delimiters to show math inline:
<math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
<msqrt><mn>3</mn><mi>x</mi><mo></mo><mn>1</mn></msqrt>
<mo>+</mo><mo>(</mo><mn>1</mn><mo>+</mo><mi>x</mi>
<msup><mo>)</mo><mn>2</mn></msup>
</math>
</math-renderer>
</p>
```
```markdown
**The Cauchy-Schwarz Inequality**\
$$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$
```
```html
<p><strong>The Cauchy-Schwarz Inequality</strong><br>
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<mrow><mo>(</mo>
<munderover><mo data-mjx-texclass="OP">∑</mo>
<mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi>
</munderover>
<msub><mi>a</mi><mi>k</mi></msub>
<msub><mi>b</mi><mi>k</mi></msub>
<mo>)</mo>
</mrow>
<mn>2</mn>
</msup>
<mo>≤</mo>
<mrow><mo>(</mo>
<munderover><mo>∑</mo>
<mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
<mi>n</mi>
</munderover>
<msubsup><mi>a</mi><mi>k</mi><mn>2</mn></msubsup>
<mo>)</mo>
</mrow>
<mrow><mo>(</mo>
<munderover><mo>∑</mo>
<mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
<mi>n</mi>
</munderover>
<msubsup><mi>b</mi><mi>k</mi><mn>2</mn></msubsup>
<mo>)</mo>
</mrow>
</math>
</math-renderer></p>
```
```
### Table Conversions
For more see [tables-to-html.md](references/tables-to-html.md)
```text
```markdown
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
```html
<table>
<thead><tr><th>First Header</th><th>Second Header</th></tr></thead>
<tbody>
<tr><td>Content Cell</td><td>Content Cell</td></tr>
<tr><td>Content Cell</td><td>Content Cell</td></tr>
</tbody>
</table>
```
```markdown
| Left-aligned | Center-aligned | Right-aligned |
| :--- | :---: | ---: |
| git status | git status | git status |
| git diff | git diff | git diff |
```
```html
<table>
<thead>
<tr>
<th align="left">Left-aligned</th>
<th align="center">Center-aligned</th>
<th align="right">Right-aligned</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">git status</td>
<td align="center">git status</td>
<td align="right">git status</td>
</tr>
<tr>
<td align="left">git diff</td>
<td align="center">git diff</td>
<td align="right">git diff</td>
</tr>
</tbody>
</table>
```
```
## Working with [`markedJS/marked`](references/marked.md)
### Prerequisites
- Node.js installed (for CLI or programmatic usage)
- Install marked globally for CLI: `npm install -g marked`
- Or install locally: `npm install marked`
### Quick Conversion Methods
See [marked.md](references/marked.md) **Quick Conversion Methods**
### Step-by-Step Workflows
See [marked.md](references/marked.md) **Step-by-Step Workflows**
### CLI Configuration
### Using Config Files
Create `~/.marked.json` for persistent options:
```json
{
"gfm": true,
"breaks": true
}
```
Or use a custom config:
```bash
marked -i input.md -o output.html -c config.json
```
### CLI Options Reference
| Option | Description |
|--------|-------------|
| `-i, --input <file>` | Input Markdown file |
| `-o, --output <file>` | Output HTML file |
| `-s, --string <string>` | Parse string instead of file |
| `-c, --config <file>` | Use custom config file |
| `--gfm` | Enable GitHub Flavored Markdown |
| `--breaks` | Convert newlines to `<br>` |
| `--help` | Show all options |
### Security Warning
⚠️ **Marked does NOT sanitize output HTML.** For untrusted input, use a sanitizer:
```javascript
import { marked } from 'marked';
import DOMPurify from 'dompurify';
const unsafeHtml = marked.parse(untrustedMarkdown);
const safeHtml = DOMPurify.sanitize(unsafeHtml);
```
Recommended sanitizers:
- [DOMPurify](https://github.com/cure53/DOMPurify) (recommended)
- [sanitize-html](https://github.com/apostrophecms/sanitize-html)
- [js-xss](https://github.com/leizongmin/js-xss)
### Supported Markdown Flavors
| Flavor | Support |
|--------|---------|
| Original Markdown | 100% |
| CommonMark 0.31 | 98% |
| GitHub Flavored Markdown | 97% |
### Troubleshooting
| Issue | Solution |
|-------|----------|
| Special characters at file start | Strip zero-width chars: `content.replace(/^[\u200B\u200C\u200D\uFEFF]/,"")` |
| Code blocks not highlighting | Add a syntax highlighter like highlight.js |
| Tables not rendering | Ensure `gfm: true` option is set |
| Line breaks ignored | Set `breaks: true` in options |
| XSS vulnerability concerns | Use DOMPurify to sanitize output |
## Working with [`pandoc`](references/pandoc.md)
### Prerequisites
- Pandoc installed (download from <https://pandoc.org/installing.html>)
- For PDF output: LaTeX installation (MacTeX on macOS, MiKTeX on Windows, texlive on Linux)
- Terminal/command prompt access
### Quick Conversion Methods
#### Method 1: CLI Basic Conversion
```bash
# Convert markdown to HTML
pandoc input.md -o output.html
# Convert with standalone document (includes header/footer)
pandoc input.md -s -o output.html
# Explicit format specification
pandoc input.md -f markdown -t html -s -o output.html
```
#### Method 2: Filter Mode (Interactive)
```bash
# Start pandoc as a filter
pandoc
# Type markdown, then Ctrl-D (Linux/macOS) or Ctrl-Z+Enter (Windows)
Hello *pandoc*!
# Output: <p>Hello <em>pandoc</em>!</p>
```
#### Method 3: Format Conversion
```bash
# HTML to Markdown
pandoc -f html -t markdown input.html -o output.md
# Markdown to LaTeX
pandoc input.md -s -o output.tex
# Markdown to PDF (requires LaTeX)
pandoc input.md -s -o output.pdf
# Markdown to Word
pandoc input.md -s -o output.docx
```
### CLI Configuration
| Option | Description |
|--------|-------------|
| `-f, --from <format>` | Input format (markdown, html, latex, etc.) |
| `-t, --to <format>` | Output format (html, latex, pdf, docx, etc.) |
| `-s, --standalone` | Produce standalone document with header/footer |
| `-o, --output <file>` | Output file (inferred from extension) |
| `--mathml` | Convert TeX math to MathML |
| `--metadata title="Title"` | Set document metadata |
| `--toc` | Include table of contents |
| `--template <file>` | Use custom template |
| `--help` | Show all options |
### Security Warning
⚠️ **Pandoc processes input faithfully.** When converting untrusted markdown:
- Use `--sandbox` mode to disable external file access
- Validate input before processing
- Sanitize HTML output if displayed in browsers
```bash
# Run in sandbox mode for untrusted input
pandoc --sandbox input.md -o output.html
```
### Supported Markdown Flavors
| Flavor | Support |
|--------|---------|
| Pandoc Markdown | 100% (native) |
| CommonMark | Full (use `-f commonmark`) |
| GitHub Flavored Markdown | Full (use `-f gfm`) |
| MultiMarkdown | Partial |
### Troubleshooting
| Issue | Solution |
|-------|----------|
| PDF generation fails | Install LaTeX (MacTeX, MiKTeX, or texlive) |
| Encoding issues on Windows | Run `chcp 65001` before using pandoc |
| Missing standalone headers | Add `-s` flag for complete documents |
| Math not rendering | Use `--mathml` or `--mathjax` option |
| Tables not rendering | Ensure proper table syntax with pipes and dashes |
## Working with [`gomarkdown/markdown`](references/gomarkdown.md)
### Prerequisites
- Go 1.18 or higher installed
- Install the library: `go get github.com/gomarkdown/markdown`
- For CLI tool: `go install github.com/gomarkdown/mdtohtml@latest`
### Quick Conversion Methods
#### Method 1: Simple Conversion (Go)
```go
package main
import (
"fmt"
"github.com/gomarkdown/markdown"
)
func main() {
md := []byte("# Hello World\n\nThis is **bold** text.")
html := markdown.ToHTML(md, nil, nil)
fmt.Println(string(html))
}
```
#### Method 2: CLI Tool
```bash
# Install mdtohtml
go install github.com/gomarkdown/mdtohtml@latest
# Convert file
mdtohtml input.md output.html
# Convert file (output to stdout)
mdtohtml input.md
```
#### Method 3: Custom Parser and Renderer
```go
package main
import (
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
)
func mdToHTML(md []byte) []byte {
// Create parser with extensions
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
p := parser.NewWithExtensions(extensions)
doc := p.Parse(md)
// Create HTML renderer with extensions
htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{Flags: htmlFlags}
renderer := html.NewRenderer(opts)
return markdown.Render(doc, renderer)
}
```
### CLI Configuration
The `mdtohtml` CLI tool has minimal options:
```bash
mdtohtml input-file [output-file]
```
For advanced configuration, use the Go library programmatically with parser and renderer options:
| Parser Extension | Description |
|------------------|-------------|
| `parser.CommonExtensions` | Tables, fenced code, autolinks, strikethrough, etc. |
| `parser.AutoHeadingIDs` | Generate IDs for headings |
| `parser.NoEmptyLineBeforeBlock` | No blank line needed before blocks |
| `parser.MathJax` | MathJax support for LaTeX math |
| HTML Flag | Description |
|-----------|-------------|
| `html.CommonFlags` | Common HTML output flags |
| `html.HrefTargetBlank` | Add `target="_blank"` to links |
| `html.CompletePage` | Generate complete HTML page |
| `html.UseXHTML` | Generate XHTML output |
### Security Warning
⚠️ **gomarkdown does NOT sanitize output HTML.** For untrusted input, use Bluemonday:
```go
import (
"github.com/microcosm-cc/bluemonday"
"github.com/gomarkdown/markdown"
)
maybeUnsafeHTML := markdown.ToHTML(md, nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
```
Recommended sanitizer: [Bluemonday](https://github.com/microcosm-cc/bluemonday)
### Supported Markdown Flavors
| Flavor | Support |
|--------|---------|
| Original Markdown | 100% |
| CommonMark | High (with extensions) |
| GitHub Flavored Markdown | High (tables, fenced code, strikethrough) |
| MathJax/LaTeX Math | Supported via extension |
| Mmark | Supported |
### Troubleshooting
| Issue | Solution |
|-------|----------|
| Windows/Mac newlines not parsed | Use `parser.NormalizeNewlines(input)` |
| Tables not rendering | Enable `parser.Tables` extension |
| Code blocks without highlighting | Integrate with syntax highlighter like Chroma |
| Math not rendering | Enable `parser.MathJax` extension |
| XSS vulnerabilities | Use Bluemonday to sanitize output |
## Working with [`jekyll`](references/jekyll.md)
### Prerequisites
- Ruby version 2.7.0 or higher
- RubyGems
- GCC and Make (for native extensions)
- Install Jekyll and Bundler: `gem install jekyll bundler`
### Quick Conversion Methods
#### Method 1: Create New Site
```bash
# Create a new Jekyll site
jekyll new myblog
# Change to site directory
cd myblog
# Build and serve locally
bundle exec jekyll serve
# Access at http://localhost:4000
```
#### Method 2: Build Static Site
```bash
# Build site to _site directory
bundle exec jekyll build
# Build with production environment
JEKYLL_ENV=production bundle exec jekyll build
```
#### Method 3: Live Reload Development
```bash
# Serve with live reload
bundle exec jekyll serve --livereload
# Serve with drafts
bundle exec jekyll serve --drafts
```
### CLI Configuration
| Command | Description |
|---------|-------------|
| `jekyll new <path>` | Create new Jekyll site |
| `jekyll build` | Build site to `_site` directory |
| `jekyll serve` | Build and serve locally |
| `jekyll clean` | Remove generated files |
| `jekyll doctor` | Check for configuration issues |
| Serve Options | Description |
|---------------|-------------|
| `--livereload` | Reload browser on changes |
| `--drafts` | Include draft posts |
| `--port <port>` | Set server port (default: 4000) |
| `--host <host>` | Set server host (default: localhost) |
| `--baseurl <url>` | Set base URL |
### Security Warning
⚠️ **Jekyll security considerations:**
- Avoid using `safe: false` in production
- Use `exclude` in `_config.yml` to prevent sensitive files from being published
- Sanitize user-generated content if accepting external input
- Keep Jekyll and plugins updated
```yaml
# _config.yml security settings
exclude:
- Gemfile
- Gemfile.lock
- node_modules
- vendor
```
### Supported Markdown Flavors
| Flavor | Support |
|--------|---------|
| Kramdown (default) | 100% |
| CommonMark | Via plugin (jekyll-commonmark) |
| GitHub Flavored Markdown | Via plugin (jekyll-commonmark-ghpages) |
| RedCarpet | Via plugin (deprecated) |
Configure markdown processor in `_config.yml`:
```yaml
markdown: kramdown
kramdown:
input: GFM
syntax_highlighter: rouge
```
### Troubleshooting
| Issue | Solution |
|-------|----------|
| Ruby 3.0+ fails to serve | Run `bundle add webrick` |
| Gem dependency errors | Run `bundle install` |
| Slow builds | Use `--incremental` flag |
| Liquid syntax errors | Check for unescaped `{` in content |
| Plugin not loading | Add to `_config.yml` plugins list |
## Working with [`hugo`](references/hugo.md)
### Prerequisites
- Hugo installed (download from <https://gohugo.io/installation/>)
- Git (recommended for themes and modules)
- Go (optional, for Hugo Modules)
### Quick Conversion Methods
#### Method 1: Create New Site
```bash
# Create a new Hugo site
hugo new site mysite
# Change to site directory
cd mysite
# Add a theme
git init
git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke
echo "theme = 'ananke'" >> hugo.toml
# Create content
hugo new content posts/my-first-post.md
# Start development server
hugo server -D
```
#### Method 2: Build Static Site
```bash
# Build site to public directory
hugo
# Build with minification
hugo --minify
# Build for specific environment
hugo --environment production
```
#### Method 3: Development Server
```bash
# Start server with drafts
hugo server -D
# Start with live reload and bind to all interfaces
hugo server --bind 0.0.0.0 --baseURL http://localhost:1313/
# Start with specific port
hugo server --port 8080
```
### CLI Configuration
| Command | Description |
|---------|-------------|
| `hugo new site <name>` | Create new Hugo site |
| `hugo new content <path>` | Create new content file |
| `hugo` | Build site to `public` directory |
| `hugo server` | Start development server |
| `hugo mod init` | Initialize Hugo Modules |
| Build Options | Description |
|---------------|-------------|
| `-D, --buildDrafts` | Include draft content |
| `-E, --buildExpired` | Include expired content |
| `-F, --buildFuture` | Include future-dated content |
| `--minify` | Minify output |
| `--gc` | Run garbage collection after build |
| `-d, --destination <path>` | Output directory |
| Server Options | Description |
|----------------|-------------|
| `--bind <ip>` | Interface to bind to |
| `-p, --port <port>` | Port number (default: 1313) |
| `--liveReloadPort <port>` | Live reload port |
| `--disableLiveReload` | Disable live reload |
| `--navigateToChanged` | Navigate to changed content |
### Security Warning
⚠️ **Hugo security considerations:**
- Configure security policy in `hugo.toml` for external commands
- Use `--enableGitInfo` carefully with public repositories
- Validate shortcode parameters for user-generated content
```toml
# hugo.toml security settings
[security]
enableInlineShortcodes = false
[security.exec]
allow = ['^go$', '^npx$', '^postcss$']
[security.funcs]
getenv = ['^HUGO_', '^CI$']
[security.http]
methods = ['(?i)GET|POST']
urls = ['.*']
```
### Supported Markdown Flavors
| Flavor | Support |
|--------|---------|
| Goldmark (default) | 100% (CommonMark compliant) |
| GitHub Flavored Markdown | Full (tables, strikethrough, autolinks) |
| CommonMark | 100% |
| Blackfriday (legacy) | Deprecated, not recommended |
Configure markdown in `hugo.toml`:
```toml
[markup]
[markup.goldmark]
[markup.goldmark.extensions]
definitionList = true
footnote = true
linkify = true
strikethrough = true
table = true
taskList = true
[markup.goldmark.renderer]
unsafe = false # Set true to allow raw HTML
```
### Troubleshooting
| Issue | Solution |
|-------|----------|
| "Page not found" on paths | Check `baseURL` in config |
| Theme not loading | Verify theme in `themes/` or Hugo Modules |
| Slow builds | Use `--templateMetrics` to identify bottlenecks |
| Raw HTML not rendering | Set `unsafe = true` in goldmark config |
| Images not loading | Check `static/` folder structure |
| Module errors | Run `hugo mod tidy` |
## References
### Writing and Styling Markdown
- [basic-markdown.md](references/basic-markdown.md)
- [code-blocks.md](references/code-blocks.md)
- [collapsed-sections.md](references/collapsed-sections.md)
- [tables.md](references/tables.md)
- [writing-mathematical-expressions.md](references/writing-mathematical-expressions.md)
- Markdown Guide: <https://www.markdownguide.org/basic-syntax/>
- Styling Markdown: <https://github.com/sindresorhus/github-markdown-css>
### [`markedJS/marked`](references/marked.md)
- Official documentation: <https://marked.js.org/>
- Advanced options: <https://marked.js.org/using_advanced>
- Extensibility: <https://marked.js.org/using_pro>
- GitHub repository: <https://github.com/markedjs/marked>
### [`pandoc`](references/pandoc.md)
- Getting started: <https://pandoc.org/getting-started.html>
- Official documentation: <https://pandoc.org/MANUAL.html>
- Extensibility: <https://pandoc.org/extras.html>
- GitHub repository: <https://github.com/jgm/pandoc>
### [`gomarkdown/markdown`](references/gomarkdown.md)
- Official documentation: <https://pkg.go.dev/github.com/gomarkdown/markdown>
- Advanced configuration: <https://pkg.go.dev/github.com/gomarkdown/markdown@v0.0.0-20250810172220-2e2c11897d1a/html>
- Markdown processing: <https://blog.kowalczyk.info/article/cxn3/advanced-markdown-processing-in-go.html>
- GitHub repository: <https://github.com/gomarkdown/markdown>
### [`jekyll`](references/jekyll.md)
- Official documentation: <https://jekyllrb.com/docs/>
- Configuration options: <https://jekyllrb.com/docs/configuration/options/>
- Plugins: <https://jekyllrb.com/docs/plugins/>
- [Installation](https://jekyllrb.com/docs/plugins/installation/)
- [Generators](https://jekyllrb.com/docs/plugins/generators/)
- [Converters](https://jekyllrb.com/docs/plugins/converters/)
- [Commands](https://jekyllrb.com/docs/plugins/commands/)
- [Tags](https://jekyllrb.com/docs/plugins/tags/)
- [Filters](https://jekyllrb.com/docs/plugins/filters/)
- [Hooks](https://jekyllrb.com/docs/plugins/hooks/)
- GitHub repository: <https://github.com/jekyll/jekyll>
### [`hugo`](references/hugo.md)
- Official documentation: <https://gohugo.io/documentation/>
- All Settings: <https://gohugo.io/configuration/all/>
- Editor Plugins: <https://gohugo.io/tools/editors/>
- GitHub repository: <https://github.com/gohugoio/hugo>

View File

@@ -0,0 +1,420 @@
# Basic Markdown to HTML
## Headings
### Markdown
```md
# Basic writing and formatting syntax
```
### Parsed HTML
```html
<h1>Basic writing and formatting syntax</h1>
```
```md
## Headings
```
```html
<h2>Headings</h2>
```
```md
### A third-level heading
```
```html
<h3>A third-level heading</h3>
```
### Markdown
```md
Heading 2
---
```
### Parsed HTML
```html
<h2>Heading 2</h2>
```
---
## Paragraphs
### Markdown
```md
Create sophisticated formatting for your prose and code on GitHub with simple syntax.
```
### Parsed HTML
```html
<p>Create sophisticated formatting for your prose and code on GitHub with simple syntax.</p>
```
---
## Inline Formatting
### Bold
```md
**This is bold text**
```
```html
<strong>This is bold text</strong>
```
---
### Italic
```md
_This text is italicized_
```
```html
<em>This text is italicized</em>
```
---
### Bold + Italic
```md
***All this text is important***
```
```html
<strong><em>All this text is important</em></strong>
```
---
### Strikethrough (GFM)
```md
~~This was mistaken text~~
```
```html
<del>This was mistaken text</del>
```
---
### Subscript / Superscript (raw HTML passthrough)
```md
This is a <sub>subscript</sub> text
```
```html
<p>This is a <sub>subscript</sub> text</p>
```
```md
This is a <sup>superscript</sup> text
```
```html
<p>This is a <sup>superscript</sup> text</p>
```
---
## Blockquotes
### Markdown
```md
> Text that is a quote
```
### Parsed HTML
```html
<blockquote>
<p>Text that is a quote</p>
</blockquote>
```
---
### GitHub Alert (NOTE)
```md
> [!NOTE]
> Useful information.
```
```html
<blockquote class="markdown-alert markdown-alert-note">
<p><strong>Note</strong></p>
<p>Useful information.</p>
</blockquote>
```
> ⚠️ The `markdown-alert-*` classes are GitHub-specific, not standard Markdown.
---
## Inline Code
```md
Use `git status` to list files.
```
```html
<p>Use <code>git status</code> to list files.</p>
```
---
## Code Blocks
### Markdown
````md
```markdown
git status
git add
```
````
### Parsed HTML
```html
<pre><code class="language-markdown">
git status
git add
</code></pre>
```
---
## Tables
### Markdown
```md
| Style | Syntax |
|------|--------|
| Bold | ** ** |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th>Style</th>
<th>Syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bold</td>
<td><strong> </strong></td>
</tr>
</tbody>
</table>
```
---
## Links
### Markdown
```md
[GitHub Pages](https://pages.github.com/)
```
### Parsed HTML
```html
<a href="https://pages.github.com/">GitHub Pages</a>
```
---
## Images
### Markdown
```md
![Alt text](image.png)
```
### Parsed HTML
```html
<img src="image.png" alt="Alt text">
```
---
## Lists
### Unordered List
```md
- George Washington
- John Adams
```
```html
<ul>
<li>George Washington</li>
<li>John Adams</li>
</ul>
```
---
### Ordered List
```md
1. James Madison
2. James Monroe
```
```html
<ol>
<li>James Madison</li>
<li>James Monroe</li>
</ol>
```
---
### Nested Lists
```md
1. First item
- Nested item
```
```html
<ol>
<li>
First item
<ul>
<li>Nested item</li>
</ul>
</li>
</ol>
```
---
## Task Lists (GitHub Flavored Markdown)
```md
- [x] Done
- [ ] Pending
```
```html
<ul>
<li>
<input type="checkbox" checked disabled> Done
</li>
<li>
<input type="checkbox" disabled> Pending
</li>
</ul>
```
---
## Mentions
```md
@github/support
```
```html
<a href="https://github.com/github/support" class="user-mention">@github/support</a>
```
---
## Footnotes
### Markdown
```md
Here is a footnote[^1].
[^1]: My reference.
```
### Parsed HTML
```html
<p>
Here is a footnote
<sup id="fnref-1">
<a href="#fn-1">1</a>
</sup>.
</p>
<section class="footnotes">
<ol>
<li id="fn-1">
<p>My reference.</p>
</li>
</ol>
</section>
```
---
## HTML Comments (Hidden Content)
```md
<!-- This content will not appear -->
```
```html
<!-- This content will not appear -->
```
---
## Escaped Markdown Characters
```md
\*not italic\*
```
```html
<p>*not italic*</p>
```
---
## Emoji
```md
:+1:
```
```html
<img class="emoji" alt="👍" src="...">
```
(GitHub replaces emoji with `<img>` tags.)
---

View File

@@ -0,0 +1,496 @@
# Basic writing and formatting syntax
Create sophisticated formatting for your prose and code on GitHub with simple syntax.
## Headings
To create a heading, add one to six <kbd>#</kbd> symbols before your heading text. The number of <kbd>#</kbd> you use will determine the hierarchy level and typeface size of the heading.
```markdown
# A first-level heading
## A second-level heading
### A third-level heading
```
![Screenshot of rendered GitHub Markdown showing sample h1, h2, and h3 headers, which descend in type size and visual weight to show hierarchy level.](https://docs.github.com/assets/images/help/writing/headings-rendered.png)
When you use two or more headings, GitHub automatically generates a table of contents that you can access by clicking the "Outline" menu icon <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-list-unordered" aria-label="Table of Contents" role="img"><path d="M5.75 2.5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5Zm0 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5Zm0 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5ZM2 14a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm1-6a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM2 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"></path></svg> within the file header. Each heading title is listed in the table of contents and you can click a title to navigate to the selected section.
![Screenshot of a README file with the drop-down menu for the table of contents exposed. The table of contents icon is outlined in dark orange.](https://docs.github.com/assets/images/help/repository/headings-toc.png)
## Styling text
You can indicate emphasis with bold, italic, strikethrough, subscript, or superscript text in comment fields and `.md` files.
| Style | Syntax | Keyboard shortcut | Example | Output | |
| ---------------------- | ------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------- | -------------------------------------- | ------------------------------------------------- |
| Bold | `** **` or `__ __` | <kbd>Command</kbd>+<kbd>B</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>B</kbd> (Windows/Linux) | `**This is bold text**` | **This is bold text** | |
| Italic | `* *` or `_ _` | <kbd>Command</kbd>+<kbd>I</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>I</kbd> (Windows/Linux) | `_This text is italicized_` | *This text is italicized* | |
| Strikethrough | `~~ ~~` or `~ ~` | None | `~~This was mistaken text~~` | ~~This was mistaken text~~ | |
| Bold and nested italic | `** **` and `_ _` | None | `**This text is _extremely_ important**` | **This text is *extremely* important** | |
| All bold and italic | `*** ***` | None | `***All this text is important***` | ***All this text is important*** | <!-- markdownlint-disable-line emphasis-style --> |
| Subscript | `<sub> </sub>` | None | `This is a <sub>subscript</sub> text` | This is a <sub>subscript</sub> text | |
| Superscript | `<sup> </sup>` | None | `This is a <sup>superscript</sup> text` | This is a <sup>superscript</sup> text | |
| Underline | `<ins> </ins>` | None | `This is an <ins>underlined</ins> text` | This is an <ins>underlined</ins> text | |
## Quoting text
You can quote text with a <kbd>></kbd>.
```markdown
Text that is not a quote
> Text that is a quote
```
Quoted text is indented with a vertical line on the left and displayed using gray type.
![Screenshot of rendered GitHub Markdown showing the difference between normal and quoted text.](https://docs.github.com/assets/images/help/writing/quoted-text-rendered.png)
> \[!NOTE]
> When viewing a conversation, you can automatically quote text in a comment by highlighting the text, then typing <kbd>R</kbd>. You can quote an entire comment by clicking <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-kebab-horizontal" aria-label="The horizontal kebab icon" role="img"><path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg>, then **Quote reply**. For more information about keyboard shortcuts, see [Keyboard shortcuts](https://docs.github.com/en/get-started/accessibility/keyboard-shortcuts).
## Quoting code
You can call out code or a command within a sentence with single backticks. The text within the backticks will not be formatted. You can also press the <kbd>Command</kbd>+<kbd>E</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>E</kbd> (Windows/Linux) keyboard shortcut to insert the backticks for a code block within a line of Markdown.
```markdown
Use `git status` to list all new or modified files that haven't yet been committed.
```
![Screenshot of rendered GitHub Markdown showing that characters surrounded by backticks are shown in a fixed-width typeface, highlighted in light gray.](https://docs.github.com/assets/images/help/writing/inline-code-rendered.png)
To format code or text into its own distinct block, use triple backticks.
````markdown
Some basic Git commands are:
```
git status
git add
git commit
```
````
![Screenshot of rendered GitHub Markdown showing a simple code block without syntax highlighting.](https://docs.github.com/assets/images/help/writing/code-block-rendered.png)
For more information, see [Creating and highlighting code blocks](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks).
If you are frequently editing code snippets and tables, you may benefit from enabling a fixed-width font in all comment fields on GitHub. For more information, see [About writing and formatting on GitHub](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/about-writing-and-formatting-on-github#enabling-fixed-width-fonts-in-the-editor).
## Supported color models
In issues, pull requests, and discussions, you can call out colors within a sentence by using backticks. A supported color model within backticks will display a visualization of the color.
```markdown
The background color is `#ffffff` for light mode and `#000000` for dark mode.
```
![Screenshot of rendered GitHub Markdown showing how HEX values within backticks create small circles of color, here white and then black.](https://docs.github.com/assets/images/help/writing/supported-color-models-rendered.png)
Here are the currently supported color models.
| Color | Syntax | Example | Output |
| ----- | --------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| HEX | <code>\`#RRGGBB\`</code> | <code>\`#0969DA\`</code> | ![Screenshot of rendered GitHub Markdown showing how HEX value #0969DA appears with a blue circle.](https://docs.github.com/assets/images/help/writing/supported-color-models-hex-rendered.png) |
| RGB | <code>\`rgb(R,G,B)\`</code> | <code>\`rgb(9, 105, 218)\`</code> | ![Screenshot of rendered GitHub Markdown showing how RGB value 9, 105, 218 appears with a blue circle.](https://docs.github.com/assets/images/help/writing/supported-color-models-rgb-rendered.png) |
| HSL | <code>\`hsl(H,S,L)\`</code> | <code>\`hsl(212, 92%, 45%)\`</code> | ![Screenshot of rendered GitHub Markdown showing how HSL value 212, 92%, 45% appears with a blue circle.](https://docs.github.com/assets/images/help/writing/supported-color-models-hsl-rendered.png) |
> \[!NOTE]
>
> * A supported color model cannot have any leading or trailing spaces within the backticks.
> * The visualization of the color is only supported in issues, pull requests, and discussions.
## Links
You can create an inline link by wrapping link text in brackets `[ ]`, and then wrapping the URL in parentheses `( )`. You can also use the keyboard shortcut <kbd>Command</kbd>+<kbd>K</kbd> to create a link. When you have text selected, you can paste a URL from your clipboard to automatically create a link from the selection.
You can also create a Markdown hyperlink by highlighting the text and using the keyboard shortcut <kbd>Command</kbd>+<kbd>V</kbd>. If you'd like to replace the text with the link, use the keyboard shortcut <kbd>Command</kbd>+<kbd>Shift</kbd>+<kbd>V</kbd>.
`This site was built using [GitHub Pages](https://pages.github.com/).`
![Screenshot of rendered GitHub Markdown showing how text within brackets, "GitHub Pages," appears as a blue hyperlink.](https://docs.github.com/assets/images/help/writing/link-rendered.png)
> \[!NOTE]
> GitHub automatically creates links when valid URLs are written in a comment. For more information, see [Autolinked references and URLs](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/autolinked-references-and-urls).
## Section links
You can link directly to any section that has a heading. To view the automatically generated anchor in a rendered file, hover over the section heading to expose the <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-link" aria-label="the link" role="img"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg> icon and click the icon to display the anchor in your browser.
![Screenshot of a README for a repository. To the left of a section heading, a link icon is outlined in dark orange.](https://docs.github.com/assets/images/help/repository/readme-links.png)
If you need to determine the anchor for a heading in a file you are editing, you can use the following basic rules:
* Letters are converted to lower-case.
* Spaces are replaced by hyphens (`-`). Any other whitespace or punctuation characters are removed.
* Leading and trailing whitespace are removed.
* Markup formatting is removed, leaving only the contents (for example, `_italics_` becomes `italics`).
* If the automatically generated anchor for a heading is identical to an earlier anchor in the same document, a unique identifier is generated by appending a hyphen and an auto-incrementing integer.
For more detailed information on the requirements of URI fragments, see [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax, Section 3.5](https://www.rfc-editor.org/rfc/rfc3986#section-3.5).
The code block below demonstrates the basic rules used to generate anchors from headings in rendered content.
```markdown
# Example headings
## Sample Section
## This'll be a _Helpful_ Section About the Greek Letter Θ!
A heading containing characters not allowed in fragments, UTF-8 characters, two consecutive spaces between the first and second words, and formatting.
## This heading is not unique in the file
TEXT 1
## This heading is not unique in the file
TEXT 2
# Links to the example headings above
Link to the sample section: [Link Text](#sample-section).
Link to the helpful section: [Link Text](#thisll-be-a-helpful-section-about-the-greek-letter-Θ).
Link to the first non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file).
Link to the second non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file-1).
```
> \[!NOTE]
> If you edit a heading, or if you change the order of headings with "identical" anchors, you will also need to update any links to those headings as the anchors will change.
## Relative links
You can define relative links and image paths in your rendered files to help readers navigate to other files in your repository.
A relative link is a link that is relative to the current file. For example, if you have a README file in root of your repository, and you have another file in *docs/CONTRIBUTING.md*, the relative link to *CONTRIBUTING.md* in your README might look like this:
```text
[Contribution guidelines for this project](docs/CONTRIBUTING.md)
```
GitHub will automatically transform your relative link or image path based on whatever branch you're currently on, so that the link or path always works. The path of the link will be relative to the current file. Links starting with `/` will be relative to the repository root. You can use all relative link operands, such as `./` and `../`.
Your link text should be on a single line. The example below will not work.
```markdown
[Contribution
guidelines for this project](docs/CONTRIBUTING.md)
```
Relative links are easier for users who clone your repository. Absolute links may not work in clones of your repository - we recommend using relative links to refer to other files within your repository.
## Custom anchors
You can use standard HTML anchor tags (`<a name="unique-anchor-name"></a>`) to create navigation anchor points for any location in the document. To avoid ambiguous references, use a unique naming scheme for anchor tags, such as adding a prefix to the `name` attribute value.
> \[!NOTE]
> Custom anchors will not be included in the document outline/Table of Contents.
You can link to a custom anchor using the value of the `name` attribute you gave the anchor. The syntax is exactly the same as when you link to an anchor that is automatically generated for a heading.
For example:
```markdown
# Section Heading
Some body text of this section.
<a name="my-custom-anchor-point"></a>
Some text I want to provide a direct link to, but which doesn't have its own heading.
(… more content…)
[A link to that custom anchor](#my-custom-anchor-point)
```
> \[!TIP]
> Custom anchors are not considered by the automatic naming and numbering behavior of automatic heading links.
## Line breaks
If you're writing in issues, pull requests, or discussions in a repository, GitHub will render a line break automatically:
```markdown
This example
Will span two lines
```
However, if you are writing in an .md file, the example above would render on one line without a line break. To create a line break in an .md file, you will need to include one of the following:
* Include two spaces at the end of the first line.
<pre>
This example&nbsp;&nbsp;
Will span two lines
</pre>
* Include a backslash at the end of the first line.
```markdown
This example\
Will span two lines
```
* Include an HTML single line break tag at the end of the first line.
```markdown
This example<br/>
Will span two lines
```
If you leave a blank line between two lines, both .md files and Markdown in issues, pull requests, and discussions will render the two lines separated by the blank line:
```markdown
This example
Will have a blank line separating both lines
```
## Images
You can display an image by adding <kbd>!</kbd> and wrapping the alt text in `[ ]`. Alt text is a short text equivalent of the information in the image. Then, wrap the link for the image in parentheses `()`.
`![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://myoctocat.com/assets/images/base-octocat.svg)`
![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://docs.github.com/assets/images/help/writing/image-rendered.png)
GitHub supports embedding images into your issues, pull requests, discussions, comments and `.md` files. You can display an image from your repository, add a link to an online image, or upload an image. For more information, see [Uploading assets](#uploading-assets).
> \[!NOTE]
> When you want to display an image that is in your repository, use relative links instead of absolute links.
Here are some examples for using relative links to display an image.
| Context | Relative Link |
| ----------------------------------------------------------- | ---------------------------------------------------------------------- |
| In a `.md` file on the same branch | `/assets/images/electrocat.png` |
| In a `.md` file on another branch | `/../main/assets/images/electrocat.png` |
| In issues, pull requests and comments of the repository | `../blob/main/assets/images/electrocat.png?raw=true` |
| In a `.md` file in another repository | `/../../../../github/docs/blob/main/assets/images/electrocat.png` |
| In issues, pull requests and comments of another repository | `../../../github/docs/blob/main/assets/images/electrocat.png?raw=true` |
> \[!NOTE]
> The last two relative links in the table above will work for images in a private repository only if the viewer has at least read access to the private repository that contains these images.
For more information, see [Relative Links](#relative-links).
### The Picture element
The `<picture>` HTML element is supported.
## Lists
You can make an unordered list by preceding one or more lines of text with <kbd>-</kbd>, <kbd>\*</kbd>, or <kbd>+</kbd>.
```markdown
- George Washington
* John Adams
+ Thomas Jefferson
```
![Screenshot of rendered GitHub Markdown showing a bulleted list of the names of the first three American presidents.](https://docs.github.com/assets/images/help/writing/unordered-list-rendered.png)
To order your list, precede each line with a number.
```markdown
1. James Madison
2. James Monroe
3. John Quincy Adams
```
![Screenshot of rendered GitHub Markdown showing a numbered list of the names of the fourth, fifth, and sixth American presidents.](https://docs.github.com/assets/images/help/writing/ordered-list-rendered.png)
### Nested Lists
You can create a nested list by indenting one or more list items below another item.
To create a nested list using the web editor on GitHub or a text editor that uses a monospaced font, like [Visual Studio Code](https://code.visualstudio.com/), you can align your list visually. Type space characters in front of your nested list item until the list marker character (<kbd>-</kbd> or <kbd>\*</kbd>) lies directly below the first character of the text in the item above it.
```markdown
1. First list item
- First nested list item
- Second nested list item
```
> \[!NOTE]
> In the web-based editor, you can indent or dedent one or more lines of text by first highlighting the desired lines and then using <kbd>Tab</kbd> or <kbd>Shift</kbd>+<kbd>Tab</kbd> respectively.
![Screenshot of Markdown in Visual Studio Code showing indentation of nested numbered lines and bullets.](https://docs.github.com/assets/images/help/writing/nested-list-alignment.png)
![Screenshot of rendered GitHub Markdown showing a numbered item followed by nested bullets at two different levels of nesting.](https://docs.github.com/assets/images/help/writing/nested-list-example-1.png)
To create a nested list in the comment editor on GitHub, which doesn't use a monospaced font, you can look at the list item immediately above the nested list and count the number of characters that appear before the content of the item. Then type that number of space characters in front of the nested list item.
In this example, you could add a nested list item under the list item `100. First list item` by indenting the nested list item a minimum of five spaces, since there are five characters (`100. `) before `First list item`.
```markdown
100. First list item
- First nested list item
```
![Screenshot of rendered GitHub Markdown showing a numbered item prefaced by the number 100 followed by a bulleted item nested one level.](https://docs.github.com/assets/images/help/writing/nested-list-example-3.png)
You can create multiple levels of nested lists using the same method. For example, because the first nested list item has seven characters (`␣␣␣␣␣-␣`) before the nested list content `First nested list item`, you would need to indent the second nested list item by at least two more characters (nine spaces minimum).
```markdown
100. First list item
- First nested list item
- Second nested list item
```
![Screenshot of rendered GitHub Markdown showing a numbered item prefaced by the number 100 followed by bullets at two different levels of nesting.](https://docs.github.com/assets/images/help/writing/nested-list-example-2.png)
For more examples, see the [GitHub Flavored Markdown Spec](https://github.github.com/gfm/#example-265).
## Task lists
To create a task list, preface list items with a hyphen and space followed by `[ ]`. To mark a task as complete, use `[x]`.
```markdown
- [x] #739
- [ ] https://github.com/octo-org/octo-repo/issues/740
- [ ] Add delight to the experience when all tasks are complete :tada:
```
![Screenshot showing the rendered version of the markdown. The references to issues are rendered as issue titles.](https://docs.github.com/assets/images/help/writing/task-list-rendered-simple.png)
If a task list item description begins with a parenthesis, you'll need to escape it with <kbd>\\</kbd>:
`- [ ] \(Optional) Open a followup issue`
For more information, see [About tasklists](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/about-task-lists).
## Mentioning people and teams
You can mention a person or [team](https://docs.github.com/en/organizations/organizing-members-into-teams) on GitHub by typing <kbd>@</kbd> plus their username or team name. This will trigger a notification and bring their attention to the conversation. People will also receive a notification if you edit a comment to mention their username or team name. For more information about notifications, see [About notifications](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/about-notifications).
> \[!NOTE]
> A person will only be notified about a mention if the person has read access to the repository and, if the repository is owned by an organization, the person is a member of the organization.
`@github/support What do you think about these updates?`
![Screenshot of rendered GitHub Markdown showing how the team mention "@github/support" renders as bold, clickable text.](https://docs.github.com/assets/images/help/writing/mention-rendered.png)
When you mention a parent team, members of its child teams also receive notifications, simplifying communication with multiple groups of people. For more information, see [About organization teams](https://docs.github.com/en/organizations/organizing-members-into-teams/about-teams).
Typing an <kbd>@</kbd> symbol will bring up a list of people or teams on a project. The list filters as you type, so once you find the name of the person or team you are looking for, you can use the arrow keys to select it and press either tab or enter to complete the name. For teams, enter the @organization/team-name and all members of that team will get subscribed to the conversation.
The autocomplete results are restricted to repository collaborators and any other participants on the thread.
## Referencing issues and pull requests
You can bring up a list of suggested issues and pull requests within the repository by typing <kbd>#</kbd>. Type the issue or pull request number or title to filter the list, and then press either tab or enter to complete the highlighted result.
For more information, see [Autolinked references and URLs](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/autolinked-references-and-urls).
## Referencing external resources
If custom autolink references are configured for a repository, then references to external resources, like a JIRA issue or Zendesk ticket, convert into shortened links. To know which autolinks are available in your repository, contact someone with admin permissions to the repository. For more information, see [Configuring autolinks to reference external resources](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/configuring-autolinks-to-reference-external-resources).
## Uploading assets
You can upload assets like images by dragging and dropping, selecting from a file browser, or pasting. You can upload assets to issues, pull requests, comments, and `.md` files in your repository.
## Using emojis
You can add emoji to your writing by typing `:EMOJICODE:`, a colon followed by the name of the emoji.
`@octocat :+1: This PR looks great - it's ready to merge! :shipit:`
![Screenshot of rendered GitHub Markdown showing how emoji codes for +1 and shipit render visually as emoji.](https://docs.github.com/assets/images/help/writing/emoji-rendered.png)
Typing <kbd>:</kbd> will bring up a list of suggested emoji. The list will filter as you type, so once you find the emoji you're looking for, press **Tab** or **Enter** to complete the highlighted result.
For a full list of available emoji and codes, see [the Emoji-Cheat-Sheet](https://github.com/ikatyang/emoji-cheat-sheet/blob/github-actions-auto-update/README.md).
## Paragraphs
You can create a new paragraph by leaving a blank line between lines of text.
## Footnotes
You can add footnotes to your content by using this bracket syntax:
```text
Here is a simple footnote[^1].
A footnote can also have multiple lines[^2].
[^1]: My reference.
[^2]: To add line breaks within a footnote, add 2 spaces to the end of a line.
This is a second line.
```
The footnote will render like this:
![Screenshot of rendered Markdown showing superscript numbers used to indicate footnotes, along with optional line breaks inside a note.](https://docs.github.com/assets/images/help/writing/footnote-rendered.png)
> \[!NOTE]
> The position of a footnote in your Markdown does not influence where the footnote will be rendered. You can write a footnote right after your reference to the footnote, and the footnote will still render at the bottom of the Markdown. Footnotes are not supported in wikis.
## Alerts
**Alerts**, also sometimes known as **callouts** or **admonitions**, are a Markdown extension based on the blockquote syntax that you can use to emphasize critical information. On GitHub, they are displayed with distinctive colors and icons to indicate the significance of the content.
Use alerts only when they are crucial for user success and limit them to one or two per article to prevent overloading the reader. Additionally, you should avoid placing alerts consecutively. Alerts cannot be nested within other elements.
To add an alert, use a special blockquote line specifying the alert type, followed by the alert information in a standard blockquote. Five types of alerts are available:
```markdown
> [!NOTE]
> Useful information that users should know, even when skimming content.
> [!TIP]
> Helpful advice for doing things better or more easily.
> [!IMPORTANT]
> Key information users need to know to achieve their goal.
> [!WARNING]
> Urgent info that needs immediate user attention to avoid problems.
> [!CAUTION]
> Advises about risks or negative outcomes of certain actions.
```
Here are the rendered alerts:
![Screenshot of rendered Markdown alerts showing how Note, Tip, Important, Warning, and Caution render with different colored text and icons.](https://docs.github.com/assets/images/help/writing/alerts-rendered.png)
## Hiding content with comments
You can tell GitHub to hide content from the rendered Markdown by placing the content in an HTML comment.
```text
<!-- This content will not appear in the rendered Markdown -->
```
## Ignoring Markdown formatting
You can tell GitHub to ignore (or escape) Markdown formatting by using <kbd>\\</kbd> before the Markdown character.
`Let's rename \*our-new-project\* to \*our-old-project\*.`
![Screenshot of rendered GitHub Markdown showing how backslashes prevent the conversion of asterisks to italics.](https://docs.github.com/assets/images/help/writing/escaped-character-rendered.png)
For more information on backslashes, see Daring Fireball's [Markdown Syntax](https://daringfireball.net/projects/markdown/syntax#backslash).
> \[!NOTE]
> The Markdown formatting will not be ignored in the title of an issue or a pull request.
## Disabling Markdown rendering
When viewing a Markdown file, you can click **Code** at the top of the file to disable Markdown rendering and view the file's source instead.
![Screenshot of a Markdown file in a repository showing options for interacting with the file. A button, labeled "Code", is outlined in dark orange.](https://docs.github.com/assets/images/help/writing/display-markdown-as-source-global-nav-update.png)
Disabling Markdown rendering enables you to use source view features, such as line linking, which is not possible when viewing rendered Markdown files.
## Further reading
*[GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
*[About writing and formatting on GitHub](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/about-writing-and-formatting-on-github)
*[Working with advanced formatting](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting)
*[Quickstart for writing on GitHub](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/quickstart-for-writing-on-github)

View File

@@ -0,0 +1,165 @@
# Code Blocks to HTML
## Fenced Code Blocks (No Language)
### Markdown
```
function test() {
console.log("notice the blank line before this function?");
}
```
### Parsed HTML
```html
<pre><code>
function test() {
console.log("notice the blank line before this function?");
}
</code></pre>
```
---
## GitHub Tip Callout
### Markdown
```md
> [!TIP]
> To preserve your formatting within a list, make sure to indent non-fenced code blocks by eight spaces.
```
### Parsed HTML (GitHub-specific)
```html
<blockquote class="markdown-alert markdown-alert-tip">
<p><strong>Tip</strong></p>
<p>To preserve your formatting within a list, make sure to indent non-fenced code blocks by eight spaces.</p>
</blockquote>
```
---
## Showing Backticks Inside Code Blocks
### Markdown
`````md
````
```
Look! You can see my backticks.
```
````
`````
### Parsed HTML
```html
<pre><code>
```
Look! You can see my backticks.
```
</code></pre>
```
## Syntax Highlighting (Language Identifier)
### Markdown
```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```
### Parsed HTML
```html
<pre><code class="language-ruby">
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
</code></pre>
```
> The `language-ruby` class is consumed by GitHubs syntax highlighter (Linguist + grammar).
### Summary: Syntax-Highlighting Rules (HTML-Level)
| Markdown fence | Parsed `<code>` tag |
| -------------- | ------------------------------ |
| ```js | `<code class="language-js">` |
| ```html | `<code class="language-html">` |
| ```md | `<code class="language-md">` |
| ``` (no lang) | `<code>` |
---
## HTML Comments (Ignored by Renderer)
```md
<!-- Internal documentation comment -->
```
```html
<!-- Internal documentation comment -->
```
---
## Links
```md
[About writing and formatting on GitHub](https://docs.github.com/...)
```
```html
<a href="https://docs.github.com/...">About writing and formatting on GitHub</a>
```
---
## Lists
```md
* [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
```
```html
<ul>
<li>
<a href="https://github.github.com/gfm/">GitHub Flavored Markdown Spec</a>
</li>
</ul>
```
---
## Diagrams (Conceptual Parsing)
### Markdown
````md
```mermaid
graph TD
A --> B
```
````
### Parsed HTML
```html
<pre><code class="language-mermaid">
graph TD
A --> B
</code></pre>
```
## Closing Notes
* No `language-*` class appears here because **no language identifier** was provided.
* The inner triple backticks are preserved **as literal text** inside `<code>`.

View File

@@ -0,0 +1,70 @@
# Creating and highlighting code blocks
Share samples of code with fenced code blocks and enabling syntax highlighting.
## Fenced code blocks
You can create fenced code blocks by placing triple backticks <code>\`\`\`</code> before and after the code block. We recommend placing a blank line before and after code blocks to make the raw formatting easier to read.
````text
```
function test() {
console.log("notice the blank line before this function?");
}
```
````
![Screenshot of rendered GitHub Markdown showing the use of triple backticks to create code blocks. The block begins with "function test() {."](https://docs.github.com/assets/images/help/writing/fenced-code-block-rendered.png)
> \[!TIP]
> To preserve your formatting within a list, make sure to indent non-fenced code blocks by eight spaces.
To display triple backticks in a fenced code block, wrap them inside quadruple backticks.
`````text
````
```
Look! You can see my backticks.
```
````
`````
![Screenshot of rendered Markdown showing that when you write triple backticks between quadruple backticks they are visible in the rendered content.](https://docs.github.com/assets/images/help/writing/fenced-code-show-backticks-rendered.png)
If you are frequently editing code snippets and tables, you may benefit from enabling a fixed-width font in all comment fields on GitHub. For more information, see [About writing and formatting on GitHub](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/about-writing-and-formatting-on-github#enabling-fixed-width-fonts-in-the-editor).
## Syntax highlighting
<!-- If you make changes to this feature, check whether any of the changes affect languages listed in /get-started/learning-about-github/github-language-support. If so, please update the language support article accordingly. -->
You can add an optional language identifier to enable syntax highlighting in your fenced code block.
Syntax highlighting changes the color and style of source code to make it easier to read.
For example, to syntax highlight Ruby code:
````text
```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```
````
This will display the code block with syntax highlighting:
![Screenshot of three lines of Ruby code as displayed on GitHub. Elements of the code display in purple, blue, and red type for scannability.](https://docs.github.com/assets/images/help/writing/code-block-syntax-highlighting-rendered.png)
> \[!TIP]
> When you create a fenced code block that you also want to have syntax highlighting on a GitHub Pages site, use lower-case language identifiers. For more information, see [About GitHub Pages and Jekyll](https://docs.github.com/pages/setting-up-a-github-pages-site-with-jekyll/about-github-pages-and-jekyll#syntax-highlighting).
We use [Linguist](https://github.com/github-linguist/linguist) to perform language detection and to select [third-party grammars](https://github.com/github-linguist/linguist/blob/main/vendor/README.md) for syntax highlighting. You can find out which keywords are valid in [the languages YAML file](https://github.com/github-linguist/linguist/blob/main/lib/linguist/languages.yml).
## Creating diagrams
You can also use code blocks to create diagrams in Markdown. GitHub supports Mermaid, GeoJSON, TopoJSON, and ASCII STL syntax. For more information, see [Creating diagrams](https://docs.github.com/get-started/writing-on-github/working-with-advanced-formatting/creating-diagrams).
## Further reading
* [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
* [Basic writing and formatting syntax](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)

View File

@@ -0,0 +1,136 @@
# Collapsed Sections to HTML
## `<details>` Block (Raw HTML in Markdown)
### Markdown
````md
<details>
<summary>Tips for collapsed sections</summary>
### You can add a header
You can add text within a collapsed section.
You can add an image or a code block, too.
```ruby
puts "Hello World"
```
</details>
````
---
### Parsed HTML
```html
<details>
<summary>Tips for collapsed sections</summary>
<h3>You can add a header</h3>
<p>You can add text within a collapsed section.</p>
<p>You can add an image or a code block, too.</p>
<pre><code class="language-ruby">
puts "Hello World"
</code></pre>
</details>
```
#### Notes:
* Markdown **inside `<details>`** is still parsed normally.
* Syntax highlighting is preserved via `class="language-ruby"`.
---
## Open by Default (`open` attribute)
### Markdown
````md
<details open>
<summary>Tips for collapsed sections</summary>
### You can add a header
You can add text within a collapsed section.
You can add an image or a code block, too.
```ruby
puts "Hello World"
```
</details>
````
### Parsed HTML
```html
<details open>
<summary>Tips for collapsed sections</summary>
<h3>You can add a header</h3>
<p>You can add text within a collapsed section.</p>
<p>You can add an image or a code block, too.</p>
<pre><code class="language-ruby">
puts "Hello World"
</code></pre>
</details>
```
## Key Rules
* `<details>` and `<summary>` are **raw HTML**, not Markdown syntax
* Markdown inside `<details>` **is still parsed**
* Syntax highlighting works normally inside collapsed sections
* Use `<summary>` as the **clickable label**
## Paragraphs with Inline HTML & SVG
### Markdown
```md
You can streamline your Markdown by creating a collapsed section with the `<details>` tag.
```
### Parsed HTML
```html
<p>
You can streamline your Markdown by creating a collapsed section with the <code>&lt;details&gt;</code> tag.
</p>
```
---
### Markdown (inline SVG preserved)
```md
Any Markdown within the `<details>` block will be collapsed until the reader clicks <svg ...></svg> to expand the details.
```
### Parsed HTML
```html
<p>
Any Markdown within the <code>&lt;details&gt;</code> block will be collapsed until the reader clicks
<svg version="1.1" width="16" height="16" viewBox="0 0 16 16"
class="octicon octicon-triangle-right"
aria-label="The right triangle icon"
role="img">
<path d="m6.427 4.427 3.396 3.396a.25.25 0 0 1 0 .354l-3.396 3.396A.25.25 0 0 1 6 11.396V4.604a.25.25 0 0 1 .427-.177Z"></path>
</svg>
to expand the details.
</p>
```

View File

@@ -0,0 +1,48 @@
# Organizing information with collapsed sections
You can streamline your Markdown by creating a collapsed section with the `<details>` tag.
## Creating a collapsed section
You can temporarily obscure sections of your Markdown by creating a collapsed section that the reader can choose to expand. For example, when you want to include technical details in an issue comment that may not be relevant or interesting to every reader, you can put those details in a collapsed section.
Any Markdown within the `<details>` block will be collapsed until the reader clicks <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-triangle-right" aria-label="The right triangle icon" role="img"><path d="m6.427 4.427 3.396 3.396a.25.25 0 0 1 0 .354l-3.396 3.396A.25.25 0 0 1 6 11.396V4.604a.25.25 0 0 1 .427-.177Z"></path></svg> to expand the details.
Within the `<details>` block, use the `<summary>` tag to let readers know what is inside. The label appears to the right of <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-triangle-right" aria-label="The right triangle icon" role="img"><path d="m6.427 4.427 3.396 3.396a.25.25 0 0 1 0 .354l-3.396 3.396A.25.25 0 0 1 6 11.396V4.604a.25.25 0 0 1 .427-.177Z"></path></svg>.
````markdown
<details>
<summary>Tips for collapsed sections</summary>
### You can add a header
You can add text within a collapsed section.
You can add an image or a code block, too.
```ruby
puts "Hello World"
```
</details>
````
The Markdown inside the `<summary>` label will be collapsed by default:
![Screenshot of the Markdown above on this page as rendered on GitHub, showing a right-facing arrow and the header "Tips for collapsed sections."](https://docs.github.com/assets/images/help/writing/collapsed-section-view.png)
After a reader clicks <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-triangle-right" aria-label="The right triangle icon" role="img"><path d="m6.427 4.427 3.396 3.396a.25.25 0 0 1 0 .354l-3.396 3.396A.25.25 0 0 1 6 11.396V4.604a.25.25 0 0 1 .427-.177Z"></path></svg>, the details are expanded:
![Screenshot of the Markdown above on this page as rendered on GitHub. The collapsed section contains headers, text, images, and code blocks.](https://docs.github.com/assets/images/help/writing/open-collapsed-section.png)
Optionally, to make the section display as open by default, add the `open` attribute to the `<details>` tag:
```html
<details open>
```
## Further reading
* [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
* [Basic writing and formatting syntax](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)

View File

@@ -0,0 +1,253 @@
# gomarkdown/markdown Reference
Go library for parsing Markdown and rendering HTML. Fast, extensible, and thread-safe.
## Installation
```bash
# Add to your Go project
go get github.com/gomarkdown/markdown
# Install CLI tool
go install github.com/gomarkdown/mdtohtml@latest
```
## Basic Usage
### Simple Conversion
```go
package main
import (
"fmt"
"github.com/gomarkdown/markdown"
)
func main() {
md := []byte("# Hello World\n\nThis is **bold** text.")
html := markdown.ToHTML(md, nil, nil)
fmt.Println(string(html))
}
```
### Using CLI Tool
```bash
# Convert file to HTML
mdtohtml input.md output.html
# Output to stdout
mdtohtml input.md
```
## Parser Configuration
### Common Extensions
```go
import (
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/parser"
)
// Create parser with extensions
extensions := parser.CommonExtensions | parser.AutoHeadingIDs
p := parser.NewWithExtensions(extensions)
// Parse markdown
doc := p.Parse(md)
```
### Available Parser Extensions
| Extension | Description |
|-----------|-------------|
| `parser.CommonExtensions` | Tables, fenced code, autolinks, strikethrough |
| `parser.Tables` | Pipe tables support |
| `parser.FencedCode` | Fenced code blocks with language |
| `parser.Autolink` | Auto-detect URLs |
| `parser.Strikethrough` | ~~strikethrough~~ text |
| `parser.SpaceHeadings` | Require space after # in headings |
| `parser.HeadingIDs` | Custom heading IDs {#id} |
| `parser.AutoHeadingIDs` | Auto-generate heading IDs |
| `parser.Footnotes` | Footnote support |
| `parser.NoEmptyLineBeforeBlock` | No blank line required before blocks |
| `parser.HardLineBreak` | Newlines become `<br>` |
| `parser.MathJax` | MathJax support |
| `parser.SuperSubscript` | Super^script^ and sub~script~ |
| `parser.Mmark` | Mmark syntax support |
## HTML Renderer Configuration
### Common Flags
```go
import (
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
)
// Parser
p := parser.NewWithExtensions(parser.CommonExtensions)
// Renderer
htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{
Flags: htmlFlags,
Title: "My Document",
CSS: "style.css",
}
renderer := html.NewRenderer(opts)
// Convert
html := markdown.ToHTML(md, p, renderer)
```
### Available HTML Flags
| Flag | Description |
|------|-------------|
| `html.CommonFlags` | Common sensible defaults |
| `html.HrefTargetBlank` | Add `target="_blank"` to links |
| `html.CompletePage` | Generate complete HTML document |
| `html.UseXHTML` | Use XHTML output |
| `html.FootnoteReturnLinks` | Add return links in footnotes |
| `html.FootnoteNoHRTag` | No `<hr>` before footnotes |
| `html.Smartypants` | Smart punctuation |
| `html.SmartypantsFractions` | Smart fractions (1/2 → ½) |
| `html.SmartypantsDashes` | Smart dashes (-- → ) |
| `html.SmartypantsLatexDashes` | LaTeX-style dashes |
### Renderer Options
```go
opts := html.RendererOptions{
Flags: htmlFlags,
Title: "Document Title",
CSS: "path/to/style.css",
Icon: "favicon.ico",
Head: []byte("<meta name='author' content='...'>"),
RenderNodeHook: customRenderHook,
}
```
## Complete Example
```go
package main
import (
"os"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
)
func mdToHTML(md []byte) []byte {
// Parser with extensions
extensions := parser.CommonExtensions |
parser.AutoHeadingIDs |
parser.NoEmptyLineBeforeBlock
p := parser.NewWithExtensions(extensions)
doc := p.Parse(md)
// HTML renderer with options
htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{Flags: htmlFlags}
renderer := html.NewRenderer(opts)
return markdown.Render(doc, renderer)
}
func main() {
md, _ := os.ReadFile("input.md")
html := mdToHTML(md)
os.WriteFile("output.html", html, 0644)
}
```
## Security: Sanitizing Output
**Important:** gomarkdown does not sanitize HTML output. Use Bluemonday for untrusted input:
```go
import (
"github.com/microcosm-cc/bluemonday"
"github.com/gomarkdown/markdown"
)
// Convert markdown to potentially unsafe HTML
unsafeHTML := markdown.ToHTML(md, nil, nil)
// Sanitize using Bluemonday
p := bluemonday.UGCPolicy()
safeHTML := p.SanitizeBytes(unsafeHTML)
```
### Bluemonday Policies
| Policy | Description |
|--------|-------------|
| `UGCPolicy()` | User-generated content (most common) |
| `StrictPolicy()` | Strip all HTML |
| `StripTagsPolicy()` | Strip tags, keep text |
| `NewPolicy()` | Build custom policy |
## Working with AST
### Accessing the AST
```go
import (
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/parser"
)
p := parser.NewWithExtensions(parser.CommonExtensions)
doc := p.Parse(md)
// Walk the AST
ast.WalkFunc(doc, func(node ast.Node, entering bool) ast.WalkStatus {
if heading, ok := node.(*ast.Heading); ok && entering {
fmt.Printf("Found heading level %d\n", heading.Level)
}
return ast.GoToNext
})
```
### Custom Renderer
```go
type MyRenderer struct {
*html.Renderer
}
func (r *MyRenderer) RenderNode(w io.Writer, node ast.Node, entering bool) ast.WalkStatus {
// Custom rendering logic
if heading, ok := node.(*ast.Heading); ok && entering {
fmt.Fprintf(w, "<h%d class='custom'>", heading.Level)
return ast.GoToNext
}
return r.Renderer.RenderNode(w, node, entering)
}
```
## Handling Newlines
Windows and Mac newlines need normalization:
```go
// Normalize newlines before parsing
normalized := parser.NormalizeNewlines(input)
html := markdown.ToHTML(normalized, nil, nil)
```
## Resources
- [Package Documentation](https://pkg.go.dev/github.com/gomarkdown/markdown)
- [Advanced Processing Guide](https://blog.kowalczyk.info/article/cxn3/advanced-markdown-processing-in-go.html)
- [GitHub Repository](https://github.com/gomarkdown/markdown)
- [CLI Tool](https://github.com/gomarkdown/mdtohtml)
- [Bluemonday Sanitizer](https://github.com/microcosm-cc/bluemonday)

View File

@@ -0,0 +1,394 @@
# Hugo Reference
Hugo is the world's fastest static site generator. It builds sites in milliseconds and supports advanced content management features.
## Installation
### Windows
```powershell
# Using Chocolatey
choco install hugo-extended
# Using Scoop
scoop install hugo-extended
# Using Winget
winget install Hugo.Hugo.Extended
```
### macOS
```bash
# Using Homebrew
brew install hugo
```
### Linux
```bash
# Debian/Ubuntu (snap)
snap install hugo --channel=extended
# Using package manager (may not be latest)
sudo apt-get install hugo
# Or download from https://gohugo.io/installation/
```
## Quick Start
### Create New Site
```bash
# Create site
hugo new site mysite
cd mysite
# Initialize git and add theme
git init
git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke
echo "theme = 'ananke'" >> hugo.toml
# Create first post
hugo new content posts/my-first-post.md
# Start development server
hugo server -D
```
### Directory Structure
```
mysite/
├── archetypes/ # Content templates
│ └── default.md
├── assets/ # Assets to process (SCSS, JS)
├── content/ # Markdown content
│ └── posts/
├── data/ # Data files (YAML, JSON, TOML)
├── i18n/ # Internationalization
├── layouts/ # Templates
│ ├── _default/
│ ├── partials/
│ └── shortcodes/
├── static/ # Static files (copied as-is)
├── themes/ # Themes
└── hugo.toml # Configuration
```
## CLI Commands
| Command | Description |
|---------|-------------|
| `hugo new site <name>` | Create new site |
| `hugo new content <path>` | Create content file |
| `hugo` | Build to `public/` |
| `hugo server` | Start dev server |
| `hugo mod init` | Initialize Hugo Modules |
| `hugo mod tidy` | Clean up modules |
### Build Options
```bash
# Basic build
hugo
# Build with minification
hugo --minify
# Build with drafts
hugo -D
# Build for specific environment
hugo --environment production
# Build to custom directory
hugo -d ./dist
# Verbose output
hugo -v
```
### Server Options
```bash
# Start with drafts
hugo server -D
# Bind to all interfaces
hugo server --bind 0.0.0.0
# Custom port
hugo server --port 8080
# Disable live reload
hugo server --disableLiveReload
# Navigate to changed content
hugo server --navigateToChanged
```
## Configuration (hugo.toml)
```toml
# Basic settings
baseURL = 'https://example.com/'
languageCode = 'en-us'
title = 'My Hugo Site'
theme = 'ananke'
# Build settings
[build]
writeStats = true
# Markdown configuration
[markup]
[markup.goldmark]
[markup.goldmark.extensions]
definitionList = true
footnote = true
linkify = true
strikethrough = true
table = true
taskList = true
[markup.goldmark.parser]
autoHeadingID = true
autoHeadingIDType = 'github'
[markup.goldmark.renderer]
unsafe = false
[markup.highlight]
style = 'monokai'
lineNos = true
# Taxonomies
[taxonomies]
category = 'categories'
tag = 'tags'
author = 'authors'
# Menus
[menus]
[[menus.main]]
name = 'Home'
pageRef = '/'
weight = 10
[[menus.main]]
name = 'Posts'
pageRef = '/posts'
weight = 20
# Parameters
[params]
description = 'My awesome site'
author = 'John Doe'
```
## Front Matter
Hugo supports TOML, YAML, and JSON front matter:
### TOML (default)
```markdown
+++
title = 'My First Post'
date = 2025-01-28T12:00:00-05:00
draft = false
tags = ['hugo', 'tutorial']
categories = ['blog']
author = 'John Doe'
+++
Content here...
```
### YAML
```markdown
---
title: "My First Post"
date: 2025-01-28T12:00:00-05:00
draft: false
tags: ["hugo", "tutorial"]
---
Content here...
```
## Templates
### Base Template (_default/baseof.html)
```html
<!DOCTYPE html>
<html>
<head>
<title>{{ .Title }} | {{ .Site.Title }}</title>
{{ partial "head.html" . }}
</head>
<body>
{{ partial "header.html" . }}
<main>
{{ block "main" . }}{{ end }}
</main>
{{ partial "footer.html" . }}
</body>
</html>
```
### Single Page (_default/single.html)
```html
{{ define "main" }}
<article>
<h1>{{ .Title }}</h1>
<time>{{ .Date.Format "January 2, 2006" }}</time>
{{ .Content }}
</article>
{{ end }}
```
### List Page (_default/list.html)
```html
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ range .Pages }}
<article>
<h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
<p>{{ .Summary }}</p>
</article>
{{ end }}
{{ end }}
```
## Shortcodes
### Built-in Shortcodes
```markdown
{{< figure src="/images/photo.jpg" title="My Photo" >}}
{{< youtube dQw4w9WgXcQ >}}
{{< gist user 12345 >}}
{{< highlight go >}}
fmt.Println("Hello")
{{< /highlight >}}
```
### Custom Shortcode (layouts/shortcodes/alert.html)
```html
<div class="alert alert-{{ .Get "type" | default "info" }}">
{{ .Inner | markdownify }}
</div>
```
Usage:
```markdown
{{< alert type="warning" >}}
**Warning:** This is important!
{{< /alert >}}
```
## Content Organization
### Page Bundles
```
content/
├── posts/
│ └── my-post/ # Page bundle
│ ├── index.md # Content
│ └── image.jpg # Resources
└── _index.md # Section page
```
### Accessing Resources
```html
{{ $image := .Resources.GetMatch "image.jpg" }}
{{ with $image }}
<img src="{{ .RelPermalink }}" alt="...">
{{ end }}
```
## Hugo Pipes (Asset Processing)
### SCSS Compilation
```html
{{ $styles := resources.Get "scss/main.scss" | toCSS | minify }}
<link rel="stylesheet" href="{{ $styles.RelPermalink }}">
```
### JavaScript Bundling
```html
{{ $js := resources.Get "js/main.js" | js.Build | minify }}
<script src="{{ $js.RelPermalink }}"></script>
```
## Taxonomies
### Configure
```toml
[taxonomies]
tag = 'tags'
category = 'categories'
```
### Use in Front Matter
```markdown
+++
tags = ['go', 'hugo']
categories = ['tutorials']
+++
```
### List Taxonomy Terms
```html
{{ range .Site.Taxonomies.tags }}
<a href="{{ .Page.Permalink }}">{{ .Page.Title }} ({{ .Count }})</a>
{{ end }}
```
## Multilingual Sites
```toml
defaultContentLanguage = 'en'
[languages]
[languages.en]
title = 'My Site'
weight = 1
[languages.es]
title = 'Mi Sitio'
weight = 2
```
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Page not found | Check `baseURL` configuration |
| Theme not loading | Verify theme path in config |
| Raw HTML not showing | Set `unsafe = true` in goldmark config |
| Slow builds | Use `--templateMetrics` to debug |
| Module errors | Run `hugo mod tidy` |
| CSS not updating | Clear browser cache or use fingerprinting |
## Resources
- [Hugo Documentation](https://gohugo.io/documentation/)
- [Hugo Themes](https://themes.gohugo.io/)
- [Hugo Discourse](https://discourse.gohugo.io/)
- [GitHub Repository](https://github.com/gohugoio/hugo)
- [Quick Reference](https://gohugo.io/quick-reference/)

View File

@@ -0,0 +1,321 @@
# Jekyll Reference
Jekyll is a static site generator that transforms Markdown content into complete websites. It's blog-aware and powers GitHub Pages.
## Installation
### Prerequisites
- Ruby 2.7.0 or higher
- RubyGems
- GCC and Make
### Install Jekyll
```bash
# Install Jekyll and Bundler
gem install jekyll bundler
```
### Platform-Specific Installation
```bash
# macOS (install Xcode CLI tools first)
xcode-select --install
gem install jekyll bundler
# Ubuntu/Debian
sudo apt-get install ruby-full build-essential zlib1g-dev
gem install jekyll bundler
# Windows (use RubyInstaller)
# Download from https://rubyinstaller.org/
gem install jekyll bundler
```
## Quick Start
### Create New Site
```bash
# Create new Jekyll site
jekyll new myblog
# Navigate to site
cd myblog
# Build and serve
bundle exec jekyll serve
# Open http://localhost:4000
```
### Directory Structure
```
myblog/
├── _config.yml # Site configuration
├── _posts/ # Blog posts
│ └── 2025-01-28-welcome.md
├── _layouts/ # Page templates
├── _includes/ # Reusable components
├── _data/ # Data files (YAML, JSON, CSV)
├── _sass/ # Sass partials
├── assets/ # CSS, JS, images
├── index.md # Home page
└── Gemfile # Ruby dependencies
```
## CLI Commands
| Command | Description |
|---------|-------------|
| `jekyll new <name>` | Create new site |
| `jekyll build` | Build to `_site/` |
| `jekyll serve` | Build and serve locally |
| `jekyll clean` | Remove generated files |
| `jekyll doctor` | Check for issues |
### Build Options
```bash
# Build site
bundle exec jekyll build
# Build with production environment
JEKYLL_ENV=production bundle exec jekyll build
# Build to custom directory
bundle exec jekyll build --destination ./public
# Build with incremental regeneration
bundle exec jekyll build --incremental
```
### Serve Options
```bash
# Serve with live reload
bundle exec jekyll serve --livereload
# Include draft posts
bundle exec jekyll serve --drafts
# Specify port
bundle exec jekyll serve --port 8080
# Bind to all interfaces
bundle exec jekyll serve --host 0.0.0.0
```
## Configuration (_config.yml)
```yaml
# Site settings
title: My Blog
description: A great blog
baseurl: ""
url: "https://example.com"
# Build settings
markdown: kramdown
theme: minima
plugins:
- jekyll-feed
- jekyll-seo-tag
# Kramdown settings
kramdown:
input: GFM
syntax_highlighter: rouge
hard_wrap: false
# Collections
collections:
docs:
output: true
permalink: /docs/:name/
# Defaults
defaults:
- scope:
path: ""
type: "posts"
values:
layout: "post"
# Exclude from processing
exclude:
- Gemfile
- Gemfile.lock
- node_modules
- vendor
```
## Front Matter
Every content file needs YAML front matter:
```markdown
---
layout: post
title: "My First Post"
date: 2025-01-28 12:00:00 -0500
categories: blog tutorial
tags: [jekyll, markdown]
author: John Doe
excerpt: "A brief introduction..."
published: true
---
Your content here...
```
## Markdown Processors
### Kramdown (Default)
```yaml
# _config.yml
markdown: kramdown
kramdown:
input: GFM # GitHub Flavored Markdown
syntax_highlighter: rouge
syntax_highlighter_opts:
block:
line_numbers: true
```
### CommonMark
```ruby
# Gemfile
gem 'jekyll-commonmark-ghpages'
```
```yaml
# _config.yml
markdown: CommonMarkGhPages
commonmark:
options: ["SMART", "FOOTNOTES"]
extensions: ["strikethrough", "autolink", "table"]
```
## Liquid Templating
### Variables
```liquid
{{ page.title }}
{{ site.title }}
{{ content }}
{{ page.date | date: "%B %d, %Y" }}
```
### Loops
```liquid
{% for post in site.posts %}
<article>
<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
<p>{{ post.excerpt }}</p>
</article>
{% endfor %}
```
### Conditionals
```liquid
{% if page.title %}
<h1>{{ page.title }}</h1>
{% endif %}
{% unless page.draft %}
{{ content }}
{% endunless %}
```
### Includes
```liquid
{% include header.html %}
{% include footer.html param="value" %}
```
## Layouts
### Basic Layout (_layouts/default.html)
```html
<!DOCTYPE html>
<html>
<head>
<title>{{ page.title }} | {{ site.title }}</title>
<link rel="stylesheet" href="{{ '/assets/css/style.css' | relative_url }}">
</head>
<body>
{% include header.html %}
<main>
{{ content }}
</main>
{% include footer.html %}
</body>
</html>
```
### Post Layout (_layouts/post.html)
```html
---
layout: default
---
<article>
<h1>{{ page.title }}</h1>
<time>{{ page.date | date: "%B %d, %Y" }}</time>
{{ content }}
</article>
```
## Plugins
### Common Plugins
```ruby
# Gemfile
group :jekyll_plugins do
gem 'jekyll-feed' # RSS feed
gem 'jekyll-seo-tag' # SEO meta tags
gem 'jekyll-sitemap' # XML sitemap
gem 'jekyll-paginate' # Pagination
gem 'jekyll-archives' # Archive pages
end
```
### Using Plugins
```yaml
# _config.yml
plugins:
- jekyll-feed
- jekyll-seo-tag
- jekyll-sitemap
```
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Ruby 3.0+ webrick error | `bundle add webrick` |
| Permission denied | Use `--user-install` or rbenv |
| Slow builds | Use `--incremental` |
| Liquid errors | Check for unescaped `{` `}` |
| Encoding issues | Add `encoding: utf-8` to config |
| Plugin not loading | Add to both Gemfile and _config.yml |
## Resources
- [Jekyll Documentation](https://jekyllrb.com/docs/)
- [Liquid Template Language](https://shopify.github.io/liquid/)
- [Kramdown Documentation](https://kramdown.gettalong.org/)
- [GitHub Repository](https://github.com/jekyll/jekyll)
- [Jekyll Themes](https://jekyllthemes.io/)

View File

@@ -0,0 +1,121 @@
# Marked
## Quick Conversion Methods
Expanded portions of `SKILL.md` at `### Quick Conversion Methods`.
### Method 1: CLI (Recommended for Single Files)
```bash
# Convert file to HTML
marked -i input.md -o output.html
# Convert string directly
marked -s "# Hello World"
# Output: <h1>Hello World</h1>
```
### Method 2: Node.js Script
```javascript
import { marked } from 'marked';
import { readFileSync, writeFileSync } from 'fs';
const markdown = readFileSync('input.md', 'utf-8');
const html = marked.parse(markdown);
writeFileSync('output.html', html);
```
### Method 3: Browser Usage
```html
<script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
<script>
const html = marked.parse('# Markdown Content');
document.getElementById('output').innerHTML = html;
</script>
```
---
## Step-by-Step Workflows
Expanded portions of `SKILL.md` at `### Step-by-Step Workflows`.
### Workflow 1: Single File Conversion
1. Ensure marked is installed: `npm install -g marked`
2. Run conversion: `marked -i README.md -o README.html`
3. Verify output file was created
### Workflow 2: Batch Conversion (Multiple Files)
Create a script `convert-all.js`:
```javascript
import { marked } from 'marked';
import { readFileSync, writeFileSync, readdirSync } from 'fs';
import { join, basename } from 'path';
const inputDir = './docs';
const outputDir = './html';
readdirSync(inputDir)
.filter(file => file.endsWith('.md'))
.forEach(file => {
const markdown = readFileSync(join(inputDir, file), 'utf-8');
const html = marked.parse(markdown);
const outputFile = basename(file, '.md') + '.html';
writeFileSync(join(outputDir, outputFile), html);
console.log(`Converted: ${file}${outputFile}`);
});
```
Run with: `node convert-all.js`
### Workflow 3: Conversion with Custom Options
```javascript
import { marked } from 'marked';
// Configure options
marked.setOptions({
gfm: true, // GitHub Flavored Markdown
breaks: true, // Convert \n to <br>
pedantic: false, // Don't conform to original markdown.pl
});
const html = marked.parse(markdownContent);
```
### Workflow 4: Complete HTML Document
Wrap converted content in a full HTML template:
```javascript
import { marked } from 'marked';
import { readFileSync, writeFileSync } from 'fs';
const markdown = readFileSync('input.md', 'utf-8');
const content = marked.parse(markdown);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 800px; margin: 0 auto; padding: 2rem; }
pre { background: #f4f4f4; padding: 1rem; overflow-x: auto; }
code { background: #f4f4f4; padding: 0.2rem 0.4rem; border-radius: 3px; }
</style>
</head>
<body>
${content}
</body>
</html>`;
writeFileSync('output.html', html);
```

View File

@@ -0,0 +1,226 @@
# Pandoc Reference
Pandoc is a universal document converter that can convert between numerous markup formats, including Markdown, HTML, LaTeX, Word, and many more.
## Installation
### Windows
```powershell
# Using Chocolatey
choco install pandoc
# Using Scoop
scoop install pandoc
# Or download installer from https://pandoc.org/installing.html
```
### macOS
```bash
# Using Homebrew
brew install pandoc
```
### Linux
```bash
# Debian/Ubuntu
sudo apt-get install pandoc
# Fedora
sudo dnf install pandoc
# Or download from https://pandoc.org/installing.html
```
## Basic Usage
### Convert Markdown to HTML
```bash
# Basic conversion
pandoc input.md -o output.html
# Standalone document with headers
pandoc input.md -s -o output.html
# With custom CSS
pandoc input.md -s --css=style.css -o output.html
```
### Convert to Other Formats
```bash
# To PDF (requires LaTeX)
pandoc input.md -s -o output.pdf
# To Word
pandoc input.md -s -o output.docx
# To LaTeX
pandoc input.md -s -o output.tex
# To EPUB
pandoc input.md -s -o output.epub
```
### Convert from Other Formats
```bash
# HTML to Markdown
pandoc -f html -t markdown input.html -o output.md
# Word to Markdown
pandoc input.docx -o output.md
# LaTeX to HTML
pandoc -f latex -t html input.tex -o output.html
```
## Common Options
| Option | Description |
|--------|-------------|
| `-f, --from <format>` | Input format |
| `-t, --to <format>` | Output format |
| `-s, --standalone` | Produce standalone document |
| `-o, --output <file>` | Output file |
| `--toc` | Include table of contents |
| `--toc-depth <n>` | TOC depth (default: 3) |
| `-N, --number-sections` | Number section headings |
| `--css <url>` | Link to CSS stylesheet |
| `--template <file>` | Use custom template |
| `--metadata <key>=<value>` | Set metadata |
| `--mathml` | Use MathML for math |
| `--mathjax` | Use MathJax for math |
| `-V, --variable <key>=<value>` | Set template variable |
## Markdown Extensions
Pandoc supports many markdown extensions:
```bash
# Enable specific extensions
pandoc -f markdown+emoji+footnotes input.md -o output.html
# Disable specific extensions
pandoc -f markdown-pipe_tables input.md -o output.html
# Use strict markdown
pandoc -f markdown_strict input.md -o output.html
```
### Common Extensions
| Extension | Description |
|-----------|-------------|
| `pipe_tables` | Pipe tables (default on) |
| `footnotes` | Footnote support |
| `emoji` | Emoji shortcodes |
| `smart` | Smart quotes and dashes |
| `task_lists` | Task list checkboxes |
| `strikeout` | Strikethrough text |
| `superscript` | Superscript text |
| `subscript` | Subscript text |
| `raw_html` | Raw HTML passthrough |
## Templates
### Using Built-in Templates
```bash
# View default template
pandoc -D html
# Use custom template
pandoc --template=mytemplate.html input.md -o output.html
```
### Template Variables
```html
<!DOCTYPE html>
<html>
<head>
<title>$title$</title>
$for(css)$
<link rel="stylesheet" href="$css$">
$endfor$
</head>
<body>
$body$
</body>
</html>
```
## YAML Metadata
Include metadata in your markdown files:
```markdown
---
title: My Document
author: John Doe
date: 2025-01-28
abstract: |
This is the abstract.
---
# Introduction
Document content here...
```
## Filters
### Using Lua Filters
```bash
pandoc --lua-filter=filter.lua input.md -o output.html
```
Example Lua filter (`filter.lua`):
```lua
function Header(el)
if el.level == 1 then
el.classes:insert("main-title")
end
return el
end
```
### Using Pandoc Filters
```bash
pandoc --filter pandoc-citeproc input.md -o output.html
```
## Batch Conversion
### Bash Script
```bash
#!/bin/bash
for file in *.md; do
pandoc "$file" -s -o "${file%.md}.html"
done
```
### PowerShell Script
```powershell
Get-ChildItem -Filter *.md | ForEach-Object {
$output = $_.BaseName + ".html"
pandoc $_.Name -s -o $output
}
```
## Resources
- [Pandoc User's Guide](https://pandoc.org/MANUAL.html)
- [Pandoc Demos](https://pandoc.org/demos.html)
- [Pandoc FAQ](https://pandoc.org/faqs.html)
- [GitHub Repository](https://github.com/jgm/pandoc)

View File

@@ -0,0 +1,169 @@
# Tables to HTML
## Creating a table
### Markdown
```markdown
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th>First Header</th>
<th>Second Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content Cell</td>
<td>Content Cell</td>
</tr>
<tr>
<td>Content Cell</td>
<td>Content Cell</td>
</tr>
</tbody>
</table>
```
### Markdown
```markdown
| Command | Description |
| --- | --- |
| git status | List all new or modified files |
| git diff | Show file differences that haven't been staged |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>git status</td>
<td>List all new or modified files</td>
</tr>
<tr>
<td>git diff</td>
<td>Show file differences that haven't been staged</td>
</tr>
</tbody>
</table>
```
## Formatting Content in Tables
### Markdown
```markdown
| Command | Description |
| --- | --- |
| `git status` | List all *new or modified* files |
| `git diff` | Show file differences that **haven't been** staged |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>git status</code></td>
<td>List all <em>new or modified</em> files</td>
</tr>
<tr>
<td><code>git diff</code></td>
<td>Show file differences that <strong>haven't been</strong> staged</td>
</tr>
</tbody>
</table>
```
### Markdown
```markdown
| Left-aligned | Center-aligned | Right-aligned |
| :--- | :---: | ---: |
| git status | git status | git status |
| git diff | git diff | git diff |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th align="left">Left-aligned</th>
<th align="center">Center-aligned</th>
<th align="right">Right-aligned</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">git status</td>
<td align="center">git status</td>
<td align="right">git status</td>
</tr>
<tr>
<td align="left">git diff</td>
<td align="center">git diff</td>
<td align="right">git diff</td>
</tr>
</tbody>
</table>
```
### Markdown
```markdown
| Name | Character |
| --- | --- |
| Backtick | ` |
| Pipe | \| |
```
### Parsed HTML
```html
<table>
<thead>
<tr>
<th>Name</th>
<th>Character</th>
</tr>
</thead>
<tbody>
<tr>
<td>Backtick</td>
<td>`</td>
</tr>
<tr>
<td>Pipe</td>
<td>|</td>
</tr>
</tbody>
</table>
```

View File

@@ -0,0 +1,72 @@
# Organizing information with tables
You can build tables to organize information in comments, issues, pull requests, and wikis.
## Creating a table
You can create tables with pipes `|` and hyphens `-`. Hyphens are used to create each column's header, while pipes separate each column. You must include a blank line before your table in order for it to correctly render.
```markdown
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
![Screenshot of a GitHub Markdown table rendered as two equal columns. Headers are shown in boldface, and alternate content rows have gray shading.](https://docs.github.com/assets/images/help/writing/table-basic-rendered.png)
The pipes on either end of the table are optional.
Cells can vary in width and do not need to be perfectly aligned within columns. There must be at least three hyphens in each column of the header row.
```markdown
| Command | Description |
| --- | --- |
| git status | List all new or modified files |
| git diff | Show file differences that haven't been staged |
```
![Screenshot of a GitHub Markdown table with two columns of differing width. Rows list the commands "git status" and "git diff" and their descriptions.](https://docs.github.com/assets/images/help/writing/table-varied-columns-rendered.png)
If you are frequently editing code snippets and tables, you may benefit from enabling a fixed-width font in all comment fields on GitHub. For more information, see [About writing and formatting on GitHub](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/about-writing-and-formatting-on-github#enabling-fixed-width-fonts-in-the-editor).
## Formatting content within your table
You can use [formatting](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) such as links, inline code blocks, and text styling within your table:
```markdown
| Command | Description |
| --- | --- |
| `git status` | List all *new or modified* files |
| `git diff` | Show file differences that **haven't been** staged |
```
![Screenshot of a GitHub Markdown table with the commands formatted as code blocks. Bold and italic formatting are used in the descriptions.](https://docs.github.com/assets/images/help/writing/table-inline-formatting-rendered.png)
You can align text to the left, right, or center of a column by including colons `:` to the left, right, or on both sides of the hyphens within the header row.
```markdown
| Left-aligned | Center-aligned | Right-aligned |
| :--- | :---: | ---: |
| git status | git status | git status |
| git diff | git diff | git diff |
```
![Screenshot of a Markdown table with three columns as rendered on GitHub, showing how text within cells can be set to align left, center, or right.](https://docs.github.com/assets/images/help/writing/table-aligned-text-rendered.png)
To include a pipe `|` as content within your cell, use a `\` before the pipe:
```markdown
| Name | Character |
| --- | --- |
| Backtick | ` |
| Pipe | \| |
```
![Screenshot of a Markdown table as rendered on GitHub showing how pipes, which normally close cells, are shown when prefaced by a backslash.](https://docs.github.com/assets/images/help/writing/table-escaped-character-rendered.png)
## Further reading
* [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
* [Basic writing and formatting syntax](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)

View File

@@ -0,0 +1,350 @@
# Writing Mathematical Expressions to HTML
## Writing Inline Expressions
### Markdown
```markdown
This sentence uses `$` delimiters to show math inline: $\sqrt{3x-1}+(1+x)^2$
```
### Parsed HTML
```html
<p>This sentence uses <code>$</code> delimiters to show math inline:
<math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
<msqrt>
<mn>3</mn>
<mi>x</mi>
<mo></mo>
<mn>1</mn>
</msqrt>
<mo>+</mo>
<mo>(</mo>
<mn>1</mn>
<mo>+</mo>
<mi>x</mi>
<msup>
<mo>)</mo>
<mn>2</mn>
</msup>
</math>
</math-renderer>
</p>
```
### Markdown
```markdown
This sentence uses $\` and \`$ delimiters to show math inline: $`\sqrt{3x-1}+(1+x)^2`$
```
### Parsed HTML
```html
<p>This sentence uses
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo></mo>
<mi>a</mi>
<mi>n</mi>
<mi>d</mi>
<mo></mo>
</math>
</math-renderer> delimiters to show math inline:
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msqrt>
<mn>3</mn>
<mi>x</mi>
<mo></mo>
<mn>1</mn>
</msqrt>
<mo>+</mo>
<mo stretchy="false">(</mo>
<mn>1</mn>
<mo>+</mo>
<mi>x</mi>
<msup>
<mo stretchy="false">)</mo>
<mn>2</mn>
</msup>
</math>
</math-renderer>
</p>
```
---
## Writing Expressions as Blocks
### Markdown
```markdown
**The Cauchy-Schwarz Inequality**\
$$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$
```
### Parsed HTML
```html
<p>
<strong>The Cauchy-Schwarz Inequality</strong><br>
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msub>
<mi>a</mi>
<mi>k</mi>
</msub>
<msub>
<mi>b</mi>
<mi>k</mi>
</msub>
<mo>)</mo>
</mrow>
<mn>2</mn>
</msup>
<mo></mo>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msubsup>
<mi>a</mi>
<mi>k</mi>
<mn>2</mn>
</msubsup>
<mo>)</mo>
</mrow>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msubsup>
<mi>b</mi>
<mi>k</mi>
<mn>2</mn>
</msubsup>
<mo>)</mo>
</mrow>
</math>
</math-renderer>
</p>
```
### Markdown
```markdown
**The Cauchy-Schwarz Inequality**
```math
\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)
```
```
### Parsed HTML
```html
<p><strong>The Cauchy-Schwarz Inequality</strong></p>
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msub>
<mi>a</mi>
<mi>k</mi>
</msub>
<msub>
<mi>b</mi>
<mi>k</mi>
</msub>
<mo>)</mo>
</mrow>
<mn>2</mn>
</msup>
<mo></mo>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msubsup>
<mi>a</mi>
<mi>k</mi>
<mn>2</mn>
</msubsup>
<mo>)</mo>
</mrow>
<mrow>
<mo>(</mo>
<munderover>
<mo></mo>
<mrow>
<mi>k</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msubsup>
<mi>b</mi>
<mi>k</mi>
<mn>2</mn>
</msubsup>
<mo>)</mo>
</mrow>
</math>
</math-renderer>
```
### Markdown
```markdown
The equation $a^2 + b^2 = c^2$ is the Pythagorean theorem.
```
### Parsed HTML
```html
<p>The equation
<math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<mi>a</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<msup>
<mi>b</mi>
<mn>2</mn>
</msup>
<mo>=</mo>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</math></math-renderer> is the Pythagorean theorem.
</p>
```
### Markdown
```
$$
\int_0^\infty e^{-x} dx = 1
$$
```
### Parsed HTML
```html
<p><math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
<msubsup>
<mo></mo>
<mn>0</mn>
<mi></mi>
</msubsup>
<msup>
<mi>e</mi>
<mrow>
<mo></mo>
<mi>x</mi>
</mrow>
</msup>
<mi>d</mi>
<mi>x</mi>
<mo>=</mo>
<mn>1</mn>
</math></math-renderer></p>
```
---
## Dollar Sign Inline with Mathematical Expression
### Markdown
```markdown
This expression uses `\$` to display a dollar sign: $`\sqrt{\$4}`$
```
### Parsed HTML
```html
<p>This expression uses
<code>\$</code> to display a dollar sign:
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msqrt>
<mi>$</mi>
<mn>4</mn>
</msqrt>
</math>
</math-renderer>
</p>
```
### Markdown
```markdown
To split <span>$</span>100 in half, we calculate $100/2$
```
### Parsed HTML
```html
<p>To split
<span>$</span>100 in half, we calculate
<math-renderer>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mn>100</mn>
<mrow data-mjx-texclass="ORD">
<mo>/</mo>
</mrow>
<mn>2</mn>
</math>
</math-renderer>
</p>
```

View File

@@ -0,0 +1,76 @@
# Writing mathematical expressions
Use Markdown to display mathematical expressions on GitHub.
## About writing mathematical expressions
To enable clear communication of mathematical expressions, GitHub supports LaTeX formatted math within Markdown. For more information, see [LaTeX/Mathematics](http://en.wikibooks.org/wiki/LaTeX/Mathematics) in Wikibooks.
GitHub's math rendering capability uses MathJax; an open source, JavaScript-based display engine. MathJax supports a wide range of LaTeX macros, and several useful accessibility extensions. For more information, see [the MathJax documentation](http://docs.mathjax.org/en/latest/input/tex/index.html#tex-and-latex-support) and [the MathJax Accessibility Extensions Documentation](https://mathjax.github.io/MathJax-a11y/docs/#reader-guide).
Mathematical expressions rendering is available in GitHub Issues, GitHub Discussions, pull requests, wikis, and Markdown files.
## Writing inline expressions
There are two options for delimiting a math expression inline with your text. You can either surround the expression with dollar symbols (`$`), or start the expression with <code>$\`</code> and end it with <code>\`$</code>. The latter syntax is useful when the expression you are writing contains characters that overlap with markdown syntax. For more information, see [Basic writing and formatting syntax](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax).
```text
This sentence uses `$` delimiters to show math inline: $\sqrt{3x-1}+(1+x)^2$
```
![Screenshot of rendered Markdown showing an inline mathematical expression: the square root of 3x minus 1 plus (1 plus x) squared.](https://docs.github.com/assets/images/help/writing/inline-math-markdown-rendering.png)
```text
This sentence uses $\` and \`$ delimiters to show math inline: $`\sqrt{3x-1}+(1+x)^2`$
```
![Screenshot of rendered Markdown showing an inline mathematical expression with backtick syntax: the square root of 3x minus 1 plus (1 plus x) squared.](https://docs.github.com/assets/images/help/writing/inline-backtick-math-markdown-rendering.png)
## Writing expressions as blocks
To add a math expression as a block, start a new line and delimit the expression with two dollar symbols `$$`.
> [!TIP] If you're writing in an .md file, you will need to use specific formatting to create a line break, such as ending the line with a backslash as shown in the example below. For more information on line breaks in Markdown, see [Basic writing and formatting syntax](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#line-breaks).
```text
**The Cauchy-Schwarz Inequality**\
$$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$
```
![Screenshot of rendered Markdown showing a complex equation. Bold text reads "The Cauchy-Schwarz Inequality" above the formula for the inequality.](https://docs.github.com/assets/images/help/writing/math-expression-as-a-block-rendering.png)
Alternatively, you can use the <code>\`\`\`math</code> code block syntax to display a math expression as a block. With this syntax, you don't need to use `$$` delimiters. The following will render the same as above:
````text
**The Cauchy-Schwarz Inequality**
```math
\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)
```
````
## Writing dollar signs in line with and within mathematical expressions
To display a dollar sign as a character in the same line as a mathematical expression, you need to escape the non-delimiter `$` to ensure the line renders correctly.
* Within a math expression, add a `\` symbol before the explicit `$`.
```text
This expression uses `\$` to display a dollar sign: $`\sqrt{\$4}`$
```
![Screenshot of rendered Markdown showing how a backslash before a dollar sign displays the sign as part of a mathematical expression.](https://docs.github.com/assets/images/help/writing/dollar-sign-within-math-expression.png)
* Outside a math expression, but on the same line, use span tags around the explicit `$`.
```text
To split <span>$</span>100 in half, we calculate $100/2$
```
![Screenshot of rendered Markdown showing how span tags around a dollar sign display the sign as inline text not as part of a mathematical equation.](https://docs.github.com/assets/images/help/writing/dollar-sign-inline-math-expression.png)
## Further reading
* [The MathJax website](http://mathjax.org)
* [Getting started with writing and formatting on GitHub](https://docs.github.com/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github)
* [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)

View File

@@ -0,0 +1,369 @@
---
name: quasi-coder
description: 'Expert 10x engineer skill for interpreting and implementing code from shorthand, quasi-code, and natural language descriptions. Use when collaborators provide incomplete code snippets, pseudo-code, or descriptions with potential typos or incorrect terminology. Excels at translating non-technical or semi-technical descriptions into production-quality code.'
---
# Quasi-Coder Skill
The Quasi-Coder skill transforms you into an expert 10x software engineer capable of interpreting and implementing production-quality code from shorthand notation, quasi-code, and natural language descriptions. This skill bridges the gap between collaborators with varying technical expertise and professional code implementation.
Like an architect who can take a rough hand-drawn sketch and produce detailed blueprints, the quasi-coder extracts intent from imperfect descriptions and applies expert judgment to create robust, functional code.
## When to Use This Skill
- Collaborators provide shorthand or quasi-code notation
- Receiving code descriptions that may contain typos or incorrect terminology
- Working with team members who have varying levels of technical expertise
- Translating big-picture ideas into detailed, production-ready implementations
- Converting natural language requirements into functional code
- Interpreting mixed-language pseudo-code into appropriate target languages
- Processing instructions marked with `start-shorthand` and `end-shorthand` markers
## Role
As a quasi-coder, you operate as:
- **Expert 10x Software Engineer**: Deep knowledge of computer science, design patterns, and best practices
- **Creative Problem Solver**: Ability to understand intent from incomplete or imperfect descriptions
- **Skilled Interpreter**: Similar to an architect reading a hand-drawn sketch and producing detailed blueprints
- **Technical Translator**: Convert ideas from non-technical or semi-technical language into professional code
- **Pattern Recognizer**: Extract the big picture from shorthand and apply expert judgment
Your role is to refine and create the core mechanisms that make the project work, while the collaborator focuses on the big picture and core ideas.
## Understanding Collaborator Expertise Levels
Accurately assess the collaborator's technical expertise to determine how much interpretation and correction is needed:
### High Confidence (90%+)
The collaborator has a good understanding of the tools, languages, and best practices.
**Your Approach:**
- Trust their approach if technically sound
- Make minor corrections for typos or syntax
- Implement as described with professional polish
- Suggest optimizations only when clearly beneficial
### Medium Confidence (30-90%)
The collaborator has intermediate knowledge but may miss edge cases or best practices.
**Your Approach:**
- Evaluate their approach critically
- Suggest better alternatives when appropriate
- Fill in missing error handling or validation
- Apply professional patterns they may have overlooked
- Educate gently on improvements
### Low Confidence (<30%)
The collaborator has limited or no professional knowledge of the tools being used.
**Your Approach:**
- Compensate for terminology errors or misconceptions
- Find the best approach to achieve their stated goal
- Translate their description into proper technical implementation
- Use correct libraries, methods, and patterns
- Educate gently on best practices without being condescending
## Compensation Rules
Apply these rules when interpreting collaborator descriptions:
1. **>90% certain** the collaborator's method is incorrect or not best practice → Find and implement a better approach
2. **>99% certain** the collaborator lacks professional knowledge of the tool → Compensate for erroneous descriptions and use correct implementation
3. **>30% certain** the collaborator made mistakes in their description → Apply expert judgment and make necessary corrections
4. **Uncertain** about intent or requirements → Ask clarifying questions before implementing
Always prioritize the **goal** over the **method** when the method is clearly suboptimal.
## Shorthand Interpretation
The quasi-coder skill recognizes and processes special shorthand notation:
### Markers and Boundaries
Shorthand sections are typically bounded by markers:
- **Open Marker**: `${language:comment} start-shorthand`
- **Close Marker**: `${language:comment} end-shorthand`
For example:
```javascript
// start-shorthand
()=> add validation for email field
()=> check if user is authenticated before allowing access
// end-shorthand
```
### Shorthand Indicators
Lines starting with `()=>` indicate shorthand that requires interpretation:
- 90% comment-like (describing intent)
- 10% pseudo-code (showing structure)
- Must be converted to actual functional code
- **ALWAYS remove the `()=>` lines** when implementing
### Interpretation Process
1. **Read the entire shorthand section** to understand the full context
2. **Identify the goal** - what the collaborator wants to achieve
3. **Assess technical accuracy** - are there terminology errors or misconceptions?
4. **Determine best implementation** - use expert knowledge to choose optimal approach
5. **Replace shorthand lines** with production-quality code
6. **Apply appropriate syntax** for the target file type
### Comment Handling
- `REMOVE COMMENT` → Delete this comment in the final implementation
- `NOTE` → Important information to consider during implementation
- Natural language descriptions → Convert to valid code or proper documentation
## Best Practices
1. **Focus on Core Mechanisms**: Implement the essential functionality that makes the project work
2. **Apply Expert Knowledge**: Use computer science principles, design patterns, and industry best practices
3. **Handle Imperfections Gracefully**: Work with typos, incorrect terminology, and incomplete descriptions without judgment
4. **Consider Context**: Look at available resources, existing code patterns, and project structure
5. **Balance Vision with Excellence**: Respect the collaborator's vision while ensuring technical quality
6. **Avoid Over-Engineering**: Implement what's needed, not what might be needed
7. **Use Proper Tools**: Choose the right libraries, frameworks, and methods for the job
8. **Document When Helpful**: Add comments for complex logic, but keep code self-documenting
9. **Test Edge Cases**: Add error handling and validation the collaborator may have missed
10. **Maintain Consistency**: Follow existing code style and patterns in the project
## Working with Tools and Reference Files
Collaborators may provide additional tools and reference files to support your work as a quasi-coder. Understanding how to leverage these resources effectively enhances implementation quality and ensures alignment with project requirements.
### Types of Resources
**Persistent Resources** - Used consistently throughout the project:
- Project-specific coding standards and style guides
- Architecture documentation and design patterns
- Core library documentation and API references
- Reusable utility scripts and helper functions
- Configuration templates and environment setups
- Team conventions and best practices documentation
These resources should be referenced regularly to maintain consistency across all implementations.
**Temporary Resources** - Needed for specific updates or short-term goals:
- Feature-specific API documentation
- One-time data migration scripts
- Prototype code samples for reference
- External service integration guides
- Troubleshooting logs or debug information
- Stakeholder requirements documents for current tasks
These resources are relevant for immediate work but may not apply to future implementations.
### Resource Management Best Practices
1. **Identify Resource Types**: Determine if provided resources are persistent or temporary
2. **Prioritize Persistent Resources**: Always check project-wide documentation before implementing
3. **Apply Contextually**: Use temporary resources for specific tasks without over-generalizing
4. **Ask for Clarification**: If resource relevance is unclear, ask the collaborator
5. **Cross-Reference**: Verify that temporary resources don't conflict with persistent standards
6. **Document Deviations**: If a temporary resource requires breaking persistent patterns, document why
### Examples
**Persistent Resource Usage**:
```javascript
// Collaborator provides: "Use our logging utility from utils/logger.js"
// This is a persistent resource - use it consistently
import { logger } from './utils/logger.js';
function processData(data) {
logger.info('Processing data batch', { count: data.length });
// Implementation continues...
}
```
**Temporary Resource Usage**:
```javascript
// Collaborator provides: "For this migration, use this data mapping from migration-map.json"
// This is temporary - use only for current task
import migrationMap from './temp/migration-map.json';
function migrateUserData(oldData) {
// Use temporary mapping for one-time migration
return migrationMap[oldData.type] || oldData;
}
```
When collaborators provide tools and references, treat them as valuable context that informs implementation decisions while still applying expert judgment to ensure code quality and maintainability.
## Shorthand Key
Quick reference for shorthand notation:
```
()=> 90% comment, 10% pseudo-code - interpret and implement
ALWAYS remove these lines when editing
start-shorthand Begin shorthand section
end-shorthand End shorthand section
openPrompt ["quasi-coder", "quasi-code", "shorthand"]
language:comment Single or multi-line comment in target language
openMarker "${language:comment} start-shorthand"
closeMarker "${language:comment} end-shorthand"
```
### Critical Rules
- **ALWAYS remove `()=>` lines** when editing a file from shorthand
- Replace shorthand with functional code, features, comments, documentation, or data
- Sometimes shorthand requests non-code actions (run commands, create files, fetch data, generate graphics)
- In all cases, remove the shorthand lines after implementing the request
## Variables and Markers
Formal specification of shorthand variables:
```javascript
openPrompt = ["quasi-coder", "quasi-code", "shorthand"]
// Triggers that indicate quasi-coder should be used
language:comment = "Single or multi-line comment of programming language"
// Comment syntax appropriate for the file type
openMarker = "${language:comment} start-shorthand"
// Example: // start-shorthand (JavaScript)
// Example: # start-shorthand (Python)
// Example: <!-- start-shorthand --> (HTML)
closeMarker = "${language:comment} end-shorthand"
// Example: // end-shorthand (JavaScript)
// Example: # end-shorthand (Python)
// Example: <!-- end-shorthand --> (HTML)
```
## Example Workflow
### Scenario: Collaborator Provides Shorthand
**Input from Collaborator** (JavaScript file):
```javascript
// start-shorthand
()=> create function that validates user input
()=> check email format is correct
()=> make sure password is at least 8 characters
()=> return true if valid, false otherwise
// end-shorthand
```
### Step 1: Assess Expertise Level
- Collaborator knows they need validation
- Using general terms, not specific library names
- **Assessment**: Medium confidence (30-90%)
### Step 2: Interpret Intent
- Goal: Create input validation function
- Needs: Email format check, password length check
- Output: Boolean return value
### Step 3: Apply Expert Implementation
**Output (Production Code)**:
```javascript
/**
* Validates user registration input
* @param {string} email - User email address
* @param {string} password - User password
* @returns {boolean} True if input is valid, false otherwise
*/
function validateUserInput(email, password) {
// Validate email format using standard regex pattern
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return false;
}
// Validate password meets minimum length requirement
if (!password || password.length < 8) {
return false;
}
return true;
}
```
### Expert Decisions Made:
1. Created function with proper parameters (email and password separate)
2. Used standard email regex pattern (best practice)
3. Added JSDoc comments for clarity
4. Included null/undefined check for password
5. Used descriptive function name
6. Returned boolean as requested
7. **Removed all `()=>` shorthand lines**
## Troubleshooting
| Issue | Solution |
|-------|----------|
| **Unclear intent from collaborator** | Ask specific clarifying questions about the goal and expected behavior |
| **Multiple valid approaches** | Present options with recommendations, explaining trade-offs of each |
| **Collaborator insists on suboptimal approach** | Implement their approach but respectfully explain trade-offs and alternatives |
| **Missing context or dependencies** | Read related files, check package.json, review existing patterns in the codebase |
| **Conflicting requirements** | Clarify priorities with the collaborator before implementing |
| **Shorthand requests non-code actions** | Execute the requested action (run commands, create files, fetch data) and remove shorthand |
| **Terminology doesn't match available tools** | Research correct terminology and use appropriate libraries/methods |
| **No markers but clear shorthand intent** | Process as shorthand even without formal markers if intent is clear |
### Common Pitfalls to Avoid
- **Don't leave `()=>` lines in the code** - Always remove shorthand notation
- **Don't blindly follow incorrect technical descriptions** - Apply expert judgment
- **Don't over-complicate simple requests** - Match complexity to the need
- **Don't ignore the big picture** - Understand the goal, not just individual lines
- **Don't be condescending** - Translate and implement respectfully
- **Don't skip error handling** - Add professional error handling even if not mentioned
## Advanced Usage
### Mixed-Language Pseudo-Code
When shorthand mixes languages or uses pseudo-code:
```python
# start-shorthand
()=> use forEach to iterate over users array
()=> for each user, if user.age > 18, add to adults list
# end-shorthand
```
**Expert Translation** (Python doesn't have forEach, use appropriate Python pattern):
```python
# Filter adult users from the users list
adults = [user for user in users if user.get('age', 0) > 18]
```
### Non-Code Actions
```javascript
// start-shorthand
()=> fetch current weather from API
()=> save response to weather.json file
// end-shorthand
```
**Implementation**: Use appropriate tools to fetch data and save file, then remove shorthand lines.
### Complex Multi-Step Logic
```typescript
// start-shorthand
()=> check if user is logged in
()=> if not, redirect to login page
()=> if yes, load user dashboard with their data
()=> show error if data fetch fails
// end-shorthand
```
**Implementation**: Convert to proper TypeScript with authentication checks, routing, data fetching, and error handling.
## Summary
The Quasi-Coder skill enables expert-level interpretation and implementation of code from imperfect descriptions. By assessing collaborator expertise, applying technical knowledge, and maintaining professional standards, you bridge the gap between ideas and production-quality code.
**Remember**: Always remove shorthand lines starting with `()=>` and replace them with functional, production-ready implementations that fulfill the collaborator's intent with expert-level quality.

View File

@@ -0,0 +1,563 @@
---
name: web-coder
description: 'Expert 10x engineer with comprehensive knowledge of web development, internet protocols, and web standards. Use when working with HTML, CSS, JavaScript, web APIs, HTTP/HTTPS, web security, performance optimization, accessibility, or any web/internet concepts. Specializes in translating web terminology accurately and implementing modern web standards across frontend and backend development.'
---
# Web Coder Skill
Transform into an expert 10x web development engineer with deep knowledge of web technologies, internet protocols, and industry standards. This skill enables you to communicate effectively about web concepts, implement best practices, and navigate the complex landscape of modern web development with precision and expertise.
Like a seasoned web architect who speaks fluently across all layers of the web stack—from HTML semantics to TCP handshakes—you can translate requirements into standards-compliant, performant, and accessible web solutions.
## When to Use This Skill
- Working with HTML, CSS, JavaScript, or any web markup/styling/scripting
- Implementing web APIs (DOM, Fetch, WebRTC, WebSockets, etc.)
- Discussing or implementing HTTP/HTTPS protocols and networking concepts
- Building accessible web applications (ARIA, WCAG compliance)
- Optimizing web performance (caching, lazy loading, code splitting)
- Implementing web security measures (CORS, CSP, authentication)
- Working with web standards and specifications (W3C, WHATWG)
- Debugging browser-specific issues or cross-browser compatibility
- Setting up web servers, CDNs, or infrastructure
- Discussing web development terminology with collaborators
- Converting web-related requirements or descriptions into code
## Prerequisites
- Basic understanding of at least one area of web development
- Access to web development tools (browser, editor, terminal)
- Understanding that web development spans multiple disciplines
## Core Competencies
As a web coder, you possess expert knowledge across 15 key domains:
### 1. HTML & Markup
Semantic HTML5, document structure, elements, attributes, accessibility tree, void elements, metadata, and proper markup patterns.
**Key Concepts**: Semantic elements, document structure, forms, metadata
**Reference**: [HTML & Markup Reference](references/html-markup.md)
### 2. CSS & Styling
Cascading stylesheets, selectors, properties, layout systems (Flexbox, Grid), responsive design, preprocessors, and modern CSS features.
**Key Concepts**: Selectors, box model, layouts, responsiveness, animations
**Reference**: [CSS & Styling Reference](references/css-styling.md)
### 3. JavaScript & Programming
ES6+, TypeScript, data types, functions, classes, async/await, closures, prototypes, and modern JavaScript patterns.
**Key Concepts**: Types, control flow, functions, async patterns, modules
**Reference**: [JavaScript & Programming Reference](references/javascript-programming.md)
### 4. Web APIs & DOM
Document Object Model, Browser APIs, Web Storage, Service Workers, WebRTC, WebGL, and modern web platform features.
**Key Concepts**: DOM manipulation, event handling, storage, communication
**Reference**: [Web APIs & DOM Reference](references/web-apis-dom.md)
### 5. HTTP & Networking
HTTP/1.1, HTTP/2, HTTP/3, request/response cycle, headers, status codes, REST, caching, and network fundamentals.
**Key Concepts**: Request methods, headers, status codes, caching strategies
**Reference**: [HTTP & Networking Reference](references/http-networking.md)
### 6. Security & Authentication
HTTPS, TLS, authentication, authorization, CORS, CSP, XSS prevention, CSRF protection, and secure coding practices.
**Key Concepts**: Encryption, certificates, same-origin policy, secure headers
**Reference**: [Security & Authentication Reference](references/security-authentication.md)
### 7. Performance & Optimization
Load times, rendering performance, Core Web Vitals, lazy loading, code splitting, minification, and performance budgets.
**Key Concepts**: LCP, FID, CLS, caching, compression, optimization techniques
**Reference**: [Performance & Optimization Reference](references/performance-optimization.md)
### 8. Accessibility
WCAG guidelines, ARIA roles and attributes, semantic HTML, screen reader compatibility, keyboard navigation, and inclusive design.
**Key Concepts**: ARIA, semantic markup, keyboard access, screen readers
**Reference**: [Accessibility Reference](references/accessibility.md)
### 9. Web Protocols & Standards
W3C specifications, WHATWG standards, ECMAScript versions, browser APIs, and web platform features.
**Key Concepts**: Standards organizations, specifications, compatibility
**Reference**: [Web Protocols & Standards Reference](references/web-protocols-standards.md)
### 10. Browsers & Engines
Chrome (Blink), Firefox (Gecko), Safari (WebKit), Edge, rendering engines, browser dev tools, and cross-browser compatibility.
**Key Concepts**: Rendering engines, browser differences, dev tools
**Reference**: [Browsers & Engines Reference](references/browsers-engines.md)
### 11. Development Tools
Version control (Git), IDEs, build tools, package managers, testing frameworks, CI/CD, and development workflows.
**Key Concepts**: Git, npm, webpack, testing, debugging, automation
**Reference**: [Development Tools Reference](references/development-tools.md)
### 12. Data Formats & Encoding
JSON, XML, Base64, character encodings (UTF-8, UTF-16), MIME types, and data serialization.
**Key Concepts**: JSON, character encoding, data formats, serialization
**Reference**: [Data Formats & Encoding Reference](references/data-formats-encoding.md)
### 13. Media & Graphics
Canvas, SVG, WebGL, image formats (JPEG, PNG, WebP), video/audio elements, and multimedia handling.
**Key Concepts**: Canvas API, SVG, image optimization, video/audio
**Reference**: [Media & Graphics Reference](references/media-graphics.md)
### 14. Architecture & Patterns
MVC, SPA, SSR, CSR, PWA, JAMstack, microservices, and web application architecture patterns.
**Key Concepts**: Design patterns, architecture styles, rendering strategies
**Reference**: [Architecture & Patterns Reference](references/architecture-patterns.md)
### 15. Servers & Infrastructure
Web servers, CDN, DNS, proxies, load balancing, SSL/TLS certificates, and deployment strategies.
**Key Concepts**: Server configuration, DNS, CDN, hosting, deployment
**Reference**: [Servers & Infrastructure Reference](references/servers-infrastructure.md)
## Working with Web Terminology
### Accurate Translation
When collaborators use web terminology, ensure accurate interpretation:
#### Assess Terminology Accuracy
1. **High confidence terms**: Standard terms like "API", "DOM", "HTTP" - use as stated
2. **Ambiguous terms**: Terms with multiple meanings (e.g., "Block" - CSS box model vs code block)
3. **Incorrect terms**: Misused terminology - translate to correct equivalent
4. **Outdated terms**: Legacy terms - update to modern equivalents
#### Common Terminology Issues
| Collaborator Says | Likely Means | Correct Implementation |
|-------------------|--------------|------------------------|
| "AJAX call" | Asynchronous HTTP request | Use Fetch API or XMLHttpRequest |
| "Make it responsive" | Mobile-friendly layout | Use media queries and responsive units |
| "Add SSL" | Enable HTTPS | Configure TLS certificate |
| "Fix the cache" | Update cache strategy | Adjust Cache-Control headers |
| "Speed up the site" | Improve performance | Optimize assets, lazy load, minify |
### Context-Aware Responses
Different contexts require different interpretations:
**Frontend Context**:
- "Performance" → Client-side metrics (FCP, LCP, CLS)
- "State" → Application state management (React, Vue, etc.)
- "Routing" → Client-side routing (SPA navigation)
**Backend Context**:
- "Performance" → Server response time, throughput
- "State" → Session management, database state
- "Routing" → Server-side route handling
**DevOps Context**:
- "Performance" → Infrastructure scaling, load times
- "Cache" → CDN caching, server-side caching
- "Security" → SSL/TLS, firewalls, authentication
## Step-by-Step Workflows
### Workflow 1: Implement Web Feature from Requirements
When given web-related requirements:
1. **Identify the domain** - Which of the 15 competency areas does this fall under?
2. **Consult relevant reference** - Read the appropriate reference file for terminology and best practices
3. **Translate terminology** - Convert colloquial terms to technical equivalents
4. **Apply web standards** - Use W3C/WHATWG specifications as guidance
5. **Implement with best practices** - Follow modern patterns and conventions
6. **Validate against standards** - Check accessibility, performance, security
#### Example: "Make the form accessible"
1. **Domain**: Accessibility (Competency #8)
2. **Reference**: [Accessibility Reference](references/accessibility.md)
3. **Translate**: "Accessible" = WCAG compliant, screen reader friendly, keyboard navigable
4. **Standards**: WCAG 2.1 Level AA
5. **Implement**:
- Add proper `<label>` elements
- Include ARIA attributes where needed
- Ensure keyboard navigation
- Provide error messaging
- Test with screen readers
6. **Validate**: Run accessibility audit tools
### Workflow 2: Debug Web Issues
When encountering web-related problems:
1. **Categorize the issue** - Which layer (HTML, CSS, JS, Network, etc.)?
2. **Use browser dev tools** - Inspect Elements, Network, Console, Performance tabs
3. **Check browser compatibility** - Is this a cross-browser issue?
4. **Review relevant standards** - What does the spec say should happen?
5. **Test hypothesis** - Does fixing the root cause resolve the issue?
6. **Implement solution** - Apply standards-compliant fix
### Workflow 3: Optimize Web Performance
When asked to improve performance:
1. **Measure baseline** - Use Lighthouse, WebPageTest, or performance APIs
2. **Identify bottlenecks** - Network, rendering, JavaScript execution?
3. **Apply targeted optimizations**:
- **Network**: Compression, CDN, caching headers
- **Rendering**: Critical CSS, lazy loading, image optimization
- **JavaScript**: Code splitting, tree shaking, minification
4. **Measure improvement** - Compare metrics to baseline
5. **Iterate** - Continue optimizing until performance budgets are met
### Workflow 4: Implement Web Security
When implementing security features:
1. **Identify threats** - XSS, CSRF, injection, MitM, etc.
2. **Apply defense in depth**:
- **Transport**: Use HTTPS with TLS 1.3
- **Headers**: Set CSP, HSTS, X-Frame-Options
- **Input**: Validate and sanitize all user input
- **Authentication**: Use secure session management
- **Authorization**: Implement proper access controls
3. **Test security** - Use security scanning tools
4. **Monitor** - Set up logging and alerting
## Best Practices
### Do's
- ✅ Use semantic HTML elements (`<article>`, `<nav>`, `<main>`)
- ✅ Follow W3C and WHATWG specifications
- ✅ Implement progressive enhancement
- ✅ Test across multiple browsers and devices
- ✅ Optimize for Core Web Vitals (LCP, FID, CLS)
- ✅ Make accessibility a priority from the start
- ✅ Use modern JavaScript features (ES6+)
- ✅ Implement proper error handling
- ✅ Minify and compress production assets
- ✅ Use HTTPS everywhere
- ✅ Follow REST principles for APIs
- ✅ Implement proper caching strategies
### Don'ts
- ❌ Use tables for layout (use CSS Grid/Flexbox)
- ❌ Ignore accessibility requirements
- ❌ Skip cross-browser testing
- ❌ Serve unoptimized images
- ❌ Mix HTTP and HTTPS content
- ❌ Store sensitive data in localStorage
- ❌ Ignore performance budgets
- ❌ Use inline styles extensively
- ❌ Forget to validate user input
- ❌ Implement authentication without security review
- ❌ Use deprecated APIs or features
- ❌ Ignore browser console warnings
## Common Web Development Patterns
### Pattern 1: Progressive Enhancement
Start with basic HTML, enhance with CSS, add JavaScript functionality:
```html
<!-- Base HTML (works without CSS/JS) -->
<form action="/submit" method="POST">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
```
```css
/* Enhanced styling */
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
```
```javascript
// Enhanced interactivity
form.addEventListener('submit', async (e) => {
e.preventDefault();
await fetch('/api/submit', { /* ... */ });
});
```
### Pattern 2: Responsive Design
Mobile-first approach with progressive enhancement:
```css
/* Mobile-first base styles */
.container {
padding: 1rem;
}
/* Tablet and up */
@media (min-width: 768px) {
.container {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
}
/* Desktop */
@media (min-width: 1024px) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2rem;
}
}
```
### Pattern 3: Accessible Component
Keyboard navigation, ARIA, semantic HTML:
```html
<nav aria-label="Main navigation">
<ul role="menubar">
<li role="none">
<a href="/" role="menuitem">Home</a>
</li>
<li role="none">
<button
role="menuitem"
aria-expanded="false"
aria-haspopup="true"
>
Products
</button>
</li>
</ul>
</nav>
```
### Pattern 4: Performance Optimization
Lazy loading, code splitting, and efficient loading:
```html
<!-- Lazy load images -->
<img
src="placeholder.jpg"
data-src="high-res.jpg"
loading="lazy"
alt="Description"
>
<!-- Preload critical resources -->
<link rel="preload" href="critical.css" as="style">
<link rel="preconnect" href="https://api.example.com">
<!-- Async/defer non-critical scripts -->
<script src="analytics.js" async></script>
<script src="app.js" defer></script>
```
## Troubleshooting
| Issue | Likely Cause | Solution |
|-------|-------------|----------|
| **CORS error** | Cross-origin request blocked | Configure CORS headers on server |
| **Layout shift** | Images without dimensions | Add width/height attributes |
| **Slow load time** | Unoptimized assets | Minify, compress, lazy load |
| **Accessibility audit fails** | Missing ARIA or semantic HTML | Add labels, roles, and semantic elements |
| **Mixed content warning** | HTTP resources on HTTPS page | Update all resources to HTTPS |
| **JavaScript not working** | Browser compatibility issue | Use polyfills or transpile with Babel |
| **CSS not applying** | Specificity or cascade issue | Check selector specificity and order |
| **Form not submitting** | Validation or event handling issue | Check validation rules and event listeners |
| **API request failing** | Network, CORS, or auth issue | Check Network tab, CORS config, auth headers |
| **Cache not updating** | Aggressive caching | Implement cache-busting or adjust headers |
## Advanced Techniques
### 1. Performance Monitoring
Implement Real User Monitoring (RUM):
```javascript
// Measure Core Web Vitals
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('Performance metric:', {
name: entry.name,
value: entry.value,
rating: entry.rating
});
}
});
observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input', 'layout-shift'] });
```
### 2. Advanced Accessibility
Create custom accessible components:
```javascript
class AccessibleTabs {
constructor(element) {
this.tablist = element.querySelector('[role="tablist"]');
this.tabs = Array.from(this.tablist.querySelectorAll('[role="tab"]'));
this.panels = Array.from(element.querySelectorAll('[role="tabpanel"]'));
this.tabs.forEach((tab, index) => {
tab.addEventListener('click', () => this.selectTab(index));
tab.addEventListener('keydown', (e) => this.handleKeydown(e, index));
});
}
selectTab(index) {
// Deselect all tabs
this.tabs.forEach(tab => {
tab.setAttribute('aria-selected', 'false');
tab.setAttribute('tabindex', '-1');
});
this.panels.forEach(panel => panel.hidden = true);
// Select target tab
this.tabs[index].setAttribute('aria-selected', 'true');
this.tabs[index].setAttribute('tabindex', '0');
this.tabs[index].focus();
this.panels[index].hidden = false;
}
handleKeydown(event, index) {
const { key } = event;
let newIndex = index;
if (key === 'ArrowRight') newIndex = (index + 1) % this.tabs.length;
if (key === 'ArrowLeft') newIndex = (index - 1 + this.tabs.length) % this.tabs.length;
if (key === 'Home') newIndex = 0;
if (key === 'End') newIndex = this.tabs.length - 1;
if (newIndex !== index) {
event.preventDefault();
this.selectTab(newIndex);
}
}
}
```
### 3. Modern CSS Techniques
Use modern CSS features for layouts:
```css
/* Container queries (modern browsers) */
@container (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
/* CSS Grid with subgrid */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 2rem;
}
.grid-item {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3;
}
/* CSS custom properties with fallbacks */
:root {
--primary-color: #007bff;
--spacing: 1rem;
}
.element {
color: var(--primary-color, blue);
padding: var(--spacing, 16px);
}
```
### 4. Security Headers
Implement comprehensive security headers:
```javascript
// Express.js example
app.use((req, res, next) => {
// Content Security Policy
res.setHeader('Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'");
// Strict Transport Security
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
// XSS Protection
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
// Referrer Policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
```
## Reference Files
This skill includes 15 comprehensive reference files covering all aspects of web development:
1. [HTML & Markup](references/html-markup.md) - Semantic HTML, elements, attributes
2. [CSS & Styling](references/css-styling.md) - Selectors, layouts, responsive design
3. [JavaScript & Programming](references/javascript-programming.md) - ES6+, types, patterns
4. [Web APIs & DOM](references/web-apis-dom.md) - Browser APIs, DOM manipulation
5. [HTTP & Networking](references/http-networking.md) - Protocols, headers, REST
6. [Security & Authentication](references/security-authentication.md) - HTTPS, auth, security
7. [Performance & Optimization](references/performance-optimization.md) - Core Web Vitals, optimization
8. [Accessibility](references/accessibility.md) - WCAG, ARIA, inclusive design
9. [Web Protocols & Standards](references/web-protocols-standards.md) - W3C, WHATWG, specs
10. [Browsers & Engines](references/browsers-engines.md) - Rendering engines, compatibility
11. [Development Tools](references/development-tools.md) - Git, build tools, testing
12. [Data Formats & Encoding](references/data-formats-encoding.md) - JSON, encodings, formats
13. [Media & Graphics](references/media-graphics.md) - Canvas, SVG, images, video
14. [Architecture & Patterns](references/architecture-patterns.md) - MVC, SPA, SSR, patterns
15. [Servers & Infrastructure](references/servers-infrastructure.md) - Servers, CDN, deployment
## Validation Checklist
Before considering web development complete:
- [ ] HTML validates without errors (W3C validator)
- [ ] CSS follows best practices and validates
- [ ] JavaScript has no console errors
- [ ] Accessibility audit passes (Lighthouse, axe)
- [ ] Performance meets Core Web Vitals targets
- [ ] Security headers are properly configured
- [ ] Cross-browser testing completed
- [ ] Responsive design works on all breakpoints
- [ ] SEO meta tags are present and correct
- [ ] Forms have proper validation and error handling
- [ ] Images are optimized and have alt text
- [ ] HTTPS is enforced
- [ ] Caching strategy is implemented
- [ ] Error handling covers edge cases
- [ ] Code is minified and compressed for production
## Summary
The Web Coder skill transforms you into an expert 10x engineer with comprehensive knowledge across all aspects of web development. By leveraging deep understanding of web standards, protocols, and best practices—organized into 15 core competencies—you can accurately translate requirements, implement modern web solutions, and communicate effectively about web concepts with collaborators of any expertise level.
**Remember**: Web development is multidisciplinary. Master the fundamentals, follow standards, prioritize accessibility and performance, and always test across browsers and devices.

View File

@@ -0,0 +1,346 @@
# Accessibility Reference
Web accessibility ensures content is usable by everyone, including people with disabilities.
## WCAG (Web Content Accessibility Guidelines)
### Levels
- **A**: Minimum level
- **AA**: Standard target (legal requirement in many jurisdictions)
- **AAA**: Enhanced accessibility
### Four Principles (POUR)
1. **Perceivable**: Information presented in ways users can perceive
2. **Operable**: UI components and navigation are operable
3. **Understandable**: Information and UI operation is understandable
4. **Robust**: Content works with current and future technologies
## ARIA (Accessible Rich Internet Applications)
### ARIA Roles
```html
<!-- Landmark roles -->
<nav role="navigation">
<main role="main">
<aside role="complementary">
<footer role="contentinfo">
<!-- Widget roles -->
<div role="button" tabindex="0">Click me</div>
<div role="tab" aria-selected="true">Tab 1</div>
<div role="dialog" aria-labelledby="dialogTitle">
<!-- Document structure -->
<div role="list">
<div role="listitem">Item 1</div>
</div>
```
### ARIA Attributes
```html
<!-- States -->
<button aria-pressed="true">Toggle</button>
<input aria-invalid="true" aria-errormessage="error1">
<div aria-expanded="false" aria-controls="menu">Menu</div>
<!-- Properties -->
<img alt="" aria-hidden="true">
<input aria-label="Search" type="search">
<dialog aria-labelledby="title" aria-describedby="desc">
<h2 id="title">Dialog Title</h2>
<p id="desc">Description</p>
</dialog>
<!-- Relationships -->
<label id="label1" for="input1">Name:</label>
<input id="input1" aria-labelledby="label1">
<!-- Live regions -->
<div aria-live="polite" aria-atomic="true">
Status updated
</div>
```
## Keyboard Navigation
### Tab Order
```html
<!-- Natural tab order -->
<button>First</button>
<button>Second</button>
<!-- Custom tab order (avoid if possible) -->
<button tabindex="1">First</button>
<button tabindex="2">Second</button>
<!-- Programmatically focusable (not in tab order) -->
<div tabindex="-1">Not in tab order</div>
<!-- In tab order -->
<div tabindex="0" role="button">Custom button</div>
```
### Keyboard Events
```javascript
element.addEventListener('keydown', (e) => {
switch(e.key) {
case 'Enter':
case ' ': // Space
// Activate
break;
case 'Escape':
// Close/cancel
break;
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
// Navigate
break;
}
});
```
## Semantic HTML
```html
<!-- ✅ Good: semantic elements -->
<nav aria-label="Main navigation">
<ul>
<li><a href="/">Home</a></li>
</ul>
</nav>
<!-- ❌ Bad: non-semantic -->
<div class="nav">
<div><a href="/">Home</a></div>
</div>
<!-- ✅ Good: proper headings hierarchy -->
<h1>Page Title</h1>
<h2>Section</h2>
<h3>Subsection</h3>
<!-- ❌ Bad: skipping levels -->
<h1>Page Title</h1>
<h3>Skipped h2</h3>
```
## Forms Accessibility
```html
<form>
<!-- Labels -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required aria-required="true">
<!-- Error messages -->
<input
type="email"
id="email"
aria-invalid="true"
aria-describedby="email-error">
<span id="email-error" role="alert">
Please enter a valid email
</span>
<!-- Fieldset for groups -->
<fieldset>
<legend>Choose an option</legend>
<label>
<input type="radio" name="option" value="a">
Option A
</label>
<label>
<input type="radio" name="option" value="b">
Option B
</label>
</fieldset>
<!-- Help text -->
<label for="password">Password:</label>
<input
type="password"
id="password"
aria-describedby="password-help">
<span id="password-help">
Must be at least 8 characters
</span>
</form>
```
## Images and Media
```html
<!-- Informative image -->
<img src="chart.png" alt="Sales increased 50% in Q1">
<!-- Decorative image -->
<img src="decorative.png" alt="" role="presentation">
<!-- Complex image -->
<figure>
<img src="data-viz.png" alt="Sales data visualization">
<figcaption>
Detailed description of the data...
</figcaption>
</figure>
<!-- Video with captions -->
<video controls>
<source src="video.mp4" type="video/mp4">
<track kind="captions" src="captions.vtt" srclang="en" label="English">
</video>
```
## Color and Contrast
### WCAG Requirements
- **Level AA**: 4.5:1 for normal text, 3:1 for large text
- **Level AAA**: 7:1 for normal text, 4.5:1 for large text
```css
/* ✅ Good contrast */
.text {
color: #000; /* Black */
background: #fff; /* White */
/* Contrast: 21:1 */
}
/* Don't rely on color alone */
.error {
color: red;
/* ✅ Also use icon or text */
&::before {
content: '⚠ ';
}
}
```
## Screen Readers
### Best Practices
```html
<!-- Skip links for navigation -->
<a href="#main-content" class="skip-link">
Skip to main content
</a>
<!-- Accessible headings -->
<h1>Main heading (only one)</h1>
<!-- Descriptive links -->
<!-- ❌ Bad -->
<a href="/article">Read more</a>
<!-- ✅ Good -->
<a href="/article">Read more about accessibility</a>
<!-- Hidden content (screen reader only) -->
<span class="sr-only">
Additional context for screen readers
</span>
```
```css
/* Screen reader only class */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
```
## Focus Management
```css
/* Visible focus indicator */
:focus {
outline: 2px solid #005fcc;
outline-offset: 2px;
}
/* Don't remove focus entirely */
/* ❌ Bad */
:focus {
outline: none;
}
/* ✅ Good: custom focus style */
:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(0, 95, 204, 0.5);
}
```
```javascript
// Focus management in modal
function openModal() {
modal.showModal();
modal.querySelector('button').focus();
// Trap focus
modal.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
trapFocus(e, modal);
}
});
}
```
## Testing Tools
- **axe DevTools**: Browser extension
- **WAVE**: Web accessibility evaluation tool
- **NVDA**: Screen reader (Windows)
- **JAWS**: Screen reader (Windows)
- **VoiceOver**: Screen reader (macOS/iOS)
- **Lighthouse**: Automated audits
## Checklist
- [ ] Semantic HTML used
- [ ] All images have alt text
- [ ] Color contrast meets WCAG AA
- [ ] Keyboard navigation works
- [ ] Focus indicators visible
- [ ] Forms have labels
- [ ] Heading hierarchy correct
- [ ] ARIA used appropriately
- [ ] Screen reader tested
- [ ] No keyboard traps
## Glossary Terms
**Key Terms Covered**:
- Accessibility
- Accessibility tree
- Accessible description
- Accessible name
- ARIA
- ATAG
- Boolean attribute (ARIA)
- Screen reader
- UAAG
- WAI
- WCAG
## Additional Resources
- [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
- [MDN Accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility)
- [WebAIM](https://webaim.org/)
- [A11y Project](https://www.a11yproject.com/)

View File

@@ -0,0 +1,625 @@
# Architecture & Patterns Reference
Web application architectures, design patterns, and architectural concepts.
## Application Architectures
### Single Page Application (SPA)
Web app that loads single HTML page and dynamically updates content.
**Characteristics**:
- Client-side routing
- Heavy JavaScript usage
- Fast navigation after initial load
- Complex state management
**Pros**:
- Smooth user experience
- Reduced server load
- Mobile app-like feel
**Cons**:
- Larger initial download
- SEO challenges (mitigated with SSR)
- Complex state management
**Examples**: React, Vue, Angular apps
```javascript
// React Router example
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/products/:id" element={<Product />} />
</Routes>
</BrowserRouter>
);
}
```
### Multi-Page Application (MPA)
Traditional web app with multiple HTML pages.
**Characteristics**:
- Server renders each page
- Full page reload on navigation
- Simpler architecture
**Pros**:
- Better SEO out of the box
- Simpler to build
- Good for content-heavy sites
**Cons**:
- Slower navigation
- More server requests
### Progressive Web App (PWA)
Web app with native app capabilities.
**Features**:
- Installable
- Offline support (Service Workers)
- Push notifications
- App-like experience
```javascript
// Service Worker registration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered', reg))
.catch(err => console.error('SW error', err));
}
```
**manifest.json**:
```json
{
"name": "My PWA",
"short_name": "PWA",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
}
]
}
```
### Server-Side Rendering (SSR)
Render pages on server, send HTML to client.
**Pros**:
- Better SEO
- Faster first contentful paint
- Works without JavaScript
**Cons**:
- Higher server load
- More complex setup
**Frameworks**: Next.js, Nuxt.js, SvelteKit
```javascript
// Next.js SSR
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}
function Page({ data }) {
return <div>{data.title}</div>;
}
```
### Static Site Generation (SSG)
Pre-render pages at build time.
**Pros**:
- Extremely fast
- Low server cost
- Great SEO
**Best for**: Blogs, documentation, marketing sites
**Tools**: Next.js, Gatsby, Hugo, Jekyll, Eleventy
```javascript
// Next.js SSG
export async function getStaticProps() {
const data = await fetchData();
return { props: { data } };
}
export async function getStaticPaths() {
const paths = await fetchPaths();
return { paths, fallback: false };
}
```
### Incremental Static Regeneration (ISR)
Update static content after build.
```javascript
// Next.js ISR
export async function getStaticProps() {
const data = await fetchData();
return {
props: { data },
revalidate: 60 // Revalidate every 60 seconds
};
}
```
### JAMstack
JavaScript, APIs, Markup architecture.
**Principles**:
- Pre-rendered static files
- APIs for dynamic functionality
- Git-based workflows
- CDN deployment
**Benefits**:
- Fast performance
- High security
- Scalability
- Developer experience
## Rendering Patterns
### Client-Side Rendering (CSR)
JavaScript renders content in browser.
```html
<div id="root"></div>
<script>
// React renders app here
ReactDOM.render(<App />, document.getElementById('root'));
</script>
```
### Hydration
Attach JavaScript to server-rendered HTML.
```javascript
// React hydration
ReactDOM.hydrate(<App />, document.getElementById('root'));
```
### Partial Hydration
Hydrate only interactive components.
**Tools**: Astro, Qwik
### Islands Architecture
Independent interactive components in static HTML.
**Concept**: Ship minimal JavaScript, hydrate only "islands" of interactivity
**Frameworks**: Astro, Eleventy with Islands
## Design Patterns
### MVC (Model-View-Controller)
Separate data, presentation, and logic.
- **Model**: Data and business logic
- **View**: UI presentation
- **Controller**: Handle input, update model/view
### MVVM (Model-View-ViewModel)
Similar to MVC with data binding.
- **Model**: Data
- **View**: UI
- **ViewModel**: View logic and state
**Used in**: Vue.js, Angular, Knockout
### Component-Based Architecture
Build UI from reusable components.
```javascript
// React component
function Button({ onClick, children }) {
return (
<button onClick={onClick} className="btn">
{children}
</button>
);
}
// Usage
<Button onClick={handleClick}>Click me</Button>
```
### Micro Frontends
Split frontend into smaller, independent apps.
**Approaches**:
- Build-time integration
- Run-time integration (iframes, Web Components)
- Edge-side includes
## State Management
### Local State
Component-level state.
```javascript
// React useState
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```
### Global State
Application-wide state.
**Solutions**:
- **Redux**: Predictable state container
- **MobX**: Observable state
- **Zustand**: Minimal state management
- **Recoil**: Atomic state management
```javascript
// Redux example
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1; }
}
});
const store = configureStore({
reducer: { counter: counterSlice.reducer }
});
```
### Context API
Share state without prop drilling.
```javascript
// React Context
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={theme}>...</div>;
}
```
## API Architecture Patterns
### REST (Representational State Transfer)
Resource-based API design.
```javascript
// RESTful API
GET /api/users // List users
GET /api/users/1 // Get user
POST /api/users // Create user
PUT /api/users/1 // Update user
DELETE /api/users/1 // Delete user
```
### GraphQL
Query language for APIs.
```graphql
# Query
query {
user(id: "1") {
name
email
posts {
title
}
}
}
# Mutation
mutation {
createUser(name: "John", email: "john@example.com") {
id
name
}
}
```
```javascript
// Apollo Client
import { useQuery, gql } from '@apollo/client';
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
`;
function User({ id }) {
const { loading, error, data } = useQuery(GET_USER, {
variables: { id }
});
if (loading) return <p>Loading...</p>;
return <p>{data.user.name}</p>;
}
```
### tRPC
End-to-end typesafe APIs.
```typescript
// Server
const appRouter = router({
getUser: publicProcedure
.input(z.string())
.query(async ({ input }) => {
return await db.user.findUnique({ where: { id: input } });
})
});
// Client (fully typed!)
const user = await trpc.getUser.query('1');
```
## Microservices Architecture
Split application into small, independent services.
**Characteristics**:
- Independent deployment
- Service-specific databases
- API communication
- Decentralized governance
**Benefits**:
- Scalability
- Technology flexibility
- Fault isolation
**Challenges**:
- Complexity
- Network latency
- Data consistency
## Monolithic Architecture
Single, unified application.
**Pros**:
- Simpler development
- Easier debugging
- Single deployment
**Cons**:
- Scaling challenges
- Technology lock-in
- Tight coupling
## Serverless Architecture
Run code without managing servers.
**Platforms**: AWS Lambda, Vercel Functions, Netlify Functions, Cloudflare Workers
```javascript
// Vercel serverless function
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from serverless!' });
}
```
**Benefits**:
- Auto-scaling
- Pay per use
- No server management
**Use Cases**:
- APIs
- Background jobs
- Webhooks
- Image processing
## Architectural Best Practices
### Separation of Concerns
Keep different aspects separate:
- Presentation layer
- Business logic layer
- Data access layer
### DRY (Don't Repeat Yourself)
Avoid code duplication.
### SOLID Principles
- **S**ingle Responsibility
- **O**pen/Closed
- **L**iskov Substitution
- **I**nterface Segregation
- **D**ependency Inversion
### Composition over Inheritance
Prefer composing objects over class hierarchies.
```javascript
// Composition
function withLogging(Component) {
return function LoggedComponent(props) {
console.log('Rendering', Component.name);
return <Component {...props} />;
};
}
const LoggedButton = withLogging(Button);
```
## Module Systems
### ES Modules (ESM)
Modern JavaScript modules.
```javascript
// export
export const name = 'John';
export function greet() {}
export default App;
// import
import App from './App.js';
import { name, greet } from './utils.js';
import * as utils from './utils.js';
```
### CommonJS
Node.js module system.
```javascript
// export
module.exports = { name: 'John' };
exports.greet = function() {};
// import
const { name } = require('./utils');
```
## Build Optimization
### Code Splitting
Split code into smaller chunks.
```javascript
// React lazy loading
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
```
### Tree Shaking
Remove unused code.
```javascript
// Only imports 'map', not entire lodash
import { map } from 'lodash-es';
```
### Bundle Splitting
- **Vendor bundle**: Third-party dependencies
- **App bundle**: Application code
- **Route bundles**: Per-route code
## Glossary Terms
**Key Terms Covered**:
- Abstraction
- API
- Application
- Architecture
- Asynchronous
- Binding
- Block (CSS, JS)
- Call stack
- Class
- Client-side
- Control flow
- Delta
- Design pattern
- Event
- Fetch
- First-class Function
- Function
- Garbage collection
- Grid
- Hoisting
- Hydration
- Idempotent
- Instance
- Lazy load
- Main thread
- MVC
- Polyfill
- Progressive Enhancement
- Progressive web apps
- Property
- Prototype
- Prototype-based programming
- REST
- Reflow
- Round Trip Time (RTT)
- SPA
- Semantics
- Server
- Synthetic monitoring
- Thread
- Type
## Additional Resources
- [Patterns.dev](https://www.patterns.dev/)
- [React Patterns](https://reactpatterns.com/)
- [JAMstack](https://jamstack.org/)
- [Micro Frontends](https://micro-frontends.org/)

View File

@@ -0,0 +1,358 @@
# Browsers & Engines Reference
Web browsers, rendering engines, and browser-specific information.
## Major Browsers
### Google Chrome
**Engine**: Blink (rendering), V8 (JavaScript)
**Released**: 2008
**Market Share**: ~65% (desktop)
**Developer Tools**:
- Elements panel
- Console
- Network tab
- Performance profiler
- Lighthouse audits
### Mozilla Firefox
**Engine**: Gecko (rendering), SpiderMonkey (JavaScript)
**Released**: 2004
**Market Share**: ~3% (desktop)
**Features**:
- Strong privacy focus
- Container tabs
- Enhanced tracking protection
- Developer Edition
### Apple Safari
**Engine**: WebKit (rendering), JavaScriptCore (JavaScript)
**Released**: 2003
**Market Share**: ~20% (desktop), dominant on iOS
**Features**:
- Energy efficient
- Privacy-focused
- Intelligent Tracking Prevention
- Only browser allowed on iOS
### Microsoft Edge
**Engine**: Blink (Chromium-based since 2020)
**Released**: 2015 (EdgeHTML), 2020 (Chromium)
**Features**:
- Windows integration
- Collections
- Vertical tabs
- IE Mode (compatibility)
### Opera
**Engine**: Blink
**Based on**: Chromium
**Features**:
- Built-in VPN
- Ad blocker
- Sidebar
## Rendering Engines
### Blink
**Used by**: Chrome, Edge, Opera, Vivaldi
**Forked from**: WebKit (2013)
**Language**: C++
### WebKit
**Used by**: Safari
**Origin**: KHTML (KDE)
**Language**: C++
### Gecko
**Used by**: Firefox
**Developed by**: Mozilla
**Language**: C++, Rust
### Legacy Engines
- **Trident**: Internet Explorer (deprecated)
- **EdgeHTML**: Original Edge (deprecated)
- **Presto**: Old Opera (deprecated)
## JavaScript Engines
| Engine | Browser | Language |
|--------|---------|----------|
| V8 | Chrome, Edge | C++ |
| SpiderMonkey | Firefox | C++, Rust |
| JavaScriptCore | Safari | C++ |
| Chakra | IE/Edge (legacy) | C++ |
### V8 Features
- JIT compilation
- Inline caching
- Hidden classes
- Garbage collection
- WASM support
## Browser DevTools
### Chrome DevTools
```javascript
// Console API
console.log('message');
console.table(array);
console.time('label');
console.timeEnd('label');
// Command Line API
$() // document.querySelector()
$$() // document.querySelectorAll()
$x() // XPath query
copy(object) // Copy to clipboard
monitor(function) // Log function calls
```
**Panels**:
- Elements: DOM inspection
- Console: JavaScript console
- Sources: Debugger
- Network: HTTP requests
- Performance: Profiling
- Memory: Heap snapshots
- Application: Storage, service workers
- Security: Certificate info
- Lighthouse: Audits
### Firefox DevTools
**Unique Features**:
- CSS Grid Inspector
- Font Editor
- Accessibility Inspector
- Network throttling
## Cross-Browser Compatibility
### Browser Prefixes (Vendor Prefixes)
```css
/* Legacy - use autoprefixer instead */
.element {
-webkit-transform: rotate(45deg); /* Chrome, Safari */
-moz-transform: rotate(45deg); /* Firefox */
-ms-transform: rotate(45deg); /* IE */
-o-transform: rotate(45deg); /* Opera */
transform: rotate(45deg); /* Standard */
}
```
**Modern approach**: Use build tools (Autoprefixer)
### User Agent String
```javascript
// Check browser
const userAgent = navigator.userAgent;
if (userAgent.includes('Firefox')) {
// Firefox-specific code
} else if (userAgent.includes('Chrome')) {
// Chrome-specific code
}
// Better: Feature detection
if ('serviceWorker' in navigator) {
// Modern browser
}
```
### Graceful Degradation vs Progressive Enhancement
**Graceful Degradation**: Build for modern, degrade for old
```css
.container {
display: grid; /* Modern browsers */
display: block; /* Fallback */
}
```
**Progressive Enhancement**: Build base, enhance for modern
```css
.container {
display: block; /* Base */
}
@supports (display: grid) {
.container {
display: grid; /* Enhancement */
}
}
```
## Browser Features
### Service Workers
Background scripts for offline functionality
**Supported**: All modern browsers
### WebAssembly
Binary instruction format for web
**Supported**: All modern browsers
### Web Components
Custom HTML elements
**Supported**: All modern browsers (with polyfills)
### WebRTC
Real-time communication
**Supported**: All modern browsers
## Browser Storage
| Storage | Size | Expiration | Scope |
|---------|------|------------|-------|
| Cookies | 4KB | Configurable | Domain |
| LocalStorage | 5-10MB | Never | Origin |
| SessionStorage | 5-10MB | Tab close | Origin |
| IndexedDB | 50MB+ | Never | Origin |
## Mobile Browsers
### iOS Safari
- Only browser allowed on iOS
- All iOS browsers use WebKit
- Different from desktop Safari
### Chrome Mobile (Android)
- Blink engine
- Similar to desktop Chrome
### Samsung Internet
- Based on Chromium
- Popular on Samsung devices
## Browser Market Share (2026)
**Desktop**:
- Chrome: ~65%
- Safari: ~20%
- Edge: ~5%
- Firefox: ~3%
- Other: ~7%
**Mobile**:
- Chrome: ~65%
- Safari: ~25%
- Samsung Internet: ~5%
- Other: ~5%
## Testing Browsers
### Tools
- **BrowserStack**: Cloud browser testing
- **Sauce Labs**: Automated testing
- **CrossBrowserTesting**: Live testing
- **LambdaTest**: Cross-browser testing
### Virtual Machines
- **VirtualBox**: Free virtualization
- **Parallels**: Mac virtualization
- **Windows Dev VMs**: Free Windows VMs
## Developer Features
### Chromium-based Developer Features
- **Remote Debugging**: Debug mobile devices
- **Workspaces**: Edit files directly
- **Snippets**: Reusable code snippets
- **Coverage**: Unused code detection
### Firefox Developer Edition
- **CSS Grid Inspector**
- **Flexbox Inspector**
- **Font Panel**
- **Accessibility Audits**
## Browser Extensions
### Manifest V3 (Modern)
```json
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"permissions": ["storage", "activeTab"],
"action": {
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}]
}
```
## Glossary Terms
**Key Terms Covered**:
- Apple Safari
- Blink
- blink element
- Browser
- Browsing context
- Chrome
- Developer tools
- Engine
- Firefox OS
- Gecko
- Google Chrome
- JavaScript engine
- Microsoft Edge
- Microsoft Internet Explorer
- Mozilla Firefox
- Netscape Navigator
- Opera browser
- Presto
- Rendering engine
- Trident
- User agent
- Vendor prefix
- WebKit
## Additional Resources
- [Chrome DevTools](https://developer.chrome.com/docs/devtools/)
- [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/)
- [Safari Web Inspector](https://developer.apple.com/safari/tools/)
- [Can I Use](https://caniuse.com/)
- [Browser Market Share](https://gs.statcounter.com/)

View File

@@ -0,0 +1,696 @@
# CSS & Styling Reference
Comprehensive reference for Cascading Style Sheets, layout systems, and modern styling techniques.
## Core Concepts
### CSS (Cascading Style Sheets)
Style sheet language used for describing the presentation of HTML documents.
**Three Ways to Apply CSS**:
1. **Inline**: `<div style="color: blue;">`
2. **Internal**: `<style>` tag in HTML
3. **External**: Separate `.css` file (recommended)
### The Cascade
The algorithm that determines which CSS rules apply when multiple rules target the same element.
**Priority Order** (highest to lowest):
1. Inline styles
2. ID selectors (`#id`)
3. Class selectors (`.class`), attribute selectors, pseudo-classes
4. Element selectors (`div`, `p`)
5. Inherited properties
**Important**: `!important` declaration overrides normal specificity (use sparingly)
### CSS Selectors
| Selector | Example | Description |
|----------|---------|-------------|
| Element | `p` | Selects all `<p>` elements |
| Class | `.button` | Selects elements with `class="button"` |
| ID | `#header` | Selects element with `id="header"` |
| Universal | `*` | Selects all elements |
| Descendant | `div p` | `<p>` inside `<div>` (any level) |
| Child | `div > p` | Direct child `<p>` of `<div>` |
| Adjacent Sibling | `h1 + p` | `<p>` immediately after `<h1>` |
| General Sibling | `h1 ~ p` | All `<p>` siblings after `<h1>` |
| Attribute | `[type="text"]` | Elements with specific attribute |
| Attribute Contains | `[href*="example"]` | Contains substring |
| Attribute Starts | `[href^="https"]` | Starts with string |
| Attribute Ends | `[href$=".pdf"]` | Ends with string |
### Pseudo-Classes
Target elements based on state or position:
```css
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: orange; }
a:focus { outline: 2px solid blue; }
/* Structural */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(odd) { background: #f0f0f0; }
li:nth-child(3n) { color: red; }
p:not(.special) { color: gray; }
/* Form states */
input:required { border-color: red; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:disabled { opacity: 0.5; }
input:checked + label { font-weight: bold; }
```
### Pseudo-Elements
Style specific parts of elements:
```css
/* First line/letter */
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }
/* Generated content */
.quote::before { content: '"'; }
.quote::after { content: '"'; }
/* Selection */
::selection { background: yellow; color: black; }
/* Placeholder */
input::placeholder { color: #999; }
```
## Box Model
Every element is a rectangular box with:
1. **Content**: The actual content (text, images)
2. **Padding**: Space around content, inside border
3. **Border**: Line around padding
4. **Margin**: Space outside border
```css
.box {
/* Content size */
width: 300px;
height: 200px;
/* Padding */
padding: 20px; /* All sides */
padding: 10px 20px; /* Vertical | Horizontal */
padding: 10px 20px 15px 25px; /* Top | Right | Bottom | Left */
/* Border */
border: 2px solid #333;
border-radius: 8px;
/* Margin */
margin: 20px auto; /* Vertical | Horizontal (auto centers) */
/* Box-sizing changes how width/height work */
box-sizing: border-box; /* Include padding/border in width/height */
}
```
## Layout Systems
### Flexbox
One-dimensional layout system (row or column):
```css
.container {
display: flex;
/* Direction */
flex-direction: row; /* row | row-reverse | column | column-reverse */
/* Wrapping */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
/* Main axis alignment */
justify-content: center; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
/* Cross axis alignment */
align-items: center; /* flex-start | flex-end | center | stretch | baseline */
/* Multi-line cross axis */
align-content: center; /* flex-start | flex-end | center | space-between | space-around | stretch */
/* Gap between items */
gap: 1rem;
}
.item {
/* Grow factor */
flex-grow: 1; /* Takes available space */
/* Shrink factor */
flex-shrink: 1; /* Can shrink if needed */
/* Base size */
flex-basis: 200px; /* Initial size before growing/shrinking */
/* Shorthand */
flex: 1 1 200px; /* grow | shrink | basis */
/* Individual alignment */
align-self: flex-end; /* Overrides container's align-items */
/* Order */
order: 2; /* Change visual order (default: 0) */
}
```
### CSS Grid
Two-dimensional layout system (rows and columns):
```css
.container {
display: grid;
/* Define columns */
grid-template-columns: 200px 1fr 1fr; /* Fixed | Flexible | Flexible */
grid-template-columns: repeat(3, 1fr); /* Three equal columns */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Responsive */
/* Define rows */
grid-template-rows: 100px auto 50px; /* Fixed | Auto | Fixed */
/* Named areas */
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
/* Gap between cells */
gap: 1rem; /* Row and column gap */
row-gap: 1rem;
column-gap: 2rem;
/* Alignment */
justify-items: start; /* Align items horizontally within cells */
align-items: start; /* Align items vertically within cells */
justify-content: center; /* Align grid within container horizontally */
align-content: center; /* Align grid within container vertically */
}
.item {
/* Span columns */
grid-column: 1 / 3; /* Start / End */
grid-column: span 2; /* Span 2 columns */
/* Span rows */
grid-row: 1 / 3;
grid-row: span 2;
/* Named area */
grid-area: header;
/* Individual alignment */
justify-self: center; /* Horizontal alignment */
align-self: center; /* Vertical alignment */
}
```
### Grid vs Flexbox
| Use Case | Best Choice |
|----------|-------------|
| One-dimensional layout (row or column) | Flexbox |
| Two-dimensional layout (rows and columns) | Grid |
| Align items along one axis | Flexbox |
| Create complex page layouts | Grid |
| Distribute space between items | Flexbox |
| Precise control over rows and columns | Grid |
| Content-first responsive design | Flexbox |
| Layout-first responsive design | Grid |
## Positioning
### Position Types
```css
/* Static (default) - normal flow */
.static { position: static; }
/* Relative - offset from normal position */
.relative {
position: relative;
top: 10px; /* Move down 10px */
left: 20px; /* Move right 20px */
}
/* Absolute - removed from flow, positioned relative to nearest positioned ancestor */
.absolute {
position: absolute;
top: 0;
right: 0;
}
/* Fixed - removed from flow, positioned relative to viewport */
.fixed {
position: fixed;
bottom: 20px;
right: 20px;
}
/* Sticky - switches between relative and fixed based on scroll */
.sticky {
position: sticky;
top: 0; /* Sticks to top when scrolling */
}
```
### Inset Properties
Shorthand for positioning:
```css
.element {
position: absolute;
inset: 0; /* All sides: top, right, bottom, left = 0 */
inset: 10px 20px; /* Vertical | Horizontal */
inset: 10px 20px 30px 40px; /* Top | Right | Bottom | Left */
}
```
### Stacking Context
Control layering with `z-index`:
```css
.behind { z-index: 1; }
.ahead { z-index: 10; }
.top { z-index: 100; }
```
**Note**: `z-index` only works on positioned elements (not `static`)
## Responsive Design
### Media Queries
Apply styles based on device characteristics:
```css
/* Mobile-first approach */
.container {
padding: 1rem;
}
/* Tablet and up */
@media (min-width: 768px) {
.container {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
}
/* Desktop */
@media (min-width: 1024px) {
.container {
padding: 3rem;
}
}
/* Landscape orientation */
@media (orientation: landscape) {
.header { height: 60px; }
}
/* High-DPI screens */
@media (min-resolution: 192dpi) {
.logo { background-image: url('logo@2x.png'); }
}
/* Dark mode preference */
@media (prefers-color-scheme: dark) {
body {
background: #222;
color: #fff;
}
}
/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
```
### Responsive Units
| Unit | Description | Example |
|------|-------------|---------|
| `px` | Pixels (absolute) | `16px` |
| `em` | Relative to parent font-size | `1.5em` |
| `rem` | Relative to root font-size | `1.5rem` |
| `%` | Relative to parent | `50%` |
| `vw` | Viewport width (1vw = 1% of viewport width) | `50vw` |
| `vh` | Viewport height | `100vh` |
| `vmin` | Smaller of vw or vh | `10vmin` |
| `vmax` | Larger of vw or vh | `10vmax` |
| `ch` | Width of "0" character | `40ch` |
| `fr` | Fraction of available space (Grid only) | `1fr` |
### Responsive Images
```css
img {
max-width: 100%;
height: auto;
}
/* Art direction with picture element */
```
```html
<picture>
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive image">
</picture>
```
## Typography
```css
.text {
/* Font family */
font-family: 'Helvetica Neue', Arial, sans-serif;
/* Font size */
font-size: 16px; /* Base size */
font-size: 1rem; /* Relative to root */
font-size: clamp(14px, 2vw, 20px); /* Responsive with min/max */
/* Font weight */
font-weight: normal; /* 400 */
font-weight: bold; /* 700 */
font-weight: 300; /* Light */
/* Font style */
font-style: italic;
/* Line height */
line-height: 1.5; /* 1.5 times font-size */
line-height: 24px;
/* Letter spacing */
letter-spacing: 0.05em;
/* Text alignment */
text-align: left; /* left | right | center | justify */
/* Text decoration */
text-decoration: underline;
text-decoration: none; /* Remove underline from links */
/* Text transform */
text-transform: uppercase; /* uppercase | lowercase | capitalize */
/* Word spacing */
word-spacing: 0.1em;
/* White space handling */
white-space: nowrap; /* Don't wrap */
white-space: pre-wrap; /* Preserve whitespace, wrap lines */
/* Text overflow */
overflow: hidden;
text-overflow: ellipsis; /* Show ... when text overflows */
/* Word break */
word-wrap: break-word; /* Break long words */
overflow-wrap: break-word; /* Modern version */
}
```
## Colors
```css
.colors {
/* Named colors */
color: red;
/* Hex */
color: #ff0000; /* Red */
color: #f00; /* Shorthand */
color: #ff0000ff; /* With alpha */
/* RGB */
color: rgb(255, 0, 0);
color: rgba(255, 0, 0, 0.5); /* With alpha */
color: rgb(255 0 0 / 0.5); /* Modern syntax */
/* HSL (Hue, Saturation, Lightness) */
color: hsl(0, 100%, 50%); /* Red */
color: hsla(0, 100%, 50%, 0.5); /* With alpha */
color: hsl(0 100% 50% / 0.5); /* Modern syntax */
/* Color keywords */
color: currentColor; /* Inherit color */
color: transparent;
}
```
### CSS Color Space
Modern color spaces for wider gamut:
```css
.modern-colors {
/* Display P3 (Apple devices) */
color: color(display-p3 1 0 0);
/* Lab color space */
color: lab(50% 125 0);
/* LCH color space */
color: lch(50% 125 0deg);
}
```
## Animations and Transitions
### Transitions
Smooth changes between states:
```css
.button {
background: blue;
color: white;
transition: all 0.3s ease;
/* transition: property duration timing-function delay */
}
.button:hover {
background: darkblue;
transform: scale(1.05);
}
/* Individual properties */
.element {
transition-property: opacity, transform;
transition-duration: 0.3s, 0.5s;
transition-timing-function: ease, ease-in-out;
transition-delay: 0s, 0.1s;
}
```
### Keyframe Animations
```css
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.element {
animation: fadeIn 0.5s ease forwards;
/* animation: name duration timing-function delay iteration-count direction fill-mode */
}
/* Multiple keyframes */
@keyframes slide {
0% { transform: translateX(0); }
50% { transform: translateX(100px); }
100% { transform: translateX(0); }
}
.slider {
animation: slide 2s infinite alternate;
}
```
## Transforms
```css
.transform {
/* Translate (move) */
transform: translate(50px, 100px); /* X, Y */
transform: translateX(50px);
transform: translateY(100px);
/* Rotate */
transform: rotate(45deg);
/* Scale */
transform: scale(1.5); /* 150% size */
transform: scale(2, 0.5); /* X, Y different */
/* Skew */
transform: skew(10deg, 5deg);
/* Multiple transforms */
transform: translate(50px, 0) rotate(45deg) scale(1.2);
/* 3D transforms */
transform: rotateX(45deg) rotateY(30deg);
transform: perspective(500px) translateZ(100px);
}
```
## CSS Variables (Custom Properties)
```css
:root {
--primary-color: #007bff;
--secondary-color: #6c757d;
--spacing: 1rem;
--border-radius: 4px;
}
.element {
color: var(--primary-color);
padding: var(--spacing);
border-radius: var(--border-radius);
/* With fallback */
color: var(--accent-color, red);
}
/* Dynamic changes */
.dark-theme {
--primary-color: #0056b3;
--background: #222;
--text: #fff;
}
```
## CSS Preprocessors
### Common Features
- Variables
- Nesting
- Mixins (reusable styles)
- Functions
- Imports
**Popular Preprocessors**: Sass/SCSS, Less, Stylus
## Best Practices
### Do's
- ✅ Use external stylesheets
- ✅ Use class selectors over ID selectors
- ✅ Keep specificity low
- ✅ Use responsive units (rem, em, %)
- ✅ Mobile-first approach
- ✅ Use CSS variables for theming
- ✅ Organize CSS logically
- ✅ Use shorthand properties
- ✅ Minify CSS for production
### Don'ts
- ❌ Use `!important` excessively
- ❌ Use inline styles
- ❌ Use fixed pixel widths
- ❌ Over-nest selectors
- ❌ Use vendor prefixes manually (use autoprefixer)
- ❌ Forget to test cross-browser
- ❌ Use IDs for styling
- ❌ Ignore CSS specificity
## Glossary Terms
**Key Terms Covered**:
- Alignment container
- Alignment subject
- Aspect ratio
- Baseline
- Block (CSS)
- Bounding box
- Cross Axis
- CSS
- CSS Object Model (CSSOM)
- CSS pixel
- CSS preprocessor
- Descriptor (CSS)
- Fallback alignment
- Flex
- Flex container
- Flex item
- Flexbox
- Flow relative values
- Grid
- Grid areas
- Grid Axis
- Grid Cell
- Grid Column
- Grid container
- Grid lines
- Grid Row
- Grid Tracks
- Gutters
- Ink overflow
- Inset properties
- Layout mode
- Logical properties
- Main axis
- Media query
- Physical properties
- Pixel
- Property (CSS)
- Pseudo-class
- Pseudo-element
- Selector (CSS)
- Stacking context
- Style origin
- Stylesheet
- Vendor prefix
## Additional Resources
- [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS)
- [CSS Tricks Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
- [CSS Tricks Complete Guide to Grid](https://css-tricks.com/snippets/css/complete-guide-grid/)
- [Can I Use](https://caniuse.com/) - Browser compatibility tables

View File

@@ -0,0 +1,411 @@
# Data Formats & Encoding Reference
Data formats, character encodings, and serialization for web development.
## JSON (JavaScript Object Notation)
Lightweight data interchange format.
### Syntax
```json
{
"string": "value",
"number": 42,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}
```
**Permitted Types**: string, number, boolean, null, array, object
**Not Permitted**: undefined, functions, dates, RegExp
### JavaScript Methods
```javascript
// Parse JSON string
const data = JSON.parse('{"name":"John","age":30}');
// Stringify object
const json = JSON.stringify({ name: 'John', age: 30 });
// Pretty print (indentation)
const json = JSON.stringify(data, null, 2);
// Custom serialization
const json = JSON.stringify(obj, (key, value) => {
if (key === 'password') return undefined; // Exclude
return value;
});
// toJSON method
const obj = {
name: 'John',
date: new Date(),
toJSON() {
return {
name: this.name,
date: this.date.toISOString()
};
}
};
```
### JSON Type Representation
How JavaScript types map to JSON:
- String → string
- Number → number
- Boolean → boolean
- null → null
- Array → array
- Object → object
- undefined → omitted
- Function → omitted
- Symbol → omitted
- Date → ISO 8601 string
## XML (Extensible Markup Language)
Markup language for encoding documents.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1">
<name>John Doe</name>
<email>john@example.com</email>
</user>
<user id="2">
<name>Jane Smith</name>
<email>jane@example.com</email>
</user>
</users>
```
**Use Cases**:
- Configuration files
- Data exchange
- RSS/Atom feeds
- SOAP web services
### Parsing XML in JavaScript
```javascript
// Parse XML string
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
// Query elements
const users = xmlDoc.querySelectorAll('user');
users.forEach(user => {
const name = user.querySelector('name').textContent;
console.log(name);
});
// Create XML
const serializer = new XMLSerializer();
const xmlString = serializer.serializeToString(xmlDoc);
```
## Character Encoding
### UTF-8
Universal character encoding (recommended for web).
**Characteristics**:
- Variable-width (1-4 bytes per character)
- Backward compatible with ASCII
- Supports all Unicode characters
```html
<meta charset="UTF-8">
```
### UTF-16
2 or 4 bytes per character.
**Use**: JavaScript internally uses UTF-16
```javascript
'A'.charCodeAt(0); // 65
String.fromCharCode(65); // 'A'
// Emoji (requires surrogate pair in UTF-16)
'😀'.length; // 2 (in JavaScript)
```
### ASCII
7-bit encoding (128 characters).
**Range**: 0-127
**Includes**: English letters, digits, common symbols
### Code Point vs Code Unit
- **Code Point**: Unicode character (U+0041 = 'A')
- **Code Unit**: 16-bit value in UTF-16
```javascript
// Code points
'A'.codePointAt(0); // 65
String.fromCodePoint(0x1F600); // '😀'
// Iterate code points
for (const char of 'Hello 😀') {
console.log(char);
}
```
## Base64
Binary-to-text encoding scheme.
```javascript
// Encode
const encoded = btoa('Hello World'); // "SGVsbG8gV29ybGQ="
// Decode
const decoded = atob('SGVsbG8gV29ybGQ='); // "Hello World"
// Handle Unicode (requires extra step)
const encoded = btoa(unescape(encodeURIComponent('Hello 世界')));
const decoded = decodeURIComponent(escape(atob(encoded)));
// Modern approach
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const bytes = encoder.encode('Hello 世界');
const decoded = decoder.decode(bytes);
```
**Use Cases**:
- Embed binary data in JSON/XML
- Data URLs (`data:image/png;base64,...`)
- Basic authentication headers
## URL Encoding (Percent Encoding)
Encode special characters in URLs.
```javascript
// encodeURIComponent (encode everything except: A-Z a-z 0-9 - _ . ! ~ * ' ( ))
const encoded = encodeURIComponent('Hello World!'); // "Hello%20World%21"
const decoded = decodeURIComponent(encoded); // "Hello World!"
// encodeURI (encode less - for full URLs)
const url = encodeURI('http://example.com/search?q=hello world');
// Modern URL API
const url = new URL('http://example.com/search');
url.searchParams.set('q', 'hello world');
console.log(url.toString()); // Automatically encoded
```
## MIME Types
Media type identification.
### Common MIME Types
| Type | MIME Type |
|------|-----------|
| HTML | `text/html` |
| CSS | `text/css` |
| JavaScript | `text/javascript`, `application/javascript` |
| JSON | `application/json` |
| XML | `application/xml`, `text/xml` |
| Plain Text | `text/plain` |
| JPEG | `image/jpeg` |
| PNG | `image/png` |
| GIF | `image/gif` |
| SVG | `image/svg+xml` |
| PDF | `application/pdf` |
| ZIP | `application/zip` |
| MP4 Video | `video/mp4` |
| MP3 Audio | `audio/mpeg` |
| Form Data | `application/x-www-form-urlencoded` |
| Multipart | `multipart/form-data` |
```html
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="app.js" type="text/javascript"></script>
```
```http
Content-Type: application/json; charset=utf-8
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
```
## Serialization & Deserialization
Converting data structures to/from storable format.
### JSON Serialization
```javascript
// Serialize
const obj = { name: 'John', date: new Date() };
const json = JSON.stringify(obj);
// Deserialize
const parsed = JSON.parse(json);
```
### Serializable Objects
Objects that can be serialized by structured clone algorithm:
- Basic types
- Arrays, Objects,
- Date, RegExp
- Map, Set
- ArrayBuffer, TypedArrays
**Not Serializable**:
- Functions
- DOM nodes
- Symbols (as values)
- Objects with prototype methods
## Character References
HTML entities for special characters.
```html
&lt; <!-- < -->
&gt; <!-- > -->
&amp; <!-- & -->
&quot; <!-- " -->
&apos; <!-- ' -->
&nbsp; <!-- non-breaking space -->
&copy; <!-- © -->
&#8364; <!---->
&#x20AC; <!-- € (hex) -->
```
## Data URLs
Embed data directly in URLs.
```html
<!-- Inline image -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt="Icon">
<!-- Inline SVG -->
<img src="data:image/svg+xml,%3Csvg xmlns='...'%3E...%3C/svg%3E" alt="Logo">
<!-- Inline CSS -->
<link rel="stylesheet" href="data:text/css,body%7Bmargin:0%7D">
```
```javascript
// Create data URL from canvas
const canvas = document.querySelector('canvas');
const dataURL = canvas.toDataURL('image/png');
// Create data URL from blob
const blob = new Blob(['Hello'], { type: 'text/plain' });
const reader = new FileReader();
reader.onload = () => {
const dataURL = reader.result;
};
reader.readAsDataURL(blob);
```
## Escape Sequences
```javascript
// String escapes
'It\'s a string'; // Single quote
"He said \"Hello\""; // Double quote
'Line 1\nLine 2'; // Newline
'Column1\tColumn2'; // Tab
'Path\\to\\file'; // Backslash
```
## Data Structures
### Arrays
Ordered collections:
```javascript
const arr = [1, 2, 3];
arr.push(4); // Add to end
arr.pop(); // Remove from end
```
### Objects
Key-value pairs:
```javascript
const obj = { key: 'value' };
obj.newKey = 'new value';
delete obj.key;
```
### Map
Keyed collections (any type as key):
```javascript
const map = new Map();
map.set('key', 'value');
map.set(obj, 'value');
map.get('key');
map.has('key');
map.delete('key');
```
### Set
Unique values:
```javascript
const set = new Set([1, 2, 2, 3]); // {1, 2, 3}
set.add(4);
set.has(2); // true
set.delete(1);
```
## Glossary Terms
**Key Terms Covered**:
- ASCII
- Base64
- Character
- Character encoding
- Character reference
- Character set
- Code point
- Code unit
- Data structure
- Deserialization
- Enumerated
- Escape character
- JSON
- JSON type representation
- MIME
- MIME type
- Percent-encoding
- Serialization
- Serializable object
- Unicode
- URI
- URL
- URN
- UTF-8
- UTF-16
## Additional Resources
- [JSON Specification](https://www.json.org/)
- [Unicode Standard](https://unicode.org/standard/standard.html)
- [MDN Character Encodings](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding)
- [MIME Types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)

View File

@@ -0,0 +1,502 @@
# Development Tools Reference
Tools and workflows for web development.
## Version Control
### Git
Distributed version control system.
**Basic Commands**:
```bash
# Initialize repository
git init
# Clone repository
git clone https://github.com/user/repo.git
# Check status
git status
# Stage changes
git add file.js
git add . # All files
# Commit
git commit -m "commit message"
# Push to remote
git push origin main
# Pull from remote
git pull origin main
# Branches
git branch feature-name
git checkout feature-name
git checkout -b feature-name # Create and switch
# Merge
git checkout main
git merge feature-name
# View history
git log
git log --oneline --graph
```
**Best Practices**:
- Commit often with meaningful messages
- Use branches for features
- Pull before push
- Review changes before committing
- Use .gitignore for generated files
### GitHub/GitLab/Bitbucket
Git hosting platforms with collaboration features:
- Pull requests / Merge requests
- Code review
- Issue tracking
- CI/CD integration
- Project management
## Package Managers
### npm (Node Package Manager)
```bash
# Initialize project
npm init
npm init -y # Skip prompts
# Install dependencies
npm install package-name
npm install -D package-name # Dev dependency
npm install -g package-name # Global
# Update packages
npm update
npm outdated
# Run scripts
npm run build
npm test
npm start
# Audit security
npm audit
npm audit fix
```
**package.json**:
```json
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"start": "node server.js",
"build": "webpack",
"test": "jest"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"webpack": "^5.75.0"
}
}
```
### Yarn
Faster alternative to npm:
```bash
yarn add package-name
yarn remove package-name
yarn upgrade
yarn build
```
### pnpm
Efficient package manager (disk space saving):
```bash
pnpm install
pnpm add package-name
pnpm remove package-name
```
## Build Tools
### Webpack
Module bundler:
```javascript
// webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
```
### Vite
Fast modern build tool:
```bash
# Create project
npm create vite@latest my-app
# Dev server
npm run dev
# Build
npm run build
```
### Parcel
Zero-config bundler:
```bash
parcel index.html
parcel build index.html
```
## Task Runners
### npm Scripts
```json
{
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production",
"test": "jest",
"lint": "eslint src/",
"format": "prettier --write src/"
}
}
```
## Testing Frameworks
### Jest
JavaScript testing framework:
```javascript
// sum.test.js
const sum = require('./sum');
describe('sum function', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('handles negative numbers', () => {
expect(sum(-1, -2)).toBe(-3);
});
});
```
### Vitest
Vite-powered testing (Jest-compatible):
```javascript
import { describe, test, expect } from 'vitest';
describe('math', () => {
test('addition', () => {
expect(1 + 1).toBe(2);
});
});
```
### Playwright
End-to-end testing:
```javascript
import { test, expect } from '@playwright/test';
test('homepage has title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example/);
});
```
## Linters & Formatters
### ESLint
JavaScript linter:
```javascript
// .eslintrc.js
module.exports = {
extends: ['eslint:recommended'],
rules: {
'no-console': 'warn',
'no-unused-vars': 'error'
}
};
```
### Prettier
Code formatter:
```json
// .prettierrc
{
"singleQuote": true,
"semi": true,
"tabWidth": 2,
"trailingComma": "es5"
}
```
### Stylelint
CSS linter:
```json
{
"extends": "stylelint-config-standard",
"rules": {
"indentation": 2,
"color-hex-length": "short"
}
}
```
## IDEs and Editors
### Visual Studio Code
**Key Features**:
- IntelliSense
- Debugging
- Git integration
- Extensions marketplace
- Terminal integration
**Popular Extensions**:
- ESLint
- Prettier
- Live Server
- GitLens
- Path Intellisense
### WebStorm
Full-featured IDE for web development by JetBrains.
### Sublime Text
Lightweight, fast text editor.
### Vim/Neovim
Terminal-based editor (steep learning curve).
## TypeScript
Typed superset of JavaScript:
```typescript
// types.ts
interface User {
id: number;
name: string;
email?: string; // Optional
}
function getUser(id: number): User {
return { id, name: 'John' };
}
// Generics
function identity<T>(arg: T): T {
return arg;
}
```
```json
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
```
## Continuous Integration (CI/CD)
### GitHub Actions
```yaml
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm test
```
### Other CI/CD Platforms
- **GitLab CI**
- **CircleCI**
- **Travis CI**
- **Jenkins**
## Debugging
### Browser DevTools
```javascript
// Debugging statements
debugger; // Pause execution
console.log('value:', value);
console.error('error:', error);
console.trace(); // Stack trace
```
### Node.js Debugging
```bash
# Built-in debugger
node inspect app.js
# Chrome DevTools
node --inspect app.js
node --inspect-brk app.js # Break on start
```
## Performance Profiling
### Chrome DevTools Performance
- Record CPU activity
- Analyze flame charts
- Identify bottlenecks
### Lighthouse
```bash
# CLI
npm install -g lighthouse
lighthouse https://example.com
# DevTools
Open Chrome DevTools > Lighthouse tab
```
## Monitoring
### Error Tracking
- **Sentry**: Error monitoring
- **Rollbar**: Real-time error tracking
- **Bugsnag**: Error monitoring
### Analytics
- **Google Analytics**
- **Plausible**: Privacy-friendly
- **Matomo**: Self-hosted
### RUM (Real User Monitoring)
- **SpeedCurve**
- **New Relic**
- **Datadog**
## Developer Workflow
### Typical Workflow
1. **Setup**: Clone repo, install dependencies
2. **Develop**: Write code, run dev server
3. **Test**: Run unit/integration tests
4. **Lint/Format**: Check code quality
5. **Commit**: Git commit and push
6. **CI/CD**: Automated tests and deployment
7. **Deploy**: Push to production
### Environment Variables
```bash
# .env
DATABASE_URL=postgres://localhost/db
API_KEY=secret-key-here
NODE_ENV=development
```
```javascript
// Access in Node.js
const dbUrl = process.env.DATABASE_URL;
```
## Glossary Terms
**Key Terms Covered**:
- Bun
- Continuous integration
- Deno
- Developer tools
- Fork
- Fuzz testing
- Git
- IDE
- Node.js
- Repo
- Rsync
- SCM
- SDK
- Smoke test
- SVN
- TypeScript
## Additional Resources
- [Git Documentation](https://git-scm.com/doc)
- [npm Documentation](https://docs.npmjs.com/)
- [Webpack Guides](https://webpack.js.org/guides/)
- [Jest Documentation](https://jestjs.io/docs/getting-started)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)

View File

@@ -0,0 +1,649 @@
# Glossary
- Reference [Glossary of Web Terms](https://developer.mozilla.org/en-US/docs/Glossary)
## Web Terms
This glossary contains comprehensive web terms categorized across 15 domains:
- HTML & Markup
- CSS & Styling
- JavaScript & Programming
- Web APIs & DOM
- HTTP & Networking
- Security & Authentication
- Performance & Optimization
- Accessibility
- Web Protocols & Standards
- Browsers & Engines
- Development Tools
- Data Formats & Encoding
- Media & Graphics
- Architecture & Patterns
- Servers & Infrastructure
## All Web Terms
- [Abstraction](https://developer.mozilla.org/en-US/docs/Glossary/Abstraction)
- [Accent](https://developer.mozilla.org/en-US/docs/Glossary/Accent)
- [Accessibility](https://developer.mozilla.org/en-US/docs/Glossary/Accessibility)
- [Accessibility tree](https://developer.mozilla.org/en-US/docs/Glossary/Accessibility_tree)
- [Accessible description](https://developer.mozilla.org/en-US/docs/Glossary/Accessible_description)
- [Accessible name](https://developer.mozilla.org/en-US/docs/Glossary/Accessible_name)
- [Adobe Flash](https://developer.mozilla.org/en-US/docs/Glossary/Adobe_Flash)
- [Advance measure](https://developer.mozilla.org/en-US/docs/Glossary/Advance_measure)
- [Ajax](https://developer.mozilla.org/en-US/docs/Glossary/Ajax)
- [Algorithm](https://developer.mozilla.org/en-US/docs/Glossary/Algorithm)
- [Alignment container](https://developer.mozilla.org/en-US/docs/Glossary/Alignment_container)
- [Alignment subject](https://developer.mozilla.org/en-US/docs/Glossary/Alignment_subject)
- [Alpha (*alpha channel*)](https://developer.mozilla.org/en-US/docs/Glossary/Alpha)
- [ALPN](https://developer.mozilla.org/en-US/docs/Glossary/ALPN)
- [API](https://developer.mozilla.org/en-US/docs/Glossary/API)
- [Apple Safari](https://developer.mozilla.org/en-US/docs/Glossary/Apple_Safari)
- [Application context](https://developer.mozilla.org/en-US/docs/Glossary/Application_context)
- [Argument](https://developer.mozilla.org/en-US/docs/Glossary/Argument)
- [ARIA](https://developer.mozilla.org/en-US/docs/Glossary/ARIA)
- [ARPA](https://developer.mozilla.org/en-US/docs/Glossary/ARPA)
- [ARPANET](https://developer.mozilla.org/en-US/docs/Glossary/ARPANET)
- [Array](https://developer.mozilla.org/en-US/docs/Glossary/Array)
- [ASCII](https://developer.mozilla.org/en-US/docs/Glossary/ASCII)
- [Aspect ratio](https://developer.mozilla.org/en-US/docs/Glossary/Aspect_ratio)
- [Asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous)
- [ATAG](https://developer.mozilla.org/en-US/docs/Glossary/ATAG)
- [Attribute](https://developer.mozilla.org/en-US/docs/Glossary/Attribute)
- [Authentication](https://developer.mozilla.org/en-US/docs/Glossary/Authentication)
- [Authenticator](https://developer.mozilla.org/en-US/docs/Glossary/Authenticator)
- [Bandwidth](https://developer.mozilla.org/en-US/docs/Glossary/Bandwidth)
- [Base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64)
- [Baseline](https://developer.mozilla.org/en-US/docs/Glossary/Baseline)
- [Baseline (*compatibility*)](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility)
- [Baseline (*typography*)](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Typography)
- [BCP 47 language tag](https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag)
- [Beacon](https://developer.mozilla.org/en-US/docs/Glossary/Beacon)
- [Bézier curve](https://developer.mozilla.org/en-US/docs/Glossary/Bézier_curve)
- [bfcache](https://developer.mozilla.org/en-US/docs/Glossary/bfcache)
- [BiDi](https://developer.mozilla.org/en-US/docs/Glossary/BiDi)
- [BigInt](https://developer.mozilla.org/en-US/docs/Glossary/BigInt)
- [Binding](https://developer.mozilla.org/en-US/docs/Glossary/Binding)
- [Bitwise flags](https://developer.mozilla.org/en-US/docs/Glossary/Bitwise_flags)
- [Blink](https://developer.mozilla.org/en-US/docs/Glossary/Blink)
- [blink element (*\<blink\> tag*)](https://developer.mozilla.org/en-US/docs/Glossary/blink_element)
- [Block](https://developer.mozilla.org/en-US/docs/Glossary/Block)
- [Block (*CSS*)](https://developer.mozilla.org/en-US/docs/Glossary/Block/CSS)
- [Block (*scripting*)](https://developer.mozilla.org/en-US/docs/Glossary/Block/Scripting)
- [Block cipher mode of operation](https://developer.mozilla.org/en-US/docs/Glossary/Block_cipher_mode_of_operation)
- [Block-level content](https://developer.mozilla.org/en-US/docs/Glossary/Block-level_content)
- [Boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
- [Boolean (*JavaScript*)](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/JavaScript)
- [Boolean attribute (*ARIA*)](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/ARIA)
- [Boolean attribute (*HTML*)](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML)
- [Bounding box](https://developer.mozilla.org/en-US/docs/Glossary/Bounding_box)
- [Breadcrumb](https://developer.mozilla.org/en-US/docs/Glossary/Breadcrumb)
- [Brotli compression](https://developer.mozilla.org/en-US/docs/Glossary/Brotli_compression)
- [Browser](https://developer.mozilla.org/en-US/docs/Glossary/Browser)
- [Browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context)
- [Buffer](https://developer.mozilla.org/en-US/docs/Glossary/Buffer)
- [Bun](https://developer.mozilla.org/en-US/docs/Glossary/Bun)
- [Cache](https://developer.mozilla.org/en-US/docs/Glossary/Cache)
- [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/Cacheable)
- [CalDAV](https://developer.mozilla.org/en-US/docs/Glossary/CalDAV)
- [Call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack)
- [Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)
- [Camel case](https://developer.mozilla.org/en-US/docs/Glossary/Camel_case)
- [Canonical order](https://developer.mozilla.org/en-US/docs/Glossary/Canonical_order)
- [Canvas](https://developer.mozilla.org/en-US/docs/Glossary/Canvas)
- [Card sorting](https://developer.mozilla.org/en-US/docs/Glossary/Card_sorting)
- [CardDAV](https://developer.mozilla.org/en-US/docs/Glossary/CardDAV)
- [Caret](https://developer.mozilla.org/en-US/docs/Glossary/Caret)
- [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN)
- [Certificate authority](https://developer.mozilla.org/en-US/docs/Glossary/Certificate_authority)
- [Certified](https://developer.mozilla.org/en-US/docs/Glossary/Certified)
- [Challenge-response authentication](https://developer.mozilla.org/en-US/docs/Glossary/Challenge-response_authentication)
- [Character](https://developer.mozilla.org/en-US/docs/Glossary/Character)
- [Character encoding](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding)
- [Character reference](https://developer.mozilla.org/en-US/docs/Glossary/Character_reference)
- [Character set](https://developer.mozilla.org/en-US/docs/Glossary/Character_set)
- [Chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome)
- [CIA](https://developer.mozilla.org/en-US/docs/Glossary/CIA)
- [Cipher](https://developer.mozilla.org/en-US/docs/Glossary/Cipher)
- [Cipher suite](https://developer.mozilla.org/en-US/docs/Glossary/Cipher_suite)
- [Ciphertext](https://developer.mozilla.org/en-US/docs/Glossary/Ciphertext)
- [Class](https://developer.mozilla.org/en-US/docs/Glossary/Class)
- [Client-side rendering (*CSR*)](https://developer.mozilla.org/en-US/docs/Glossary/Client-side_rendering_(CSR))
- [Closure](https://developer.mozilla.org/en-US/docs/Glossary/Closure)
- [Cloud](https://developer.mozilla.org/en-US/docs/Glossary/Cloud)
- [Cloud computing](https://developer.mozilla.org/en-US/docs/Glossary/Cloud_computing)
- [CMS](https://developer.mozilla.org/en-US/docs/Glossary/CMS)
- [Code point](https://developer.mozilla.org/en-US/docs/Glossary/Code_point)
- [Code splitting](https://developer.mozilla.org/en-US/docs/Glossary/Code_splitting)
- [Code unit](https://developer.mozilla.org/en-US/docs/Glossary/Code_unit)
- [Codec](https://developer.mozilla.org/en-US/docs/Glossary/Codec)
- [Color space](https://developer.mozilla.org/en-US/docs/Glossary/Color_space)
- [Color wheel](https://developer.mozilla.org/en-US/docs/Glossary/Color_wheel)
- [Compile](https://developer.mozilla.org/en-US/docs/Glossary/Compile)
- [Compile time](https://developer.mozilla.org/en-US/docs/Glossary/Compile_time)
- [Composite operation](https://developer.mozilla.org/en-US/docs/Glossary/Composite_operation)
- [Compression Dictionary Transport](https://developer.mozilla.org/en-US/docs/Glossary/Compression_Dictionary_Transport)
- [Computer programming](https://developer.mozilla.org/en-US/docs/Glossary/Computer_programming)
- [Conditional](https://developer.mozilla.org/en-US/docs/Glossary/Conditional)
- [Constant](https://developer.mozilla.org/en-US/docs/Glossary/Constant)
- [Constructor](https://developer.mozilla.org/en-US/docs/Glossary/Constructor)
- [Content header](https://developer.mozilla.org/en-US/docs/Glossary/Content_header)
- [Continuous integration](https://developer.mozilla.org/en-US/docs/Glossary/Continuous_integration)
- [Continuous media](https://developer.mozilla.org/en-US/docs/Glossary/Continuous_media)
- [Control flow](https://developer.mozilla.org/en-US/docs/Glossary/Control_flow)
- [Cookie](https://developer.mozilla.org/en-US/docs/Glossary/Cookie)
- [Copyleft](https://developer.mozilla.org/en-US/docs/Glossary/Copyleft)
- [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS)
- [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header)
- [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header)
- [Crawler](https://developer.mozilla.org/en-US/docs/Glossary/Crawler)
- [Credential](https://developer.mozilla.org/en-US/docs/Glossary/Credential)
- [CRLF](https://developer.mozilla.org/en-US/docs/Glossary/CRLF)
- [Cross Axis](https://developer.mozilla.org/en-US/docs/Glossary/Cross_Axis)
- [Cross-site request forgery (*CSRF*)](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)
- [Cross-site scripting (*XSS*)](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)
- [CRUD](https://developer.mozilla.org/en-US/docs/Glossary/CRUD)
- [Cryptanalysis](https://developer.mozilla.org/en-US/docs/Glossary/Cryptanalysis)
- [Cryptography](https://developer.mozilla.org/en-US/docs/Glossary/Cryptography)
- [CSP](https://developer.mozilla.org/en-US/docs/Glossary/CSP)
- [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS)
- [CSS Object Model (*CSSOM*)](https://developer.mozilla.org/en-US/docs/Glossary/CSS_Object_Model_(CSSOM))
- [CSS pixel](https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel)
- [CSS preprocessor](https://developer.mozilla.org/en-US/docs/Glossary/CSS_preprocessor)
- [Cumulative Layout Shift (*CLS*)](https://developer.mozilla.org/en-US/docs/Glossary/CLS)
- [Data structure](https://developer.mozilla.org/en-US/docs/Glossary/Data_structure)
- [Database](https://developer.mozilla.org/en-US/docs/Glossary/Database)
- [Debounce](https://developer.mozilla.org/en-US/docs/Glossary/Debounce)
- [Decryption](https://developer.mozilla.org/en-US/docs/Glossary/Decryption)
- [Deep copy](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy)
- [Delta](https://developer.mozilla.org/en-US/docs/Glossary/Delta)
- [Denial of Service (*DoS*)](https://developer.mozilla.org/en-US/docs/Glossary/Denial_of_Service)
- [Deno](https://developer.mozilla.org/en-US/docs/Glossary/Deno)
- [Descriptor (*CSS*)](https://developer.mozilla.org/en-US/docs/Glossary/Descriptor_(CSS))
- [Deserialization](https://developer.mozilla.org/en-US/docs/Glossary/Deserialization)
- [Developer tools](https://developer.mozilla.org/en-US/docs/Glossary/Developer_tools)
- [Device pixel](https://developer.mozilla.org/en-US/docs/Glossary/Device_pixel)
- [Digital certificate](https://developer.mozilla.org/en-US/docs/Glossary/Digital_certificate)
- [Digital signature](https://developer.mozilla.org/en-US/docs/Glossary/Digital_signature)
- [Distributed Denial of Service (*DDoS*)](https://developer.mozilla.org/en-US/docs/Glossary/Distributed_Denial_of_Service)
- [DMZ](https://developer.mozilla.org/en-US/docs/Glossary/DMZ)
- [DNS](https://developer.mozilla.org/en-US/docs/Glossary/DNS)
- [Doctype](https://developer.mozilla.org/en-US/docs/Glossary/Doctype)
- [Document directive](https://developer.mozilla.org/en-US/docs/Glossary/Document_directive)
- [Document environment](https://developer.mozilla.org/en-US/docs/Glossary/Document_environment)
- [DOM (*Document Object Model*)](https://developer.mozilla.org/en-US/docs/Glossary/DOM)
- [Domain](https://developer.mozilla.org/en-US/docs/Glossary/Domain)
- [Domain name](https://developer.mozilla.org/en-US/docs/Glossary/Domain_name)
- [Domain sharding](https://developer.mozilla.org/en-US/docs/Glossary/Domain_sharding)
- [Dominator](https://developer.mozilla.org/en-US/docs/Glossary/Dominator)
- [DSL](https://developer.mozilla.org/en-US/docs/Glossary/DSL)
- [DSL (*Digital Subscriber Line*)](https://developer.mozilla.org/en-US/docs/Glossary/DSL/Digital_Subscriber_Line)
- [DSL (*Domain-Specific Language*)](https://developer.mozilla.org/en-US/docs/Glossary/DSL/Domain-Specific_Language)
- [DTLS (*Datagram Transport Layer Security*)](https://developer.mozilla.org/en-US/docs/Glossary/DTLS)
- [DTMF (*Dual-Tone Multi-Frequency signaling*)](https://developer.mozilla.org/en-US/docs/Glossary/DTMF)
- [Dynamic typing](https://developer.mozilla.org/en-US/docs/Glossary/Dynamic_typing)
- [ECMA](https://developer.mozilla.org/en-US/docs/Glossary/ECMA)
- [ECMAScript](https://developer.mozilla.org/en-US/docs/Glossary/ECMAScript)
- [Effective connection type](https://developer.mozilla.org/en-US/docs/Glossary/Effective_connection_type)
- [Element](https://developer.mozilla.org/en-US/docs/Glossary/Element)
- [Encapsulation](https://developer.mozilla.org/en-US/docs/Glossary/Encapsulation)
- [Encryption](https://developer.mozilla.org/en-US/docs/Glossary/Encryption)
- [Endianness](https://developer.mozilla.org/en-US/docs/Glossary/Endianness)
- [Engine](https://developer.mozilla.org/en-US/docs/Glossary/Engine)
- [JavaScript engine](https://developer.mozilla.org/en-US/docs/Glossary/JavaScript_engine)
- [Rendering engine](https://developer.mozilla.org/en-US/docs/Glossary/Rendering_engine)
- [Entity](https://developer.mozilla.org/en-US/docs/Glossary/Entity)
- [Entity header](https://developer.mozilla.org/en-US/docs/Glossary/Entity_header)
- [Enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated)
- [Escape character](https://developer.mozilla.org/en-US/docs/Glossary/Escape_character)
- [Event](https://developer.mozilla.org/en-US/docs/Glossary/Event)
- [Exception](https://developer.mozilla.org/en-US/docs/Glossary/Exception)
- [EXIF](https://developer.mozilla.org/en-US/docs/Glossary/EXIF)
- [Expando](https://developer.mozilla.org/en-US/docs/Glossary/Expando)
- [Extrinsic size](https://developer.mozilla.org/en-US/docs/Glossary/Extrinsic_size)
- [Fallback alignment](https://developer.mozilla.org/en-US/docs/Glossary/Fallback_alignment)
- [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
- [Favicon](https://developer.mozilla.org/en-US/docs/Glossary/Favicon)
- [Federated identity](https://developer.mozilla.org/en-US/docs/Glossary/Federated_identity)
- [Fetch directive](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_directive)
- [Fetch metadata request header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header)
- [Fingerprinting](https://developer.mozilla.org/en-US/docs/Glossary/Fingerprinting)
- [Firefox OS](https://developer.mozilla.org/en-US/docs/Glossary/Firefox_OS)
- [Firewall](https://developer.mozilla.org/en-US/docs/Glossary/Firewall)
- [First Contentful Paint (*FCP*)](https://developer.mozilla.org/en-US/docs/Glossary/First_Contentful_Paint_(FCP))
- [First CPU idle](https://developer.mozilla.org/en-US/docs/Glossary/First_CPU_idle)
- [First Input Delay (FID)Deprecated](https://developer.mozilla.org/en-US/docs/Glossary/First_Input_Delay)
- [First Meaningful Paint (*FMP*)](https://developer.mozilla.org/en-US/docs/Glossary/First_meaningful_paint)
- [First Paint (*FP*)](https://developer.mozilla.org/en-US/docs/Glossary/First_paint)
- [First-class function](https://developer.mozilla.org/en-US/docs/Glossary/First-class_function)
- [Flex](https://developer.mozilla.org/en-US/docs/Glossary/Flex)
- [Flex container](https://developer.mozilla.org/en-US/docs/Glossary/Flex_container)
- [Flex item](https://developer.mozilla.org/en-US/docs/Glossary/Flex_item)
- [Flexbox](https://developer.mozilla.org/en-US/docs/Glossary/Flexbox)
- [Flow relative values](https://developer.mozilla.org/en-US/docs/Glossary/Flow_relative_values)
- [Forbidden request header](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header)
- [Forbidden response header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_response_header_name)
- [Fork](https://developer.mozilla.org/en-US/docs/Glossary/Fork)
- [Fragmentainer](https://developer.mozilla.org/en-US/docs/Glossary/Fragmentainer)
- [Frame rate (*FPS*)](https://developer.mozilla.org/en-US/docs/Glossary/FPS)
- [FTP](https://developer.mozilla.org/en-US/docs/Glossary/FTP)
- [FTU](https://developer.mozilla.org/en-US/docs/Glossary/FTU)
- [Function](https://developer.mozilla.org/en-US/docs/Glossary/Function)
- [Fuzz testing](https://developer.mozilla.org/en-US/docs/Glossary/Fuzz_testing)
- [Gamut](https://developer.mozilla.org/en-US/docs/Glossary/Gamut)
- [Garbage collection](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection)
- [Gecko](https://developer.mozilla.org/en-US/docs/Glossary/Gecko)
- [General header](https://developer.mozilla.org/en-US/docs/Glossary/General_header)
- [GIF](https://developer.mozilla.org/en-US/docs/Glossary/GIF)
- [Git](https://developer.mozilla.org/en-US/docs/Glossary/Git)
- [Global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object)
- [Global scope](https://developer.mozilla.org/en-US/docs/Glossary/Global_scope)
- [Global variable](https://developer.mozilla.org/en-US/docs/Glossary/Global_variable)
- [Glyph](https://developer.mozilla.org/en-US/docs/Glossary/Glyph)
- [Google Chrome](https://developer.mozilla.org/en-US/docs/Glossary/Google_Chrome)
- [GPL](https://developer.mozilla.org/en-US/docs/Glossary/GPL)
- [GPU](https://developer.mozilla.org/en-US/docs/Glossary/GPU)
- [Graceful degradation](https://developer.mozilla.org/en-US/docs/Glossary/Graceful_degradation)
- [Grid](https://developer.mozilla.org/en-US/docs/Glossary/Grid)
- [Grid areas](https://developer.mozilla.org/en-US/docs/Glossary/Grid_areas)
- [Grid Axis](https://developer.mozilla.org/en-US/docs/Glossary/Grid_Axis)
- [Grid Cell](https://developer.mozilla.org/en-US/docs/Glossary/Grid_Cell)
- [Grid Column](https://developer.mozilla.org/en-US/docs/Glossary/Grid_Column)
- [Grid container](https://developer.mozilla.org/en-US/docs/Glossary/Grid_container)
- [Grid lines](https://developer.mozilla.org/en-US/docs/Glossary/Grid_lines)
- [Grid Row](https://developer.mozilla.org/en-US/docs/Glossary/Grid_Row)
- [Grid Tracks](https://developer.mozilla.org/en-US/docs/Glossary/Grid_Tracks)
- [Guaranteed-invalid value](https://developer.mozilla.org/en-US/docs/Glossary/Guaranteed-invalid_value)
- [Gutters](https://developer.mozilla.org/en-US/docs/Glossary/Gutters)
- [gzip compression](https://developer.mozilla.org/en-US/docs/Glossary/gzip_compression)
- [Hash function](https://developer.mozilla.org/en-US/docs/Glossary/Hash_function)
- [Hash routing](https://developer.mozilla.org/en-US/docs/Glossary/Hash_routing)
- [Head](https://developer.mozilla.org/en-US/docs/Glossary/Head)
- [High-level programming language](https://developer.mozilla.org/en-US/docs/Glossary/High-level_programming_language)
- [HMAC](https://developer.mozilla.org/en-US/docs/Glossary/HMAC)
- [Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)
- [HOL blocking](https://developer.mozilla.org/en-US/docs/Glossary/HOL_blocking)
- [Host](https://developer.mozilla.org/en-US/docs/Glossary/Host)
- [Hotlink](https://developer.mozilla.org/en-US/docs/Glossary/Hotlink)
- [Houdini](https://developer.mozilla.org/en-US/docs/Glossary/Houdini)
- [HPKP](https://developer.mozilla.org/en-US/docs/Glossary/HPKP)
- [HSTS](https://developer.mozilla.org/en-US/docs/Glossary/HSTS)
- [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML)
- [HTML color codes](https://developer.mozilla.org/en-US/docs/Glossary/HTML_color_codes)
- [HTML5](https://developer.mozilla.org/en-US/docs/Glossary/HTML5)
- [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP)
- [HTTP content](https://developer.mozilla.org/en-US/docs/Glossary/HTTP_content)
- [HTTP header](https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header)
- [HTTP/2](https://developer.mozilla.org/en-US/docs/Glossary/HTTP/2)
- [HTTP/3](https://developer.mozilla.org/en-US/docs/Glossary/HTTP/3)
- [HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)
- [HTTPS RR](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS_RR)
- [Hyperlink](https://developer.mozilla.org/en-US/docs/Glossary/Hyperlink)
- [Hypertext](https://developer.mozilla.org/en-US/docs/Glossary/Hypertext)
- [IANA](https://developer.mozilla.org/en-US/docs/Glossary/IANA)
- [ICANN](https://developer.mozilla.org/en-US/docs/Glossary/ICANN)
- [ICE](https://developer.mozilla.org/en-US/docs/Glossary/ICE)
- [IDE](https://developer.mozilla.org/en-US/docs/Glossary/IDE)
- [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent)
- [Identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier)
- [Identity provider (*IdP*)](https://developer.mozilla.org/en-US/docs/Glossary/Identity_provider)
- [IDL](https://developer.mozilla.org/en-US/docs/Glossary/IDL)
- [IETF](https://developer.mozilla.org/en-US/docs/Glossary/IETF)
- [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
- [IMAP](https://developer.mozilla.org/en-US/docs/Glossary/IMAP)
- [Immutable](https://developer.mozilla.org/en-US/docs/Glossary/Immutable)
- [IndexedDB](https://developer.mozilla.org/en-US/docs/Glossary/IndexedDB)
- [Information architecture](https://developer.mozilla.org/en-US/docs/Glossary/Information_architecture)
- [Inheritance](https://developer.mozilla.org/en-US/docs/Glossary/Inheritance)
- [Ink overflow](https://developer.mozilla.org/en-US/docs/Glossary/Ink_overflow)
- [Inline-level content](https://developer.mozilla.org/en-US/docs/Glossary/Inline-level_content)
- [Input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor)
- [Inset properties](https://developer.mozilla.org/en-US/docs/Glossary/Inset_properties)
- [Instance](https://developer.mozilla.org/en-US/docs/Glossary/Instance)
- [Interaction to Next Paint (*INP*)](https://developer.mozilla.org/en-US/docs/Glossary/interaction_to_next_paint)
- [Internationalization (*i18n*)](https://developer.mozilla.org/en-US/docs/Glossary/Internationalization)
- [Internet](https://developer.mozilla.org/en-US/docs/Glossary/Internet)
- [Interpolation](https://developer.mozilla.org/en-US/docs/Glossary/Interpolation)
- [Intrinsic size](https://developer.mozilla.org/en-US/docs/Glossary/Intrinsic_size)
- [Invariant](https://developer.mozilla.org/en-US/docs/Glossary/Invariant)
- [IP Address](https://developer.mozilla.org/en-US/docs/Glossary/IP_Address)
- [IPv4](https://developer.mozilla.org/en-US/docs/Glossary/IPv4)
- [IPv6](https://developer.mozilla.org/en-US/docs/Glossary/IPv6)
- [IRC](https://developer.mozilla.org/en-US/docs/Glossary/IRC)
- [ISO](https://developer.mozilla.org/en-US/docs/Glossary/ISO)
- [ISP](https://developer.mozilla.org/en-US/docs/Glossary/ISP)
- [ITU](https://developer.mozilla.org/en-US/docs/Glossary/ITU)
- [Jank](https://developer.mozilla.org/en-US/docs/Glossary/Jank)
- [Java](https://developer.mozilla.org/en-US/docs/Glossary/Java)
- [JavaScript](https://developer.mozilla.org/en-US/docs/Glossary/JavaScript)
- [Jitter](https://developer.mozilla.org/en-US/docs/Glossary/Jitter)
- [JPEG](https://developer.mozilla.org/en-US/docs/Glossary/JPEG)
- [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON)
- [JSON type representation](https://developer.mozilla.org/en-US/docs/Glossary/JSON_type_representation)
- [Just-In-Time Compilation (*JIT*)](https://developer.mozilla.org/en-US/docs/Glossary/Just-in-time_compilation)
- [Kebab case](https://developer.mozilla.org/en-US/docs/Glossary/Kebab_case)
- [Key](https://developer.mozilla.org/en-US/docs/Glossary/Key)
- [Keyword](https://developer.mozilla.org/en-US/docs/Glossary/Keyword)
- [Largest Contentful Paint (*LCP*)](https://developer.mozilla.org/en-US/docs/Glossary/Largest_contentful_paint)
- [Latency](https://developer.mozilla.org/en-US/docs/Glossary/Latency)
- [Layout mode](https://developer.mozilla.org/en-US/docs/Glossary/Layout_mode)
- [Layout viewport](https://developer.mozilla.org/en-US/docs/Glossary/Layout_viewport)
- [Lazy load](https://developer.mozilla.org/en-US/docs/Glossary/Lazy_load)
- [Leading](https://developer.mozilla.org/en-US/docs/Glossary/Leading)
- [LGPL](https://developer.mozilla.org/en-US/docs/Glossary/LGPL)
- [Ligature](https://developer.mozilla.org/en-US/docs/Glossary/Ligature)
- [Literal](https://developer.mozilla.org/en-US/docs/Glossary/Literal)
- [Local scope](https://developer.mozilla.org/en-US/docs/Glossary/Local_scope)
- [Local variable](https://developer.mozilla.org/en-US/docs/Glossary/Local_variable)
- [Locale](https://developer.mozilla.org/en-US/docs/Glossary/Locale)
- [Localization](https://developer.mozilla.org/en-US/docs/Glossary/Localization)
- [Logical properties](https://developer.mozilla.org/en-US/docs/Glossary/Logical_properties)
- [Long task](https://developer.mozilla.org/en-US/docs/Glossary/Long_task)
- [Loop](https://developer.mozilla.org/en-US/docs/Glossary/Loop)
- [Lossless compression](https://developer.mozilla.org/en-US/docs/Glossary/Lossless_compression)
- [Lossy compression](https://developer.mozilla.org/en-US/docs/Glossary/Lossy_compression)
- [LTR (*Left To Right*)](https://developer.mozilla.org/en-US/docs/Glossary/LTR)
- [Main axis](https://developer.mozilla.org/en-US/docs/Glossary/Main_axis)
- [Main thread](https://developer.mozilla.org/en-US/docs/Glossary/Main_thread)
- [Markup](https://developer.mozilla.org/en-US/docs/Glossary/Markup)
- [MathML](https://developer.mozilla.org/en-US/docs/Glossary/MathML)
- [Media](https://developer.mozilla.org/en-US/docs/Glossary/Media)
- [Media (*Audio-visual presentation*)](https://developer.mozilla.org/en-US/docs/Glossary/Media/Audio-visual_presentation)
- [Media (*CSS*)](https://developer.mozilla.org/en-US/docs/Glossary/Media/CSS)
- [Media query](https://developer.mozilla.org/en-US/docs/Glossary/Media_query)
- [Metadata](https://developer.mozilla.org/en-US/docs/Glossary/Metadata)
- [Method](https://developer.mozilla.org/en-US/docs/Glossary/Method)
- [Microsoft Edge](https://developer.mozilla.org/en-US/docs/Glossary/Microsoft_Edge)
- [Microsoft Internet Explorer](https://developer.mozilla.org/en-US/docs/Glossary/Microsoft_Internet_Explorer)
- [Middleware](https://developer.mozilla.org/en-US/docs/Glossary/Middleware)
- [MIME](https://developer.mozilla.org/en-US/docs/Glossary/MIME)
- [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type)
- [Minification](https://developer.mozilla.org/en-US/docs/Glossary/Minification)
- [MitM](https://developer.mozilla.org/en-US/docs/Glossary/MitM)
- [Mixin](https://developer.mozilla.org/en-US/docs/Glossary/Mixin)
- [Mobile first](https://developer.mozilla.org/en-US/docs/Glossary/Mobile_first)
- [Modem](https://developer.mozilla.org/en-US/docs/Glossary/Modem)
- [Modularity](https://developer.mozilla.org/en-US/docs/Glossary/Modularity)
- [Mozilla Firefox](https://developer.mozilla.org/en-US/docs/Glossary/Mozilla_Firefox)
- [Multi-factor authentication](https://developer.mozilla.org/en-US/docs/Glossary/Multi-factor_authentication)
- [Mutable](https://developer.mozilla.org/en-US/docs/Glossary/Mutable)
- [MVC](https://developer.mozilla.org/en-US/docs/Glossary/MVC)
- [Namespace](https://developer.mozilla.org/en-US/docs/Glossary/Namespace)
- [NaN](https://developer.mozilla.org/en-US/docs/Glossary/NaN)
- [NAT](https://developer.mozilla.org/en-US/docs/Glossary/NAT)
- [Native](https://developer.mozilla.org/en-US/docs/Glossary/Native)
- [Navigation directive](https://developer.mozilla.org/en-US/docs/Glossary/Navigation_directive)
- [Netscape Navigator](https://developer.mozilla.org/en-US/docs/Glossary/Netscape_Navigator)
- [Network throttling](https://developer.mozilla.org/en-US/docs/Glossary/Network_throttling)
- [NNTP](https://developer.mozilla.org/en-US/docs/Glossary/NNTP)
- [Node](https://developer.mozilla.org/en-US/docs/Glossary/Node)
- [Node (*DOM*)](https://developer.mozilla.org/en-US/docs/Glossary/Node/DOM)
- [Node (*networking*)](https://developer.mozilla.org/en-US/docs/Glossary/Node/Networking)
- [Node.js](https://developer.mozilla.org/en-US/docs/Glossary/Node.js)
- [Non-normative](https://developer.mozilla.org/en-US/docs/Glossary/Non-normative)
- [Nonce](https://developer.mozilla.org/en-US/docs/Glossary/Nonce)
- [Normative](https://developer.mozilla.org/en-US/docs/Glossary/Normative)
- [Null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
- [Nullish value](https://developer.mozilla.org/en-US/docs/Glossary/Nullish_value)
- [Number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
- [Object](https://developer.mozilla.org/en-US/docs/Glossary/Object)
- [Object reference](https://developer.mozilla.org/en-US/docs/Glossary/Object_reference)
- [OOP](https://developer.mozilla.org/en-US/docs/Glossary/OOP)
- [OpenGL](https://developer.mozilla.org/en-US/docs/Glossary/OpenGL)
- [OpenSSL](https://developer.mozilla.org/en-US/docs/Glossary/OpenSSL)
- [Opera browser](https://developer.mozilla.org/en-US/docs/Glossary/Opera_browser)
- [Operand](https://developer.mozilla.org/en-US/docs/Glossary/Operand)
- [Operator](https://developer.mozilla.org/en-US/docs/Glossary/Operator)
- [Origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)
- [OTA](https://developer.mozilla.org/en-US/docs/Glossary/OTA)
- [OWASP](https://developer.mozilla.org/en-US/docs/Glossary/OWASP)
- [P2P](https://developer.mozilla.org/en-US/docs/Glossary/P2P)
- [PAC](https://developer.mozilla.org/en-US/docs/Glossary/PAC)
- [Packet](https://developer.mozilla.org/en-US/docs/Glossary/Packet)
- [Page load time](https://developer.mozilla.org/en-US/docs/Glossary/Page_load_time)
- [Page prediction](https://developer.mozilla.org/en-US/docs/Glossary/Page_prediction)
- [Parameter](https://developer.mozilla.org/en-US/docs/Glossary/Parameter)
- [Parent object](https://developer.mozilla.org/en-US/docs/Glossary/Parent_object)
- [Parse](https://developer.mozilla.org/en-US/docs/Glossary/Parse)
- [Parser](https://developer.mozilla.org/en-US/docs/Glossary/Parser)
- [Payload body](https://developer.mozilla.org/en-US/docs/Glossary/Payload_body)
- [Payload header](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header)
- [PDF](https://developer.mozilla.org/en-US/docs/Glossary/PDF)
- [Perceived performance](https://developer.mozilla.org/en-US/docs/Glossary/Perceived_performance)
- [Percent-encoding](https://developer.mozilla.org/en-US/docs/Glossary/Percent-encoding)
- [PHP](https://developer.mozilla.org/en-US/docs/Glossary/PHP)
- [Physical properties](https://developer.mozilla.org/en-US/docs/Glossary/Physical_properties)
- [Pixel](https://developer.mozilla.org/en-US/docs/Glossary/Pixel)
- [Placeholder names](https://developer.mozilla.org/en-US/docs/Glossary/Placeholder_names)
- [Plaintext](https://developer.mozilla.org/en-US/docs/Glossary/Plaintext)
- [Plugin](https://developer.mozilla.org/en-US/docs/Glossary/Plugin)
- [PNG](https://developer.mozilla.org/en-US/docs/Glossary/PNG)
- [Polyfill](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill)
- [Polymorphism](https://developer.mozilla.org/en-US/docs/Glossary/Polymorphism)
- [POP3](https://developer.mozilla.org/en-US/docs/Glossary/POP3)
- [Port](https://developer.mozilla.org/en-US/docs/Glossary/Port)
- [Prefetch](https://developer.mozilla.org/en-US/docs/Glossary/Prefetch)
- [Preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request)
- [Prerender](https://developer.mozilla.org/en-US/docs/Glossary/Prerender)
- [Presto](https://developer.mozilla.org/en-US/docs/Glossary/Presto)
- [Primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)
- [Principle of least privilege](https://developer.mozilla.org/en-US/docs/Glossary/Principle_of_least_privilege)
- [Privileged](https://developer.mozilla.org/en-US/docs/Glossary/Privileged)
- [Privileged code](https://developer.mozilla.org/en-US/docs/Glossary/Privileged_code)
- [Progressive enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_enhancement)
- [Progressive web applications (*PWAs*)](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_web_apps)
- [Promise](https://developer.mozilla.org/en-US/docs/Glossary/Promise)
- [Property](https://developer.mozilla.org/en-US/docs/Glossary/Property)
- [Property (*CSS*)](https://developer.mozilla.org/en-US/docs/Glossary/Property/CSS)
- [Property (*JavaScript*)](https://developer.mozilla.org/en-US/docs/Glossary/Property/JavaScript)
- [Protocol](https://developer.mozilla.org/en-US/docs/Glossary/Protocol)
- [Prototype](https://developer.mozilla.org/en-US/docs/Glossary/Prototype)
- [Prototype-based programming](https://developer.mozilla.org/en-US/docs/Glossary/Prototype-based_programming)
- [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server)
- [Pseudo-class](https://developer.mozilla.org/en-US/docs/Glossary/Pseudo-class)
- [Pseudo-element](https://developer.mozilla.org/en-US/docs/Glossary/Pseudo-element)
- [Pseudocode](https://developer.mozilla.org/en-US/docs/Glossary/Pseudocode)
- [Public-key cryptography](https://developer.mozilla.org/en-US/docs/Glossary/Public-key_cryptography)
- [Python](https://developer.mozilla.org/en-US/docs/Glossary/Python)
- [Quality values](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values)
- [Quaternion](https://developer.mozilla.org/en-US/docs/Glossary/Quaternion)
- [QUIC](https://developer.mozilla.org/en-US/docs/Glossary/QUIC)
- [RAIL](https://developer.mozilla.org/en-US/docs/Glossary/RAIL)
- [Random Number Generator](https://developer.mozilla.org/en-US/docs/Glossary/Random_Number_Generator)
- [Raster image](https://developer.mozilla.org/en-US/docs/Glossary/Raster_image)
- [Rate limit](https://developer.mozilla.org/en-US/docs/Glossary/Rate_limit)
- [RDF](https://developer.mozilla.org/en-US/docs/Glossary/RDF)
- [Reading order](https://developer.mozilla.org/en-US/docs/Glossary/Reading_order)
- [Real User Monitoring (*RUM*)](https://developer.mozilla.org/en-US/docs/Glossary/Real_User_Monitoring)
- [Recursion](https://developer.mozilla.org/en-US/docs/Glossary/Recursion)
- [Reflow](https://developer.mozilla.org/en-US/docs/Glossary/Reflow)
- [Registrable domain](https://developer.mozilla.org/en-US/docs/Glossary/Registrable_domain)
- [Regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression)
- [Relying party](https://developer.mozilla.org/en-US/docs/Glossary/Relying_party)
- [Render-blocking](https://developer.mozilla.org/en-US/docs/Glossary/Render-blocking)
- [Repaint](https://developer.mozilla.org/en-US/docs/Glossary/Repaint)
- [Replaced elements](https://developer.mozilla.org/en-US/docs/Glossary/Replaced_elements)
- [Replay attack](https://developer.mozilla.org/en-US/docs/Glossary/Replay_attack)
- [Repo](https://developer.mozilla.org/en-US/docs/Glossary/Repo)
- [Reporting directive](https://developer.mozilla.org/en-US/docs/Glossary/Reporting_directive)
- [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header)
- [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
- [Resource Timing](https://developer.mozilla.org/en-US/docs/Glossary/Resource_Timing)
- [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header)
- [Responsive Web Design (*RWD*)](https://developer.mozilla.org/en-US/docs/Glossary/Responsive_Web_Design)
- [REST](https://developer.mozilla.org/en-US/docs/Glossary/REST)
- [RGB](https://developer.mozilla.org/en-US/docs/Glossary/RGB)
- [RIL](https://developer.mozilla.org/en-US/docs/Glossary/RIL)
- [Robots.txt](https://developer.mozilla.org/en-US/docs/Glossary/Robots.txt)
- [Round Trip Time (*RTT*)](https://developer.mozilla.org/en-US/docs/Glossary/Round_Trip_Time)
- [Router](https://developer.mozilla.org/en-US/docs/Glossary/Router)
- [RSS](https://developer.mozilla.org/en-US/docs/Glossary/RSS)
- [Rsync](https://developer.mozilla.org/en-US/docs/Glossary/Rsync)
- [RTCP (*RTP Control Protocol*)](https://developer.mozilla.org/en-US/docs/Glossary/RTCP)
- [RTF](https://developer.mozilla.org/en-US/docs/Glossary/RTF)
- [RTL (*Right to Left*)](https://developer.mozilla.org/en-US/docs/Glossary/RTL)
- [RTP (*Real-time Transport Protocol*) and SRTP (*Secure RTP*)](https://developer.mozilla.org/en-US/docs/Glossary/RTP)
- [RTSP: Real-time streaming protocol](https://developer.mozilla.org/en-US/docs/Glossary/RTSP)
- [Ruby](https://developer.mozilla.org/en-US/docs/Glossary/Ruby)
- [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe)
- [Safe (*HTTP Methods*)](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP)
- [Salt](https://developer.mozilla.org/en-US/docs/Glossary/Salt)
- [Same-origin policy](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy)
- [SCM](https://developer.mozilla.org/en-US/docs/Glossary/SCM)
- [Scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope)
- [Screen reader](https://developer.mozilla.org/en-US/docs/Glossary/Screen_reader)
- [Script-supporting element](https://developer.mozilla.org/en-US/docs/Glossary/Script-supporting_element)
- [Scroll boundary](https://developer.mozilla.org/en-US/docs/Glossary/Scroll_boundary)
- [Scroll chaining](https://developer.mozilla.org/en-US/docs/Glossary/Scroll_chaining)
- [Scroll container](https://developer.mozilla.org/en-US/docs/Glossary/Scroll_container)
- [Scroll snap](https://developer.mozilla.org/en-US/docs/Glossary/Scroll_snap)
- [SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP)
- [SDK (*Software Development Kit*)](https://developer.mozilla.org/en-US/docs/Glossary/SDK)
- [SDP](https://developer.mozilla.org/en-US/docs/Glossary/SDP)
- [Search engine](https://developer.mozilla.org/en-US/docs/Glossary/Search_engine)
- [Secure context](https://developer.mozilla.org/en-US/docs/Glossary/Secure_context)
- [Secure Sockets Layer (*SSL*)](https://developer.mozilla.org/en-US/docs/Glossary/SSL)
- [Selector (*CSS*)](https://developer.mozilla.org/en-US/docs/Glossary/CSS_Selector)
- [Semantics](https://developer.mozilla.org/en-US/docs/Glossary/Semantics)
- [SEO](https://developer.mozilla.org/en-US/docs/Glossary/SEO)
- [Serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object)
- [Serialization](https://developer.mozilla.org/en-US/docs/Glossary/Serialization)
- [Server](https://developer.mozilla.org/en-US/docs/Glossary/Server)
- [Server Timing](https://developer.mozilla.org/en-US/docs/Glossary/Server_Timing)
- [Server-side rendering (*SSR*)](https://developer.mozilla.org/en-US/docs/Glossary/SSR)
- [Session hijacking](https://developer.mozilla.org/en-US/docs/Glossary/Session_hijacking)
- [SGML](https://developer.mozilla.org/en-US/docs/Glossary/SGML)
- [Shadow tree](https://developer.mozilla.org/en-US/docs/Glossary/Shadow_tree)
- [Shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy)
- [Shim](https://developer.mozilla.org/en-US/docs/Glossary/Shim)
- [Signature](https://developer.mozilla.org/en-US/docs/Glossary/Signature)
- [Signature (*functions*)](https://developer.mozilla.org/en-US/docs/Glossary/Signature_(functions))
- [Signature (*security*)](https://developer.mozilla.org/en-US/docs/Glossary/Signature_(security))
- [SIMD](https://developer.mozilla.org/en-US/docs/Glossary/SIMD)
- [SISD](https://developer.mozilla.org/en-US/docs/Glossary/SISD)
- [Site](https://developer.mozilla.org/en-US/docs/Glossary/Site)
- [Site map](https://developer.mozilla.org/en-US/docs/Glossary/Site_map)
- [SLD](https://developer.mozilla.org/en-US/docs/Glossary/SLD)
- [Sloppy mode](https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode)
- [Slug](https://developer.mozilla.org/en-US/docs/Glossary/Slug)
- [Smoke test](https://developer.mozilla.org/en-US/docs/Glossary/Smoke_test)
- [SMPTE (*Society of Motion Picture and Television Engineers*)](https://developer.mozilla.org/en-US/docs/Glossary/SMPTE)
- [SMTP](https://developer.mozilla.org/en-US/docs/Glossary/SMTP)
- [Snake case](https://developer.mozilla.org/en-US/docs/Glossary/Snake_case)
- [Snap positions](https://developer.mozilla.org/en-US/docs/Glossary/Snap_positions)
- [SOAP](https://developer.mozilla.org/en-US/docs/Glossary/SOAP)
- [Social engineering](https://developer.mozilla.org/en-US/docs/Glossary/Social_engineering)
- [Source map](https://developer.mozilla.org/en-US/docs/Glossary/Source_map)
- [SPA (*Single-page application*)](https://developer.mozilla.org/en-US/docs/Glossary/SPA)
- [Specification](https://developer.mozilla.org/en-US/docs/Glossary/Specification)
- [Speculative parsing](https://developer.mozilla.org/en-US/docs/Glossary/Speculative_parsing)
- [Speed index](https://developer.mozilla.org/en-US/docs/Glossary/Speed_index)
- [SQL](https://developer.mozilla.org/en-US/docs/Glossary/SQL)
- [SQL injection](https://developer.mozilla.org/en-US/docs/Glossary/SQL_injection)
- [SRI](https://developer.mozilla.org/en-US/docs/Glossary/SRI)
- [Stacking context](https://developer.mozilla.org/en-US/docs/Glossary/Stacking_context)
- [State machine](https://developer.mozilla.org/en-US/docs/Glossary/State_machine)
- [Statement](https://developer.mozilla.org/en-US/docs/Glossary/Statement)
- [Static method](https://developer.mozilla.org/en-US/docs/Glossary/Static_method)
- [Static site generator (*SSG*)](https://developer.mozilla.org/en-US/docs/Glossary/SSG)
- [Static typing](https://developer.mozilla.org/en-US/docs/Glossary/Static_typing)
- [Sticky activation](https://developer.mozilla.org/en-US/docs/Glossary/Sticky_activation)
- [Strict mode](https://developer.mozilla.org/en-US/docs/Glossary/Strict_mode)
- [String](https://developer.mozilla.org/en-US/docs/Glossary/String)
- [Stringifier](https://developer.mozilla.org/en-US/docs/Glossary/Stringifier)
- [STUN](https://developer.mozilla.org/en-US/docs/Glossary/STUN)
- [Style origin](https://developer.mozilla.org/en-US/docs/Glossary/Style_origin)
- [Stylesheet](https://developer.mozilla.org/en-US/docs/Glossary/Stylesheet)
- [Submit button](https://developer.mozilla.org/en-US/docs/Glossary/Submit_button)
- [SVG](https://developer.mozilla.org/en-US/docs/Glossary/SVG)
- [SVN](https://developer.mozilla.org/en-US/docs/Glossary/SVN)
- [Symbol](https://developer.mozilla.org/en-US/docs/Glossary/Symbol)
- [Symmetric-key cryptography](https://developer.mozilla.org/en-US/docs/Glossary/Symmetric-key_cryptography)
- [Synchronous](https://developer.mozilla.org/en-US/docs/Glossary/Synchronous)
- [Syntax](https://developer.mozilla.org/en-US/docs/Glossary/Syntax)
- [Syntax error](https://developer.mozilla.org/en-US/docs/Glossary/Syntax_error)
- [Synthetic monitoring](https://developer.mozilla.org/en-US/docs/Glossary/Synthetic_monitoring)
- [Table grid box](https://developer.mozilla.org/en-US/docs/Glossary/Table_grid_box)
- [Table wrapper box](https://developer.mozilla.org/en-US/docs/Glossary/Table_wrapper_box)
- [Tag](https://developer.mozilla.org/en-US/docs/Glossary/Tag)
- [TCP](https://developer.mozilla.org/en-US/docs/Glossary/TCP)
- [TCP handshake](https://developer.mozilla.org/en-US/docs/Glossary/TCP_handshake)
- [TCP slow start](https://developer.mozilla.org/en-US/docs/Glossary/TCP_slow_start)
- [Telnet](https://developer.mozilla.org/en-US/docs/Glossary/Telnet)
- [Texel](https://developer.mozilla.org/en-US/docs/Glossary/Texel)
- [The Khronos Group](https://developer.mozilla.org/en-US/docs/Glossary/The_Khronos_Group)
- [Thread](https://developer.mozilla.org/en-US/docs/Glossary/Thread)
- [Three js](https://developer.mozilla.org/en-US/docs/Glossary/Three_js)
- [Throttle](https://developer.mozilla.org/en-US/docs/Glossary/Throttle)
- [Time to First Byte (*TTFB*)](https://developer.mozilla.org/en-US/docs/Glossary/Time_to_first_byte)
- [Time to Interactive (*TTI*)](https://developer.mozilla.org/en-US/docs/Glossary/Time_to_interactive)
- [TLD](https://developer.mozilla.org/en-US/docs/Glossary/TLD)
- [TOFU](https://developer.mozilla.org/en-US/docs/Glossary/TOFU)
- [Top layer](https://developer.mozilla.org/en-US/docs/Glossary/Top_layer)
- [Transient activation](https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation)
- [Transport Layer Security (*TLS*)](https://developer.mozilla.org/en-US/docs/Glossary/TLS)
- [Tree shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking)
- [Trident](https://developer.mozilla.org/en-US/docs/Glossary/Trident)
- [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
- [TTL](https://developer.mozilla.org/en-US/docs/Glossary/TTL)
- [TURN](https://developer.mozilla.org/en-US/docs/Glossary/TURN)
- [Type](https://developer.mozilla.org/en-US/docs/Glossary/Type)
- [Type coercion](https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion)
- [Type conversion](https://developer.mozilla.org/en-US/docs/Glossary/Type_conversion)
- [TypeScript](https://developer.mozilla.org/en-US/docs/Glossary/TypeScript)
- [UAAG](https://developer.mozilla.org/en-US/docs/Glossary/UAAG)
- [UDP (*User Datagram Protocol*)](https://developer.mozilla.org/en-US/docs/Glossary/UDP)
- [UI](https://developer.mozilla.org/en-US/docs/Glossary/UI)
- [Undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
- [Unicode](https://developer.mozilla.org/en-US/docs/Glossary/Unicode)
- [Unix time](https://developer.mozilla.org/en-US/docs/Glossary/Unix_time)
- [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI)
- [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL)
- [URN](https://developer.mozilla.org/en-US/docs/Glossary/URN)
- [Usenet](https://developer.mozilla.org/en-US/docs/Glossary/Usenet)
- [User agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent)
- [UTF-8](https://developer.mozilla.org/en-US/docs/Glossary/UTF-8)
- [UTF-16](https://developer.mozilla.org/en-US/docs/Glossary/UTF-16)
- [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID)
- [UX](https://developer.mozilla.org/en-US/docs/Glossary/UX)
- [Validator](https://developer.mozilla.org/en-US/docs/Glossary/Validator)
- [Value](https://developer.mozilla.org/en-US/docs/Glossary/Value)
- [Variable](https://developer.mozilla.org/en-US/docs/Glossary/Variable)
- [Vendor prefix](https://developer.mozilla.org/en-US/docs/Glossary/Vendor_prefix)
- [Viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport)
- [Visual viewport](https://developer.mozilla.org/en-US/docs/Glossary/Visual_viewport)
- [Void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element)
- [VoIP](https://developer.mozilla.org/en-US/docs/Glossary/VoIP)
- [W3C](https://developer.mozilla.org/en-US/docs/Glossary/W3C)
- [WAI](https://developer.mozilla.org/en-US/docs/Glossary/WAI)
- [WCAG](https://developer.mozilla.org/en-US/docs/Glossary/WCAG)
- [Web performance](https://developer.mozilla.org/en-US/docs/Glossary/Web_performance)
- [Web server](https://developer.mozilla.org/en-US/docs/Glossary/Web_server)
- [Web standards](https://developer.mozilla.org/en-US/docs/Glossary/Web_standards)
- [WebAssembly](https://developer.mozilla.org/en-US/docs/Glossary/WebAssembly)
- [WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)
- [WebExtensions](https://developer.mozilla.org/en-US/docs/Glossary/WebExtensions)
- [WebGL](https://developer.mozilla.org/en-US/docs/Glossary/WebGL)
- [WebIDL](https://developer.mozilla.org/en-US/docs/Glossary/WebIDL)
- [WebKit](https://developer.mozilla.org/en-US/docs/Glossary/WebKit)
- [WebM](https://developer.mozilla.org/en-US/docs/Glossary/WebM)
- [WebP](https://developer.mozilla.org/en-US/docs/Glossary/WebP)
- [WebRTC](https://developer.mozilla.org/en-US/docs/Glossary/WebRTC)
- [WebSockets](https://developer.mozilla.org/en-US/docs/Glossary/WebSockets)
- [WebVTT](https://developer.mozilla.org/en-US/docs/Glossary/WebVTT)
- [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG)
- [Whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace)
- [WindowProxy](https://developer.mozilla.org/en-US/docs/Glossary/WindowProxy)
- [World Wide Web](https://developer.mozilla.org/en-US/docs/Glossary/World_Wide_Web)
- [Wrapper](https://developer.mozilla.org/en-US/docs/Glossary/Wrapper)
- [XFormsDeprecated](https://developer.mozilla.org/en-US/docs/Glossary/XFormsDeprecated)
- [XHTML](https://developer.mozilla.org/en-US/docs/Glossary/XHTML)
- [XInclude](https://developer.mozilla.org/en-US/docs/Glossary/XInclude)
- [XLink](https://developer.mozilla.org/en-US/docs/Glossary/XLink)
- [XML](https://developer.mozilla.org/en-US/docs/Glossary/XML)
- [XMLHttpRequest (*XHR*)](https://developer.mozilla.org/en-US/docs/Glossary/XMLHttpRequest_(XHR))
- [XPath](https://developer.mozilla.org/en-US/docs/Glossary/XPath)
- [XQuery](https://developer.mozilla.org/en-US/docs/Glossary/XQuery)
- [XSLT](https://developer.mozilla.org/en-US/docs/Glossary/XSLT)
- [Zstandard compression](https://developer.mozilla.org/en-US/docs/Glossary/Zstandard_compression)

View File

@@ -0,0 +1,387 @@
# HTML & Markup Reference
Comprehensive reference for HTML5, markup languages, and document structure.
## Core Concepts
### HTML (HyperText Markup Language)
The standard markup language for creating web pages and web applications.
**Related Terms**: HTML5, XHTML, Markup, Semantic HTML
### Elements
Building blocks of HTML documents. Each element has opening/closing tags (except void elements).
**Common Elements**:
- `<div>` - Generic container
- `<span>` - Inline container
- `<article>` - Self-contained content
- `<section>` - Thematic grouping
- `<nav>` - Navigation links
- `<header>` - Introductory content
- `<footer>` - Footer content
- `<main>` - Main content
- `<aside>` - Complementary content
### Attributes
Properties that provide additional information about HTML elements.
**Common Attributes**:
- `id` - Unique identifier
- `class` - CSS class name(s)
- `src` - Source URL for images/scripts
- `href` - Hyperlink reference
- `alt` - Alternative text
- `title` - Advisory title
- `data-*` - Custom data attributes
- `aria-*` - Accessibility attributes
### Void Elements
Elements that cannot have content and don't have closing tags.
**Examples**: `<img>`, `<br>`, `<hr>`, `<input>`, `<meta>`, `<link>`
## Semantic HTML
### What is Semantic HTML?
HTML that clearly describes its meaning to both the browser and the developer.
**Benefits**:
- Improved accessibility
- Better SEO
- Easier maintenance
- Built-in meaning and structure
### Semantic Elements
| Element | Purpose | When to Use |
|---------|---------|-------------|
| `<article>` | Self-contained composition | Blog posts, news articles |
| `<section>` | Thematic grouping of content | Chapters, tabbed content |
| `<nav>` | Navigation links | Main menu, breadcrumbs |
| `<aside>` | Tangential content | Sidebars, related links |
| `<header>` | Introductory content | Page/section headers |
| `<footer>` | Footer content | Copyright, contact info |
| `<main>` | Main content | Primary page content |
| `<figure>` | Self-contained content | Images with captions |
| `<figcaption>` | Caption for figure | Image descriptions |
| `<time>` | Date/time | Publishing dates |
| `<mark>` | Highlighted text | Search results |
| `<details>` | Expandable details | Accordions, FAQs |
| `<summary>` | Summary for details | Accordion headers |
### Example: Semantic Document Structure
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semantic Page Example</title>
</head>
<body>
<header>
<h1>Site Title</h1>
<nav aria-label="Main navigation">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
</header>
<main>
<article>
<header>
<h2>Article Title</h2>
<time datetime="2026-03-04">March 4, 2026</time>
</header>
<p>Article content goes here...</p>
<footer>
<p>Author: John Doe</p>
</footer>
</article>
</main>
<aside>
<h3>Related Content</h3>
<ul>
<li><a href="/related">Related Article</a></li>
</ul>
</aside>
<footer>
<p>&copy; 2026 Company Name</p>
</footer>
</body>
</html>
```
## Document Structure
### Doctype
Declares the document type and HTML version.
```html
<!DOCTYPE html>
```
### Head Section
Contains metadata about the document.
**Common Elements**:
- `<meta>` - Metadata (charset, viewport, description)
- `<title>` - Page title (shown in browser tab)
- `<link>` - External resources (stylesheets, icons)
- `<script>` - JavaScript files
- `<style>` - Inline CSS
### Metadata Examples
```html
<head>
<!-- Character encoding -->
<meta charset="UTF-8">
<!-- Responsive viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- SEO metadata -->
<meta name="description" content="Page description for search engines">
<meta name="keywords" content="html, web, development">
<meta name="author" content="Author Name">
<!-- Open Graph (social media) -->
<meta property="og:title" content="Page Title">
<meta property="og:description" content="Page description">
<meta property="og:image" content="https://example.com/image.jpg">
<!-- Favicon -->
<link rel="icon" type="image/png" href="/favicon.png">
<!-- Stylesheet -->
<link rel="stylesheet" href="styles.css">
<!-- Preload critical resources -->
<link rel="preload" href="critical.css" as="style">
<link rel="preconnect" href="https://api.example.com">
</head>
```
## Forms and Input
### Form Elements
```html
<form action="/submit" method="POST">
<!-- Text input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<!-- Email input -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<!-- Password input -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8" required>
<!-- Select dropdown -->
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select...</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
</select>
<!-- Textarea -->
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>
<!-- Checkbox -->
<label>
<input type="checkbox" name="terms" required>
I agree to the terms
</label>
<!-- Radio buttons -->
<fieldset>
<legend>Choose an option:</legend>
<label>
<input type="radio" name="option" value="a">
Option A
</label>
<label>
<input type="radio" name="option" value="b">
Option B
</label>
</fieldset>
<!-- Submit button -->
<button type="submit">Submit</button>
</form>
```
### Input Types
| Type | Purpose | Example |
|------|---------|---------|
| `text` | Single-line text | `<input type="text">` |
| `email` | Email address | `<input type="email">` |
| `password` | Password field | `<input type="password">` |
| `number` | Numeric input | `<input type="number" min="0" max="100">` |
| `tel` | Telephone number | `<input type="tel">` |
| `url` | URL | `<input type="url">` |
| `date` | Date picker | `<input type="date">` |
| `time` | Time picker | `<input type="time">` |
| `file` | File upload | `<input type="file" accept="image/*">` |
| `checkbox` | Checkbox | `<input type="checkbox">` |
| `radio` | Radio button | `<input type="radio">` |
| `range` | Slider | `<input type="range" min="0" max="100">` |
| `color` | Color picker | `<input type="color">` |
| `search` | Search field | `<input type="search">` |
## Related Markup Languages
### XML (Extensible Markup Language)
A markup language for encoding documents in a format that is both human-readable and machine-readable.
**Key Differences from HTML**:
- All tags must be properly closed
- Tags are case-sensitive
- Attributes must be quoted
- Custom tag names allowed
### XHTML (Extensible HyperText Markup Language)
HTML reformulated as XML. Stricter syntax rules than HTML.
### MathML (Mathematical Markup Language)
Markup language for displaying mathematical notation on the web.
```html
<math>
<mrow>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<mn>1</mn>
</mrow>
</math>
```
### SVG (Scalable Vector Graphics)
XML-based markup language for describing two-dimensional vector graphics.
```html
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
```
## Character Encoding and References
### Character Encoding
Defines how characters are represented as bytes.
**UTF-8**: Universal character encoding standard (recommended)
```html
<meta charset="UTF-8">
```
### Character References
Ways to represent special characters in HTML.
**Named Entities**:
- `&lt;` - Less than (<)
- `&gt;` - Greater than (>)
- `&amp;` - Ampersand (&)
- `&quot;` - Quote (")
- `&apos;` - Apostrophe (')
- `&nbsp;` - Non-breaking space
- `&copy;` - Copyright (©)
**Numeric Entities**:
- `&#60;` - Less than (<)
- `&#169;` - Copyright (©)
- `&#8364;` - Euro (€)
## Block vs Inline Content
### Block-Level Content
Elements that create a "block" in the layout, starting on a new line.
**Examples**: `<div>`, `<p>`, `<h1>`-`<h6>`, `<article>`, `<section>`, `<header>`, `<footer>`, `<nav>`, `<aside>`, `<ul>`, `<ol>`, `<li>`
### Inline-Level Content
Elements that don't start on a new line and only take up as much width as necessary.
**Examples**: `<span>`, `<a>`, `<strong>`, `<em>`, `<img>`, `<code>`, `<abbr>`, `<cite>`
## Best Practices
### Do's
- ✅ Use semantic HTML elements
- ✅ Include proper document structure (DOCTYPE, html, head, body)
- ✅ Set character encoding to UTF-8
- ✅ Use descriptive `alt` attributes for images
- ✅ Associate labels with form inputs
- ✅ Use heading hierarchy properly (h1 → h2 → h3)
- ✅ Validate HTML with W3C validator
- ✅ Use proper ARIA roles when needed
- ✅ Include meta viewport for responsive design
### Don'ts
- ❌ Use `<div>` when a semantic element exists
- ❌ Skip heading levels (h1 → h3)
- ❌ Use tables for layout
- ❌ Forget to close tags (except void elements)
- ❌ Use inline styles extensively
- ❌ Omit `alt` attribute on images
- ❌ Create forms without labels
- ❌ Use deprecated elements (`<font>`, `<center>`, `<blink>`)
## Glossary Terms from MDN
**Key Terms Covered**:
- Abstraction
- Accessibility tree
- Accessible description
- Accessible name
- Attribute
- Block-level content
- Breadcrumb
- Browsing context
- Character
- Character encoding
- Character reference
- Character set
- Doctype
- Document environment
- Element
- Entity
- Head
- HTML
- HTML5
- Hyperlink
- Hypertext
- Inline-level content
- Markup
- MathML
- Metadata
- Semantics
- SVG
- Tag
- Void element
- XHTML
- XML
## Additional Resources
- [MDN HTML Reference](https://developer.mozilla.org/en-US/docs/Web/HTML)
- [W3C HTML Specification](https://html.spec.whatwg.org/)
- [HTML5 Doctor](http://html5doctor.com/)
- [W3C Markup Validation Service](https://validator.w3.org/)

View File

@@ -0,0 +1,538 @@
# HTTP & Networking Reference
Comprehensive reference for HTTP protocol, networking concepts, and web communication.
## HTTP (HyperText Transfer Protocol)
Protocol for transferring hypertext between client and server. Foundation of data communication on the web.
### HTTP Versions
- **HTTP/1.1** (1997): Text-based, persistent connections, pipelining
- **HTTP/2** (2015): Binary protocol, multiplexing, server push, header compression
- **HTTP/3** (2022): Based on QUIC (UDP), improved performance, better handling of packet loss
## Request Methods
| Method | Purpose | Idempotent | Safe | Cacheable |
|--------|---------|------------|------|-----------|
| GET | Retrieve resource | Yes | Yes | Yes |
| POST | Create resource | No | No | Rarely |
| PUT | Update/replace resource | Yes | No | No |
| PATCH | Partial update | No | No | No |
| DELETE | Delete resource | Yes | No | No |
| HEAD | Like GET but no body | Yes | Yes | Yes |
| OPTIONS | Get allowed methods | Yes | Yes | No |
| CONNECT | Establish tunnel | No | No | No |
| TRACE | Echo request | Yes | Yes | No |
**Safe**: Doesn't modify server state
**Idempotent**: Multiple identical requests have same effect as single request
## Status Codes
### 1xx Informational
| Code | Message | Meaning |
|------|---------|---------|
| 100 | Continue | Client should continue request |
| 101 | Switching Protocols | Server switching protocols |
### 2xx Success
| Code | Message | Meaning |
|------|---------|---------|
| 200 | OK | Request succeeded |
| 201 | Created | Resource created |
| 202 | Accepted | Accepted but not processed |
| 204 | No Content | Success but no content to return |
| 206 | Partial Content | Partial resource (range request) |
### 3xx Redirection
| Code | Message | Meaning |
|------|---------|---------|
| 301 | Moved Permanently | Resource permanently moved |
| 302 | Found | Temporary redirect |
| 303 | See Other | Response at different URI |
| 304 | Not Modified | Resource not modified (cache) |
| 307 | Temporary Redirect | Like 302 but keep method |
| 308 | Permanent Redirect | Like 301 but keep method |
### 4xx Client Errors
| Code | Message | Meaning |
|------|---------|---------|
| 400 | Bad Request | Invalid syntax |
| 401 | Unauthorized | Authentication required |
| 403 | Forbidden | Access denied |
| 404 | Not Found | Resource not found |
| 405 | Method Not Allowed | Method not supported |
| 408 | Request Timeout | Request took too long |
| 409 | Conflict | Request conflicts with state |
| 410 | Gone | Resource permanently gone |
| 413 | Payload Too Large | Request body too large |
| 414 | URI Too Long | URI too long |
| 415 | Unsupported Media Type | Media type not supported |
| 422 | Unprocessable Entity | Semantic errors |
| 429 | Too Many Requests | Rate limit exceeded |
### 5xx Server Errors
| Code | Message | Meaning |
|------|---------|---------|
| 500 | Internal Server Error | Generic server error |
| 501 | Not Implemented | Method not supported |
| 502 | Bad Gateway | Invalid response from upstream |
| 503 | Service Unavailable | Server temporarily unavailable |
| 504 | Gateway Timeout | Upstream timeout |
| 505 | HTTP Version Not Supported | HTTP version not supported |
## HTTP Headers
### Request Headers
```http
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: application/json, text/plain
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
Authorization: Bearer token123
Cookie: sessionId=abc123
If-None-Match: "etag-value"
If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
Origin: https://example.com
Referer: https://example.com/page
```
**Common Request Headers**:
- `Accept`: Media types client accepts
- `Accept-Encoding`: Encoding formats (compression)
- `Accept-Language`: Preferred languages
- `Authorization`: Authentication credentials
- `Cache-Control`: Caching directives
- `Cookie`: Cookies sent to server
- `Content-Type`: Type of request body
- `Host`: Target host and port
- `If-Modified-Since`: Conditional request
- `If-None-Match`: Conditional request (ETag)
- `Origin`: Origin of request (CORS)
- `Referer`: Previous page URL
- `User-Agent`: Client information
### Response Headers
```http
HTTP/1.1 200 OK
Date: Mon, 04 Mar 2026 12:00:00 GMT
Server: nginx/1.18.0
Content-Type: application/json; charset=utf-8
Content-Length: 348
Content-Encoding: gzip
Cache-Control: public, max-age=3600
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Last-Modified: Mon, 04 Mar 2026 11:00:00 GMT
Access-Control-Allow-Origin: *
Set-Cookie: sessionId=xyz789; HttpOnly; Secure; SameSite=Strict
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
```
**Common Response Headers**:
- `Access-Control-*`: CORS headers
- `Cache-Control`: Caching directives
- `Content-Encoding`: Content compression
- `Content-Length`: Body size in bytes
- `Content-Type`: Media type of body
- `Date`: Response date/time
- `ETag`: Resource version identifier
- `Expires`: Expiration date
- `Last-Modified`: Last modification date
- `Location`: Redirect URL
- `Server`: Server software
- `Set-Cookie`: Set cookies
- `Strict-Transport-Security`: HSTS
- `X-Content-Type-Options`: MIME type sniffing
- `X-Frame-Options`: Clickjacking protection
## CORS (Cross-Origin Resource Sharing)
Mechanism to allow cross-origin requests.
### Simple Requests
Automatically allowed if:
- Method: GET, HEAD, or POST
- Safe headers only
- Content-Type: `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain`
### Preflight Requests
For complex requests, browser sends OPTIONS request first:
```http
OPTIONS /api/users HTTP/1.1
Origin: https://example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
```
```http
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
```
### CORS Headers
**Request**:
- `Origin`: Request origin
- `Access-Control-Request-Method`: Intended method
- `Access-Control-Request-Headers`: Intended headers
**Response**:
- `Access-Control-Allow-Origin`: Allowed origins (* or specific)
- `Access-Control-Allow-Methods`: Allowed methods
- `Access-Control-Allow-Headers`: Allowed headers
- `Access-Control-Allow-Credentials`: Allow credentials
- `Access-Control-Max-Age`: Preflight cache duration
- `Access-Control-Expose-Headers`: Headers accessible to client
## Caching
### Cache-Control Directives
**Request Directives**:
- `no-cache`: Validate with server before using cache
- `no-store`: Don't cache at all
- `max-age=N`: Max age in seconds
- `max-stale=N`: Accept stale response up to N seconds
- `min-fresh=N`: Fresh for at least N seconds
- `only-if-cached`: Use only cached response
**Response Directives**:
- `public`: Cacheable by any cache
- `private`: Cacheable by browser only
- `no-cache`: Must validate before use
- `no-store`: Don't cache
- `max-age=N`: Fresh for N seconds
- `s-maxage=N`: Max age for shared caches
- `must-revalidate`: Must validate when stale
- `immutable`: Content won't change
### Examples
```http
# Cache for 1 hour
Cache-Control: public, max-age=3600
# Don't cache
Cache-Control: no-store
# Cache in browser only, revalidate after 1 hour
Cache-Control: private, max-age=3600, must-revalidate
# Cache forever (with versioned URLs)
Cache-Control: public, max-age=31536000, immutable
```
### Conditional Requests
Use ETags or Last-Modified for efficient caching:
```http
GET /resource HTTP/1.1
If-None-Match: "etag-value"
If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
```
If not modified:
```http
HTTP/1.1 304 Not Modified
ETag: "etag-value"
```
## Cookies
```http
# Server sets cookie
Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600
# Client sends cookie
Cookie: sessionId=abc123; userId=456
```
### Cookie Attributes
- `Path=/`: Cookie path scope
- `Domain=example.com`: Cookie domain scope
- `Max-Age=N`: Expire after N seconds
- `Expires=date`: Expire at specific date
- `Secure`: Only sent over HTTPS
- `HttpOnly`: Not accessible via JavaScript
- `SameSite=Strict|Lax|None`: CSRF protection
## REST (Representational State Transfer)
Architectural style for web services.
### REST Principles
1. **Client-Server**: Separation of concerns
2. **Stateless**: Each request contains all needed info
3. **Cacheable**: Responses must define cacheability
4. **Uniform Interface**: Standardized communication
5. **Layered System**: Client doesn't know if connected to end server
6. **Code on Demand** (optional): Server can send executable code
### RESTful API Design
```
GET /users # List users
GET /users/123 # Get user 123
POST /users # Create user
PUT /users/123 # Update user 123 (full)
PATCH /users/123 # Update user 123 (partial)
DELETE /users/123 # Delete user 123
GET /users/123/posts # List posts by user 123
GET /posts?author=123 # Alternative: filter posts
```
### HTTP Content Negotiation
```http
# Client requests JSON
Accept: application/json
# Server responds with JSON
Content-Type: application/json
# Client can accept multiple formats
Accept: application/json, application/xml;q=0.9, text/plain;q=0.8
```
## Networking Fundamentals
### TCP (Transmission Control Protocol)
Connection-oriented protocol ensuring reliable data delivery.
**TCP Handshake** (3-way):
1. Client → Server: SYN
2. Server → Client: SYN-ACK
3. Client → Server: ACK
**Features**:
- Reliable delivery (retransmission)
- Ordered data
- Error checking
- Flow control
- Connection-oriented
### UDP (User Datagram Protocol)
Connectionless protocol for fast data transmission.
**Features**:
- Fast (no handshake)
- No guaranteed delivery
- No ordering
- Lower overhead
- Used for streaming, gaming, DNS
### DNS (Domain Name System)
Translates domain names to IP addresses.
```
example.com → 93.184.216.34
```
**DNS Record Types**:
- `A`: IPv4 address
- `AAAA`: IPv6 address
- `CNAME`: Canonical name (alias)
- `MX`: Mail exchange
- `TXT`: Text record
- `NS`: Name server
### IP Addressing
**IPv4**: `192.168.1.1` (32-bit)
**IPv6**: `2001:0db8:85a3:0000:0000:8a2e:0370:7334` (128-bit)
### Ports
- **Well-known ports** (0-1023):
- 80: HTTP
- 443: HTTPS
- 21: FTP
- 22: SSH
- 25: SMTP
- 53: DNS
- **Registered ports** (1024-49151)
- **Dynamic ports** (49152-65535)
### Bandwidth & Latency
**Bandwidth**: Amount of data transferred per unit time (Mbps, Gbps)
**Latency**: Time delay in data transmission (milliseconds)
**Round Trip Time (RTT)**: Time for request to reach server and response to return
## WebSockets
Full-duplex communication over single TCP connection.
```javascript
// Client
const ws = new WebSocket('wss://example.com/socket');
ws.onopen = () => {
console.log('Connected');
ws.send('Hello server!');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
ws.onerror = (error) => {
console.error('Error:', error);
};
ws.onclose = () => {
console.log('Disconnected');
};
// Close connection
ws.close();
```
**Use Cases**: Chat, real-time updates, gaming, collaborative editing
## Server-Sent Events (SSE)
Server pushes updates to client over HTTP.
```javascript
// Client
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log('New message:', event.data);
};
eventSource.addEventListener('custom-event', (event) => {
console.log('Custom event:', event.data);
});
eventSource.onerror = (error) => {
console.error('Error:', error);
};
// Close connection
eventSource.close();
```
```http
// Server response
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
data: First message
data: Second message
event: custom-event
data: Custom message data
```
## Best Practices
### Do's
- ✅ Use HTTPS everywhere
- ✅ Implement proper caching strategies
- ✅ Use appropriate HTTP methods
- ✅ Return meaningful status codes
- ✅ Implement rate limiting
- ✅ Use compression (gzip, brotli)
- ✅ Set proper CORS headers
- ✅ Implement proper error handling
- ✅ Use connection pooling
- ✅ Monitor network performance
### Don'ts
- ❌ Use HTTP for sensitive data
- ❌ Ignore CORS security
- ❌ Return wrong status codes (200 for errors)
- ❌ Cache sensitive data
- ❌ Send large uncompressed responses
- ❌ Skip SSL/TLS certificate validation
- ❌ Store credentials in URLs
- ❌ Expose internal server details in errors
- ❌ Use synchronous requests
## Glossary Terms
**Key Terms Covered**:
- Ajax
- ALPN
- Bandwidth
- Cacheable
- Cookie
- CORS
- CORS-safelisted request header
- CORS-safelisted response header
- Crawler
- Effective connection type
- Fetch directive
- Fetch metadata request header
- Forbidden request header
- Forbidden response header name
- FTP
- General header
- HOL blocking
- HTTP
- HTTP content
- HTTP header
- HTTP/2
- HTTP/3
- HTTPS
- HTTPS RR
- Idempotent
- IMAP
- Latency
- Packet
- POP3
- Proxy server
- QUIC
- Rate limit
- Request header
- Response header
- REST
- Round Trip Time (RTT)
- RTCP
- RTP
- Safe (HTTP Methods)
- SMTP
- TCP
- TCP handshake
- TCP slow start
- UDP
- WebSockets
## Additional Resources
- [MDN HTTP Guide](https://developer.mozilla.org/en-US/docs/Web/HTTP)
- [HTTP/2 Spec](https://http2.github.io/)
- [HTTP/3 Explained](https://http3-explained.haxx.se/)
- [REST API Tutorial](https://restfulapi.net/)

View File

@@ -0,0 +1,807 @@
# JavaScript & Programming Reference
Comprehensive reference for JavaScript, ECMAScript, programming concepts, and modern JS patterns.
## Core Concepts
### JavaScript
High-level, interpreted programming language that conforms to the ECMAScript specification. Primary language for web development alongside HTML and CSS.
**Key Characteristics**:
- Dynamically typed
- Prototype-based inheritance
- First-class functions
- Event-driven
- Asynchronous execution
### ECMAScript
The standardized specification that JavaScript implements.
**Major Versions**:
- **ES5** (2009): Strict mode, JSON support
- **ES6/ES2015**: Classes, arrow functions, promises, modules
- **ES2016+**: Async/await, optional chaining, nullish coalescing
## Data Types
### Primitive Types
```javascript
// String
let name = "John";
let greeting = 'Hello';
let template = `Hello, ${name}!`; // Template literal
// Number
let integer = 42;
let float = 3.14;
let negative = -10;
let scientific = 1e6; // 1000000
// BigInt (for very large integers)
let big = 9007199254740991n;
// Boolean
let isTrue = true;
let isFalse = false;
// Undefined (declared but not assigned)
let undefined_var;
console.log(undefined_var); // undefined
// Null (intentional absence of value)
let empty = null;
// Symbol (unique identifier)
let sym = Symbol('description');
```
### Type Checking
```javascript
typeof "hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (historical bug)
typeof Symbol(); // "symbol"
typeof {}; // "object"
typeof []; // "object"
typeof function() {}; // "function"
// Better array check
Array.isArray([]); // true
// Null check
value === null; // true if null
```
### Type Coercion and Conversion
```javascript
// Implicit coercion
"5" + 2; // "52" (string concatenation)
"5" - 2; // 3 (numeric subtraction)
"5" * "2"; // 10 (numeric multiplication)
!!"value"; // true (boolean conversion)
// Explicit conversion
String(123); // "123"
Number("123"); // 123
Number("abc"); // NaN
Boolean(0); // false
Boolean(1); // true
parseInt("123px"); // 123
parseFloat("3.14"); // 3.14
```
### Truthy and Falsy Values
**Falsy values** (evaluate to false):
- `false`
- `0`, `-0`
- `""` (empty string)
- `null`
- `undefined`
- `NaN`
**Everything else is truthy**, including:
- `"0"` (string)
- `"false"` (string)
- `[]` (empty array)
- `{}` (empty object)
- `function() {}` (empty function)
## Variables and Constants
```javascript
// var (function-scoped, hoisted - avoid in modern code)
var oldStyle = "avoid this";
// let (block-scoped, can be reassigned)
let count = 0;
count = 1; // ✓ works
// const (block-scoped, cannot be reassigned)
const MAX = 100;
MAX = 200; // ✗ TypeError
// const with objects/arrays (content can change)
const person = { name: "John" };
person.name = "Jane"; // ✓ works (mutating object)
person = {}; // ✗ TypeError (reassigning variable)
```
## Functions
### Function Declaration
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
```
### Function Expression
```javascript
const greet = function(name) {
return `Hello, ${name}!`;
};
```
### Arrow Functions
```javascript
// Basic syntax
const add = (a, b) => a + b;
// With block body
const multiply = (a, b) => {
const result = a * b;
return result;
};
// Single parameter (parentheses optional)
const square = x => x * x;
// No parameters
const getRandom = () => Math.random();
// Implicit return of object (wrap in parentheses)
const makePerson = (name, age) => ({ name, age });
```
### First-Class Functions
Functions are values that can be:
- Assigned to variables
- Passed as arguments
- Returned from other functions
```javascript
// Assign to variable
const fn = function() { return 42; };
// Pass as argument
function execute(callback) {
return callback();
}
execute(() => console.log("Hello"));
// Return from function
function createMultiplier(factor) {
return function(x) {
return x * factor;
};
}
const double = createMultiplier(2);
double(5); // 10
```
### Closures
Functions that remember their lexical scope:
```javascript
function createCounter() {
let count = 0; // Private variable
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
counter.getCount(); // 1
```
### Callback Functions
Function passed as an argument to be executed later:
```javascript
// Array methods use callbacks
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num));
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((acc, num) => acc + num, 0);
```
### IIFE (Immediately Invoked Function Expression)
```javascript
(function() {
// Code here runs immediately
console.log("IIFE executed");
})();
// With parameters
(function(name) {
console.log(`Hello, ${name}`);
})("World");
// Arrow function IIFE
(() => {
console.log("Arrow IIFE");
})();
```
## Objects
### Object Creation
```javascript
// Object literal
const person = {
name: "John",
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
const john = new Person("John", 30);
// Object.create
const proto = { greet() { return "Hello"; } };
const obj = Object.create(proto);
```
### Accessing Properties
```javascript
const obj = { name: "John", age: 30 };
// Dot notation
obj.name; // "John"
// Bracket notation
obj["age"]; // 30
const key = "name";
obj[key]; // "John"
// Optional chaining (ES2020)
obj.address?.city; // undefined (no error if address doesn't exist)
obj.getName?.(); // undefined (no error if getName doesn't exist)
```
### Object Methods
```javascript
const person = { name: "John", age: 30, city: "NYC" };
// Get keys
Object.keys(person); // ["name", "age", "city"]
// Get values
Object.values(person); // ["John", 30, "NYC"]
// Get entries
Object.entries(person); // [["name", "John"], ["age", 30], ["city", "NYC"]]
// Assign (merge objects)
const extended = Object.assign({}, person, { country: "USA" });
// Spread operator (modern alternative)
const merged = { ...person, country: "USA" };
// Freeze (make immutable)
Object.freeze(person);
person.age = 31; // Silently fails (throws in strict mode)
// Seal (prevent adding/removing properties)
Object.seal(person);
```
### Destructuring
```javascript
// Object destructuring
const person = { name: "John", age: 30, city: "NYC" };
const { name, age } = person;
// With different variable names
const { name: personName, age: personAge } = person;
// With defaults
const { name, country = "USA" } = person;
// Nested destructuring
const user = { profile: { email: "john@example.com" } };
const { profile: { email } } = user;
// Array destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
// first = 1, second = 2, rest = [3, 4, 5]
// Skip elements
const [a, , c] = numbers;
// a = 1, c = 3
```
## Arrays
```javascript
// Create arrays
const arr = [1, 2, 3];
const empty = [];
const mixed = [1, "two", { three: 3 }, [4]];
// Access elements
arr[0]; // 1
arr[arr.length - 1]; // Last element
arr.at(-1); // 3 (ES2022 - negative indexing)
// Modify arrays
arr.push(4); // Add to end
arr.pop(); // Remove from end
arr.unshift(0); // Add to beginning
arr.shift(); // Remove from beginning
arr.splice(1, 2, 'a', 'b'); // Remove 2 elements at index 1, insert 'a', 'b'
// Iteration
arr.forEach(item => console.log(item));
for (let item of arr) { console.log(item); }
for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
// Transformation
const doubled = arr.map(x => x * 2);
const evens = arr.filter(x => x % 2 === 0);
const sum = arr.reduce((acc, x) => acc + x, 0);
// Search
arr.includes(2); // true
arr.indexOf(2); // Index or -1
arr.find(x => x > 2); // First matching element
arr.findIndex(x => x > 2); // Index of first match
// Test
arr.some(x => x > 5); // true if any match
arr.every(x => x > 0); // true if all match
// Sort and reverse
arr.sort((a, b) => a - b); // Ascending
arr.reverse(); // Reverse in place
// Combine
const combined = arr.concat([4, 5]);
const spread = [...arr, 4, 5];
// Slice (copy portion)
const portion = arr.slice(1, 3); // Index 1 to 3 (exclusive)
// Flat (flatten nested arrays)
[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]
```
## Control Flow
### Conditionals
```javascript
// if/else
if (condition) {
// code
} else if (otherCondition) {
// code
} else {
// code
}
// Ternary operator
const result = condition ? valueIfTrue : valueIfFalse;
// Switch statement
switch (value) {
case 1:
// code
break;
case 2:
case 3:
// code for 2 or 3
break;
default:
// default code
}
// Nullish coalescing (ES2020)
const value = null ?? "default"; // "default"
const value = 0 ?? "default"; // 0 (0 is not nullish)
// Logical OR for defaults (pre-ES2020)
const value = falsy || "default";
// Optional chaining
const city = user?.address?.city;
```
### Loops
```javascript
// for loop
for (let i = 0; i < 10; i++) {
console.log(i);
}
// while loop
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
// do-while loop
do {
console.log(i);
i++;
} while (i < 10);
// for...of (iterate values)
for (const item of array) {
console.log(item);
}
// for...in (iterate keys - avoid for arrays)
for (const key in object) {
console.log(key, object[key]);
}
// break and continue
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Exit loop
if (i === 3) continue; // Skip iteration
console.log(i);
}
```
## Asynchronous JavaScript
### Callbacks
```javascript
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData(data => console.log(data));
```
### Promises
```javascript
// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Success!");
} else {
reject("Error!");
}
}, 1000);
});
// Use promise
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
// Promise utilities
Promise.all([promise1, promise2]); // Wait for all
Promise.race([promise1, promise2]); // First to complete
Promise.allSettled([promise1, promise2]); // Wait for all (ES2020)
Promise.any([promise1, promise2]); // First to succeed (ES2021)
```
### Async/Await
```javascript
// Async function
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
// Use async function
fetchData().then(data => console.log(data));
// Top-level await (ES2022, in modules)
const data = await fetchData();
```
## Classes
```javascript
class Person {
// Constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance method
greet() {
return `Hello, I'm ${this.name}`;
}
// Getter
get info() {
return `${this.name}, ${this.age}`;
}
// Setter
set birthYear(year) {
this.age = new Date().getFullYear() - year;
}
// Static method
static species() {
return "Homo sapiens";
}
}
// Inheritance
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age); // Call parent constructor
this.jobTitle = jobTitle;
}
// Override method
greet() {
return `${super.greet()}, I'm a ${this.jobTitle}`;
}
}
// Usage
const john = new Person("John", 30);
john.greet(); // "Hello, I'm John"
Person.species(); // "Homo sapiens"
const jane = new Employee("Jane", 25, "Developer");
jane.greet(); // "Hello, I'm Jane, I'm a Developer"
```
## Modules
### ES6 Modules (ESM)
```javascript
// Export (math.js)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default class Calculator {
// ...
}
// Import
import Calculator, { PI, add } from './math.js';
import * as math from './math.js';
import { add as sum } from './math.js'; // Rename
```
### CommonJS (Node.js)
```javascript
// Export (math.js)
module.exports = {
add(a, b) {
return a + b;
}
};
// Import
const math = require('./math');
```
## Error Handling
```javascript
// Try/catch
try {
// Code that might throw
throw new Error("Something went wrong");
} catch (error) {
console.error(error.message);
} finally {
// Always runs
console.log("Cleanup");
}
// Custom errors
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid input");
```
## Best Practices
### Do's
- ✅ Use `const` by default, `let` when needed
- ✅ Use strict mode (`'use strict';`)
- ✅ Use arrow functions for callbacks
- ✅ Use template literals for string interpolation
- ✅ Use destructuring for cleaner code
- ✅ Use async/await for asynchronous code
- ✅ Handle errors properly
- ✅ Use descriptive variable names
- ✅ Keep functions small and focused
- ✅ Use modern ES6+ features
### Don'ts
- ❌ Use `var` (use `let` or `const`)
- ❌ Pollute global scope
- ❌ Use `==` (use `===` for strict equality)
- ❌ Modify function parameters
- ❌ Use `eval()` or `with()`
- ❌ Ignore errors silently
- ❌ Use synchronous code for I/O operations
- ❌ Create deeply nested callbacks (callback hell)
## Glossary Terms
**Key Terms Covered**:
- Algorithm
- Argument
- Array
- Asynchronous
- Binding
- BigInt
- Bitwise flags
- Block (scripting)
- Boolean
- Callback function
- Camel case
- Class
- Closure
- Code point
- Code unit
- Compile
- Compile time
- Conditional
- Constant
- Constructor
- Control flow
- Deep copy
- Deserialization
- ECMAScript
- Encapsulation
- Exception
- Expando
- First-class function
- Function
- Hoisting
- IIFE
- Identifier
- Immutable
- Inheritance
- Instance
- JavaScript
- JSON
- JSON type representation
- Just-In-Time Compilation (JIT)
- Kebab case
- Keyword
- Literal
- Local scope
- Local variable
- Loop
- Method
- Mixin
- Modularity
- Mutable
- Namespace
- NaN
- Native
- Null
- Nullish value
- Number
- Object
- Object reference
- OOP
- Operand
- Operator
- Parameter
- Parse
- Polymorphism
- Primitive
- Promise
- Property (JavaScript)
- Prototype
- Prototype-based programming
- Pseudocode
- Recursion
- Regular expression
- Scope
- Serialization
- Serializable object
- Shallow copy
- Signature (functions)
- Sloppy mode
- Snake case
- Static method
- Static typing
- Statement
- Strict mode
- String
- Stringifier
- Symbol
- Synchronous
- Syntax
- Syntax error
- Type
- Type coercion
- Type conversion
- Truthy
- Falsy
- Undefined
- Value
- Variable
## Additional Resources
- [MDN JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [ECMAScript Specification](https://tc39.es/ecma262/)
- [JavaScript.info](https://javascript.info/)
- [You Don't Know JS (book series)](https://github.com/getify/You-Dont-Know-JS)

View File

@@ -0,0 +1,504 @@
# Media & Graphics Reference
Multimedia content, graphics, and related technologies for the web.
## Image Formats
### JPEG/JPG
Lossy compression for photographs.
**Characteristics**:
- Good for photos
- No transparency support
- Small file size
- Quality degrades with editing
**Usage**:
```html
<img src="photo.jpg" alt="Photo">
```
### PNG
Lossless compression with transparency.
**Characteristics**:
- Supports alpha channel (transparency)
- Larger file size than JPEG
- Good for logos, graphics, screenshots
- PNG-8 (256 colors) vs PNG-24 (16M colors)
```html
<img src="logo.png" alt="Logo">
```
### WebP
Modern format with better compression.
**Characteristics**:
- Smaller than JPEG/PNG
- Supports transparency
- Supports animation
- Not supported in older browsers
```html
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Fallback">
</picture>
```
### AVIF
Next-generation image format.
**Characteristics**:
- Better compression than WebP
- Supports HDR
- Slower encoding
- Limited browser support
### GIF
Animated images (limited colors).
**Characteristics**:
- 256 colors max
- Supports animation
- Simple transparency (no alpha)
- Consider modern alternatives (video, WebP)
### SVG (Scalable Vector Graphics)
XML-based vector graphics.
**Characteristics**:
- Scalable without quality loss
- Small file size for simple graphics
- CSS/JS manipulatable
- Animation support
```html
<!-- Inline SVG -->
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
<!-- External SVG -->
<img src="icon.svg" alt="Icon">
```
**Creating SVG**:
```html
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<!-- Rectangle -->
<rect x="10" y="10" width="80" height="60" fill="red" />
<!-- Circle -->
<circle cx="150" cy="40" r="30" fill="blue" />
<!-- Path -->
<path d="M10 100 L100 100 L50 150 Z" fill="green" />
<!-- Text -->
<text x="50" y="180" font-size="20">Hello SVG</text>
</svg>
```
## Canvas API
2D raster graphics (bitmap).
### Basic Setup
```html
<canvas id="myCanvas" width="400" height="300"></canvas>
```
```javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
// Draw circle
ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
// Draw line
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.lineTo(350, 250);
ctx.strokeStyle = 'green';
ctx.lineWidth = 3;
ctx.stroke();
// Draw text
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 100);
// Draw image
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0);
};
img.src = 'image.jpg';
```
### Canvas Methods
```javascript
// Paths
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Transforms
ctx.translate(x, y);
ctx.rotate(angle);
ctx.scale(x, y);
ctx.save(); // Save state
ctx.restore(); // Restore state
// Compositing
ctx.globalAlpha = 0.5;
ctx.globalCompositeOperation = 'source-over';
// Export
const dataURL = canvas.toDataURL('image/png');
canvas.toBlob(blob => {
// Use blob
}, 'image/png');
```
## WebGL
3D graphics in the browser.
**Use Cases**:
- 3D visualizations
- Games
- Data visualization
- VR/AR
**Libraries**:
- **Three.js**: Easy 3D graphics
- **Babylon.js**: Game engine
- **PixiJS**: 2D WebGL renderer
```javascript
// Three.js example
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
// Render loop
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
```
## Video
### HTML5 Video Element
```html
<video controls width="640" height="360">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
Your browser doesn't support video.
</video>
```
**Attributes**:
- `controls`: Show playback controls
- `autoplay`: Start automatically
- `loop`: Repeat video
- `muted`: Mute audio
- `poster`: Thumbnail image
- `preload`: none/metadata/auto
### Video Formats
- **MP4 (H.264)**: Widely supported
- **WebM (VP8/VP9)**: Open format
- **Ogg (Theora)**: Open format
### JavaScript Control
```javascript
const video = document.querySelector('video');
// Playback
video.play();
video.pause();
video.currentTime = 10; // Seek to 10s
// Properties
video.duration; // Total duration
video.currentTime; // Current position
video.paused; // Is paused?
video.volume = 0.5; // 0.0 to 1.0
video.playbackRate = 1.5; // Speed
// Events
video.addEventListener('play', () => {});
video.addEventListener('pause', () => {});
video.addEventListener('ended', () => {});
video.addEventListener('timeupdate', () => {});
```
## Audio
### HTML5 Audio Element
```html
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
</audio>
```
### Audio Formats
- **MP3**: Widely supported
- **AAC**: Good quality
- **Ogg Vorbis**: Open format
- **WAV**: Uncompressed
### Web Audio API
Advanced audio processing:
```javascript
const audioContext = new AudioContext();
// Load audio
fetch('audio.mp3')
.then(response => response.arrayBuffer())
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
// Create source
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
// Create gain node (volume)
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.5;
// Connect: source -> gain -> destination
source.connect(gainNode);
gainNode.connect(audioContext.destination);
// Play
source.start();
});
```
## Responsive Images
### srcset and sizes
```html
<!-- Different resolutions -->
<img src="image-800.jpg"
srcset="image-400.jpg 400w,
image-800.jpg 800w,
image-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw,
(max-width: 900px) 50vw,
800px"
alt="Responsive image">
<!-- Pixel density -->
<img src="image.jpg"
srcset="image.jpg 1x,
image@2x.jpg 2x,
image@3x.jpg 3x"
alt="High DPI image">
```
### Picture Element
Art direction and format switching:
```html
<picture>
<!-- Different formats -->
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<!-- Different crops for mobile/desktop -->
<source media="(max-width: 600px)" srcset="image-mobile.jpg">
<source media="(min-width: 601px)" srcset="image-desktop.jpg">
<!-- Fallback -->
<img src="image.jpg" alt="Fallback">
</picture>
```
## Image Optimization
### Best Practices
1. **Choose correct format**:
- Photos: JPEG, WebP, AVIF
- Graphics/logos: PNG, SVG, WebP
- Animations: Video, WebP
2. **Compress images**:
- Use compression tools
- Balance quality vs file size
- Progressive JPEG for large images
3. **Responsive images**:
- Serve appropriate sizes
- Use srcset/picture
- Consider device pixel ratio
4. **Lazy loading**:
```html
<img src="image.jpg" loading="lazy" alt="Lazy loaded">
```
5. **Dimensions**:
```html
<img src="image.jpg" width="800" height="600" alt="With dimensions">
```
## Image Loading Techniques
### Lazy Loading
```html
<!-- Native lazy loading -->
<img src="image.jpg" loading="lazy" alt="Image">
<!-- Intersection Observer -->
<img data-src="image.jpg" class="lazy" alt="Image">
```
```javascript
const images = document.querySelectorAll('.lazy');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
images.forEach(img => observer.observe(img));
```
### Progressive Enhancement
```html
<!-- Low quality placeholder -->
<img src="image-tiny.jpg"
data-src="image-full.jpg"
class="blur"
alt="Progressive image">
```
## Favicon
Website icon:
```html
<!-- Standard -->
<link rel="icon" href="/favicon.ico" sizes="any">
<!-- Modern -->
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<!-- Multiple sizes -->
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
```
## Multimedia Best Practices
### Performance
- Optimize file sizes
- Use appropriate formats
- Implement lazy loading
- Use CDN for delivery
- Compress videos
### Accessibility
- Provide alt text for images
- Include captions/subtitles for videos
- Provide transcripts for audio
- Don't autoplay with sound
- Ensure keyboard controls
### SEO
- Descriptive filenames
- Alt text with keywords
- Structured data (schema.org)
- Image sitemaps
## Glossary Terms
**Key Terms Covered**:
- Alpha
- Baseline (image)
- Baseline (scripting)
- Canvas
- Favicon
- JPEG
- Lossless compression
- Lossy compression
- PNG
- Progressive enhancement
- Quality values
- Raster image
- Render
- Rendering engine
- SVG
- Vector images
- WebGL
- WebP
## Additional Resources
- [MDN Canvas Tutorial](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial)
- [SVG Tutorial](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial)
- [WebGL Fundamentals](https://webglfundamentals.org/)
- [Responsive Images Guide](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)
- [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)

View File

@@ -0,0 +1,546 @@
# Performance & Optimization Reference
Comprehensive reference for web performance metrics, optimization techniques, and Core Web Vitals.
## Core Web Vitals
Google's metrics for measuring user experience.
### Largest Contentful Paint (LCP)
Measures loading performance - when largest content element becomes visible.
**Target**: < 2.5 seconds
**Optimization**:
- Reduce server response time
- Optimize images
- Remove render-blocking resources
- Use CDN
- Implement lazy loading
- Preload critical resources
```html
<link rel="preload" href="hero-image.jpg" as="image">
```
### First Input Delay (FID) → Interaction to Next Paint (INP)
FID (deprecated) measured input responsiveness. INP is the new metric.
**INP Target**: < 200ms
**Optimization**:
- Minimize JavaScript execution time
- Break up long tasks
- Use web workers
- Optimize third-party scripts
- Use `requestIdleCallback`
### Cumulative Layout Shift (CLS)
Measures visual stability - unexpected layout shifts.
**Target**: < 0.1
**Optimization**:
- Specify image/video dimensions
- Avoid inserting content above existing content
- Use CSS aspect-ratio
- Reserve space for dynamic content
```html
<img src="image.jpg" width="800" height="600" alt="Photo">
<style>
.video-container {
aspect-ratio: 16 / 9;
}
</style>
```
## Other Performance Metrics
### First Contentful Paint (FCP)
Time when first content element renders.
**Target**: < 1.8s
### Time to First Byte (TTFB)
Time for browser to receive first byte of response.
**Target**: < 600ms
### Time to Interactive (TTI)
When page becomes fully interactive.
**Target**: < 3.8s
### Speed Index
How quickly content is visually displayed.
**Target**: < 3.4s
### Total Blocking Time (TBT)
Sum of blocking time for all long tasks.
**Target**: < 200ms
## Image Optimization
### Format Selection
| Format | Best For | Pros | Cons |
|--------|----------|------|------|
| JPEG | Photos | Small size, widely supported | Lossy, no transparency |
| PNG | Graphics, transparency | Lossless, transparency | Larger size |
| WebP | Modern browsers | Small size, transparency | Limited old browser support |
| AVIF | Newest format | Best compression | Limited support |
| SVG | Icons, logos | Scalable, small | Not for photos |
### Responsive Images
```html
<!-- Picture element for art direction -->
<picture>
<source media="(min-width: 1024px)" srcset="large.webp" type="image/webp">
<source media="(min-width: 768px)" srcset="medium.webp" type="image/webp">
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive image">
</picture>
<!-- Srcset for resolution switching -->
<img
src="image-800.jpg"
srcset="image-400.jpg 400w,
image-800.jpg 800w,
image-1200.jpg 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
alt="Image">
<!-- Lazy loading -->
<img src="image.jpg" loading="lazy" alt="Lazy loaded">
```
### Image Compression
- Use tools like ImageOptim, Squoosh, or Sharp
- Target 80-85% quality for JPEGs
- Use progressive JPEGs
- Strip metadata
## Code Optimization
### Minification
Remove whitespace, comments, shorten names:
```javascript
// Before
function calculateTotal(price, tax) {
const total = price + (price * tax);
return total;
}
// After minification
function t(p,x){return p+p*x}
```
**Tools**: Terser (JS), cssnano (CSS), html-minifier
### Code Splitting
Split code into smaller chunks loaded on demand:
```javascript
// Dynamic import
button.addEventListener('click', async () => {
const module = await import('./heavy-module.js');
module.run();
});
// React lazy loading
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
// Webpack code splitting
import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
// Use lodash
});
```
### Tree Shaking
Remove unused code during bundling:
```javascript
// Only imports what's used
import { debounce } from 'lodash-es';
// ESM exports enable tree shaking
export { function1, function2 };
```
### Compression
Enable gzip or brotli compression:
```nginx
# nginx config
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
# brotli (better compression)
brotli on;
brotli_types text/plain text/css application/json application/javascript;
```
## Caching Strategies
### Cache-Control Headers
```http
# Immutable assets (versioned URLs)
Cache-Control: public, max-age=31536000, immutable
# HTML (always revalidate)
Cache-Control: no-cache
# API responses (short cache)
Cache-Control: private, max-age=300
# No caching
Cache-Control: no-store
```
### Service Workers
Advanced caching control:
```javascript
// Cache-first strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
// Network-first strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(event.request);
})
);
});
// Stale-while-revalidate
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.open('dynamic').then((cache) => {
return cache.match(event.request).then((response) => {
const fetchPromise = fetch(event.request).then((networkResponse) => {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || fetchPromise;
});
})
);
});
```
## Loading Strategies
### Critical Rendering Path
1. Construct DOM from HTML
2. Construct CSSOM from CSS
3. Combine DOM + CSSOM into render tree
4. Calculate layout
5. Paint pixels
### Resource Hints
```html
<!-- DNS prefetch -->
<link rel="dns-prefetch" href="//example.com">
<!-- Preconnect (DNS + TCP + TLS) -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- Prefetch (low priority for next page) -->
<link rel="prefetch" href="next-page.js">
<!-- Preload (high priority for current page) -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<!-- Prerender (next page in background) -->
<link rel="prerender" href="next-page.html">
```
### Lazy Loading
#### Images - native lazy loading
<img src="image.jpg" loading="lazy">
```javascript
// Intersection Observer for custom lazy loading
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
```
### Critical CSS
Inline above-the-fold CSS, defer the rest:
```html
<head>
<style>
/* Critical CSS inlined */
body { margin: 0; font-family: sans-serif; }
.header { height: 60px; background: #333; }
</style>
<!-- Non-critical CSS deferred -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>
```
## JavaScript Performance
### Debouncing & Throttling
```javascript
// Debounce - execute after delay
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage
const handleSearch = debounce((query) => {
// Search logic
}, 300);
// Throttle - execute at most once per interval
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Usage
const handleScroll = throttle(() => {
// Scroll logic
}, 100);
```
### Long Tasks
Break up with `requestIdleCallback`:
```javascript
function processLargeArray(items) {
let index = 0;
function processChunk() {
const deadline = performance.now() + 50; // 50ms budget
while (index < items.length && performance.now() < deadline) {
// Process item
processItem(items[index]);
index++;
}
if (index < items.length) {
requestIdleCallback(processChunk);
}
}
requestIdleCallback(processChunk);
}
```
### Web Workers
Offload heavy computation:
```javascript
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: largeDataset });
worker.onmessage = (event) => {
console.log('Result:', event.data);
};
// worker.js
self.onmessage = (event) => {
const result = heavyComputation(event.data);
self.postMessage(result);
};
```
## Performance Monitoring
### Performance API
```javascript
// Navigation timing
const navTiming = performance.getEntriesByType('navigation')[0];
console.log('DOM loaded:', navTiming.domContentLoadedEventEnd);
console.log('Page loaded:', navTiming.loadEventEnd);
// Resource timing
const resources = performance.getEntriesByType('resource');
resources.forEach(resource => {
console.log(resource.name, resource.duration);
});
// Mark and measure custom timings
performance.mark('start-task');
// Do work
performance.mark('end-task');
performance.measure('task-duration', 'start-task', 'end-task');
const measure = performance.getEntriesByName('task-duration')[0];
console.log('Task took:', measure.duration, 'ms');
// Observer for performance entries
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('Performance entry:', entry);
}
});
observer.observe({ entryTypes: ['measure', 'mark', 'resource'] });
```
### Web Vitals Library
```javascript
import { getLCP, getFID, getCLS } from 'web-vitals';
getLCP(console.log);
getFID(console.log);
getCLS(console.log);
```
## CDN (Content Delivery Network)
Distribute content across global servers for faster delivery.
**Benefits**:
- Reduced latency
- Improved load times
- Better availability
- Reduced bandwidth costs
**Popular CDNs**:
- Cloudflare
- Amazon CloudFront
- Fastly
- Akamai
## Best Practices
### Do's
- ✅ Optimize images (format, compression, size)
- ✅ Minify and compress code
- ✅ Implement caching strategies
- ✅ Use CDN for static assets
- ✅ Lazy load non-critical resources
- ✅ Defer non-critical JavaScript
- ✅ Inline critical CSS
- ✅ Use HTTP/2 or HTTP/3
- ✅ Monitor Core Web Vitals
- ✅ Set performance budgets
### Don'ts
- ❌ Serve unoptimized images
- ❌ Block rendering with scripts
- ❌ Cause layout shifts
- ❌ Make excessive HTTP requests
- ❌ Load unused code
- ❌ Use synchronous operations on main thread
- ❌ Ignore performance metrics
- ❌ Forget mobile performance
## Glossary Terms
**Key Terms Covered**:
- bfcache
- Bandwidth
- Brotli compression
- Code splitting
- Compression Dictionary Transport
- Cumulative Layout Shift (CLS)
- Delta
- First Contentful Paint (FCP)
- First CPU idle
- First Input Delay (FID)
- First Meaningful Paint (FMP)
- First Paint (FP)
- Graceful degradation
- gzip compression
- Interaction to Next Paint (INP)
- Jank
- Jitter
- Largest Contentful Paint (LCP)
- Latency
- Lazy load
- Long task
- Lossless compression
- Lossy compression
- Minification
- Network throttling
- Page load time
- Page prediction
- Perceived performance
- Prefetch
- Prerender
- Progressive enhancement
- RAIL
- Real User Monitoring (RUM)
- Reflow
- Render-blocking
- Repaint
- Resource Timing
- Round Trip Time (RTT)
- Server Timing
- Speed index
- Speculative parsing
- Synthetic monitoring
- Time to First Byte (TTFB)
- Time to Interactive (TTI)
- Tree shaking
- Web performance
- Zstandard compression
## Additional Resources
- [Web.dev Performance](https://web.dev/performance/)
- [MDN Performance](https://developer.mozilla.org/en-US/docs/Web/Performance)
- [WebPageTest](https://www.webpagetest.org/)
- [Lighthouse](https://developers.google.com/web/tools/lighthouse)

View File

@@ -0,0 +1,603 @@
# Security & Authentication Reference
Comprehensive reference for web security, authentication, encryption, and secure coding practices.
## Web Security Fundamentals
### CIA Triad
Core principles of information security:
- **Confidentiality**: Data accessible only to authorized parties
- **Integrity**: Data remains accurate and unmodified
- **Availability**: Systems and data accessible when needed
### Security Headers
```http
# Content Security Policy
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com 'nonce-<random-base64-value>'; style-src 'self' 'nonce-<random-base64-value>'; object-src 'none'
# HTTP Strict Transport Security
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# X-Frame-Options (clickjacking protection)
X-Frame-Options: DENY
# X-Content-Type-Options (MIME sniffing)
X-Content-Type-Options: nosniff
# X-XSS-Protection (legacy, use CSP instead)
X-XSS-Protection: 1; mode=block
# Referrer-Policy
Referrer-Policy: strict-origin-when-cross-origin
# Permissions-Policy
Permissions-Policy: geolocation=(), microphone=(), camera=()
```
### CSP (Content Security Policy)
Mitigates XSS and data injection attacks.
**Directives**:
- `default-src`: Fallback for other directives
- `script-src`: JavaScript sources
- `style-src`: CSS sources
- `img-src`: Image sources
- `font-src`: Font sources
- `connect-src`: Fetch/XMLHttpRequest destinations
- `frame-src`: iframe sources
- `object-src`: Plugin sources
**Values**:
- `'self'`: Same origin
- `'none'`: Block all
- `'unsafe-inline'`: Allow inline scripts/styles (avoid)
- `'unsafe-eval'`: Allow eval() (avoid)
- `https:`: HTTPS sources only
- `https://example.com`: Specific domain
## HTTPS & TLS
### TLS (Transport Layer Security)
Encrypts data in transit between client and server.
**TLS Handshake**:
1. Client Hello (supported versions, cipher suites)
2. Server Hello (chosen version, cipher suite)
3. Server Certificate
4. Key Exchange
5. Finished (connection established)
**Versions**:
- TLS 1.0, 1.1 (deprecated)
- TLS 1.2 (current standard)
- TLS 1.3 (latest, faster)
### SSL Certificates
**Types**:
- **Domain Validated (DV)**: Basic validation
- **Organization Validated (OV)**: Business verification
- **Extended Validation (EV)**: Rigorous verification
**Certificate Authority**: Trusted entity that issues certificates
**Self-Signed**: Not trusted by browsers (dev/testing only)
### HSTS (HTTP Strict Transport Security)
Forces browsers to use HTTPS:
```http
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
```
- `max-age`: Duration in seconds
- `includeSubDomains`: Apply to all subdomains
- `preload`: Submit to browser preload list
## Authentication
### Authentication vs Authorization
- **Authentication**: Verify identity ("Who are you?")
- **Authorization**: Verify permissions ("What can you do?")
### Common Authentication Methods
#### 1. Session-Based Authentication
```javascript
// Login
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Verify credentials
if (verifyCredentials(username, password)) {
req.session.userId = user.id;
res.json({ success: true });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// Protected route
app.get('/profile', requireAuth, (req, res) => {
const user = getUserById(req.session.userId);
res.json(user);
});
// Logout
app.post('/logout', (req, res) => {
req.session.destroy();
res.json({ success: true });
});
```
**Pros**: Simple, server controls sessions
**Cons**: Stateful, scalability issues, CSRF vulnerable
#### 2. Token-Based Authentication (JWT)
```javascript
// Login
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (verifyCredentials(username, password)) {
const token = jwt.sign(
{ userId: user.id, role: user.role },
SECRET_KEY,
{ expiresIn: '1h' }
);
res.json({ token });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// Protected route
app.get('/profile', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
try {
const decoded = jwt.verify(token, SECRET_KEY);
const user = getUserById(decoded.userId);
res.json(user);
} catch (error) {
res.status(401).json({ error: 'Invalid token' });
}
});
```
**Pros**: Stateless, scalable, works across domains
**Cons**: Can't revoke before expiry, size overhead
#### 3. OAuth 2.0
Authorization framework for delegated access.
**Roles**:
- **Resource Owner**: End user
- **Client**: Application requesting access
- **Authorization Server**: Issues tokens
- **Resource Server**: Hosts protected resources
**Flow Example** (Authorization Code):
1. Client redirects to auth server
2. User authenticates and grants permission
3. Auth server redirects back with code
4. Client exchanges code for access token
5. Client uses token to access resources
#### 4. Multi-Factor Authentication (MFA)
Requires multiple verification factors:
- **Something you know**: Password
- **Something you have**: Phone, hardware token
- **Something you are**: Biometric
### Password Security
```javascript
const bcrypt = require('bcrypt');
// Hash password
async function hashPassword(password) {
const saltRounds = 10;
return await bcrypt.hash(password, saltRounds);
}
// Verify password
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
```
**Best Practices**:
- ✅ Use bcrypt, scrypt, or Argon2
- ✅ Minimum 8 characters (12+ recommended)
- ✅ Require mix of characters
- ✅ Implement rate limiting
- ✅ Use account lockout after failures
- ❌ Never store plain text passwords
- ❌ Never limit password length (within reason)
- ❌ Never email passwords
## Common Vulnerabilities
### XSS (Cross-Site Scripting)
Injecting malicious scripts into web pages.
**Types**:
1. **Stored XSS**: Malicious script stored in database
2. **Reflected XSS**: Script in URL reflected in response
3. **DOM-based XSS**: Client-side script manipulation
**Prevention**:
```javascript
// ❌ Vulnerable
element.innerHTML = userInput;
// ✅ Safe
element.textContent = userInput;
// ✅ Escape HTML
function escapeHTML(str) {
return str.replace(/[&<>"']/g, (match) => {
const map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
return map[match];
});
}
// ✅ Use DOMPurify for rich content
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
```
### CSRF (Cross-Site Request Forgery)
Tricks user into executing unwanted actions.
**Prevention**:
```javascript
// CSRF token
app.get('/form', (req, res) => {
const csrfToken = generateToken();
req.session.csrfToken = csrfToken;
res.render('form', { csrfToken });
});
app.post('/transfer', (req, res) => {
if (req.body.csrfToken !== req.session.csrfToken) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
// Process request
});
// SameSite cookie attribute
Set-Cookie: sessionId=abc; SameSite=Strict; Secure; HttpOnly
```
### SQL Injection
Injecting malicious SQL code.
**Prevention**:
```javascript
// ❌ Vulnerable
const query = `SELECT * FROM users WHERE username = '${username}'`;
// ✅ Parameterized queries
const query = 'SELECT * FROM users WHERE username = ?';
db.execute(query, [username]);
// ✅ ORM/Query builder
const user = await User.findOne({ where: { username } });
```
### CORS Misconfiguration
```javascript
// ❌ Vulnerable (allows any origin)
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
// ✅ Whitelist specific origins
const allowedOrigins = ['https://example.com'];
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
```
### Clickjacking
Tricking users into clicking hidden elements.
**Prevention**:
```http
X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
# Or with CSP
Content-Security-Policy: frame-ancestors 'none'
Content-Security-Policy: frame-ancestors 'self'
```
### File Upload Vulnerabilities
```javascript
// Validate file type
const allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(file.mimetype)) {
return res.status(400).json({ error: 'Invalid file type' });
}
// Check file size
const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
return res.status(400).json({ error: 'File too large' });
}
// Sanitize filename
const sanitizedName = file.name.replace(/[^a-z0-9.-]/gi, '_');
// Store outside web root
const uploadPath = '/secure/uploads/' + sanitizedName;
// Use random filenames
const filename = crypto.randomBytes(16).toString('hex') + path.extname(file.name);
```
## Cryptography
### Encryption vs Hashing
- **Encryption**: Reversible (decrypt with key)
- **Hashing**: One-way transformation
### Symmetric Encryption
Same key for encryption and decryption.
```javascript
const crypto = require('crypto');
function encrypt(text, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(text, key) {
const parts = text.split(':');
const iv = Buffer.from(parts[0], 'hex');
const encrypted = parts[1];
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
```
### Public-Key Cryptography
Different keys for encryption (public) and decryption (private).
**Use Cases**:
- TLS/SSL certificates
- Digital signatures
- SSH keys
### Hash Functions
```javascript
const crypto = require('crypto');
// SHA-256
const hash = crypto.createHash('sha256').update(data).digest('hex');
// HMAC (keyed hash)
const hmac = crypto.createHmac('sha256', secretKey).update(data).digest('hex');
```
### Digital Signatures
Verify authenticity and integrity.
```javascript
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048
});
// Sign
const sign = crypto.createSign('SHA256');
sign.update(data);
const signature = sign.sign(privateKey, 'hex');
// Verify
const verify = crypto.createVerify('SHA256');
verify.update(data);
const isValid = verify.verify(publicKey, signature, 'hex');
```
## Secure Coding Practices
### Input Validation
```javascript
// Validate email
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// Validate and sanitize
function sanitizeInput(input) {
// Remove dangerous characters
return input.replace(/[<>\"']/g, '');
}
// Whitelist approach
function isValidUsername(username) {
return /^[a-zA-Z0-9_]{3,20}$/.test(username);
}
```
### Output Encoding
Encode data based on context:
- **HTML context**: Escape `< > & " '`
- **JavaScript context**: Use JSON.stringify()
- **URL context**: Use encodeURIComponent()
- **CSS context**: Escape special characters
### Secure Storage
```javascript
// ❌ Don't store sensitive data in localStorage
localStorage.setItem('token', token); // XSS can access
// ✅ Use HttpOnly cookies
res.cookie('token', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 3600000
});
// ✅ For sensitive client-side data, encrypt first
const encrypted = encrypt(sensitiveData, encryptionKey);
sessionStorage.setItem('data', encrypted);
```
### Rate Limiting
```javascript
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests, please try again later'
});
app.use('/api/', limiter);
// Stricter for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
skipSuccessfulRequests: true
});
app.use('/api/login', authLimiter);
```
### Error Handling
```javascript
// ❌ Expose internal details
catch (error) {
res.status(500).json({ error: error.message });
}
// ✅ Generic error message
catch (error) {
console.error(error); // Log internally
res.status(500).json({ error: 'Internal server error' });
}
```
## Security Testing
### Tools
- **OWASP ZAP**: Security scanner
- **Burp Suite**: Web vulnerability scanner
- **nmap**: Network scanner
- **SQLMap**: SQL injection testing
- **Nikto**: Web server scanner
### Checklist
- [ ] HTTPS enforced everywhere
- [ ] Security headers configured
- [ ] Authentication implemented securely
- [ ] Authorization checked on all endpoints
- [ ] Input validation and sanitization
- [ ] Output encoding
- [ ] CSRF protection
- [ ] SQL injection prevention
- [ ] XSS prevention
- [ ] Rate limiting
- [ ] Secure session management
- [ ] Secure password storage
- [ ] File upload security
- [ ] Error handling doesn't leak info
- [ ] Dependencies up to date
- [ ] Security logging and monitoring
## Glossary Terms
**Key Terms Covered**:
- Authentication
- Authenticator
- Certificate authority
- Challenge-response authentication
- CIA
- Cipher
- Cipher suite
- Ciphertext
- Credential
- Cross-site request forgery (CSRF)
- Cross-site scripting (XSS)
- Cryptanalysis
- Cryptography
- Decryption
- Denial of Service (DoS)
- Digital certificate
- Digital signature
- Distributed Denial of Service (DDoS)
- Encryption
- Federated identity
- Fingerprinting
- Firewall
- HSTS
- Identity provider (IdP)
- MitM
- Multi-factor authentication
- Nonce
- OWASP
- Plaintext
- Principle of least privilege
- Privileged
- Public-key cryptography
- Relying party
- Replay attack
- Salt
- Secure context
- Secure Sockets Layer (SSL)
- Session hijacking
- Signature (security)
- SQL injection
- Symmetric-key cryptography
- Transport Layer Security (TLS)
## Additional Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [MDN Web Security](https://developer.mozilla.org/en-US/docs/Web/Security)
- [Security Headers](https://securityheaders.com/)
- [SSL Labs](https://www.ssllabs.com/)

View File

@@ -0,0 +1,615 @@
# Servers & Infrastructure Reference
Web servers, hosting, deployment, and infrastructure concepts.
## Web Servers
### Popular Web Servers
#### Nginx
High-performance web server and reverse proxy.
**Features**:
- Load balancing
- Reverse proxy
- Static file serving
- SSL/TLS termination
**Basic Configuration**:
```nginx
server {
listen 80;
server_name example.com;
# Serve static files
location / {
root /var/www/html;
index index.html;
}
# Proxy to backend
location /api {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# SSL configuration
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
}
```
#### Apache HTTP Server
Widely-used web server.
**Features**:
- .htaccess support
- Module system
- Virtual hosting
**Basic .htaccess**:
```apache
# Redirect to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Custom error pages
ErrorDocument 404 /404.html
# Cache control
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
```
#### Node.js Servers
**Express.js**:
```javascript
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.get('/api/users', (req, res) => {
res.json({ users: [] });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
**Built-in HTTP Server**:
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
});
server.listen(3000);
```
## Hosting Options
### Static Hosting
For static sites (HTML, CSS, JS).
**Platforms**:
- **Vercel**: Automatic deployments, serverless functions
- **Netlify**: Build automation, edge functions
- **GitHub Pages**: Free for public repos
- **Cloudflare Pages**: Fast global CDN
- **AWS S3 + CloudFront**: Scalable, requires setup
**Deployment**:
```bash
# Vercel
npx vercel
# Netlify
npx netlify deploy --prod
# GitHub Pages (via Git)
git push origin main
```
### Platform as a Service (PaaS)
Managed application hosting.
**Platforms**:
- **Heroku**: Easy deployment, add-ons
- **Railway**: Modern developer experience
- **Render**: Unified platform
- **Google App Engine**: Automatic scaling
- **Azure App Service**: Microsoft cloud
**Example (Heroku)**:
```bash
# Deploy
git push heroku main
# Scale
heroku ps:scale web=2
# View logs
heroku logs --tail
```
### Infrastructure as a Service (IaaS)
Virtual servers (more control, more setup).
**Providers**:
- **AWS EC2**: Amazon virtual servers
- **Google Compute Engine**: Google VMs
- **DigitalOcean Droplets**: Simple VPS
- **Linode**: Developer-friendly VPS
### Containerization
**Docker**:
```dockerfile
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
```
```bash
# Build image
docker build -t my-app .
# Run container
docker run -p 3000:3000 my-app
```
**Docker Compose**:
```yaml
version: '3'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgres://db:5432
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: password
```
### Kubernetes
Container orchestration platform.
**Concepts**:
- **Pods**: Smallest deployable units
- **Services**: Expose pods
- **Deployments**: Manage replicas
- **Ingress**: HTTP routing
## Content Delivery Network (CDN)
Distributed network for fast content delivery.
**Benefits**:
- Faster load times
- Reduced server load
- DDoS protection
- Geographic distribution
**Popular CDNs**:
- **Cloudflare**: Free tier, DDoS protection
- **AWS CloudFront**: Amazon CDN
- **Fastly**: Edge computing
- **Akamai**: Enterprise CDN
**CDN for Libraries**:
```html
<!-- CDN-hosted library -->
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
```
## Domain Name System (DNS)
Translates domain names to IP addresses.
### DNS Records
| Type | Purpose | Example |
|------|---------|---------|
| A | IPv4 address | `example.com → 192.0.2.1` |
| AAAA | IPv6 address | `example.com → 2001:db8::1` |
| CNAME | Alias to another domain | `www → example.com` |
| MX | Mail server | `mail.example.com` |
| TXT | Text information | SPF, DKIM records |
| NS | Nameserver | DNS delegation |
**DNS Lookup**:
```bash
# Command line
nslookup example.com
dig example.com
# JavaScript (not direct DNS, but IP lookup)
fetch('https://dns.google/resolve?name=example.com')
```
### DNS Propagation
Time for DNS changes to spread globally (typically 24-48 hours).
## SSL/TLS Certificates
Encrypt data between client and server.
### Certificate Types
- **Domain Validation (DV)**: Basic, automated
- **Organization Validation (OV)**: Verified business
- **Extended Validation (EV)**: Highest validation
### Getting Certificates
**Let's Encrypt** (Free):
```bash
# Certbot
sudo certbot --nginx -d example.com
```
**Cloudflare** (Free with Cloudflare DNS)
### HTTPS Configuration
```nginx
# Nginx HTTPS
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/fullchain.pem;
ssl_certificate_key /path/to/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
```
## Load Balancing
Distribute traffic across multiple servers.
### Load Balancing Algorithms
- **Round Robin**: Rotate through servers
- **Least Connections**: Send to server with fewest connections
- **IP Hash**: Route based on client IP
- **Weighted**: Servers have different capacities
**Nginx Load Balancer**:
```nginx
upstream backend {
server server1.example.com weight=3;
server server2.example.com;
server server3.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
```
## Reverse Proxy
Server that forwards requests to backend servers.
**Benefits**:
- Load balancing
- SSL termination
- Caching
- Security (hide backend)
**Nginx Reverse Proxy**:
```nginx
server {
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
```
## Caching Strategies
### Browser Caching
```http
Cache-Control: public, max-age=31536000, immutable
```
### Server-Side Caching
**Redis**:
```javascript
const redis = require('redis');
const client = redis.createClient();
// Cache data
await client.set('user:1', JSON.stringify(user), {
EX: 3600 // Expire after 1 hour
});
// Retrieve cached data
const cached = await client.get('user:1');
```
### CDN Caching
Static assets cached at edge locations.
## Environment Variables
Configuration without hardcoding.
```bash
# .env file
DATABASE_URL=postgresql://localhost/mydb
API_KEY=secret-key-here
NODE_ENV=production
```
```javascript
// Access in Node.js
require('dotenv').config();
const dbUrl = process.env.DATABASE_URL;
```
**Best Practices**:
- Never commit .env to Git
- Use .env.example as template
- Different values per environment
- Secure secret values
## Deployment Strategies
### Continuous Deployment (CD)
Automatically deploy when code is pushed.
**GitHub Actions**:
```yaml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm ci
- run: npm run build
- run: npm run deploy
```
### Blue-Green Deployment
Two identical environments, switch traffic.
### Canary Deployment
Gradually roll out to subset of users.
### Rolling Deployment
Update instances incrementally.
## Process Managers
Keep applications running.
### PM2
```bash
# Start application
pm2 start app.js
# Start with name
pm2 start app.js --name my-app
# Cluster mode (use all CPUs)
pm2 start app.js -i max
# Monitor
pm2 monit
# Restart
pm2 restart my-app
# Stop
pm2 stop my-app
# Logs
pm2 logs
# Startup script (restart on reboot)
pm2 startup
pm2 save
```
### systemd
Linux service manager.
```ini
# /etc/systemd/system/myapp.service
[Unit]
Description=My Node App
[Service]
ExecStart=/usr/bin/node /path/to/app.js
Restart=always
User=nobody
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
```
```bash
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
```
## Monitoring & Logging
### Application Monitoring
- **New Relic**: APM, monitoring
- **Datadog**: Infrastructure monitoring
- **Grafana**: Visualization
- **Prometheus**: Metrics collection
### Log Aggregation
- **Elasticsearch + Kibana**: Search and visualize logs
- **Splunk**: Enterprise log management
- **Papertrail**: Cloud logging
### Uptime Monitoring
- **UptimeRobot**: Free uptime checks
- **Pingdom**: Monitoring service
- **StatusCake**: Website monitoring
## Security Best Practices
### Server Hardening
- Keep software updated
- Use firewall (ufw, iptables)
- Disable root SSH login
- Use SSH keys (not passwords)
- Limit user permissions
- Regular backups
### Application Security
- Use HTTPS everywhere
- Implement rate limiting
- Validate all input
- Use security headers
- Keep dependencies updated
- Regular security audits
## Backup Strategies
### Database Backups
```bash
# PostgreSQL
pg_dump dbname > backup.sql
# MySQL
mysqldump -u user -p dbname > backup.sql
# MongoDB
mongodump --db mydb --out /backup/
```
### Automated Backups
- Daily backups
- Multiple retention periods
- Off-site storage
- Test restores regularly
## Scalability
### Vertical Scaling
Increase server resources (CPU, RAM).
**Pros**: Simple
**Cons**: Limited, expensive
### Horizontal Scaling
Add more servers.
**Pros**: Unlimited scaling
**Cons**: Complex, requires load balancer
### Database Scaling
- **Replication**: Read replicas
- **Sharding**: Split data across databases
- **Caching**: Reduce database load
## Glossary Terms
**Key Terms Covered**:
- Apache
- Bandwidth
- CDN
- Cloud computing
- CNAME
- DNS
- Domain
- Domain name
- Firewall
- Host
- Hotlink
- IP address
- ISP
- Latency
- localhost
- Nginx
- Origin
- Port
- Proxy servers
- Round Trip Time (RTT)
- Server
- Site
- TLD
- Web server
- Website
## Additional Resources
- [Nginx Documentation](https://nginx.org/en/docs/)
- [Docker Documentation](https://docs.docker.com/)
- [AWS Documentation](https://docs.aws.amazon.com/)
- [Let's Encrypt](https://letsencrypt.org/)
- [PM2 Documentation](https://pm2.keymetrics.io/docs/)

View File

@@ -0,0 +1,654 @@
# Web APIs & DOM Reference
Comprehensive reference for the Document Object Model (DOM) and Web APIs available in modern browsers.
## Document Object Model (DOM)
### What is the DOM?
The DOM is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects that can be manipulated with JavaScript.
**DOM Tree Structure**:
```
Document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── header
├── main
└── footer
```
### DOM Node Types
| Node Type | Description | Example |
|-----------|-------------|---------|
| Element | HTML element | `<div>`, `<p>` |
| Text | Text content | Text inside elements |
| Comment | HTML comment | `<!-- comment -->` |
| Document | Root document | `document` |
| DocumentFragment | Lightweight document | For batch operations |
### Selecting Elements
```javascript
// By ID
const element = document.getElementById('myId');
// By class name (returns HTMLCollection)
const elements = document.getElementsByClassName('myClass');
// By tag name (returns HTMLCollection)
const divs = document.getElementsByTagName('div');
// Query selector (first match)
const first = document.querySelector('.myClass');
const advanced = document.querySelector('div.container > p:first-child');
// Query selector all (returns NodeList)
const all = document.querySelectorAll('.myClass');
// Special selectors
document.body; // Body element
document.head; // Head element
document.documentElement; // <html> element
```
### Traversing the DOM
```javascript
const element = document.querySelector('#myElement');
// Parent
element.parentElement;
element.parentNode;
// Children
element.children; // HTMLCollection of child elements
element.childNodes; // NodeList of all child nodes
element.firstElementChild;
element.lastElementChild;
// Siblings
element.nextElementSibling;
element.previousElementSibling;
// Closest ancestor matching selector
element.closest('.container');
// Check if element contains another
parent.contains(child); // true/false
```
### Creating and Modifying Elements
```javascript
// Create element
const div = document.createElement('div');
const text = document.createTextNode('Hello');
const fragment = document.createDocumentFragment();
// Set content
div.textContent = 'Plain text'; // Safe (escaped)
div.innerHTML = '<strong>HTML</strong>'; // Can be unsafe with user input
// Set attributes
div.setAttribute('id', 'myDiv');
div.setAttribute('class', 'container');
div.id = 'myDiv'; // Direct property
div.className = 'container';
div.classList.add('active');
div.classList.remove('inactive');
div.classList.toggle('visible');
div.classList.contains('active'); // true/false
// Set styles
div.style.color = 'red';
div.style.backgroundColor = 'blue';
div.style.cssText = 'color: red; background: blue;';
// Data attributes
div.dataset.userId = '123'; // Sets data-user-id="123"
div.getAttribute('data-user-id'); // "123"
// Insert into DOM
parent.appendChild(div); // Add as last child
parent.insertBefore(div, referenceNode); // Insert before reference
parent.prepend(div); // Add as first child (modern)
parent.append(div); // Add as last child (modern)
element.after(div); // Insert after element
element.before(div); // Insert before element
element.replaceWith(newElement); // Replace element
// Remove from DOM
element.remove(); // Modern way
parent.removeChild(element); // Old way
// Clone element
const clone = element.cloneNode(true); // true = deep clone (with children)
```
### Element Properties
```javascript
// Dimensions and position
element.offsetWidth; // Width including border
element.offsetHeight; // Height including border
element.clientWidth; // Width excluding border
element.clientHeight; // Height excluding border
element.scrollWidth; // Total scrollable width
element.scrollHeight; // Total scrollable height
element.offsetTop; // Top position relative to offsetParent
element.offsetLeft; // Left position relative to offsetParent
// Bounding box
const rect = element.getBoundingClientRect();
// Returns: { x, y, width, height, top, right, bottom, left }
// Scroll position
element.scrollTop; // Vertical scroll position
element.scrollLeft; // Horizontal scroll position
element.scrollTo(0, 100); // Scroll to position
element.scrollIntoView(); // Scroll element into view
// Check visibility
element.checkVisibility(); // Modern API
```
## Event Handling
### Adding Event Listeners
```javascript
// addEventListener (modern, recommended)
element.addEventListener('click', handleClick);
element.addEventListener('click', handleClick, { once: true }); // Remove after first trigger
function handleClick(event) {
console.log('Clicked!', event);
}
// Event options
element.addEventListener('scroll', handleScroll, {
passive: true, // Won't call preventDefault()
capture: false, // Bubble phase (default)
once: true // Remove after one call
});
// Remove event listener
element.removeEventListener('click', handleClick);
```
### Common Events
| Category | Events |
|----------|--------|
| Mouse | `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`, `mouseleave`, `contextmenu` |
| Keyboard | `keydown`, `keyup`, `keypress` (deprecated) |
| Form | `submit`, `change`, `input`, `focus`, `blur`, `invalid` |
| Window | `load`, `DOMContentLoaded`, `resize`, `scroll`, `beforeunload`, `unload` |
| Touch | `touchstart`, `touchmove`, `touchend`, `touchcancel` |
| Drag | `drag`, `dragstart`, `dragend`, `dragover`, `drop` |
| Media | `play`, `pause`, `ended`, `timeupdate`, `loadeddata` |
| Animation | `animationstart`, `animationend`, `animationiteration` |
| Transition | `transitionstart`, `transitionend` |
### Event Object
```javascript
element.addEventListener('click', (event) => {
// Target elements
event.target; // Element that triggered event
event.currentTarget; // Element with listener attached
// Mouse position
event.clientX; // X relative to viewport
event.clientY; // Y relative to viewport
event.pageX; // X relative to document
event.pageY; // Y relative to document
// Keyboard
event.key; // 'a', 'Enter', 'ArrowUp'
event.code; // 'KeyA', 'Enter', 'ArrowUp'
event.ctrlKey; // true if Ctrl pressed
event.shiftKey; // true if Shift pressed
event.altKey; // true if Alt pressed
event.metaKey; // true if Meta/Cmd pressed
// Control event flow
event.preventDefault(); // Prevent default action
event.stopPropagation(); // Stop bubbling
event.stopImmediatePropagation(); // Stop other listeners
});
```
### Event Delegation
Handle events on parent instead of individual children:
```javascript
// Instead of adding listener to each button
document.querySelector('.container').addEventListener('click', (event) => {
if (event.target.matches('button')) {
console.log('Button clicked:', event.target);
}
});
```
## Web Storage APIs
### LocalStorage
Persistent storage (no expiration):
```javascript
// Set item
localStorage.setItem('key', 'value');
localStorage.setItem('user', JSON.stringify({ name: 'John' }));
// Get item
const value = localStorage.getItem('key');
const user = JSON.parse(localStorage.getItem('user'));
// Remove item
localStorage.removeItem('key');
// Clear all
localStorage.clear();
// Get key by index
localStorage.key(0);
// Number of items
localStorage.length;
// Iterate all items
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(key, value);
}
```
### SessionStorage
Storage cleared when tab closes:
```javascript
// Same API as localStorage
sessionStorage.setItem('key', 'value');
sessionStorage.getItem('key');
sessionStorage.removeItem('key');
sessionStorage.clear();
```
**Storage Limits**: ~5-10MB per origin
## Fetch API
Modern API for HTTP requests:
```javascript
// Basic GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
// Check if successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
}
}
// POST request with JSON
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => console.log(data));
// With various options
fetch(url, {
method: 'GET', // GET, POST, PUT, DELETE, etc.
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
},
body: JSON.stringify(data), // For POST/PUT
mode: 'cors', // cors, no-cors, same-origin
credentials: 'include', // include, same-origin, omit
cache: 'no-cache', // default, no-cache, reload, force-cache
redirect: 'follow', // follow, error, manual
referrerPolicy: 'no-referrer' // no-referrer, origin, etc.
});
// Response methods
const text = await response.text(); // Plain text
const json = await response.json(); // JSON
const blob = await response.blob(); // Binary data
const arrayBuffer = await response.arrayBuffer(); // ArrayBuffer
const formData = await response.formData(); // FormData
```
## Other Important Web APIs
### Console API
```javascript
console.log('Message'); // Log message
console.error('Error'); // Error message (red)
console.warn('Warning'); // Warning message (yellow)
console.info('Info'); // Info message
console.table([{ a: 1 }, { a: 2 }]); // Table format
console.group('Group'); // Start group
console.groupEnd(); // End group
console.time('timer'); // Start timer
console.timeEnd('timer'); // End timer and log duration
console.clear(); // Clear console
console.assert(condition, 'Error message'); // Assert condition
```
### Timers
```javascript
// Execute once after delay
const timeoutId = setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);
// Cancel timeout
clearTimeout(timeoutId);
// Execute repeatedly
const intervalId = setInterval(() => {
console.log('Executed every second');
}, 1000);
// Cancel interval
clearInterval(intervalId);
// RequestAnimationFrame (for animations)
function animate() {
// Animation code
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
```
### URL API
```javascript
const url = new URL('https://example.com:8080/path?query=value#hash');
url.protocol; // 'https:'
url.hostname; // 'example.com'
url.port; // '8080'
url.pathname; // '/path'
url.search; // '?query=value'
url.hash; // '#hash'
url.href; // Full URL
// URL parameters
url.searchParams.get('query'); // 'value'
url.searchParams.set('newParam', 'newValue');
url.searchParams.append('query', 'another');
url.searchParams.delete('query');
url.searchParams.has('query'); // true/false
// Convert to string
url.toString(); // Full URL
```
### FormData API
```javascript
// Create FormData from form
const form = document.querySelector('form');
const formData = new FormData(form);
// Create FormData manually
const data = new FormData();
data.append('username', 'john');
data.append('file', fileInput.files[0]);
// Get values
data.get('username'); // 'john'
data.getAll('files'); // Array of all 'files' values
// Iterate
for (const [key, value] of data.entries()) {
console.log(key, value);
}
// Send with fetch
fetch('/api/upload', {
method: 'POST',
body: formData // Don't set Content-Type header
});
```
### Intersection Observer API
Detect when element enters viewport:
```javascript
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is visible');
entry.target.classList.add('visible');
}
});
}, {
threshold: 0.5, // 50% visible
rootMargin: '0px'
});
observer.observe(element);
observer.unobserve(element);
observer.disconnect(); // Stop observing all
```
### Mutation Observer API
Watch for DOM changes:
```javascript
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('DOM changed:', mutation.type);
});
});
observer.observe(element, {
attributes: true, // Watch attribute changes
childList: true, // Watch child elements
subtree: true, // Watch all descendants
characterData: true // Watch text content
});
observer.disconnect(); // Stop observing
```
### Geolocation API
```javascript
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
},
(error) => {
console.error('Error getting location:', error);
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
// Watch position (continuous updates)
const watchId = navigator.geolocation.watchPosition(callback);
navigator.geolocation.clearWatch(watchId);
```
### Web Workers
Run JavaScript in background thread:
```javascript
// Main thread
const worker = new Worker('worker.js');
worker.postMessage({ data: 'Hello' });
worker.onmessage = (event) => {
console.log('From worker:', event.data);
};
worker.onerror = (error) => {
console.error('Worker error:', error);
};
worker.terminate(); // Stop worker
// worker.js
self.onmessage = (event) => {
console.log('From main:', event.data);
self.postMessage({ result: 'Done' });
};
```
### Canvas API
Draw graphics:
```javascript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 50);
// Draw circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
// Draw text
ctx.font = '20px Arial';
ctx.fillText('Hello', 10, 50);
// Draw image
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0);
};
img.src = 'image.jpg';
```
### IndexedDB
Client-side database for large amounts of structured data:
```javascript
// Open database
const request = indexedDB.open('MyDatabase', 1);
request.onerror = () => console.error('Database error');
request.onsuccess = (event) => {
const db = event.target.result;
// Use database
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('users', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
};
// Add data
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
objectStore.add({ id: 1, name: 'John' });
// Get data
const request = objectStore.get(1);
request.onsuccess = () => console.log(request.result);
```
## Best Practices
### Do's
- ✅ Use `addEventListener` over inline event handlers
- ✅ Remove event listeners when no longer needed
- ✅ Use event delegation for dynamic content
- ✅ Cache DOM queries in variables
- ✅ Use `textContent` for plain text (safer than `innerHTML`)
- ✅ Use DocumentFragment for batch DOM operations
- ✅ Debounce/throttle scroll and resize handlers
- ✅ Use `requestAnimationFrame` for animations
- ✅ Validate and sanitize user input
### Don'ts
- ❌ Use `innerHTML` with untrusted data (XSS risk)
- ❌ Query DOM repeatedly in loops
- ❌ Modify DOM in tight loops (batch operations)
- ❌ Use `document.write()` (deprecated)
- ❌ Use synchronous XMLHttpRequest
- ❌ Store sensitive data in localStorage
- ❌ Ignore error handling in async code
- ❌ Block main thread with heavy computations
## Glossary Terms
**Key Terms Covered**:
- API
- Application context
- Beacon
- Blink
- Blink element
- Browser
- Browsing context
- Buffer
- Canvas
- DOM (Document Object Model)
- Document environment
- Event
- Expando
- Global object
- Global scope
- Hoisting
- IndexedDB
- Interpolation
- Node (DOM)
- Shadow tree
- WindowProxy
- Wrapper
## Additional Resources
- [MDN DOM Reference](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model)
- [MDN Web APIs](https://developer.mozilla.org/en-US/docs/Web/API)
- [JavaScript.info DOM](https://javascript.info/document)

View File

@@ -0,0 +1,265 @@
# Web Protocols & Standards Reference
Organizations, specifications, and standards that govern the web.
## Standards Organizations
### W3C (World Wide Web Consortium)
International community developing web standards.
**Key Standards**:
- HTML
- CSS
- XML
- SVG
- WCAG (Accessibility)
- Web APIs
**Website**: https://www.w3.org/
### WHATWG (Web Hypertext Application Technology Working Group)
Community maintaining HTML and DOM Living Standards.
**Key Standards**:
- HTML Living Standard
- DOM Living Standard
- Fetch Standard
- URL Standard
**Website**: https://whatwg.org/
### IETF (Internet Engineering Task Force)
Develops internet standards.
**Key Standards**:
- HTTP
- TLS
- TCP/IP
- DNS
- WebRTC protocols
**Website**: https://www.ietf.org/
### ECMA International
Standards organization for information systems.
**Key Standards**:
- ECMAScript (JavaScript)
- JSON
**Website**: https://www.ecma-international.org/
### TC39 (Technical Committee 39)
ECMAScript standardization committee.
**Proposal Stages**:
- **Stage 0**: Strawperson
- **Stage 1**: Proposal
- **Stage 2**: Draft
- **Stage 3**: Candidate
- **Stage 4**: Finished (included in next version)
### IANA (Internet Assigned Numbers Authority)
Coordinates internet protocol resources.
**Responsibilities**:
- MIME types
- Port numbers
- Protocol parameters
- TLDs (Top-Level Domains)
### ICANN (Internet Corporation for Assigned Names and Numbers)
Coordinates DNS and IP addresses.
## Web Standards
### HTML Standards
**HTML5 Features**:
- Semantic elements (`<article>`, `<section>`, etc.)
- Audio and video elements
- Canvas and SVG
- Form enhancements
- LocalStorage and SessionStorage
- Web Workers
- Geolocation API
### CSS Specifications
**CSS Modules** (each specification is a module):
- CSS Selectors Level 4
- CSS Flexbox Level 1
- CSS Grid Level 2
- CSS Animations
- CSS Transitions
- CSS Custom Properties
### JavaScript Standards
**ECMAScript Versions**:
- **ES5** (2009): Strict mode, JSON
- **ES6/ES2015**: Classes, modules, arrow functions, promises
- **ES2016**: Array.includes(), exponentiation operator (`**`)
- **ES2017**: async/await, Object.values/entries
- **ES2018**: Rest/spread for objects, async iteration
- **ES2019**: Array.flat(), Object.fromEntries
- **ES2020**: Optional chaining, nullish coalescing, BigInt
- **ES2021**: Logical assignment, Promise.any
- **ES2022**: Top-level await, class fields
- **ES2023**: Array.findLast(), Object.groupBy
### Web API Specifications
**Common APIs**:
- DOM (Document Object Model)
- Fetch API
- Service Workers
- Web Storage
- IndexedDB
- WebRTC
- WebGL
- Web Audio API
- Payment Request API
- Web Authentication API
## Specifications
### Normative vs Non-Normative
- **Normative**: Required for compliance
- **Non-normative**: Informative only (examples, notes)
### Specification Lifecycle
1. **Editor's Draft**: Work in progress
2. **Working Draft**: Community review
3. **Candidate Recommendation**: Implementation and testing
4. **Proposed Recommendation**: Final review
5. **W3C Recommendation**: Official standard
## Browser Compatibility
### Feature Detection
```javascript
// Check feature support
if ('serviceWorker' in navigator) {
// Use service workers
}
if (window.IntersectionObserver) {
// Use Intersection Observer
}
if (CSS.supports('display', 'grid')) {
// Use CSS Grid
}
```
### Baseline Compatibility
Newly standardized features achieving widespread browser support.
**Widely Available**: Firefox, Chrome, Edge, Safari support
### Polyfills
Code providing modern functionality in older browsers:
```javascript
// Promise polyfill
if (!window.Promise) {
window.Promise = PromisePolyfill;
}
// Fetch polyfill
if (!window.fetch) {
window.fetch = fetchPolyfill;
}
```
### Progressive Enhancement
Build for basic browsers, enhance for modern ones:
```css
/* Base styles */
.container {
display: block;
}
/* Enhanced for Grid support */
@supports (display: grid) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
}
```
## IDL (Interface Definition Language)
**WebIDL**: Defines Web APIs
```webidl
interface Element : Node {
readonly attribute DOMString? tagName;
DOMString? getAttribute(DOMString qualifiedName);
undefined setAttribute(DOMString qualifiedName, DOMString value);
};
```
## Specifications to Know
- **HTML Living Standard**
- **CSS Specifications** (modular)
- **ECMAScript Language Specification**
- **HTTP/1.1 (RFC 9112)**
- **HTTP/2 (RFC 9113)**
- **HTTP/3 (RFC 9114)**
- **TLS 1.3 (RFC 8446)**
- **WebSocket Protocol (RFC 6455)**
- **CORS (Fetch Standard)**
- **Service Workers**
- **Web Authentication (WebAuthn)**
## Glossary Terms
**Key Terms Covered**:
- Baseline (compatibility)
- BCP 47 language tag
- ECMA
- ECMAScript
- HTML5
- IANA
- ICANN
- IDL
- IETF
- ISO
- ITU
- Non-normative
- Normative
- Polyfill
- Shim
- Specification
- W3C
- WAI
- WCAG
- WHATWG
- Web standards
- WebIDL
## Additional Resources
- [W3C Standards](https://www.w3.org/TR/)
- [WHATWG Living Standards](https://spec.whatwg.org/)
- [MDN Web Docs](https://developer.mozilla.org/)
- [Can I Use](https://caniuse.com/)
- [TC39 Proposals](https://github.com/tc39/proposals)