Skip to content

Docs: Snippet

ng-druid edited this page Aug 8, 2025 · 1 revision

Documentation for Angular Snippet Library


Table of Contents

  1. Introduction
  2. Installation
  3. Overview
  4. Key Concepts
    • Snippet Model
    • Token Integration
    • Dynamic Content Parsing
  5. Core Components
    • SnippetModule
    • SnippetFormComponent
  6. Key Services
    • SnippetParserService
  7. Usage
    • Managing Snippets
    • Parsing and Previewing Dynamic Content
    • Token Replacement in Templates
  8. API Reference
  9. Examples
  10. Testing

1. Introduction

The Angular Snippet Library provides tools for managing dynamic content snippets, handling templates, and integrating tokens with reactive forms. It enables applications to parse, preview, and modify snippet content dynamically using predefined models and token-based placeholders.


2. Installation

To install the Snippet Library and its dependencies, run:

npm install @rollthecloudinc/material @rollthecloudinc/utils angular-split ngx-json-viewer ngx-markdown

Add the required libraries to your Angular module configuration as necessary.


3. Overview

The library is centered around the concept of snippets, which represent dynamic content blocks that can be integrated into forms, rendered dynamically, and processed using services. It provides features such as:

  • Snippet Forms: Fully reactive form for snippet creation/editing.
  • Snippet Parsing: Helper service to parse content dynamically.
  • Token Integration: Replace tokens in snippet content with dynamic values.
  • Preview and Markdown Support: Real-time content preview with Markdown rendering.

4. Key Concepts

4.1 Snippet Model

A Snippet is the core model representing dynamic content blocks for template management. It encapsulates:

  • content: The actual text or markup in the snippet.
  • contentType: The type of content (e.g., text/html, text/markdown).
  • jsFile: Optional JavaScript file references for behavior.
  • jsScript: Inline JavaScript content associated with the snippet.

Example:

const snippet = new Snippet({
  content: '<h1>Hello, World!</h1>',
  contentType: 'text/html',
});

4.2 Token Integration

Tokens are dynamic placeholders embedded in snippet content, such as [placeholder]. Tokens can be replaced with actual values using the replaceTokens logic in the SnippetFormComponent.


4.3 Dynamic Content Parsing

Dynamic snippet content is parsed using the SnippetParserService, enabling pre-processing, type handling, and real-time updates to enhance interactivity and flexibility.


5. Core Components

SnippetModule

The SnippetModule is the primary module encapsulating snippet-related functionality. It includes:

  • SnippetFormComponent for handling snippet creation and editing.
  • Dependencies for Markdown rendering, JSON visualization, and form handling.

Example:

import { SnippetModule } from '@rollthecloudinc/snippet';

@NgModule({
  imports: [SnippetModule],
})
export class AppModule {}

SnippetFormComponent

The SnippetFormComponent is a reusable form component for creating and editing snippets using Angular's reactive forms framework. It includes dynamic token integration and real-time content preview.

Key Features:
  • Real-time snippet content preview.
  • Markdown rendering for text/markdown content types.
  • Token replacement integration (tokens input).
  • Flexible editor options (rows, cols, splitDirection inputs).
  • Reactive form with validation.

Example:

<classifieds-ui-snippet-form
  [tokens]="myTokenMap"
  splitDirection="horizontal"
  rows="30"
  cols="80"
  (submitted)="onSnippetSubmit($event)">
</classifieds-ui-snippet-form>

6. Key Services

SnippetParserService

The SnippetParserService parses the content of snippets and returns observable results. This allows content to be processed or transformed before rendering.

Method:

  • parseSnippet({ snippet }: { snippet: Snippet }): Observable<string>: Parses and returns the snippet's content.

Example:

constructor(private parserService: SnippetParserService) {}

ngOnInit() {
  const snippet = new Snippet({ content: 'My Content', contentType: 'text/html' });
  this.parserService.parseSnippet({ snippet }).subscribe(parsedContent => {
    console.log('Parsed Content:', parsedContent);
  });
}

7. Usage

7.1 Managing Snippets

To manage snippets, use the SnippetFormComponent. Pass tokens for dynamic content replacement or handle snippet submission for later processing.

Example:

<classifieds-ui-snippet-form
  [tokens]="tokenMap"
  [rows]="40"
  [cols]="100"
  (submitted)="handleSnippetSubmit($event)">
</classifieds-ui-snippet-form>

7.2 Parsing and Previewing Dynamic Content

Set up real-time content processing inside reactive snippet forms using the SnippetFormComponent:

Example:

ngOnInit() {
  myForm.get('content').valueChanges.pipe(
    debounceTime(300), 
    distinctUntilChanged()
  ).subscribe(content => {
    this.preview = content; // Enable real-time previews
  });
}

7.3 Token Replacement in Templates

Tokens can be integrated into snippet content for dynamic substitution. For example, [userName] can be replaced with the actual username value.

Example:

replaceTokens(content: string, tokens: Map<string, any>): string {
  tokens.forEach((value, key) => {
    content = content.replace(`[${key}]`, `${value}`);
  });

  return content;
}

8. API Reference

Classes

  1. Snippet

    • Represents a snippet model with content, contentType, jsFile, and jsScript.
  2. SnippetParserService

    • Parse snippet content dynamically.

Components

  1. SnippetFormComponent
    • Reactive snippet form with real-time preview, token replacement, and validation.

Inputs for SnippetFormComponent:

  • tokens: A Map of token-value pairs for dynamic replacements.
  • splitDirection: Direction of the form split, e.g., 'vertical' or 'horizontal'.
  • rows: Number of rows for text area inputs.
  • cols: Number of columns for text area inputs.
  • rootForm: Boolean indicating if the snippet form is used as a root form.

Outputs for SnippetFormComponent:

  • submitted: An event emitter triggered upon snippet submission.

9. Examples

Example 1: Dynamic Snippet Form

<classifieds-ui-snippet-form
  [tokens]="tokenMap"
  (submitted)="handleSnippetSubmission($event)">
</classifieds-ui-snippet-form>

Example 2: Parsing Snippets via Service

const snippet = new Snippet({ content: '<h1>Hello, World!</h1>', contentType: 'text/html' });
snippetParserService.parseSnippet({ snippet }).subscribe(parsedContent => {
  console.log('Parsed Content:', parsedContent);
});

10. Testing

Example: Testing SnippetFormComponent

import { SnippetFormComponent } from './snippet-form.component';

describe('SnippetFormComponent', () => {
  let component: SnippetFormComponent;

  beforeEach(() => {
    component = new SnippetFormComponent(/* dependencies */);
  });

  it('should create the form', () => {
    expect(component).toBeTruthy();
    expect(component.contentForm.valid).toBeFalse();
  });

  it('should validate a properly filled form', () => {
    component.contentForm.setValue({
      content: '<h1>Hello World</h1>',
      contentType: 'text/html',
      jsScript: '',
    });
    expect(component.contentForm.valid).toBeTrue();
  });
});

Conclusion

The Angular Snippet Library provides a robust framework for managing, parsing, and editing content snippets in a way that supports dynamic token replacement and integrates seamlessly with reactive forms. It is suitable for rich content workflows in modern Angular applications requiring dynamic rendering and flexibility.

For questions, bug reports, or contributions, feel free to reach out!

Clone this wiki locally