feat: macros for posts to extend page functionality

This commit is contained in:
2026-02-12 16:02:34 +01:00
parent 5ed0371456
commit 5c6fcb46ef
10 changed files with 1266 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
/**
* Gallery Macro
*
* Renders an image gallery from a linked media file or folder.
*
* Usage: [[gallery link="media/photos" columns="3" caption="My Photos"]]
*
* Parameters:
* - link (required): Path to media file or folder
* - columns: Number of columns (default: 3)
* - caption: Gallery caption
*/
import { registerMacro } from '../registry';
import type { MacroDefinition, MacroParams, MacroRenderContext } from '../types';
const galleryMacro: MacroDefinition = {
name: 'gallery',
description: 'Renders an image gallery from linked media',
validate(params: MacroParams): string | undefined {
if (!params.link) {
return 'Gallery macro requires a "link" parameter';
}
if (params.columns) {
const cols = parseInt(params.columns, 10);
if (isNaN(cols) || cols < 1 || cols > 6) {
return 'Gallery columns must be a number between 1 and 6';
}
}
return undefined;
},
editorPreview(params: MacroParams): string {
const link = params.link || '?';
return `📷 Gallery: ${link}`;
},
render(params: MacroParams, context: MacroRenderContext): string {
const { link, columns = '3', caption } = params;
const colCount = parseInt(columns, 10) || 3;
// Build the gallery HTML
const classes = ['macro-gallery', `gallery-cols-${colCount}`];
if (context.isPreview) {
classes.push('gallery-preview');
}
let html = `<div class="${classes.join(' ')}" data-link="${link}">`;
// In preview mode, show a placeholder
// In production, this would load actual images
if (context.isPreview) {
html += `<div class="gallery-placeholder">`;
html += `<span class="gallery-icon">🖼️</span>`;
html += `<span class="gallery-info">Gallery: ${link}</span>`;
if (caption) {
html += `<span class="gallery-caption">${caption}</span>`;
}
html += `</div>`;
} else {
// Production render would load images here
// For now, create a placeholder that frontend JS can hydrate
html += `<div class="gallery-container" data-columns="${colCount}">`;
html += `<!-- Gallery images loaded dynamically from: ${link} -->`;
html += `</div>`;
if (caption) {
html += `<figcaption class="gallery-caption">${caption}</figcaption>`;
}
}
html += `</div>`;
return html;
},
};
// Self-register
registerMacro(galleryMacro);
export default galleryMacro;

View File

@@ -0,0 +1,17 @@
/**
* Macro Definitions Index
*
* This file imports all macro definitions so they self-register.
* To add a new macro:
* 1. Create a new file in this folder (e.g., myMacro.ts)
* 2. Implement MacroDefinition interface
* 3. Call registerMacro() at the end
* 4. Import it here
*/
// Import all macro definitions - they self-register on import
import './gallery';
import './youtube';
// Add new macro imports here:
// import './myNewMacro';

View File

@@ -0,0 +1,89 @@
/**
* YouTube Macro
*
* Embeds a YouTube video player.
*
* Usage: [[youtube id="dQw4w9WgXcQ" title="Video Title"]]
*
* Parameters:
* - id (required): YouTube video ID
* - title: Accessible title for the iframe
* - start: Start time in seconds
* - autoplay: Whether to autoplay (default: false)
*/
import { registerMacro } from '../registry';
import type { MacroDefinition, MacroParams, MacroRenderContext } from '../types';
const youtubeMacro: MacroDefinition = {
name: 'youtube',
description: 'Embeds a YouTube video player',
validate(params: MacroParams): string | undefined {
if (!params.id) {
return 'YouTube macro requires an "id" parameter (the video ID)';
}
// Basic validation of YouTube ID format
if (!/^[\w-]{11}$/.test(params.id)) {
return 'Invalid YouTube video ID format';
}
return undefined;
},
editorPreview(params: MacroParams): string {
const id = params.id || '?';
const title = params.title;
return title ? `▶ YouTube: ${title}` : `▶ YouTube: ${id}`;
},
render(params: MacroParams, context: MacroRenderContext): string {
const { id, title = 'YouTube video', start, autoplay } = params;
// Build embed URL with parameters
const embedParams = new URLSearchParams();
if (start) {
embedParams.set('start', start);
}
if (autoplay === 'true') {
embedParams.set('autoplay', '1');
}
embedParams.set('rel', '0'); // Don't show related videos
const queryString = embedParams.toString();
const embedUrl = `https://www.youtube.com/embed/${id}${queryString ? '?' + queryString : ''}`;
if (context.isPreview) {
// In preview, show thumbnail with play button overlay
return `
<div class="macro-youtube youtube-preview">
<div class="youtube-thumbnail" style="background-image: url('https://img.youtube.com/vi/${id}/maxresdefault.jpg')">
<div class="youtube-play-overlay">
<span class="youtube-play-button">▶</span>
</div>
<span class="youtube-title">${title}</span>
</div>
</div>
`;
}
// Production render - full iframe embed
return `
<div class="macro-youtube">
<div class="youtube-container">
<iframe
src="${embedUrl}"
title="${title}"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
</div>
`;
},
};
// Self-register
registerMacro(youtubeMacro);
export default youtubeMacro;

