Picasso Documentation

repository·master·Indexed 22 days ago

https://github.com/wuba/picasso

A Sketch plugin and parsing engine developed by 58.com that automatically converts Sketch design files into high-fidelity frontend code. It supports multiple target platforms including Web (HTML/SCSS), WeChat Mini Programs (WXML/WXSS), and React Native (JSX/StyleSheet). The ecosystem includes @wubafe/picasso-parse for core parsing, picasso-layout for automatic layout inference, and RestoreDSL for high-fidelity structural representation and version diffing.

Tokens
38.9K
Snippets
115
Records
157
Agent score
78%

What's inside Picasso

  1. Understand the role of picasso-layout

    master

    The picasso-layout package is responsible for the automatic layout phase of the Picasso pipeline. It operates on the grouping results produced by picasso-group to infer flex, block, and inline layouts, as well as alignment settings.

    Key responsibilities include:

    • Overlap Handling (handleOverlap): Decides between absolute and relative positioning for overlapping layers.
    • Row Layout (calculateRow / row): Infers horizontal arrangements, spacing, and alignment.
    • Block Layout (isBlock / calculateBlock): Identifies block-level elements and calculates their dimensions.
    • Text Handling: Includes special logic for when a parent node is text (handleParentIsText) and marking pure text nodes to avoid unnecessary container wrapping (markIsOnlyText).
    • Styling & Metadata: Corrects border widths (getBorderWidth) and derives layout-related class names (calculateClassName).
    • Dispatching: Distributes layout logic based on node types (handleTypeLayout/).
  2. Core principles of RestoreDSL rendering

    master

    RestoreDSL is a semantic specification for consumers (e.g., LLM prompts, deterministic renderers, diff visualizers). When consuming RestoreDSL, follow these core principles:

    • Contractual Mapping: The DSL outputs CSS-ready final values. Consumers must perform a direct "field $\rightarrow$ property" mapping. Do not implement fallback logic, inference, or type conversion; if a field is missing, it means the element does not have that property in Sketch.
    • Units: All units are in pt (defined by meta.units). For Web rendering, $1\text{pt} = 1\text{px}$ is a direct mapping.
    • Artboard Background: artboard.fills is the mandatory page background. It is always provided (defaults to white if empty), so consumers do not need to provide a fallback.
    • Omitted Defaults: Fields like visible:true, rotation:0, opacity:1, or empty arrays are omitted from the DSL to save space. Their absence implies the default value.
    • Coordinate Systems:
      • frame: Relative coordinates to the parent (use directly for CSS positioning).
      • absFrame: Absolute coordinates within the artboard tree, or local coordinates within a components[].tree.
    • Stable IDs: The id field is a stable identifier for cross-version diffing. It is recommended to use this as a unique key during rendering. For HTML consumers, use the data-dsl-id attribute to allow traceability back to the DSL node.
  3. Understand the RestoreDSL Schema and Rendering Guide

    master

    RestoreDSL (the output of picassoArtboardRestoreParse) is governed by two primary files distributed with the npm tarball. These files define the format and the rendering semantics for the DSL:

    1. restore-dsl.schema.json: The source of truth for the output format (JSON Schema draft-07). It defines required fields, enum values, and default omission conventions. Use this to answer "Is this JSON valid?".
    2. restore-dsl-rendering-guide.md: The specification for how a consumer should render a valid DSL. This is intended for server-side LLM prompts, deterministic renderers (like tools/gen_restore_html.js), and diff visualization tools. Use this to answer "How should this JSON be rendered into pixels?".
  4. Understand the role of picasso-dsl in the data flow

    master

    The picasso-dsl package serves as the type definition layer for the Picasso intermediate DSL. It describes the 'platform-agnostic component tree' that is created after Sketch JSON is parsed.

    It is important to distinguish picasso-dsl from sketch-dsl to avoid confusion in the data pipeline:

    1. sketch-dsl (Input Side): Describes the raw data structure exported by the Sketch tool. It is constrained by the Sketch file format.
    2. picasso-dsl (Intermediate State): Describes the cross-platform intermediate state after parsing but before layout/generation. This is a custom Picasso format that can evolve independently of Sketch.

    Data Flow: Sketch Raw JSON $\rightarrow$ (via sketch-dsl) $\rightarrow$ Picasso Intermediate DSL (via picasso-dsl) $\rightarrow$ Web/Mini-program/RN Code

  5. Maintain RestoreDSL schema synchronization

    master

    To ensure the renderer remains a valid baseline for comparison, the following components must be kept in sync whenever changes occur:

    1. Node.js rendering tools (in this directory)
    2. ../schema/restore-dsl.schema.json
    3. ../schema/restore-dsl-rendering-guide.md
    4. RESTORE_SCHEMA_VERSION in ../src/parseRestoreDSL/restoreTypes.ts

    Failure to synchronize these will cause the renderer to decouple from the actual data, destroying its value as a regression testing tool.

  6. Handle strokes and paths in rendering

    master

    When rendering strokes and paths:

    • Thin lines: Single-color solid lines where height or width $\le 1$ are baked into fills rectangles (using center-line semantics) by the parser. Consumers do not need special handling.
    • General stroke paths: In SVG rendering, strokes expand outward by half the thickness. Because SVG elements often default to overflow: hidden, strokes may be clipped. Ensure that <path> elements with strokes use overflow: visible to prevent clipping (e.g., a 4px stroke on a 1px viewBox will be clipped to 1px if overflow: hidden is active).
  7. Understand the role of picasso-trans

    master

    picasso-trans is a collection of transformation utilities for Picasso. It handles format and unit-level conversions across different platforms.

    Note: This package is marked as "private": true and is not published to npm independently. Its code is bundled into the dist/ directory of @wubafe/picasso-parse during compilation. It is primarily used by picasso-code-browser for generating platform-specific code and by picasso-parse as an integrated part of its distribution.

  8. Understand the Picasso project structure

    master

    The repository is divided into two main layers:

    1. Plugin Core (src/): The Sketch plugin itself (CocoaScript/JS). It is responsible for layer extraction, asset preprocessing (images, fonts, symbols), and saving the output.
    2. Parsing Engine (packages/): A TypeScript monorepo containing the logic for converting design data to code.

    Parsing Engine Packages:

    • @wubafe/picasso-parse: The single public entry point.
    • picasso-code-browser: Cross-platform code generator (private).
    • picasso-dsl: Picasso intermediate DSL types (private).
    • picasso-group: Feature grouping (private).
    • picasso-layout: Layout calculation (private).
    • picasso-trans: Conversions for colors, units, CSS order, etc. (private).
    • sketch-dsl: Sketch raw JSON type layer (private).
  9. Understand the role of sketch-dsl in the Picasso data flow

    master

    The sketch-dsl package provides the TypeScript type definitions for the raw JSON output produced by Sketch (e.g., via sketch.export(artboard, { formats: 'json' })). It defines the structural skeleton of Sketch layers and properties, serving as the formal input definition for the Picasso parsing process.

    It is important to distinguish sketch-dsl from picasso-dsl:

    • sketch-dsl: Describes the raw data structure exported directly from Sketch. It is constrained by the Sketch file format and sits at the input side (upstream) of the data flow. Typical types include SKLayer, SKColor, SKFrame, and Panel.
    • picasso-dsl: Describes the cross-platform intermediate state after Picasso has parsed the Sketch data. It is a custom Picasso format used for layout and code generation. Typical types include Component, Structure, and Style.

    Data Flow: Sketch File $\rightarrow$ Sketch Raw JSON (described by sketch-dsl) $\rightarrow$ Picasso Intermediate DSL (picasso-dsl) $\rightarrow$ Web/Mini-program/RN Code

  10. Handle components and masks in RestoreDSL rendering

    master

    When rendering components and masks from a RestoreDSL, follow these rules:

    • Component Rendering: Use the children of a SymbolInstance as the source of truth for rendering (after applying overrides). Do not read components[componentKey].tree, as that is the master definition used only for reuse analysis.
    • Masks: A mask is treated as a frame clipping approximation. Implement this using overflow: hidden on the parent container. If the parent container has a borderRadius, ensure both overflow: hidden and the corner radius are applied simultaneously.
  11. Use RestoreDSL for high-fidelity structural representation

    master

    RestoreDSL (v0.1.0) provides a high-fidelity intermediate representation that mirrors the layer tree 1:1 without layout inference. It is designed for version diffing and structural preservation.

    Recommended Workflow:

    1. Prepare three exports: exportA (original JSON), exportB (unbound Symbol copy), and mastersC (optional symbol masters).
    2. Call annotateStableIds(exportB, exportA, mastersC) to inject stable IDs and content/style hashes into the unbound tree.
    3. Consume the annotated tree using either standard picassoArtboard*Parse functions or picassoArtboardRestoreParse.

    Key RestoreDSL APIs:

    • annotateStableIds(exportB, exportA?, mastersC?): Injects stableId, contentHash, styleHash, and subtreeHash into the tree.
    • picassoArtboardRestoreParse(exportA, exportB, mastersC?, options?): Merges the three inputs to produce a structure-faithful RestoreDSL.
    • assessRestoreDiffability(prev, next): Determines if two RestoreDSL versions are same-artboard, duplicated-artboard, or unrelated for diffing strategies.
    • toRenderProfile(restore): Creates a stripped-down view for LLM prompts (reduces size by 31-44%).
    • bakeRestoreTree(node): Performs CSS-ready post-processing (e.g., handling gradients, rotations, and slices). Note: If using as a plugin, this must be called again after image URLs are filled in.