From d1625bfe872b8f689706a709c25d5e2ba2adbb85 Mon Sep 17 00:00:00 2001 From: Urata Daiki <7nohe@users.noreply.github.com> Date: Wed, 17 Dec 2025 14:24:11 +0900 Subject: [PATCH] feat: unify background config with auto-detection and Figma component backgrounds --- CLAUDE.md | 23 +- examples/backgrounds.md | 105 ++-- packages/cli/src/config.test.ts | 310 ++++++++++-- packages/cli/src/config.ts | 308 ++++++++++-- packages/cli/templates/ai-rules-body.md | 5 +- packages/cli/templates/init.md | 6 +- .../docs/src/content/docs/en/api-reference.md | 5 +- .../docs/src/content/docs/en/markdown-spec.md | 90 +++- .../docs/src/content/docs/ja/api-reference.md | 5 +- .../docs/src/content/docs/ja/markdown-spec.md | 90 +++- packages/plugin/src/node-cache.ts | 15 + packages/plugin/src/slide-utils.ts | 258 ++++++++-- packages/shared/src/types.ts | 38 ++ packages/vscode/README.md | 162 ++++++- packages/vscode/snippets/figdeck.json | 37 +- .../vscode/src/diagnostics/analyzer.test.ts | 450 ++++++++++++++++++ packages/vscode/src/diagnostics/analyzer.ts | 44 +- packages/vscode/src/frontmatter-spec.ts | 100 +++- 18 files changed, 1850 insertions(+), 201 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b5b8f03..f4fe61b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -240,11 +240,20 @@ Global settings at file start, or per-slide after `---`: ```yaml --- figdeck: true # Required for VSCode extension to recognize file -background: "#1a1a2e" # Solid color -gradient: "#0d1117:0%,#1f2937:50%,#58a6ff:100%@45" # Gradient with angle -template: "Style Name" # Figma paint style name -backgroundImage: "./bg.png" # Local image (PNG, JPEG, GIF) -backgroundImage: "https://..." # Remote image URL +background: "#1a1a2e" # Solid color (auto-detect) +background: "#0d1117:0%,#58a6ff:100%@45" # Gradient (auto-detect) +background: "./bg.png" # Local image (auto-detect) +background: "https://figma.com/...?node-id=123-456" # Figma component (auto-detect) +background: # Object format (explicit) + color: "#1a1a2e" # Solid color + gradient: "#0d1117:0%,#58a6ff:100%@45" # Gradient with angle + template: "Style Name" # Figma paint style name + image: "./bg.png" # Local image (PNG, JPEG, GIF) or URL + component: # Figma Component/Frame as background + link: "https://www.figma.com/design/xxx?node-id=123-456" + fit: "cover" # cover | contain | stretch + align: "center" # center | top-left | top-right | bottom-left | bottom-right + opacity: 0.8 # 0-1 color: "#ffffff" # Base text color for all elements headings: h1: { size: 72, color: "#fff" } @@ -294,7 +303,7 @@ transition: # Full configuration --- ``` -**Background Priority:** templateStyle > gradient > solid > image +**Background Priority (object format):** template > gradient > color > image **Transition Styles:** `none`, `dissolve`, `smart-animate`, `slide-from-*`, `push-from-*`, `move-from-*`, `slide-out-to-*`, `move-out-to-*` (where * = left, right, top, bottom) @@ -338,7 +347,7 @@ Supported text override formatting: **bold**, *italic*, ~~strikethrough~~, [link - `fonts.md` - Custom font family configuration - `slide-numbers.md` - Slide number configuration - `figma-links.md` - Figma node embedding - - `backgrounds.md` - Background styles + - `backgrounds.md` - All background types (color, gradient, image, template, Figma component) - `rich-formatting.md` - Inline formatting - `transitions.md` - Slide transition animations - `images.md` - Image size and position specifications (Marp-style) diff --git a/examples/backgrounds.md b/examples/backgrounds.md index fb8dcdf..0039e7b 100644 --- a/examples/backgrounds.md +++ b/examples/backgrounds.md @@ -4,9 +4,9 @@ background: "#1a1a2e" color: "#ffffff" --- -# Background & Text Color Examples +# Background Examples -This presentation demonstrates background and text color options. +This presentation demonstrates all background options. All slides use dark background with white text by default. @@ -19,31 +19,21 @@ This slide uses the global settings from YAML frontmatter. No per-slide frontmatter needed! --- - +background: "#16213e" --- -## background: "#16213e" - ## Override with Different Color - This slide overrides the default with its own frontmatter - Per-slide settings take priority over global defaults --- - +background: "#0d1117:0%,#1f2937:50%,#3b82f6:100%@45" --- -## gradient: "#0d1117:0%,#1f2937:50%,#3b82f6:100%@45" +# Gradient Background -# Gradient Override - -Gradients also override the default background. - ---- - -## Back to Default - -This slide has no frontmatter, so it uses the global default again. +Gradients are auto-detected from the string format. --- background: "#f0f4f8" @@ -55,7 +45,7 @@ color: "#020202" This slide uses light background with dark text. --- -backgroundImage: "https://images.unsplash.com/photo-1557683316-973673baf926?w=1920&h=1080&fit=crop" +background: "https://images.unsplash.com/photo-1557683316-973673baf926?w=1920&h=1080&fit=crop" color: "#ffffff" --- @@ -63,12 +53,10 @@ color: "#ffffff" This slide uses a remote image URL as background. -The image is fetched by the Figma plugin. +URLs are auto-detected as images. --- - ---- -backgroundImage: "./local-bg.png" +background: "./local-bg.png" color: "#ffffff" --- @@ -79,21 +67,80 @@ This slide uses a local image file. The CLI reads and embeds the image as base64. --- +background: + template: "Inter" +--- -## Summary +## Template Style + +Use a Figma paint style by name. + +--- +background: "https://figma.com/...?node-id=123-456" +--- + +## Figma Component (URL Shorthand) -YAML frontmatter format: +Copy a Figma link with node-id from your Component or Frame. + +The component will be scaled to cover the slide by default. + +--- +background: + component: + link: "https://figma.com/...?node-id=123-456" + fit: "contain" + align: "center" +--- + +## Figma Component Options + +- `fit`: cover (default), contain, stretch +- `align`: center (default), top-left, top-right, bottom-left, bottom-right +- `opacity`: 0-1 + +--- +background: + color: "#1a1a2e" + component: + link: "https://figma.com/...?node-id=123-456" + fit: "cover" + opacity: 0.8 +--- + +## Combined Background + +Component can be combined with color/gradient/image. + +The component renders as a layer on top of the base fill. + +--- + +## Summary ```yaml --- +# String format (auto-detect) background: "#1a1a2e" # Solid color -gradient: "#0d1117:0%,#58a6ff:100%@45" # Gradient -backgroundImage: "./bg.png" # Local image -backgroundImage: "https://..." # Remote image URL -color: "#ffffff" # Text color +background: "#000:0%,#fff:100%" # Gradient +background: "./bg.png" # Local image +background: "https://..." # Remote image +background: "https://figma.com/...?node-id=123-456" # Figma component + +# Object format (explicit) +background: + color: "#1a1a2e" + gradient: "#000:0%,#fff:100%@45" + template: "Style Name" + image: "./bg.png" + component: + link: "https://figma.com/...?node-id=123-456" + fit: "cover" # cover | contain | stretch + align: "center" # center | top-left | ... + opacity: 0.8 # 0-1 --- ``` -Global (file start) sets defaults, per-slide overrides. +Priority: template > gradient > color > image -Priority: template > gradient > solid > image +Component works with same-file nodes only (MVP limitation). diff --git a/packages/cli/src/config.test.ts b/packages/cli/src/config.test.ts index 5727e7d..d8fddb6 100644 --- a/packages/cli/src/config.test.ts +++ b/packages/cli/src/config.test.ts @@ -39,69 +39,285 @@ describe("parseFontSize", () => { }); describe("parseSlideConfig", () => { - describe("background parsing", () => { - it("should parse solid background", () => { - const result = parseSlideConfig({ background: "#1a1a2e" }); - expect(result.background).toEqual({ solid: "#1a1a2e" }); - }); + describe("unified background parsing", () => { + describe("string format (auto-detect)", () => { + it("should parse solid color from hex string", () => { + const result = parseSlideConfig({ background: "#1a1a2e" }); + expect(result.background).toEqual({ solid: "#1a1a2e" }); + }); - it("should parse gradient background", () => { - const result = parseSlideConfig({ - gradient: "#000:0%,#fff:100%@45", + it("should parse solid color from short hex", () => { + const result = parseSlideConfig({ background: "#fff" }); + expect(result.background).toEqual({ solid: "#ffffff" }); }); - expect(result.background?.gradient?.stops).toHaveLength(2); - expect(result.background?.gradient?.angle).toBe(45); - }); - it("should parse template style", () => { - const result = parseSlideConfig({ template: "Dark Mode" }); - expect(result.background).toEqual({ templateStyle: "Dark Mode" }); - }); + it("should parse gradient from string", () => { + const result = parseSlideConfig({ + background: "#000:0%,#fff:100%@45", + }); + expect(result.background?.gradient?.stops).toHaveLength(2); + expect(result.background?.gradient?.angle).toBe(45); + }); - it("should prioritize template over gradient over solid", () => { - const result = parseSlideConfig({ - background: "#fff", - gradient: "#000:0%,#fff:100%", - template: "Custom", + it("should parse Figma component URL", () => { + const result = parseSlideConfig({ + background: "https://www.figma.com/design/abc123?node-id=456-789", + }); + expect(result.background?.component).toEqual({ + link: "https://www.figma.com/design/abc123?node-id=456-789", + nodeId: "456:789", + fileKey: "abc123", + }); }); - expect(result.background).toEqual({ templateStyle: "Custom" }); - }); - it("should parse remote background image URL", () => { - const result = parseSlideConfig({ - backgroundImage: "https://example.com/bg.png", + it("should treat Figma URL without node-id as image", () => { + const result = parseSlideConfig({ + background: "https://www.figma.com/design/abc123", + }); + // Without node-id, Figma URL is treated as a regular image URL + expect(result.background?.image?.url).toBe( + "https://www.figma.com/design/abc123", + ); }); - expect(result.background).toEqual({ - image: { - url: "https://example.com/bg.png", - source: "remote", - }, + + it("should parse remote image URL", () => { + const result = parseSlideConfig({ + background: "https://example.com/bg.png", + }); + expect(result.background).toEqual({ + image: { + url: "https://example.com/bg.png", + source: "remote", + }, + }); }); - }); - it("should prioritize solid over image", () => { - const result = parseSlideConfig({ - background: "#fff", - backgroundImage: "https://example.com/bg.png", + it("should parse local image path", () => { + const result = parseSlideConfig({ + background: "./bg.png", + }); + // Without basePath, local image should return null + expect(result.background).toBeNull(); }); - expect(result.background).toEqual({ solid: "#ffffff" }); }); - it("should prioritize gradient over image", () => { - const result = parseSlideConfig({ - gradient: "#000:0%,#fff:100%", - backgroundImage: "https://example.com/bg.png", + describe("object format (explicit)", () => { + it("should parse explicit color property", () => { + const result = parseSlideConfig({ + background: { color: "#1a1a2e" }, + }); + expect(result.background).toEqual({ solid: "#1a1a2e" }); + }); + + it("should parse explicit gradient property", () => { + const result = parseSlideConfig({ + background: { gradient: "#000:0%,#fff:100%@45" }, + }); + expect(result.background?.gradient?.stops).toHaveLength(2); + expect(result.background?.gradient?.angle).toBe(45); + }); + + it("should parse explicit template property", () => { + const result = parseSlideConfig({ + background: { template: "Dark Mode" }, + }); + expect(result.background).toEqual({ templateStyle: "Dark Mode" }); + }); + + it("should parse explicit image property", () => { + const result = parseSlideConfig({ + background: { image: "https://example.com/bg.png" }, + }); + expect(result.background).toEqual({ + image: { + url: "https://example.com/bg.png", + source: "remote", + }, + }); + }); + + it("should parse explicit component property (URL string)", () => { + const result = parseSlideConfig({ + background: { + component: "https://www.figma.com/design/abc?node-id=123-456", + }, + }); + expect(result.background?.component).toEqual({ + link: "https://www.figma.com/design/abc?node-id=123-456", + nodeId: "123:456", + fileKey: "abc", + }); + }); + + it("should parse explicit component property (object)", () => { + const result = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/xyz?node-id=111-222", + fit: "cover", + align: "center", + opacity: 0.8, + }, + }, + }); + expect(result.background?.component).toEqual({ + link: "https://www.figma.com/design/xyz?node-id=111-222", + nodeId: "111:222", + fileKey: "xyz", + fit: "cover", + align: "center", + opacity: 0.8, + }); + }); + + it("should prioritize template > gradient > color > image", () => { + const result = parseSlideConfig({ + background: { + color: "#fff", + gradient: "#000:0%,#fff:100%", + template: "Custom", + image: "https://example.com/bg.png", + }, + }); + expect(result.background).toEqual({ templateStyle: "Custom" }); + }); + + it("should combine component with color background", () => { + const result = parseSlideConfig({ + background: { + color: "#1a1a2e", + component: "https://www.figma.com/design/abc?node-id=123-456", + }, + }); + expect(result.background?.solid).toBe("#1a1a2e"); + expect(result.background?.component?.nodeId).toBe("123:456"); + }); + + it("should combine component with gradient background", () => { + const result = parseSlideConfig({ + background: { + gradient: "#000:0%,#fff:100%@45", + component: "https://www.figma.com/design/abc?node-id=123-456", + }, + }); + expect(result.background?.gradient).toBeDefined(); + expect(result.background?.component?.nodeId).toBe("123:456"); }); - expect(result.background?.gradient).toBeDefined(); - expect(result.background?.image).toBeUndefined(); }); - it("should return null for unsupported local image format without basePath", () => { - const result = parseSlideConfig({ - backgroundImage: "./bg.svg", + describe("component options validation", () => { + it("should validate fit option values", () => { + const validFits = ["cover", "contain", "stretch"] as const; + for (const fit of validFits) { + const result = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/abc?node-id=111-222", + fit, + }, + }, + }); + expect(result.background?.component?.fit).toBe(fit); + } + + // Invalid fit should be ignored + const invalidResult = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/abc?node-id=111-222", + fit: "invalid", + }, + }, + }); + expect(invalidResult.background?.component?.fit).toBeUndefined(); + }); + + it("should validate align option values", () => { + const validAligns = [ + "center", + "top-left", + "top-right", + "bottom-left", + "bottom-right", + ] as const; + for (const align of validAligns) { + const result = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/abc?node-id=111-222", + align, + }, + }, + }); + expect(result.background?.component?.align).toBe(align); + } + + // Invalid align should be ignored + const invalidResult = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/abc?node-id=111-222", + align: "invalid", + }, + }, + }); + expect(invalidResult.background?.component?.align).toBeUndefined(); + }); + + it("should normalize align with underscores to kebab-case", () => { + const result = parseSlideConfig({ + background: { + component: { + link: "https://www.figma.com/design/abc?node-id=111-222", + align: "top_left", + }, + }, + }); + expect(result.background?.component?.align).toBe("top-left"); + }); + + it("should validate opacity range (0-1)", () => { + const testLink = "https://www.figma.com/design/abc?node-id=111-222"; + // Valid opacity values + expect( + parseSlideConfig({ + background: { component: { link: testLink, opacity: 0 } }, + }).background?.component?.opacity, + ).toBe(0); + expect( + parseSlideConfig({ + background: { component: { link: testLink, opacity: 0.5 } }, + }).background?.component?.opacity, + ).toBe(0.5); + expect( + parseSlideConfig({ + background: { component: { link: testLink, opacity: 1 } }, + }).background?.component?.opacity, + ).toBe(1); + + // Invalid opacity values + expect( + parseSlideConfig({ + background: { component: { link: testLink, opacity: -0.1 } }, + }).background?.component?.opacity, + ).toBeUndefined(); + expect( + parseSlideConfig({ + background: { component: { link: testLink, opacity: 1.1 } }, + }).background?.component?.opacity, + ).toBeUndefined(); + }); + + it("should ignore component object without link", () => { + const result = parseSlideConfig({ + background: { + component: { + fit: "cover", + } as { link?: string; fit?: string }, + }, + }); + expect(result.background).toBeNull(); }); - // SVG is not supported, and no basePath provided - expect(result.background).toBeNull(); }); }); diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts index 5459458..c6af885 100644 --- a/packages/cli/src/config.ts +++ b/packages/cli/src/config.ts @@ -1,4 +1,7 @@ import type { + BackgroundComponent, + BackgroundComponentAlign, + BackgroundComponentFit, BackgroundImage, FontConfig, FontVariant, @@ -121,13 +124,43 @@ interface FontsYamlConfig { } /** - * Full slide configuration from YAML frontmatter + * Background component configuration from YAML + * Accepts URL string or object with link and fit/align/opacity options */ -export interface SlideConfig { - background?: string; +interface BackgroundComponentYamlConfig { + link?: string; + fit?: string; + align?: string; + opacity?: number; +} + +/** + * Unified background configuration from YAML + * Can be a string (auto-detected) or object with explicit properties + */ +interface BackgroundYamlConfig { + /** Solid color (hex or CSS color) */ + color?: string; + /** Gradient string (e.g., "#000:0%,#fff:100%@45") */ gradient?: string; + /** Figma paint style name */ template?: string; - backgroundImage?: string; + /** Image path or URL */ + image?: string; + /** Figma component/frame (URL string or config object) */ + component?: string | BackgroundComponentYamlConfig; +} + +/** + * Full slide configuration from YAML frontmatter + */ +export interface SlideConfig { + /** + * Background configuration - unified property that accepts: + * - String: auto-detected as color, gradient, image, or Figma component + * - Object: explicit configuration with color/gradient/template/image/component + */ + background?: string | BackgroundYamlConfig; color?: string; headings?: HeadingsConfig; paragraphs?: TextStyle; @@ -278,7 +311,7 @@ export interface ParseSlideConfigOptions { } /** - * Parse backgroundImage into BackgroundImage + * Parse background image URL/path into BackgroundImage */ function parseBackgroundImage( url: string, @@ -316,6 +349,242 @@ function parseBackgroundImage( return null; } +/** + * Validate and normalize backgroundComponent fit option + */ +function parseBackgroundComponentFit( + value: string | undefined, +): BackgroundComponentFit | undefined { + if (!value) return undefined; + const normalized = value.toLowerCase(); + if ( + normalized === "cover" || + normalized === "contain" || + normalized === "stretch" + ) { + return normalized; + } + console.warn( + `[figdeck] Invalid backgroundComponent fit: ${value}. Using default "cover".`, + ); + return undefined; +} + +/** + * Validate and normalize backgroundComponent align option + */ +function parseBackgroundComponentAlign( + value: string | undefined, +): BackgroundComponentAlign | undefined { + if (!value) return undefined; + const normalized = value.toLowerCase().replace(/_/g, "-"); + const validAligns: BackgroundComponentAlign[] = [ + "center", + "top-left", + "top-right", + "bottom-left", + "bottom-right", + ]; + if (validAligns.includes(normalized as BackgroundComponentAlign)) { + return normalized as BackgroundComponentAlign; + } + console.warn( + `[figdeck] Invalid backgroundComponent align: ${value}. Using default "center".`, + ); + return undefined; +} + +/** + * Validate backgroundComponent opacity (0-1) + */ +function parseBackgroundComponentOpacity( + value: number | undefined, +): number | undefined { + if (value === undefined) return undefined; + const opacity = Number(value); + if (!Number.isNaN(opacity) && opacity >= 0 && opacity <= 1) { + return opacity; + } + console.warn( + `[figdeck] Invalid backgroundComponent opacity: ${value}. Must be 0-1.`, + ); + return undefined; +} + +/** + * Parse backgroundComponent from YAML config + * Accepts either a Figma URL string or object with link and options + */ +function parseBackgroundComponent( + config: string | BackgroundComponentYamlConfig | undefined, +): BackgroundComponent | null { + if (!config) return null; + + // Shorthand: just a Figma URL + if (typeof config === "string") { + const parsed = parseFigmaUrl(config); + if (!parsed.nodeId) { + console.warn( + `[figdeck] backgroundComponent URL must include node-id: ${config}`, + ); + return null; + } + return { + link: config, + nodeId: parsed.nodeId, + fileKey: parsed.fileKey, + }; + } + + // Object form - requires link + if (!config.link) { + console.warn("[figdeck] backgroundComponent requires link with node-id"); + return null; + } + + const parsed = parseFigmaUrl(config.link); + if (!parsed.nodeId) { + console.warn( + `[figdeck] backgroundComponent URL must include node-id: ${config.link}`, + ); + return null; + } + + const result: BackgroundComponent = { + link: config.link, + nodeId: parsed.nodeId, + fileKey: parsed.fileKey, + }; + + const fit = parseBackgroundComponentFit(config.fit); + if (fit) { + result.fit = fit; + } + + const align = parseBackgroundComponentAlign(config.align); + if (align) { + result.align = align; + } + + const opacity = parseBackgroundComponentOpacity(config.opacity); + if (opacity !== undefined) { + result.opacity = opacity; + } + + return result; +} + +/** + * Check if a string looks like a color (hex or CSS color name) + */ +function looksLikeColor(value: string): boolean { + // Hex colors + if (/^#[0-9a-fA-F]{3,8}$/.test(value)) return true; + // rgb/rgba/hsl/hsla + if (/^(rgb|hsl)a?\s*\(/.test(value)) return true; + // Named colors (basic check - normalize will handle validation) + if (/^[a-zA-Z]+$/.test(value)) return true; + return false; +} + +/** + * Check if a string looks like a gradient (contains color stops with positions) + */ +function looksLikeGradient(value: string): boolean { + // Gradient format: #color:position%,#color:position%[@angle] + return /^#?[0-9a-fA-F]{3,8}:\d+%/.test(value); +} + +/** + * Check if a string is a Figma URL with node-id + */ +function isFigmaComponentUrl(value: string): boolean { + return ( + /^https?:\/\/(?:www\.)?figma\.com\//.test(value) && + /[?&]node-id=/.test(value) + ); +} + +/** + * Parse unified background configuration + * Handles both string (auto-detect) and object formats + */ +function parseUnifiedBackground( + config: string | BackgroundYamlConfig | undefined, + basePath?: string, +): { background: SlideBackground | null; templateName?: string } { + if (!config) return { background: null }; + + // String format - auto-detect type + if (typeof config === "string") { + // Check if it's a Figma component URL + if (isFigmaComponentUrl(config)) { + const component = parseBackgroundComponent(config); + if (component) { + return { background: { component } }; + } + return { background: null }; + } + + // Check if it's a gradient + if (looksLikeGradient(config)) { + const gradient = parseGradient(config); + if (gradient) { + return { background: { gradient } }; + } + } + + // Check if it's a color + if (looksLikeColor(config)) { + return { background: { solid: normalizeColor(config) } }; + } + + // Otherwise treat as image path/URL + const image = parseBackgroundImage(config, basePath); + if (image) { + return { background: { image } }; + } + + return { background: null }; + } + + // Object format - explicit configuration + let background: SlideBackground | null = null; + let templateName: string | undefined; + + // Priority: template > gradient > color > image + if (config.template) { + background = { templateStyle: config.template }; + templateName = config.template; + } else if (config.gradient) { + const gradient = parseGradient(config.gradient); + if (gradient) { + background = { gradient }; + } + } else if (config.color) { + background = { solid: normalizeColor(config.color) }; + } else if (config.image) { + const image = parseBackgroundImage(config.image, basePath); + if (image) { + background = { image }; + } + } + + // Component can be combined with other backgrounds + if (config.component) { + const component = parseBackgroundComponent(config.component); + if (component) { + if (background) { + background.component = component; + } else { + background = { component }; + } + } + } + + return { background, templateName }; +} + /** * Parse slide config from YAML frontmatter */ @@ -323,7 +592,6 @@ export function parseSlideConfig( config: SlideConfig, options: ParseSlideConfigOptions = {}, ): ParsedConfigResult { - let background: SlideBackground | null = null; const styles: SlideStyles = {}; const baseColor = config.color ? normalizeColor(config.color) : undefined; @@ -337,25 +605,11 @@ export function parseSlideConfig( return { color: baseColor }; }; - // Priority: templateStyle > gradient > solid > image - if (config.template) { - background = { templateStyle: config.template }; - } else if (config.gradient) { - const gradient = parseGradient(config.gradient); - if (gradient) { - background = { gradient }; - } - } else if (config.background) { - background = { solid: normalizeColor(config.background) }; - } else if (config.backgroundImage) { - const image = parseBackgroundImage( - config.backgroundImage, - options.basePath, - ); - if (image) { - background = { image }; - } - } + // Parse unified background + const { background, templateName } = parseUnifiedBackground( + config.background, + options.basePath, + ); // Parse headings const headingStyles: NonNullable = { @@ -402,9 +656,9 @@ export function parseSlideConfig( spacing: config.titlePrefix.spacing, }; } - } else if (config.template) { + } else if (templateName) { // Look up template defaults - const templateDefaults = getTemplateDefaults(config.template); + const templateDefaults = getTemplateDefaults(templateName); if (templateDefaults?.titlePrefix) { titlePrefix = templateDefaults.titlePrefix; } diff --git a/packages/cli/templates/ai-rules-body.md b/packages/cli/templates/ai-rules-body.md index 86fadc4..82a5cac 100644 --- a/packages/cli/templates/ai-rules-body.md +++ b/packages/cli/templates/ai-rules-body.md @@ -40,9 +40,8 @@ color: "#111827" ``` Common settings: -- `background`, `color` (prefer hex like `"#RRGGBB"`) -- `gradient: "#000:0%,#fff:100%@45"` -- `backgroundImage` (local path or URL) +- `background` (hex like `"#111827"`, gradient like `"#000:0%,#fff:100%@45"`, image path/URL, or Figma component URL) +- `color` (prefer hex like `"#RRGGBB"`) - `align: left|center|right`, `valign: top|middle|bottom` - `transition` (e.g. `dissolve`, `slide-from-right 0.5`, or the detailed object form) - `fonts` (falls back to Inter if unavailable) diff --git a/packages/cli/templates/init.md b/packages/cli/templates/init.md index dcbb2a7..d01cacb 100644 --- a/packages/cli/templates/init.md +++ b/packages/cli/templates/init.md @@ -149,9 +149,9 @@ Set via YAML frontmatter: ```yaml --- -background: "#16213e" # Solid color -gradient: "#000:0%,#fff:100%@45" # Gradient -backgroundImage: "./bg.png" # Image +background: "#16213e" # Solid color +# background: "#000:0%,#fff:100%@45" # Gradient +# background: "./bg.png" # Image (local path or URL) --- ``` diff --git a/packages/docs/src/content/docs/en/api-reference.md b/packages/docs/src/content/docs/en/api-reference.md index dd52f19..b5c1f83 100644 --- a/packages/docs/src/content/docs/en/api-reference.md +++ b/packages/docs/src/content/docs/en/api-reference.md @@ -155,10 +155,7 @@ color: "#58a6ff" | Property | Type | Description | |----------|------|-------------| -| `background` | `string` | Background color (hex) | -| `gradient` | `string` | Gradient (`color:pos%,...@angle` format) | -| `template` | `string` | Figma Paint Style name | -| `backgroundImage` | `string` | Background image (local path or URL) | +| `background` | `string \| object` | Unified background config: string (color/gradient/image/component) or object (`color`, `gradient`, `template`, `image`, `component`) | | `color` | `string` | Base text color (applied to all elements) | | `headings` | `object` | Heading styles (h1-h4) | | `paragraphs` | `object` | Paragraph styles | diff --git a/packages/docs/src/content/docs/en/markdown-spec.md b/packages/docs/src/content/docs/en/markdown-spec.md index d5b7bd6..d0c19cc 100644 --- a/packages/docs/src/content/docs/en/markdown-spec.md +++ b/packages/docs/src/content/docs/en/markdown-spec.md @@ -85,10 +85,7 @@ Back to global settings (dark background, dissolve) | Setting | Description | |---------|-------------| | `figdeck` | Enable VSCode extension features (`true`/`false`) | -| `background` | Background color (hex) | -| `gradient` | Gradient background | -| `backgroundImage` | Background image (local path or URL) | -| `template` | Figma paint style name | +| `background` | Unified background: color, gradient, image, template, or Figma component | | `color` | Base text color | | `headings` | Heading styles (h1, h2, h3, h4) | | `paragraphs` | Paragraph styles | @@ -273,6 +270,90 @@ Check the [documentation](https://example.com) for more details. ::: ``` +## Background + +The `background` property is a unified configuration for all background types. It supports string format (auto-detected) or object format (explicit). + +### String Format (Auto-detect) + +```yaml +--- +# Solid color (hex) +background: "#1a1a2e" + +# Gradient +background: "#0d1117:0%,#1f2937:50%,#58a6ff:100%@45" + +# Image (local path or URL) +background: "./bg.png" +background: "https://example.com/bg.png" + +# Figma component (URL with node-id) +background: "https://www.figma.com/design/YOUR_FILE_KEY?node-id=123-456" +--- +``` + +### Object Format (Explicit) + +```yaml +--- +background: + color: "#1a1a2e" # Solid color + gradient: "#000:0%,#fff:100%@45" # Gradient + template: "Dark Mode" # Figma paint style name + image: "./bg.png" # Image path or URL + component: # Figma component + link: "https://www.figma.com/design/xxx?node-id=123-456" + fit: "cover" # cover | contain | stretch + align: "center" # center | top-left | top-right | bottom-left | bottom-right + opacity: 0.8 # 0-1 +--- +``` + +### Combined Background + +Component can be combined with color/gradient/image backgrounds. The component renders as a layer on top: + +```yaml +--- +background: + color: "#1a1a2e" + component: + link: "https://www.figma.com/design/xxx?node-id=123-456" + opacity: 0.6 +--- +``` + +### Priority + +When multiple properties are specified in object format: `template` > `gradient` > `color` > `image` + +### Component Fit Options + +| Value | Description | +|-------|-------------| +| `cover` | Scale to cover entire slide, may crop (default) | +| `contain` | Scale to fit within slide, may have empty space | +| `stretch` | Stretch to fill slide, ignores aspect ratio | + +### Component Align Options + +When using `cover` or `contain`, you can specify alignment: + +| Value | Description | +|-------|-------------| +| `center` | Center of slide (default) | +| `top-left` | Top-left corner | +| `top-right` | Top-right corner | +| `bottom-left` | Bottom-left corner | +| `bottom-right` | Bottom-right corner | + +### Limitations + +- Component only works with nodes in the **same Figma file** (MVP limitation) +- Supported node types: Component, ComponentSet, Frame, Instance +- Recommended background size: 1920x1080 (slide dimensions) + ## Images Images can be inserted using `![alt](url)` format. @@ -902,3 +983,4 @@ This example generates the following 5 slides: | Footnotes | Supported | GFM, displayed at slide bottom | | Transitions | Supported | Slide transition animations | | Custom Fonts | Supported | Per-element font families | +| Background Component | Supported | Figma Component/Frame as background | diff --git a/packages/docs/src/content/docs/ja/api-reference.md b/packages/docs/src/content/docs/ja/api-reference.md index 65a682f..f4804d4 100644 --- a/packages/docs/src/content/docs/ja/api-reference.md +++ b/packages/docs/src/content/docs/ja/api-reference.md @@ -155,10 +155,7 @@ color: "#58a6ff" | プロパティ | 型 | 説明 | |------------|------|------| -| `background` | `string` | 背景色(hex) | -| `gradient` | `string` | グラデーション(`color:pos%,...@angle` 形式) | -| `template` | `string` | Figma Paint Style 名 | -| `backgroundImage` | `string` | 背景画像(ローカルパスまたは URL) | +| `background` | `string \| object` | 統一された背景設定: string(色/グラデーション/画像/コンポーネント)または object(`color`, `gradient`, `template`, `image`, `component`) | | `color` | `string` | 基本テキスト色(全要素に適用) | | `headings` | `object` | 見出しスタイル(h1〜h4) | | `paragraphs` | `object` | 段落スタイル | diff --git a/packages/docs/src/content/docs/ja/markdown-spec.md b/packages/docs/src/content/docs/ja/markdown-spec.md index 198dd9b..e68246c 100644 --- a/packages/docs/src/content/docs/ja/markdown-spec.md +++ b/packages/docs/src/content/docs/ja/markdown-spec.md @@ -85,10 +85,7 @@ transition: slide-from-right | 設定 | 説明 | |------|------| | `figdeck` | VSCode 拡張機能の機能を有効化(`true`/`false`) | -| `background` | 背景色(16進数) | -| `gradient` | グラデーション背景 | -| `backgroundImage` | 背景画像(ローカルパスまたはURL) | -| `template` | Figma ペイントスタイル名 | +| `background` | 統合背景設定:色、グラデーション、画像、テンプレート、Figma コンポーネント | | `color` | ベーステキスト色 | | `headings` | 見出しスタイル(h1, h2, h3, h4) | | `paragraphs` | 段落スタイル | @@ -273,6 +270,90 @@ bullets: ::: ``` +## 背景 + +`background` プロパティは、すべての背景タイプを統合した設定です。文字列形式(自動検出)またはオブジェクト形式(明示的)で指定できます。 + +### 文字列形式(自動検出) + +```yaml +--- +# 単色(16進数) +background: "#1a1a2e" + +# グラデーション +background: "#0d1117:0%,#1f2937:50%,#58a6ff:100%@45" + +# 画像(ローカルパスまたはURL) +background: "./bg.png" +background: "https://example.com/bg.png" + +# Figma コンポーネント(node-id 付きURL) +background: "https://www.figma.com/design/YOUR_FILE_KEY?node-id=123-456" +--- +``` + +### オブジェクト形式(明示的) + +```yaml +--- +background: + color: "#1a1a2e" # 単色 + gradient: "#000:0%,#fff:100%@45" # グラデーション + template: "Dark Mode" # Figma ペイントスタイル名 + image: "./bg.png" # 画像パスまたはURL + component: # Figma コンポーネント + link: "https://www.figma.com/design/xxx?node-id=123-456" + fit: "cover" # cover | contain | stretch + align: "center" # center | top-left | top-right | bottom-left | bottom-right + opacity: 0.8 # 0-1 +--- +``` + +### 背景の組み合わせ + +コンポーネントは color/gradient/image 背景と組み合わせて使用できます。コンポーネントは上位レイヤーとして描画されます: + +```yaml +--- +background: + color: "#1a1a2e" + component: + link: "https://www.figma.com/design/xxx?node-id=123-456" + opacity: 0.6 +--- +``` + +### 優先順位 + +オブジェクト形式で複数のプロパティを指定した場合の優先順位: `template` > `gradient` > `color` > `image` + +### コンポーネントの fit オプション + +| 値 | 説明 | +|----|------| +| `cover` | スライド全体を覆うようにスケール、はみ出し部分はクリップ(デフォルト) | +| `contain` | スライド内に収まるようにスケール、余白が生じる場合あり | +| `stretch` | スライドサイズに合わせて引き伸ばし、アスペクト比は維持されない | + +### コンポーネントの align オプション + +`cover` または `contain` 使用時に配置位置を指定できます: + +| 値 | 説明 | +|----|------| +| `center` | スライドの中央(デフォルト) | +| `top-left` | 左上隅 | +| `top-right` | 右上隅 | +| `bottom-left` | 左下隅 | +| `bottom-right` | 右下隅 | + +### 制限事項 + +- コンポーネントは**同一 Figma ファイル内**のノードのみ対応(MVP 制限) +- 対応ノードタイプ: Component, ComponentSet, Frame, Instance +- 推奨背景サイズ: 1920x1080(スライドサイズ) + ## 画像 `![alt](url)` 形式で画像を挿入できます。 @@ -902,3 +983,4 @@ CLI と Figma Plugin が連携して動作します。 | 脚注 | ✅ | GFM、スライド下部に表示 | | トランジション | ✅ | スライド切り替えアニメーション | | カスタムフォント | ✅ | 要素ごとのフォントファミリー | +| 背景コンポーネント | ✅ | Figma コンポーネント/フレームを背景に | diff --git a/packages/plugin/src/node-cache.ts b/packages/plugin/src/node-cache.ts index b4e99b4..18fc8c9 100644 --- a/packages/plugin/src/node-cache.ts +++ b/packages/plugin/src/node-cache.ts @@ -153,6 +153,21 @@ export function cloneNode(node: SceneNode): SceneNode | null { if (node.type === "COMPONENT") { return (node as ComponentNode).createInstance(); } + if (node.type === "COMPONENT_SET") { + // For component sets, create an instance of the default variant + const componentSet = node as ComponentSetNode; + const defaultVariant = componentSet.defaultVariant; + if (defaultVariant) { + return defaultVariant.createInstance(); + } + // Fallback: try the first child if no default variant + const firstChild = componentSet.children[0]; + if (firstChild && firstChild.type === "COMPONENT") { + return (firstChild as ComponentNode).createInstance(); + } + console.warn("[figdeck] Component set has no usable variants"); + return null; + } return node.clone(); } catch (e) { // Node reference is stale - the node was likely deleted by the user diff --git a/packages/plugin/src/slide-utils.ts b/packages/plugin/src/slide-utils.ts index 0c7609f..f1c0d71 100644 --- a/packages/plugin/src/slide-utils.ts +++ b/packages/plugin/src/slide-utils.ts @@ -1,8 +1,10 @@ import type { + BackgroundComponent, BackgroundImage, SlideBackground, SlideNumberConfig, } from "@figdeck/shared"; +import { SLIDE_HEIGHT, SLIDE_WIDTH } from "@figdeck/shared"; import { base64ToUint8Array } from "./base64"; import { createGradientTransform, parseColor } from "./colors"; import { @@ -31,6 +33,15 @@ const missingPaintStyleNotifications = new Set(); // Node cache for slide number templates const slideNumberNodeCache = createNodeCache(); +// Node cache for background component templates +const backgroundComponentNodeCache = createNodeCache(); + +// Track background component nodes we've already notified about +const missingBackgroundComponentNotifications = new Set(); + +/** Background component node name for cleanup */ +const BACKGROUND_COMPONENT_NODE_NAME = "__figdeck_background_component__"; + async function resolvePaintStyleId(styleName: string): Promise { const cachedId = paintStyleCache.get(styleName); if (cachedId) { @@ -43,20 +54,28 @@ async function resolvePaintStyleId(styleName: string): Promise { } const lookupPromise = (async (): Promise => { - const localStyles = await figma.getLocalPaintStylesAsync(); - const localStyle = localStyles.find((style) => style.name === styleName); - - if (localStyle) { - return localStyle.id; - } - try { - const importedStyle = await figma.importStyleByKeyAsync(styleName); - if (importedStyle && importedStyle.type === "PAINT") { - return importedStyle.id; + // Check if getLocalPaintStylesAsync is available + if (typeof figma.getLocalPaintStylesAsync === "function") { + const localStyles = await figma.getLocalPaintStylesAsync(); + const localStyle = localStyles.find( + (style) => style.name === styleName, + ); + + if (localStyle) { + return localStyle.id; + } + } + + // Try importing by key (only if the API is available) + if (typeof figma.importStyleByKeyAsync === "function") { + const importedStyle = await figma.importStyleByKeyAsync(styleName); + if (importedStyle && importedStyle.type === "PAINT") { + return importedStyle.id; + } } } catch (_e) { - // ignore and fall through to null + // Paint style APIs may not be available in all contexts } return null; @@ -151,33 +170,198 @@ async function applyImageBackground( } } +/** + * Apply background component (Figma Component/Frame) to slide + * The component is rendered as a layer on top of the base background + */ +async function applyBackgroundComponent( + slideNode: SlideNode, + component: BackgroundComponent, +): Promise { + const { nodeId, fit = "cover", align = "center", opacity = 1 } = component; + + // Guard against missing nodeId + if (!nodeId) { + return false; + } + + // Find the source node + const sourceNode = await backgroundComponentNodeCache.findNode(nodeId, { + allowedTypes: ["COMPONENT", "COMPONENT_SET", "FRAME", "INSTANCE"], + errorPrefix: "Background component", + }); + + if (!sourceNode) { + if (!missingBackgroundComponentNotifications.has(nodeId)) { + figma.notify(`Background component not found: ${nodeId}`, { + error: true, + }); + missingBackgroundComponentNotifications.add(nodeId); + } + return false; + } + + // Clone the node + const clonedNode = cloneNode(sourceNode); + if (!clonedNode) { + backgroundComponentNodeCache.clear(); + return false; + } + + clonedNode.name = BACKGROUND_COMPONENT_NODE_NAME; + + // Calculate scale based on fit mode + const sourceWidth = sourceNode.width; + const sourceHeight = sourceNode.height; + const targetWidth = SLIDE_WIDTH; + const targetHeight = SLIDE_HEIGHT; + + let scaleX = 1; + let scaleY = 1; + + if (fit === "stretch") { + // Stretch: scale to exactly fill the slide (non-uniform) + scaleX = targetWidth / sourceWidth; + scaleY = targetHeight / sourceHeight; + } else if (fit === "cover") { + // Cover: scale uniformly to cover entire slide (may crop) + const scale = Math.max( + targetWidth / sourceWidth, + targetHeight / sourceHeight, + ); + scaleX = scale; + scaleY = scale; + } else if (fit === "contain") { + // Contain: scale uniformly to fit within slide (may have empty space) + const scale = Math.min( + targetWidth / sourceWidth, + targetHeight / sourceHeight, + ); + scaleX = scale; + scaleY = scale; + } + + // Apply scale by resizing + const newWidth = sourceWidth * scaleX; + const newHeight = sourceHeight * scaleY; + + // Check if the node supports resize + if ("resize" in clonedNode) { + (clonedNode as FrameNode | ComponentNode | InstanceNode).resize( + newWidth, + newHeight, + ); + } else if ("rescale" in clonedNode) { + // Fallback for nodes without resize - use scale transform + (clonedNode as SceneNode & { rescale: (scale: number) => void }).rescale( + scaleX, + ); + } + + // Calculate position based on alignment + let x = 0; + let y = 0; + + // For cover/contain, center by default or use specified alignment + if (fit !== "stretch") { + const offsetX = (targetWidth - newWidth) / 2; + const offsetY = (targetHeight - newHeight) / 2; + + switch (align) { + case "center": + x = offsetX; + y = offsetY; + break; + case "top-left": + x = 0; + y = 0; + break; + case "top-right": + x = targetWidth - newWidth; + y = 0; + break; + case "bottom-left": + x = 0; + y = targetHeight - newHeight; + break; + case "bottom-right": + x = targetWidth - newWidth; + y = targetHeight - newHeight; + break; + default: + x = offsetX; + y = offsetY; + } + } + + // Apply opacity if not 1 + if (opacity < 1 && "opacity" in clonedNode) { + (clonedNode as SceneNode & { opacity: number }).opacity = opacity; + } + + // Insert at the back (index 0 = bottommost layer) + slideNode.insertChild(0, clonedNode); + + // Set position after inserting + clonedNode.x = x; + clonedNode.y = y; + + // Use absolute positioning to avoid auto-layout interference + // Only needed if the parent has auto-layout (layoutMode !== "NONE") + if ( + "layoutPositioning" in clonedNode && + "layoutMode" in slideNode && + slideNode.layoutMode !== "NONE" + ) { + (clonedNode as FrameNode | InstanceNode).layoutPositioning = "ABSOLUTE"; + } + + // Clear the notification set since we successfully used the node + missingBackgroundComponentNotifications.delete(nodeId); + + return true; +} + /** * Apply background fill to a slide node + * Background component can be combined with base fill (solid/gradient/image) + * The component is rendered as a layer on top of the base fill */ export async function applyBackground( slideNode: SlideNode, background: SlideBackground, ): Promise { - // Priority: templateStyle > gradient > solid > image + // Remove any existing background component first + // Check if slideNode has children (some slide types may not) + if (slideNode.children && slideNode.children.length > 0) { + // Iterate backwards since we're potentially removing items + for (let i = slideNode.children.length - 1; i >= 0; i--) { + const child = slideNode.children[i]; + if (child && child.name === BACKGROUND_COMPONENT_NODE_NAME) { + child.remove(); + } + } + } + + let baseFillApplied = false; + + // Priority for base fill: templateStyle > gradient > solid > image if (background.templateStyle) { const styleName = background.templateStyle; - const styleId = await resolvePaintStyleId(styleName); if (styleId) { missingPaintStyleNotifications.delete(styleName); slideNode.fillStyleId = styleId; - return; - } - - if (!missingPaintStyleNotifications.has(styleName)) { - figma.notify(`Paint style "${styleName}" not found`, { error: true }); - missingPaintStyleNotifications.add(styleName); + baseFillApplied = true; + } else { + if (!missingPaintStyleNotifications.has(styleName)) { + figma.notify(`Paint style "${styleName}" not found`, { error: true }); + missingPaintStyleNotifications.add(styleName); + } + // Don't return - still try to apply component if present } - return; - } - - if (background.gradient) { + } else if (background.gradient) { const { stops, angle = 0 } = background.gradient; const gradientStops: ColorStop[] = []; @@ -198,11 +382,9 @@ export async function applyBackground( gradientStops, }; slideNode.fills = [gradientFill]; + baseFillApplied = true; } - return; - } - - if (background.solid) { + } else if (background.solid) { const color = parseColor(background.solid); if (color) { const solidFill: SolidPaint = { @@ -211,15 +393,15 @@ export async function applyBackground( opacity: color.a ?? 1, }; slideNode.fills = [solidFill]; + baseFillApplied = true; } else { figma.notify(`Invalid color "${background.solid}"`, { error: true }); } - return; - } - - if (background.image) { + } else if (background.image) { const success = await applyImageBackground(slideNode, background.image); - if (!success) { + if (success) { + baseFillApplied = true; + } else { figma.notify( `Failed to load background image "${background.image.url}"`, { @@ -228,6 +410,18 @@ export async function applyBackground( ); } } + + // Apply background component if present (layer on top of base fill) + if (background.component) { + const success = await applyBackgroundComponent( + slideNode, + background.component, + ); + if (!success && !baseFillApplied) { + // Both component and base fill failed - no background applied + console.warn("[figdeck] No background could be applied"); + } + } } /** diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index d8425d4..5c5c2bc 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -10,6 +10,42 @@ export interface BackgroundImage { source?: "local" | "remote"; } +/** + * Fit mode for background component + * - cover: Scale to cover entire slide, cropping if necessary + * - contain: Scale to fit within slide, may have empty space + * - stretch: Stretch to fill slide, ignoring aspect ratio + */ +export type BackgroundComponentFit = "cover" | "contain" | "stretch"; + +/** + * Alignment for background component positioning + */ +export type BackgroundComponentAlign = + | "center" + | "top-left" + | "top-right" + | "bottom-left" + | "bottom-right"; + +/** + * Background component configuration for using a Figma Component/Frame as background + */ +export interface BackgroundComponent { + /** Figma URL link to the component/frame */ + link?: string; + /** Figma node ID (extracted from link or specified directly) */ + nodeId: string; + /** Figma file key (extracted from link) */ + fileKey?: string; + /** How the component should be scaled to fit the slide (default: cover) */ + fit?: BackgroundComponentFit; + /** Position alignment when component doesn't fill the slide (default: center) */ + align?: BackgroundComponentAlign; + /** Opacity of the background component (0-1, default: 1) */ + opacity?: number; +} + export interface SlideBackground { solid?: string; gradient?: { @@ -18,6 +54,8 @@ export interface SlideBackground { }; templateStyle?: string; image?: BackgroundImage; + /** Figma Component/Frame used as background layer */ + component?: BackgroundComponent; } export interface CodeBlock { diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 49060b6..26a03cd 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -91,23 +91,175 @@ If not found, you'll be prompted to install or configure it. ## Development +### Build Commands + ```bash -# Build extension cd packages/vscode + +# Build for production (minified) bun run build -# Watch mode +# Build for development (with sourcemaps) +bun run build:dev + +# Watch mode for development bun run dev # Type check bun run typecheck + +# Run tests +bun test src ``` ### Debugging -1. Open VS Code in the figdeck workspace -2. Press F5 to launch Extension Development Host -3. Open a Markdown file to activate the extension +The project includes VS Code launch configurations in `.vscode/` for debugging the extension. + +#### Quick Start + +1. Open the figdeck workspace in VS Code +2. Press `F5` (or Run > Start Debugging) +3. Select **"Run Extension"** configuration +4. A new VS Code window (Extension Development Host) will open +5. Open a Markdown file with `figdeck: true` in frontmatter to activate the extension + +#### Available Launch Configurations + +| Configuration | Description | +|---------------|-------------| +| **Run Extension** | Build once and launch Extension Development Host | +| **Run Extension (Watch)** | Start watch mode and launch Extension Development Host | + +#### Available Tasks + +Run via `Cmd+Shift+P` > "Tasks: Run Task": + +| Task | Description | +|------|-------------| +| `vscode: build dev` | Build with sourcemaps | +| `vscode: watch` | Watch mode (background task) | +| `vscode: build` | Production build | +| `vscode: test` | Run tests | + +#### Debugging Tips + +- **Breakpoints**: Set breakpoints in `src/` files. Sourcemaps are enabled in dev builds. +- **Console output**: View extension logs in the Debug Console panel. +- **Reload extension**: In the Extension Development Host, run `Developer: Reload Window` to reload after code changes. +- **Watch mode**: Use "Run Extension (Watch)" for automatic rebuilds on file changes. + +#### Configuration Files + +The debug configuration files are located in the repository root `.vscode/` directory: + +
+.vscode/launch.json + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Run Extension", + "type": "extensionHost", + "request": "launch", + "args": [ + "--extensionDevelopmentPath=${workspaceFolder}/packages/vscode" + ], + "outFiles": [ + "${workspaceFolder}/packages/vscode/dist/**/*.js" + ], + "sourceMaps": true, + "preLaunchTask": "vscode: build dev" + }, + { + "name": "Run Extension (Watch)", + "type": "extensionHost", + "request": "launch", + "args": [ + "--extensionDevelopmentPath=${workspaceFolder}/packages/vscode" + ], + "outFiles": [ + "${workspaceFolder}/packages/vscode/dist/**/*.js" + ], + "sourceMaps": true, + "preLaunchTask": "vscode: watch" + } + ] +} +``` + +
+ +
+.vscode/tasks.json + +```json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "vscode: build dev", + "type": "shell", + "command": "bun", + "args": ["run", "build:dev"], + "options": { + "cwd": "${workspaceFolder}/packages/vscode" + }, + "group": "build", + "problemMatcher": "$esbuild" + }, + { + "label": "vscode: watch", + "type": "shell", + "command": "bun", + "args": ["run", "dev"], + "options": { + "cwd": "${workspaceFolder}/packages/vscode" + }, + "isBackground": true, + "group": "build", + "problemMatcher": { + "owner": "esbuild", + "pattern": { + "regexp": "^✘ \\[ERROR\\] (.+)$", + "message": 1 + }, + "background": { + "activeOnStart": true, + "beginsPattern": "^\\[watch\\]", + "endsPattern": "^\\s*dist/extension\\.js" + } + } + }, + { + "label": "vscode: build", + "type": "shell", + "command": "bun", + "args": ["run", "build"], + "options": { + "cwd": "${workspaceFolder}/packages/vscode" + }, + "group": "build", + "problemMatcher": "$esbuild" + }, + { + "label": "vscode: test", + "type": "shell", + "command": "bun", + "args": ["test", "src"], + "options": { + "cwd": "${workspaceFolder}/packages/vscode" + }, + "group": "test", + "problemMatcher": [] + } + ] +} +``` + +
## License diff --git a/packages/vscode/snippets/figdeck.json b/packages/vscode/snippets/figdeck.json index 328391f..cc272d0 100644 --- a/packages/vscode/snippets/figdeck.json +++ b/packages/vscode/snippets/figdeck.json @@ -209,27 +209,46 @@ ], "description": "Image with percentage width" }, - "figdeck: Gradient Background": { - "prefix": ["gradient:", "figdeck-gradient"], + "figdeck: Background (Gradient)": { + "prefix": ["background-gradient", "figdeck-bg-gradient"], "body": [ - "gradient: \"${1:#0d1117}:0%,${2:#1f2937}:50%,${3:#3b82f6}:100%@${4:45}\"" + "background: \"${1:#0d1117}:0%,${2:#1f2937}:50%,${3:#3b82f6}:100%@${4:45}\"" ], "description": "Gradient background (color:stop,...@angle)" }, - "figdeck: Background Image (Local)": { - "prefix": ["backgroundImage-local", "figdeck-bg-local"], + "figdeck: Background (Image Local)": { + "prefix": ["background-local", "figdeck-bg-local"], "body": [ - "backgroundImage: \"./${1:bg.png}\"" + "background: \"./${1:bg.png}\"" ], "description": "Local background image" }, - "figdeck: Background Image (URL)": { - "prefix": ["backgroundImage-url", "figdeck-bg-url"], + "figdeck: Background (Image URL)": { + "prefix": ["background-url", "figdeck-bg-url"], "body": [ - "backgroundImage: \"${1:https://example.com/image.jpg}\"" + "background: \"${1:https://example.com/image.jpg}\"" ], "description": "Remote background image URL" }, + "figdeck: Background (Component URL)": { + "prefix": ["background-component", "figdeck-bg-component"], + "body": [ + "background: \"${1:https://www.figma.com/design/xxx?node-id=123-456}\"" + ], + "description": "Figma Component/Frame as slide background (URL shorthand)" + }, + "figdeck: Background (Component Full)": { + "prefix": ["background-component-full", "figdeck-bg-component-full"], + "body": [ + "background:", + " component:", + " link: \"${1:https://www.figma.com/design/xxx?node-id=123-456}\"", + " fit: ${2|cover,contain,stretch|}", + " align: ${3|center,top-left,top-right,bottom-left,bottom-right|}", + " opacity: ${4:1}" + ], + "description": "Figma Component/Frame as slide background (full options)" + }, "figdeck: Title Prefix": { "prefix": ["titlePrefix:", "figdeck-titleprefix"], "body": [ diff --git a/packages/vscode/src/diagnostics/analyzer.test.ts b/packages/vscode/src/diagnostics/analyzer.test.ts index 49880fb..6173e45 100644 --- a/packages/vscode/src/diagnostics/analyzer.test.ts +++ b/packages/vscode/src/diagnostics/analyzer.test.ts @@ -3,6 +3,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import type * as vscode from "vscode"; import { + analyzeBackgroundImages, analyzeColumnsBlocks, analyzeDocument, analyzeFigmaBlocks, @@ -937,6 +938,455 @@ describe("analyzeImages", () => { }); }); +describe("analyzeBackgroundImages", () => { + let statSpy: ReturnType | null = null; + + afterEach(() => { + statSpy?.mockRestore(); + statSpy = null; + clearImageDiagnosticsCache(); + }); + + it("skips solid hex color background", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", 'background: "#1a1a2e"', "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips hex color with alpha", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", 'background: "#1a1a2eff"', "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips rgb/rgba colors", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: rgb(255, 0, 0)", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips named colors", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: red", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips gradient background", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", 'background: "#0d1117:0%,#58a6ff:100%@45"', "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips gradient without leading hash", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: 0d1117:0%,58a6ff:100%", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips 3-character hex color", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", 'background: "#fff"', "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips hsl color", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: hsl(0, 100%, 50%)", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips hsla color", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: hsla(0, 100%, 50%, 0.5)", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips rgba color", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: rgba(255, 0, 0, 0.5)", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips remote http URLs", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: http://example.com/image.png", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("skips remote https URLs", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = ["---", "background: https://example.com/image.png", "---"]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); + + it("reports error for non-existent background image (string format)", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/missing.png", "---"]; + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async () => { + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some((issue) => issue.code === "background-image-not-found"), + ).toBe(true); + }); + + it("reports error for non-existent background image (object format)", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = [ + "---", + "background:", + " image: ./images/missing.png", + "---", + ]; + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async () => { + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some((issue) => issue.code === "background-image-not-found"), + ).toBe(true); + }); + + it("warns for unsupported background image format", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/bg.webp", "---"]; + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async () => { + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some( + (issue) => issue.code === "background-image-unsupported-format", + ), + ).toBe(true); + }); + + it("warns for oversized background image", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/large.png", "---"]; + + const expectedPath = path.resolve( + path.dirname(documentPath), + "images/large.png", + ); + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async ( + filePath: fs.PathLike, + ) => { + if (String(filePath) === expectedPath) { + return { + size: 10 * 1024 * 1024, // 10MB + isFile: () => true, + } as unknown as fs.Stats; + } + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some((issue) => issue.code === "background-image-too-large"), + ).toBe(true); + }); + + it("detects image path in object format with image property", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background:", " image: ./images/large.png", "---"]; + + const expectedPath = path.resolve( + path.dirname(documentPath), + "images/large.png", + ); + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async ( + filePath: fs.PathLike, + ) => { + if (String(filePath) === expectedPath) { + return { + size: 10 * 1024 * 1024, // 10MB + isFile: () => true, + } as unknown as fs.Stats; + } + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some((issue) => issue.code === "background-image-too-large"), + ).toBe(true); + }); + + it("does not warn when image size is within limit", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/small.png", "---"]; + + const expectedPath = path.resolve( + path.dirname(documentPath), + "images/small.png", + ); + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async ( + filePath: fs.PathLike, + ) => { + if (String(filePath) === expectedPath) { + return { + size: 1 * 1024 * 1024, // 1MB + isFile: () => true, + } as unknown as fs.Stats; + } + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect( + issues.some((issue) => issue.code === "background-image-too-large"), + ).toBe(false); + expect( + issues.some((issue) => issue.code === "background-image-not-found"), + ).toBe(false); + }); + + it("respects maxSizeMb option", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/medium.png", "---"]; + + const expectedPath = path.resolve( + path.dirname(documentPath), + "images/medium.png", + ); + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async ( + filePath: fs.PathLike, + ) => { + if (String(filePath) === expectedPath) { + return { + size: 2 * 1024 * 1024, // 2MB + isFile: () => true, + } as unknown as fs.Stats; + } + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + { maxSizeMb: 1 }, + ); + + expect( + issues.some((issue) => issue.code === "background-image-too-large"), + ).toBe(true); + }); + + it("allows disabling size check via maxSizeMb: null", async () => { + const basePath = path.resolve("test-workspace"); + const documentPath = path.join(basePath, "docs", "slides.md"); + const documentUri = makeFileUri(documentPath); + const lines = ["---", "background: ./images/huge.png", "---"]; + + const expectedPath = path.resolve( + path.dirname(documentPath), + "images/huge.png", + ); + + statSpy = spyOn(fs.promises, "stat").mockImplementation((async ( + filePath: fs.PathLike, + ) => { + if (String(filePath) === expectedPath) { + return { + size: 100 * 1024 * 1024, // 100MB + isFile: () => true, + } as unknown as fs.Stats; + } + throw new Error("ENOENT"); + }) as unknown as typeof fs.promises.stat); + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + { maxSizeMb: null }, + ); + + expect( + issues.some((issue) => issue.code === "background-image-too-large"), + ).toBe(false); + }); + + it("skips per-slide frontmatter with color background", async () => { + const basePath = path.resolve("test-workspace"); + const documentUri = makeFileUri(path.join(basePath, "docs", "slides.md")); + const lines = [ + "---", + 'background: "#000"', + "---", + "", + "# Title", + "", + "---", + 'background: "#fff"', + "---", + "", + "## Slide 2", + ]; + + const issues = await analyzeBackgroundImages( + lines, + basePath, + documentUri as unknown as vscode.Uri, + ); + + expect(issues).toHaveLength(0); + }); +}); + describe("analyzeDocument", () => { let statSpy: ReturnType | null = null; diff --git a/packages/vscode/src/diagnostics/analyzer.ts b/packages/vscode/src/diagnostics/analyzer.ts index ff7fecf..75ebca2 100644 --- a/packages/vscode/src/diagnostics/analyzer.ts +++ b/packages/vscode/src/diagnostics/analyzer.ts @@ -234,6 +234,21 @@ export function analyzeFrontmatterStructure(lines: string[]): Issue[] { const SUPPORTED_IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "gif"]; +function looksLikeColor(value: string): boolean { + // Hex colors + if (/^#[0-9a-fA-F]{3,8}$/.test(value)) return true; + // rgb/rgba/hsl/hsla + if (/^(rgb|hsl)a?\s*\(/.test(value)) return true; + // Named colors (basic check - CLI will validate) + if (/^[a-zA-Z]+$/.test(value)) return true; + return false; +} + +function looksLikeGradient(value: string): boolean { + // Gradient format: #color:position%,#color:position%[@angle] + return /^#?[0-9a-fA-F]{3,8}:\d+%/.test(value); +} + /** * Find the line number where a key appears in frontmatter content */ @@ -253,7 +268,7 @@ function findKeyLineInFrontmatter( } /** - * Analyze backgroundImage references in frontmatter for issues + * Analyze background image references in frontmatter for issues * @internal Exported for testing */ export async function analyzeBackgroundImages( @@ -278,10 +293,29 @@ export async function analyzeBackgroundImages( if (typeof parsed !== "object" || parsed === null) continue; - const backgroundImage = (parsed as Record).backgroundImage; - if (typeof backgroundImage !== "string" || !backgroundImage) continue; + const background = (parsed as Record).background; + if (background === undefined || background === null) continue; + + let url: string | null = null; + let keyForLineSearch: string = "background"; + + if (typeof background === "string") { + const trimmed = background.trim(); + if (!trimmed) continue; + if (looksLikeColor(trimmed) || looksLikeGradient(trimmed)) continue; + url = trimmed; + } else if (typeof background === "object") { + const image = (background as Record).image; + if (typeof image !== "string") continue; + const trimmed = image.trim(); + if (!trimmed) continue; + url = trimmed; + keyForLineSearch = "image"; + } else { + continue; + } - const url = backgroundImage.trim(); + if (!url) continue; // Skip remote URLs if (url.startsWith("http://") || url.startsWith("https://")) { @@ -292,7 +326,7 @@ export async function analyzeBackgroundImages( lines, block.startLine, block.endLine, - "backgroundImage", + keyForLineSearch, ); const lineLength = lines[keyLine]?.length ?? 100; diff --git a/packages/vscode/src/frontmatter-spec.ts b/packages/vscode/src/frontmatter-spec.ts index 13e5ec0..12e0247 100644 --- a/packages/vscode/src/frontmatter-spec.ts +++ b/packages/vscode/src/frontmatter-spec.ts @@ -184,25 +184,89 @@ export const FRONTMATTER_SPEC: Record = { description: "Enable figdeck processing for this file", }, background: { - kind: "string", - description: "Solid background color (e.g., #1a1a2e)", - pattern: COLOR_HEX_PATTERN, - patternError: "Invalid color format. Use #rgb or #rrggbb", - }, - gradient: { - kind: "string", + kind: "oneOf", description: - "Gradient background (e.g., #0d1117:0%,#1f2937:50%,#58a6ff:100%@45)", - pattern: /^#[0-9a-fA-F]{3,6}:\d+%/, - patternError: "Invalid gradient format. Use #color:0%,#color:100%[@angle]", - }, - backgroundImage: { - kind: "string", - description: "Background image path or URL", - }, - template: { - kind: "string", - description: "Figma paint style name", + "Unified background: color, gradient, image, or Figma component", + options: [ + { + kind: "string", + description: + "Auto-detected: color (#hex), gradient (#color:0%,...), image (path/URL), or Figma component URL", + }, + { + kind: "object", + description: "Explicit background configuration", + children: { + color: { + kind: "string", + description: "Solid background color", + pattern: COLOR_HEX_PATTERN, + patternError: "Invalid color format. Use #rgb or #rrggbb", + }, + gradient: { + kind: "string", + description: "Gradient (e.g., #0d1117:0%,#fff:100%@45)", + pattern: /^#[0-9a-fA-F]{3,6}:\d+%/, + patternError: + "Invalid gradient format. Use #color:0%,#color:100%[@angle]", + }, + template: { + kind: "string", + description: "Figma paint style name", + }, + image: { + kind: "string", + description: "Background image path or URL", + }, + component: { + kind: "oneOf", + description: "Figma Component/Frame as background layer", + options: [ + { + kind: "string", + description: "Figma URL with node-id", + pattern: FIGMA_URL_PATTERN, + patternError: "Must be a valid Figma URL with node-id", + }, + { + kind: "object", + description: "Component configuration", + children: { + link: { + kind: "string", + description: "Figma component/frame link", + pattern: FIGMA_URL_PATTERN, + patternError: "Must be a valid Figma URL", + }, + fit: { + kind: "string", + description: "How the component should be scaled", + values: ["cover", "contain", "stretch"], + }, + align: { + kind: "string", + description: "Position alignment", + values: [ + "center", + "top-left", + "top-right", + "bottom-left", + "bottom-right", + ], + }, + opacity: { + kind: "number", + description: "Opacity (0-1)", + min: 0, + max: 1, + }, + }, + }, + ], + }, + }, + }, + ], }, color: { kind: "string",