View File

@@ -0,0 +1,42 @@
/**
* Macros Module
*
* Provides a simple extension system for rendering custom content blocks
* in markdown using [[macro param="value"]] syntax.
*
* Usage:
* 1. Import this module to register all macros
* 2. Use the registry functions to render macros
*
* Adding new macros:
* 1. Create a file in ./definitions/ (e.g., myMacro.ts)
* 2. Implement MacroDefinition interface
* 3. Call registerMacro() to self-register
* 4. Import the file in ./definitions/index.ts
*/
// Import all macro definitions so they register
import './definitions';
// Re-export types
export type {
MacroDefinition,
MacroParams,
MacroRenderContext,
ParsedMacro,
} from './types';
// Re-export registry functions
export {
registerMacro,
getMacro,
hasMacro,
getMacroNames,
getAllMacros,
clearMacros,
parseParams,
parseMacros,
renderMacro,
renderAllMacros,
getEditorPreview,
} from './registry';

View File

@@ -0,0 +1,207 @@
/**
* Macro Registry
*
* Central registry for all macro definitions.
* Macros self-register using registerMacro() function.
*/
import type { MacroDefinition, MacroParams, MacroRenderContext, ParsedMacro } from './types';
// Internal registry storage
const macroRegistry = new Map<string, MacroDefinition>();
/**
* Register a macro definition.
* Call this from each macro definition file.
*
* @param macro - The macro definition to register
* @throws Error if a macro with the same name is already registered
*/
export function registerMacro(macro: MacroDefinition): void {
const name = macro.name.toLowerCase();
if (macroRegistry.has(name)) {
console.warn(`Macro "${name}" is already registered. Overwriting.`);
}
macroRegistry.set(name, macro);
}
/**
* Get a macro definition by name.
*
* @param name - The macro name (case-insensitive)
* @returns The macro definition or undefined if not found
*/
export function getMacro(name: string): MacroDefinition | undefined {
return macroRegistry.get(name.toLowerCase());
}
/**
* Check if a macro is registered.
*
* @param name - The macro name (case-insensitive)
*/
export function hasMacro(name: string): boolean {
return macroRegistry.has(name.toLowerCase());
}
/**
* Get all registered macro names.
*/
export function getMacroNames(): string[] {
return Array.from(macroRegistry.keys());
}
/**
* Get all registered macro definitions.
*/
export function getAllMacros(): MacroDefinition[] {
return Array.from(macroRegistry.values());
}
/**
* Clear all registered macros (useful for testing).
*/
export function clearMacros(): void {
macroRegistry.clear();
}
// Regex to match [[macroName param1="value1" param2='value2']]
// Supports both single and double quotes for values
const MACRO_REGEX = /\[\[(\w+)(?:\s+([^\]]+))?\]\]/g;
// Regex to extract individual parameters
const PARAM_REGEX = /(\w+)=["']([^"']*?)["']/g;
/**
* Parse parameters from a macro parameter string.
*
* @param paramString - The parameter string (e.g., 'link="file.jpg" caption="Hello"')
* @returns Parsed key-value pairs
*/
export function parseParams(paramString: string | undefined): MacroParams {
if (!paramString) return {};
const params: MacroParams = {};
let match;
while ((match = PARAM_REGEX.exec(paramString)) !== null) {
params[match[1]] = match[2];
}
// Reset regex lastIndex for next use
PARAM_REGEX.lastIndex = 0;
return params;
}
/**
* Parse all macros from a markdown string.
*
* @param markdown - The markdown content to parse
* @returns Array of parsed macros with their positions
*/
export function parseMacros(markdown: string): ParsedMacro[] {
const macros: ParsedMacro[] = [];
let match;
while ((match = MACRO_REGEX.exec(markdown)) !== null) {
macros.push({
name: match[1].toLowerCase(),
params: parseParams(match[2]),
rawText: match[0],
start: match.index,
end: match.index + match[0].length,
});
}
// Reset regex lastIndex for next use
MACRO_REGEX.lastIndex = 0;
return macros;
}
/**
* Render a single macro to HTML.
*
* @param macro - The parsed macro
* @param context - Render context
* @returns The rendered HTML or an error placeholder
*/
export async function renderMacro(
macro: ParsedMacro,
context: MacroRenderContext
): Promise<string> {
const definition = getMacro(macro.name);
if (!definition) {
return `<span class="macro-error" title="Unknown macro: ${macro.name}">${macro.rawText}</span>`;
}
// Validate if validator exists
if (definition.validate) {
const error = definition.validate(macro.params);
if (error) {
return `<span class="macro-error" title="${error}">${macro.rawText}</span>`;
}
}
try {
const result = definition.render(macro.params, context);
return result instanceof Promise ? await result : result;
} catch (error) {
const message = error instanceof Error ? error.message : 'Render error';
return `<span class="macro-error" title="${message}">${macro.rawText}</span>`;
}
}
/**
* Render all macros in a markdown string to HTML.
* Returns the markdown with macros replaced by their rendered HTML.
*
* @param markdown - The markdown content
* @param context - Render context
* @returns Markdown with macros replaced by rendered HTML
*/
export async function renderAllMacros(
markdown: string,
context: MacroRenderContext
): Promise<string> {
const macros = parseMacros(markdown);
if (macros.length === 0) return markdown;
// Render all macros in parallel
const rendered = await Promise.all(
macros.map(macro => renderMacro(macro, context))
);
// Replace macros from end to start to preserve positions
let result = markdown;
for (let i = macros.length - 1; i >= 0; i--) {
const macro = macros[i];
result = result.slice(0, macro.start) + rendered[i] + result.slice(macro.end);
}
return result;
}
/**
* Get the editor preview text for a macro.
*
* @param name - The macro name
* @param params - The macro parameters
* @returns Preview text for the editor
*/
export function getEditorPreview(name: string, params: MacroParams): string {
const definition = getMacro(name);
if (!definition) {
return `${name}`;
}
if (definition.editorPreview) {
return definition.editorPreview(params);
}
return `${definition.name}`;
}

View File

@@ -0,0 +1,77 @@
/**
* Interface for macro definitions.
*
* Macros are custom content blocks that can be inserted into markdown
* using the syntax: [[macroName param1="value1" param2="value2"]]
*
* They are rendered in the editor with a shaded background showing the raw syntax,
* and can be transformed to custom HTML during preview/export.
*/
export interface MacroParams {
[key: string]: string;
}
export interface MacroRenderContext {
/** The post ID if available */
postId?: string;
/** Base path for resolving relative URLs */
basePath?: string;
/** Whether rendering for preview (true) or final export (false) */
isPreview: boolean;
}
export interface MacroDefinition {
/**
* Unique name for the macro (lowercase, no spaces).
* Used in the syntax: [[name ...]]
*/
name: string;
/**
* Human-readable description of what this macro does.
*/
description: string;
/**
* Render the macro to HTML for preview/export.
*
* @param params - Key-value pairs from the macro syntax
* @param context - Additional context for rendering
* @returns HTML string to replace the macro with
*/
render(params: MacroParams, context: MacroRenderContext): string | Promise<string>;
/**
* Optional: Short preview text shown in the editor.
* If not provided, shows the macro name.
*
* @param params - Key-value pairs from the macro syntax
* @returns Preview text (not HTML, just plain text)
*/
editorPreview?(params: MacroParams): string;
/**
* Optional: Validate macro parameters.
*
* @param params - Key-value pairs to validate
* @returns Error message if invalid, undefined if valid
*/
validate?(params: MacroParams): string | undefined;
}
/**
* Parsed macro from markdown content
*/
export interface ParsedMacro {
/** The macro name */
name: string;
/** Parsed parameters */
params: MacroParams;
/** Original raw text including [[ and ]] */
rawText: string;
/** Start position in the source text */
start: number;
/** End position in the source text */
end: number;
}