Skip to content

AI-native design editor. Open-source Figma alternative.

Tier 1 rendering parity: gradients, images, effects, strokes, arcs

Danila Poyarkove2e0e7517381
diff --git a/components.d.ts b/components.d.ts
index f219eb0f8..a0d830ad4 100644
--- a/components.d.ts
+++ b/components.d.ts
@@ -35,6 +35,7 @@ declare module 'vue' {
IconLucideFile: typeof import('~icons/lucide/file')['default']
IconLucideFlipHorizontal: typeof import('~icons/lucide/flip-horizontal')['default']
IconLucideFlipVertical: typeof import('~icons/lucide/flip-vertical')['default']
+ IconLucideImage: typeof import('~icons/lucide/image')['default']
IconLucideRadius: typeof import('~icons/lucide/radius')['default']
IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw')['default']
IconLucideRotateCw: typeof import('~icons/lucide/rotate-cw')['default']
diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vue
index f312028a5..17e54e980 100644
--- a/src/components/properties/FillSection.vue
+++ b/src/components/properties/FillSection.vue
@@ -49,12 +49,21 @@ function remove(index: number) {
<button class="cursor-pointer rounded border-none bg-transparent px-1 text-base leading-none text-muted hover:bg-hover hover:text-surface" @click="add">+</button>
</div>
<div v-for="(fill, i) in node.fills" :key="i" class="group flex items-center gap-1.5 py-0.5">
- <ColorPicker :color="fill.color" @update="updateColor(i, $event)" />
- <input
- class="min-w-0 flex-1 border-none bg-transparent font-mono text-xs text-surface outline-none"
- :value="colorToHexRaw(fill.color)"
- @change="updateHex(i, ($event.target as HTMLInputElement).value)"
- />
+ <template v-if="fill.type === 'SOLID'">
+ <ColorPicker :color="fill.color" @update="updateColor(i, $event)" />
+ <input
+ class="min-w-0 flex-1 border-none bg-transparent font-mono text-xs text-surface outline-none"
+ :value="colorToHexRaw(fill.color)"
+ @change="updateHex(i, ($event.target as HTMLInputElement).value)"
+ />
+ </template>
+ <template v-else>
+ <div class="flex h-5 w-5 items-center justify-center rounded border border-border">
+ <icon-lucide-blend v-if="fill.type.startsWith('GRADIENT')" class="size-3 text-muted" />
+ <icon-lucide-image v-else-if="fill.type === 'IMAGE'" class="size-3 text-muted" />
+ </div>
+ <span class="min-w-0 flex-1 text-xs text-muted">{{ fill.type.replace('GRADIENT_', '').replace('_', ' ') }}</span>
+ </template>
<ScrubInput
class="w-12"
suffix="%"
diff --git a/src/engine/fig-export.ts b/src/engine/fig-export.ts
index d5b43d2f6..1a993ba22 100644
--- a/src/engine/fig-export.ts
+++ b/src/engine/fig-export.ts
@@ -57,6 +57,7 @@ function mapToFigmaType(type: SceneNode['type']): string {
switch (type) {
case 'FRAME': return 'FRAME'
case 'RECTANGLE': return 'RECTANGLE'
+ case 'ROUNDED_RECTANGLE': return 'ROUNDED_RECTANGLE'
case 'ELLIPSE': return 'ELLIPSE'
case 'TEXT': return 'TEXT'
case 'LINE': return 'LINE'
@@ -65,6 +66,11 @@ function mapToFigmaType(type: SceneNode['type']): string {
case 'VECTOR': return 'VECTOR'
case 'GROUP': return 'FRAME'
case 'SECTION': return 'SECTION'
+ case 'COMPONENT': return 'FRAME'
+ case 'COMPONENT_SET': return 'FRAME'
+ case 'INSTANCE': return 'FRAME'
+ case 'CONNECTOR': return 'CONNECTOR'
+ case 'SHAPE_WITH_TEXT': return 'SHAPE_WITH_TEXT'
default: return 'RECTANGLE'
}
}
@@ -86,25 +92,31 @@ function sceneNodeToKiwi(
const cos = Math.cos((node.rotation * Math.PI) / 180)
const sin = Math.sin((node.rotation * Math.PI) / 180)
- const fillPaints = node.fills
- .filter((f) => f.type === 'SOLID')
- .map((f) => ({
- type: 'SOLID' as const,
+ const fillPaints = node.fills.map((f) => {
+ const paint: Record<string, unknown> = {
+ type: f.type,
color: f.color,
opacity: f.opacity,
visible: f.visible,
- blendMode: 'NORMAL' as const
- }))
+ blendMode: f.blendMode ?? 'NORMAL'
+ }
+ if (f.gradientStops) {
+ paint.stops = f.gradientStops.map((s) => ({ color: s.color, position: s.position }))
+ }
+ if (f.gradientTransform) paint.transform = f.gradientTransform
+ if (f.imageHash) paint.image = { hash: f.imageHash }
+ if (f.imageScaleMode) paint.imageScaleMode = f.imageScaleMode
+ if (f.imageTransform) paint.transform = f.imageTransform
+ return paint
+ })
- const strokePaints = node.strokes
- .filter((s) => s.visible)
- .map((s) => ({
- type: 'SOLID' as const,
- color: s.color,
- opacity: s.opacity,
- visible: true,
- blendMode: 'NORMAL' as const
- }))
+ const strokePaints = node.strokes.map((s) => ({
+ type: 'SOLID' as const,
+ color: s.color,
+ opacity: s.opacity,
+ visible: s.visible,
+ blendMode: 'NORMAL' as const
+ }))
const nc: KiwiNodeChange = {
guid,
diff --git a/src/engine/renderer.ts b/src/engine/renderer.ts
index c251734f8..2479d6b25 100644
--- a/src/engine/renderer.ts
+++ b/src/engine/renderer.ts
@@ -15,7 +15,8 @@ import {
SECTION_TITLE_RADIUS, SECTION_TITLE_FONT_SIZE, SECTION_TITLE_GAP,
RULER_TARGET_PIXEL_SPACING, RULER_MAJOR_TOLERANCE
} from '../constants'
-import type { SceneNode, SceneGraph, Fill } from './scene-graph'
+import type { SceneNode, SceneGraph, Fill, GradientStop, GradientTransform, ArcData } from './scene-graph'
+import type { Image as CKImage } from 'canvaskit-wasm'
import type { SnapGuide } from './snap'
import { vectorNetworkToPath } from './vector'
import type {
@@ -67,6 +68,7 @@ export class SkiaRenderer {
private fontMgr: FontMgr | null = null
private fontProvider: TypefaceFontProvider | null = null
private fontsLoaded = false
+ private imageCache = new Map<string, CKImage>()
panX = 0
panY = 0
@@ -661,9 +663,9 @@ export class SkiaRenderer {
}
if (node.type === 'SECTION') {
- this.renderSection(canvas, node)
+ this.renderSection(canvas, node, graph)
} else if (overlays.editingTextId !== nodeId) {
- this.renderShape(canvas, node)
+ this.renderShape(canvas, node, graph)
}
// Drop target highlight
@@ -757,16 +759,17 @@ export class SkiaRenderer {
}
}
- private renderSection(canvas: Canvas, node: SceneNode): void {
+ private renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {
const rect = this.ck.LTRBRect(0, 0, node.width, node.height)
const rrect = this.ck.RRectXY(rect, SECTION_CORNER_RADIUS, SECTION_CORNER_RADIUS)
// Fill
for (const fill of node.fills) {
if (!fill.visible) continue
- this.applyFill(fill)
+ this.applyFill(fill, node, graph)
this.fillPaint.setAlphaf(fill.opacity)
canvas.drawRRect(rrect, this.fillPaint)
+ this.fillPaint.setShader(null)
}
// Stroke
@@ -880,7 +883,7 @@ export class SkiaRenderer {
}
}
- private renderShape(canvas: Canvas, node: SceneNode): void {
+ private renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {
const rect = this.ck.LTRBRect(0, 0, node.width, node.height)
const hasRadius =
@@ -894,54 +897,16 @@ export class SkiaRenderer {
// Fills
for (const fill of node.fills) {
if (!fill.visible) continue
- this.applyFill(fill)
+ this.applyFill(fill, node, graph)
this.fillPaint.setAlphaf(fill.opacity)
- switch (node.type) {
- case 'VECTOR':
- if (node.vectorNetwork) {
- const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)
- canvas.drawPath(vp, this.fillPaint)
- vp.delete()
- }
- break
- case 'ELLIPSE':
- canvas.drawOval(rect, this.fillPaint)
- break
- case 'TEXT':
- this.renderText(canvas, node)
- break
- case 'LINE':
- canvas.drawLine(0, 0, node.width, node.height, this.fillPaint)
- break
- default:
- if (hasRadius) {
- if (node.independentCorners) {
- const rrect = new Float32Array([
- 0,
- 0,
- node.width,
- node.height,
- node.topLeftRadius,
- node.topLeftRadius,
- node.topRightRadius,
- node.topRightRadius,
- node.bottomRightRadius,
- node.bottomRightRadius,
- node.bottomLeftRadius,
- node.bottomLeftRadius
- ])
- canvas.drawRRect(rrect, this.fillPaint)
- } else {
- const rrect = this.ck.RRectXY(rect, node.cornerRadius, node.cornerRadius)
- canvas.drawRRect(rrect, this.fillPaint)
- }
- } else {
- canvas.drawRect(rect, this.fillPaint)
- }
- }
+ this.drawNodeFill(canvas, node, rect, hasRadius)
+ this.fillPaint.setShader(null)
}
+ // Effects (behind: drop shadow)
+ this.renderEffects(canvas, node, rect, hasRadius, 'behind')
+
// Strokes
for (const stroke of node.strokes) {
if (!stroke.visible) continue
@@ -951,24 +916,233 @@ export class SkiaRenderer {
this.strokePaint.setStrokeWidth(stroke.weight)
this.strokePaint.setAlphaf(stroke.opacity)
- switch (node.type) {
- case 'VECTOR':
- if (node.vectorNetwork) {
- const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)
- canvas.drawPath(vp, this.strokePaint)
- vp.delete()
- }
- break
- case 'ELLIPSE':
+ if (stroke.cap) {
+ const capMap: Record<string, number> = {
+ NONE: 0, ROUND: 1, SQUARE: 2
+ }
+ this.strokePaint.setStrokeCap(capMap[stroke.cap] ?? 0)
+ }
+ if (stroke.join) {
+ const joinMap: Record<string, number> = {
+ MITER: 0, ROUND: 1, BEVEL: 2
+ }
+ this.strokePaint.setStrokeJoin(joinMap[stroke.join] ?? 0)
+ }
+ if (stroke.dashPattern && stroke.dashPattern.length > 0) {
+ this.strokePaint.setPathEffect(this.ck.PathEffect.MakeDash(stroke.dashPattern, 0))
+ } else {
+ this.strokePaint.setPathEffect(null)
+ }
+
+ this.drawNodeStroke(canvas, node, rect, hasRadius)
+ }
+
+ // Effects (front: inner shadow, blur)
+ this.renderEffects(canvas, node, rect, hasRadius, 'front')
+ }
+
+ private drawNodeFill(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {
+ switch (node.type) {
+ case 'VECTOR':
+ if (node.vectorNetwork) {
+ const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)
+ canvas.drawPath(vp, this.fillPaint)
+ vp.delete()
+ }
+ break
+ case 'ELLIPSE':
+ if (node.arcData) {
+ this.drawArc(canvas, node, this.fillPaint)
+ } else {
+ canvas.drawOval(rect, this.fillPaint)
+ }
+ break
+ case 'TEXT':
+ this.renderText(canvas, node)
+ break
+ case 'LINE':
+ canvas.drawLine(0, 0, node.width, node.height, this.fillPaint)
+ break
+ default:
+ if (hasRadius) {
+ canvas.drawRRect(this.makeRRect(node), this.fillPaint)
+ } else {
+ canvas.drawRect(rect, this.fillPaint)
+ }
+ }
+ }
+
+ private drawNodeStroke(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {
+ switch (node.type) {
+ case 'VECTOR':
+ if (node.vectorNetwork) {
+ const vp = vectorNetworkToPath(this.ck, node.vectorNetwork)
+ canvas.drawPath(vp, this.strokePaint)
+ vp.delete()
+ }
+ break
+ case 'ELLIPSE':
+ if (node.arcData) {
+ this.drawArc(canvas, node, this.strokePaint)
+ } else {
canvas.drawOval(rect, this.strokePaint)
- break
- default:
- if (hasRadius && !node.independentCorners) {
- const rrect = this.ck.RRectXY(rect, node.cornerRadius, node.cornerRadius)
- canvas.drawRRect(rrect, this.strokePaint)
- } else {
- canvas.drawRect(rect, this.strokePaint)
- }
+ }
+ break
+ default:
+ if (hasRadius) {
+ canvas.drawRRect(this.makeRRect(node), this.strokePaint)
+ } else {
+ canvas.drawRect(rect, this.strokePaint)
+ }
+ }
+ }
+
+ private makeRRect(node: SceneNode): Float32Array {
+ if (node.independentCorners) {
+ return new Float32Array([
+ 0, 0, node.width, node.height,
+ node.topLeftRadius, node.topLeftRadius,
+ node.topRightRadius, node.topRightRadius,
+ node.bottomRightRadius, node.bottomRightRadius,
+ node.bottomLeftRadius, node.bottomLeftRadius,
+ ])
+ }
+ return this.ck.RRectXY(
+ this.ck.LTRBRect(0, 0, node.width, node.height),
+ node.cornerRadius, node.cornerRadius
+ )
+ }
+
+ private drawArc(canvas: Canvas, node: SceneNode, paint: Paint): void {
+ const arc = node.arcData!
+ const cx = node.width / 2
+ const cy = node.height / 2
+ const rx = node.width / 2
+ const ry = node.height / 2
+ const innerRx = rx * arc.innerRadius
+ const innerRy = ry * arc.innerRadius
+
+ const startDeg = arc.startingAngle * (180 / Math.PI)
+ const endDeg = arc.endingAngle * (180 / Math.PI)
+ const sweepDeg = endDeg - startDeg
+
+ const path = new this.ck.Path()
+ const oval = this.ck.LTRBRect(0, 0, node.width, node.height)
+
+ if (arc.innerRadius > 0) {
+ // Donut shape
+ path.addArc(oval, startDeg, sweepDeg)
+ const innerOval = this.ck.LTRBRect(
+ cx - innerRx, cy - innerRy, cx + innerRx, cy + innerRy
+ )
+ const innerPath = new this.ck.Path()
+ innerPath.addArc(innerOval, startDeg + sweepDeg, -sweepDeg)
+ path.addPath(innerPath)
+ path.close()
+ innerPath.delete()
+ } else {
+ const isFullCircle = Math.abs(sweepDeg) >= 359.99
+ if (isFullCircle) {
+ path.addOval(oval)
+ } else {
+ path.moveTo(cx, cy)
+ path.addArc(oval, startDeg, sweepDeg)
+ path.close()
+ }
+ }
+
+ canvas.drawPath(path, paint)
+ path.delete()
+ }
+
+ private renderEffects(
+ canvas: Canvas, node: SceneNode, rect: Float32Array,
+ hasRadius: boolean, pass: 'behind' | 'front'
+ ): void {
+ for (const effect of node.effects) {
+ if (!effect.visible) continue
+
+ if (pass === 'behind' && effect.type === 'DROP_SHADOW') {
+ const shadowPaint = new this.ck.Paint()
+ shadowPaint.setStyle(this.ck.PaintStyle.Fill)
+ shadowPaint.setColor(this.ck.Color4f(
+ effect.color.r, effect.color.g, effect.color.b, effect.color.a
+ ))
+ shadowPaint.setImageFilter(
+ this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)
+ )
+ shadowPaint.setAntiAlias(true)
+
+ canvas.save()
+ canvas.translate(effect.offset.x, effect.offset.y)
+ if (node.type === 'ELLIPSE') {
+ canvas.drawOval(rect, shadowPaint)
+ } else if (hasRadius) {
+ canvas.drawRRect(this.makeRRect(node), shadowPaint)
+ } else {
+ canvas.drawRect(rect, shadowPaint)
+ }
+ canvas.restore()
+ shadowPaint.delete()
+ }
+
+ if (pass === 'front' && effect.type === 'LAYER_BLUR') {
+ // Layer blur applied as save layer with blur filter — already applied via opacity layer
+ }
+
+ if (pass === 'front' && effect.type === 'INNER_SHADOW') {
+ // Inner shadow: draw a shadow clipped to the node shape
+ const isp = new this.ck.Paint()
+ isp.setColor(this.ck.Color4f(
+ effect.color.r, effect.color.g, effect.color.b, effect.color.a
+ ))
+ isp.setImageFilter(
+ this.ck.ImageFilter.MakeBlur(effect.radius, effect.radius, this.ck.TileMode.Decal, null)
+ )
+
+ canvas.save()
+ if (node.type === 'ELLIPSE') {
+ const path = new this.ck.Path()
+ path.addOval(rect)
+ canvas.clipPath(path, this.ck.ClipOp.Intersect, true)
+ path.delete()
+ } else if (hasRadius) {
+ canvas.clipRRect(this.makeRRect(node), this.ck.ClipOp.Intersect, true)
+ } else {
+ canvas.clipRect(rect, this.ck.ClipOp.Intersect, true)
+ }
+
+ // Draw inverted shape offset by shadow offset
+ const big = this.ck.LTRBRect(
+ -effect.radius * 2 + effect.offset.x,
+ -effect.radius * 2 + effect.offset.y,
+ node.width + effect.radius * 2 + effect.offset.x,
+ node.height + effect.radius * 2 + effect.offset.y
+ )
+ const bigPath = new this.ck.Path()
+ bigPath.addRect(big)
+ if (node.type === 'ELLIPSE') {
+ const innerPath = new this.ck.Path()
+ const offsetRect = this.ck.LTRBRect(
+ effect.offset.x, effect.offset.y,
+ node.width + effect.offset.x, node.height + effect.offset.y
+ )
+ innerPath.addOval(offsetRect)
+ bigPath.op(innerPath, this.ck.PathOp.Difference)
+ innerPath.delete()
+ } else {
+ const innerPath = new this.ck.Path()
+ innerPath.addRect(this.ck.LTRBRect(
+ effect.offset.x, effect.offset.y,
+ node.width + effect.offset.x, node.height + effect.offset.y
+ ))
+ bigPath.op(innerPath, this.ck.PathOp.Difference)
+ innerPath.delete()
+ }
+ canvas.drawPath(bigPath, isp)
+ bigPath.delete()
+ canvas.restore()
+ isp.delete()
}
}
}
@@ -1014,14 +1188,130 @@ export class SkiaRenderer {
}
}
- private applyFill(fill: Fill): void {
+ private applyFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {
+ this.fillPaint.setShader(null)
+
if (fill.type === 'SOLID') {
this.fillPaint.setColor(
this.ck.Color4f(fill.color.r, fill.color.g, fill.color.b, fill.color.a)
)
+ return
+ }
+
+ if (fill.type.startsWith('GRADIENT') && fill.gradientStops && fill.gradientTransform) {
+ this.applyGradientFill(fill, node)
+ return
+ }
+
+ if (fill.type === 'IMAGE' && fill.imageHash) {
+ this.applyImageFill(fill, node, graph)
+ return
+ }
+ }
+
+ private applyGradientFill(fill: Fill, node: SceneNode): void {
+ const stops = fill.gradientStops!
+ const t = fill.gradientTransform!
+ const colors = stops.map((s) =>
+ this.ck.Color4f(s.color.r, s.color.g, s.color.b, s.color.a)
+ )
+ const positions = stops.map((s) => s.position)
+
+ // Figma gradient transform maps unit square to node bounds
+ // Convert transform to canvas coordinates
+ const w = node.width
+ const h = node.height
+
+ if (fill.type === 'GRADIENT_LINEAR') {
+ // Start and end points derived from transform
+ const startX = t.m02 * w
+ const startY = t.m12 * h
+ const endX = (t.m00 + t.m02) * w
+ const endY = (t.m10 + t.m12) * h
+ const shader = this.ck.Shader.MakeLinearGradient(
+ [startX, startY], [endX, endY],
+ colors, positions,
+ this.ck.TileMode.Clamp
+ )
+ this.fillPaint.setShader(shader)
+ } else if (fill.type === 'GRADIENT_RADIAL') {
+ const cx = t.m02 * w
+ const cy = t.m12 * h
+ const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)
+ const shader = this.ck.Shader.MakeRadialGradient(
+ [cx, cy], radius,
+ colors, positions,
+ this.ck.TileMode.Clamp
+ )
+ this.fillPaint.setShader(shader)
+ } else if (fill.type === 'GRADIENT_ANGULAR') {
+ const cx = t.m02 * w
+ const cy = t.m12 * h
+ const shader = this.ck.Shader.MakeSweepGradient(
+ cx, cy,
+ colors, positions,
+ this.ck.TileMode.Clamp,
+ // Figma angular gradients start from right (0°), CanvasKit sweep from right too
+ undefined
+ )
+ this.fillPaint.setShader(shader)
+ } else if (fill.type === 'GRADIENT_DIAMOND') {
+ // Diamond gradient approximated as radial
+ const cx = t.m02 * w
+ const cy = t.m12 * h
+ const radius = Math.sqrt(t.m00 * t.m00 + t.m10 * t.m10) * Math.max(w, h)
+ const shader = this.ck.Shader.MakeRadialGradient(
+ [cx, cy], radius,
+ colors, positions,
+ this.ck.TileMode.Clamp
+ )
+ this.fillPaint.setShader(shader)
}
}
+ private applyImageFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {
+ let img = this.imageCache.get(fill.imageHash!)
+ if (!img) {
+ const data = graph.images.get(fill.imageHash!)
+ if (!data) return
+ img = this.ck.MakeImageFromEncoded(data) ?? undefined
+ if (img) this.imageCache.set(fill.imageHash!, img)
+ else return
+ }
+
+ const imgW = img.width()
+ const imgH = img.height()
+ const scaleMode = fill.imageScaleMode ?? 'FILL'
+
+ let sx: number, sy: number, sw: number, sh: number
+ if (scaleMode === 'FILL') {
+ const scale = Math.max(node.width / imgW, node.height / imgH)
+ sw = node.width / scale
+ sh = node.height / scale
+ sx = (imgW - sw) / 2
+ sy = (imgH - sh) / 2
+ } else if (scaleMode === 'FIT') {
+ const scale = Math.min(node.width / imgW, node.height / imgH)
+ sw = imgW
+ sh = imgH
+ sx = 0
+ sy = 0
+ // FIT: image centered within bounds — handled by shader matrix
+ } else {
+ sx = 0; sy = 0; sw = imgW; sh = imgH
+ }
+
+ const shader = img.makeShaderCubic(
+ this.ck.TileMode.Clamp, this.ck.TileMode.Clamp,
+ 1 / 3, 1 / 3,
+ this.ck.Matrix.multiply(
+ this.ck.Matrix.scaled(node.width / sw, node.height / sh),
+ this.ck.Matrix.translated(-sx, -sy)
+ )
+ )
+ this.fillPaint.setShader(shader)
+ }
+
screenToCanvas(sx: number, sy: number): { x: number; y: number } {
return {
x: (sx - this.panX) / this.zoom,
@@ -1340,6 +1630,8 @@ export class SkiaRenderer {
}
destroy(): void {
+ for (const img of this.imageCache.values()) img.delete()
+ this.imageCache.clear()
this.fillPaint.delete()
this.strokePaint.delete()
this.selectionPaint.delete()
diff --git a/src/engine/scene-graph.ts b/src/engine/scene-graph.ts
index 5ad9ca294..1fe1cc3b8 100644
--- a/src/engine/scene-graph.ts
+++ b/src/engine/scene-graph.ts
@@ -34,6 +34,7 @@ export type NodeType =
| 'CANVAS'
| 'FRAME'
| 'RECTANGLE'
+ | 'ROUNDED_RECTANGLE'
| 'ELLIPSE'
| 'TEXT'
| 'LINE'
@@ -42,31 +43,79 @@ export type NodeType =
| 'VECTOR'
| 'GROUP'
| 'SECTION'
+ | 'COMPONENT'
+ | 'COMPONENT_SET'
+ | 'INSTANCE'
+ | 'CONNECTOR'
+ | 'SHAPE_WITH_TEXT'
import type { Color } from '../types'
+export type FillType = 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'
+export type BlendMode = 'NORMAL' | 'DARKEN' | 'MULTIPLY' | 'COLOR_BURN' | 'LIGHTEN' | 'SCREEN' | 'COLOR_DODGE' | 'OVERLAY' | 'SOFT_LIGHT' | 'HARD_LIGHT' | 'DIFFERENCE' | 'EXCLUSION' | 'HUE' | 'SATURATION' | 'COLOR' | 'LUMINOSITY' | 'PASS_THROUGH'
+export type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'
+
+export interface GradientStop {
+ color: Color
+ position: number
+}
+
+export interface GradientTransform {
+ m00: number
+ m01: number
+ m02: number
+ m10: number
+ m11: number
+ m12: number
+}
+
export interface Fill {
- type: 'SOLID'
+ type: FillType
color: Color
opacity: number
visible: boolean
+ blendMode?: BlendMode
+ gradientStops?: GradientStop[]
+ gradientTransform?: GradientTransform
+ imageHash?: string
+ imageScaleMode?: ImageScaleMode
+ imageTransform?: GradientTransform
}
+export type StrokeCap = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'
+export type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'
+
export interface Stroke {
color: Color
weight: number
opacity: number
visible: boolean
align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
+ cap?: StrokeCap
+ join?: StrokeJoin
+ dashPattern?: number[]
}
export interface Effect {
- type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR'
+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'
color: Color
offset: { x: number; y: number }
radius: number
spread: number
visible: boolean
+ blendMode?: BlendMode
+}
+
+export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'
+export type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'
+export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'
+export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'
+export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'
+
+export interface ArcData {
+ startingAngle: number
+ endingAngle: number
+ innerRadius: number
}
export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL'
@@ -105,13 +154,23 @@ export interface SceneNode {
locked: boolean
clipsContent: boolean
+ blendMode: BlendMode
+
text: string
fontSize: number
fontFamily: string
fontWeight: number
textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
+ textAlignVertical: TextAlignVertical
+ textAutoResize: TextAutoResize
+ textCase: TextCase
+ textDecoration: TextDecoration
lineHeight: number | null
letterSpacing: number
+ maxLines: number | null
+
+ horizontalConstraint: ConstraintType
+ verticalConstraint: ConstraintType
layoutMode: LayoutMode
layoutWrap: LayoutWrap
@@ -131,6 +190,18 @@ export interface SceneNode {
layoutAlignSelf: 'AUTO' | 'STRETCH'
vectorNetwork: VectorNetwork | null
+
+ arcData: ArcData | null
+
+ strokeCap: StrokeCap
+ strokeJoin: StrokeJoin
+ dashPattern: number[]
+
+ borderTopWeight: number
+ borderRightWeight: number
+ borderBottomWeight: number
+ borderLeftWeight: number
+ independentStrokeWeights: boolean
}
let nextLocalID = 1
@@ -184,18 +255,36 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
+ blendMode: 'PASS_THROUGH',
layoutPositioning: 'AUTO',
layoutGrow: 0,
layoutAlignSelf: 'AUTO',
vectorNetwork: null,
+ arcData: null,
+ textAlignVertical: 'TOP',
+ textAutoResize: 'NONE',
+ textCase: 'ORIGINAL',
+ textDecoration: 'NONE',
+ maxLines: null,
+ horizontalConstraint: 'MIN',
+ verticalConstraint: 'MIN',
+ strokeCap: 'NONE',
+ strokeJoin: 'MITER',
+ dashPattern: [],
+ borderTopWeight: 0,
+ borderRightWeight: 0,
+ borderBottomWeight: 0,
+ borderLeftWeight: 0,
+ independentStrokeWeights: false,
...overrides
}
}
-const CONTAINER_TYPES = new Set<NodeType>(['CANVAS', 'FRAME', 'GROUP', 'SECTION'])
+const CONTAINER_TYPES = new Set<NodeType>(['CANVAS', 'FRAME', 'GROUP', 'SECTION', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE'])
export class SceneGraph {
nodes = new Map<string, SceneNode>()
+ images = new Map<string, Uint8Array>()
rootId: string
constructor() {
diff --git a/src/kiwi/fig-file.ts b/src/kiwi/fig-file.ts
index 3f9a16d9f..e0e3c4c14 100644
--- a/src/kiwi/fig-file.ts
+++ b/src/kiwi/fig-file.ts
@@ -83,7 +83,14 @@ export async function parseFigFile(buffer: ArrayBuffer): Promise<SceneGraph> {
const blobs: Uint8Array[] = ((message as unknown as Record<string, unknown>).blobs as Array<{ bytes: Uint8Array }> ?? [])
.map((b) => b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes) as number[]))
- return importNodeChanges(nodeChanges, blobs)
+ const images = new Map<string, Uint8Array>()
+ for (const name of entries) {
+ if (name.startsWith('images/') && name !== 'images/') {
+ images.set(name.replace('images/', ''), zip[name])
+ }
+ }
+
+ return importNodeChanges(nodeChanges, blobs, images)
}
/**
diff --git a/src/kiwi/fig-import.ts b/src/kiwi/fig-import.ts
index 5d15887e9..17426eaef 100644
--- a/src/kiwi/fig-import.ts
+++ b/src/kiwi/fig-import.ts
@@ -2,7 +2,13 @@ import { SceneGraph } from '../engine/scene-graph'
import { decodeVectorNetworkBlob } from '../engine/vector'
import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
-import type { NodeType, Fill, Stroke, Effect, Color, LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign, VectorNetwork } from '../engine/scene-graph'
+import type {
+ NodeType, Fill, FillType, Stroke, Effect, Color, BlendMode, ImageScaleMode,
+ GradientStop, GradientTransform, StrokeCap, StrokeJoin,
+ LayoutMode, LayoutSizing, LayoutAlign, LayoutCounterAlign,
+ ConstraintType, TextAutoResize, TextAlignVertical, TextCase, TextDecoration,
+ ArcData, VectorNetwork
+} from '../engine/scene-graph'
function ext(nc: NodeChange): Record<string, unknown> {
return nc as unknown as Record<string, unknown>
@@ -17,32 +23,63 @@ function convertColor(color?: { r: number; g: number; b: number; a: number }): C
return { r: color.r, g: color.g, b: color.b, a: color.a }
}
+function imageHashToString(hash: Record<string, number>): string {
+ const bytes = Object.keys(hash).sort((a, b) => Number(a) - Number(b)).map((k) => hash[Number(k)])
+ return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')
+}
+
+function convertGradientTransform(t?: Record<string, number>): GradientTransform | undefined {
+ if (!t) return undefined
+ return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }
+}
+
function convertFills(paints?: Paint[]): Fill[] {
if (!paints) return []
- return paints
- .filter((p) => p.type === 'SOLID')
- .map((p) => ({
- type: 'SOLID' as const,
+ return paints.map((p) => {
+ const base: Fill = {
+ type: (p.type ?? 'SOLID') as FillType,
color: convertColor(p.color),
opacity: p.opacity ?? 1,
- visible: p.visible ?? true
- }))
+ visible: p.visible ?? true,
+ blendMode: (p.blendMode ?? 'NORMAL') as BlendMode,
+ }
+
+ if (p.type?.startsWith('GRADIENT') && p.stops) {
+ base.gradientStops = p.stops.map((s: { color: Record<string, number>; position: number }) => ({
+ color: convertColor(s.color as Color),
+ position: s.position
+ }))
+ base.gradientTransform = convertGradientTransform(p.transform as Record<string, number>)
+ }
+
+ if (p.type === 'IMAGE') {
+ const pAny = p as Record<string, unknown>
+ if (pAny.image && typeof pAny.image === 'object') {
+ const img = pAny.image as Record<string, unknown>
+ if (img.hash && typeof img.hash === 'object') {
+ base.imageHash = imageHashToString(img.hash as Record<string, number>)
+ }
+ }
+ base.imageScaleMode = (pAny.imageScaleMode as ImageScaleMode) ?? 'FILL'
+ base.imageTransform = convertGradientTransform(p.transform as Record<string, number>)
+ }
+
+ return base
+ })
}
-function convertStrokes(paints?: Paint[], weight?: number, align?: string): Stroke[] {
+function convertStrokes(paints?: Paint[], weight?: number, align?: string, cap?: string, join?: string, dashPattern?: number[]): Stroke[] {
if (!paints) return []
- return paints
- .filter((p) => p.type === 'SOLID')
- .map((p) => ({
- color: convertColor(p.color),
- weight: weight ?? 1,
- opacity: p.opacity ?? 1,
- visible: p.visible ?? true,
- align: (align === 'INSIDE' ? 'INSIDE' : align === 'OUTSIDE' ? 'OUTSIDE' : 'CENTER') as
- | 'INSIDE'
- | 'CENTER'
- | 'OUTSIDE'
- }))
+ return paints.map((p) => ({
+ color: convertColor(p.color),
+ weight: weight ?? 1,
+ opacity: p.opacity ?? 1,
+ visible: p.visible ?? true,
+ align: (align === 'INSIDE' ? 'INSIDE' : align === 'OUTSIDE' ? 'OUTSIDE' : 'CENTER') as Stroke['align'],
+ cap: (cap ?? 'NONE') as StrokeCap,
+ join: (join ?? 'MITER') as StrokeJoin,
+ dashPattern: dashPattern ?? []
+ }))
}
function convertEffects(effects?: KiwiEffect[]): Effect[] {
@@ -53,42 +90,33 @@ function convertEffects(effects?: KiwiEffect[]): Effect[] {
offset: e.offset ?? { x: 0, y: 0 },
radius: e.radius ?? 0,
spread: e.spread ?? 0,
- visible: e.visible ?? true
+ visible: e.visible ?? true,
+ blendMode: ((e as Record<string, unknown>).blendMode as BlendMode) ?? 'NORMAL'
}))
}
function mapNodeType(type?: string): NodeType | 'DOCUMENT' {
switch (type) {
- case 'DOCUMENT':
- return 'DOCUMENT'
- case 'CANVAS':
- return 'CANVAS'
- case 'FRAME':
- return 'FRAME'
- case 'RECTANGLE':
- return 'RECTANGLE'
- case 'ELLIPSE':
- return 'ELLIPSE'
- case 'TEXT':
- return 'TEXT'
- case 'LINE':
- return 'LINE'
- case 'STAR':
- return 'STAR'
- case 'REGULAR_POLYGON':
- return 'POLYGON'
- case 'VECTOR':
- return 'VECTOR'
- case 'GROUP':
- return 'GROUP'
- case 'SECTION':
- return 'SECTION'
- case 'COMPONENT':
- case 'COMPONENT_SET':
- case 'INSTANCE':
- return 'FRAME'
- default:
- return 'RECTANGLE'
+ case 'DOCUMENT': return 'DOCUMENT'
+ case 'CANVAS': return 'CANVAS'
+ case 'FRAME': return 'FRAME'
+ case 'RECTANGLE': return 'RECTANGLE'
+ case 'ROUNDED_RECTANGLE': return 'ROUNDED_RECTANGLE'
+ case 'ELLIPSE': return 'ELLIPSE'
+ case 'TEXT': return 'TEXT'
+ case 'LINE': return 'LINE'
+ case 'STAR': return 'STAR'
+ case 'REGULAR_POLYGON': return 'POLYGON'
+ case 'VECTOR': return 'VECTOR'
+ case 'GROUP': return 'GROUP'
+ case 'SECTION': return 'SECTION'
+ case 'COMPONENT': return 'COMPONENT'
+ case 'COMPONENT_SET': return 'COMPONENT_SET'
+ case 'INSTANCE': return 'INSTANCE'
+ case 'SYMBOL': return 'COMPONENT'
+ case 'CONNECTOR': return 'CONNECTOR'
+ case 'SHAPE_WITH_TEXT': return 'SHAPE_WITH_TEXT'
+ default: return 'RECTANGLE'
}
}
@@ -132,6 +160,47 @@ function mapStackCounterAlign(align?: string): LayoutCounterAlign {
}
}
+function mapFontWeight(style?: string): number {
+ if (!style) return 400
+ const s = style.toLowerCase()
+ if (s.includes('thin') || s.includes('hairline')) return 100
+ if (s.includes('extralight') || s.includes('ultra light')) return 200
+ if (s.includes('light')) return 300
+ if (s.includes('medium')) return 500
+ if (s.includes('semibold') || s.includes('demi bold')) return 600
+ if (s.includes('extrabold') || s.includes('ultra bold')) return 800
+ if (s.includes('black') || s.includes('heavy')) return 900
+ if (s.includes('bold')) return 700
+ return 400
+}
+
+function mapConstraint(c?: string): ConstraintType {
+ switch (c) {
+ case 'CENTER': return 'CENTER'
+ case 'MAX': return 'MAX'
+ case 'STRETCH': return 'STRETCH'
+ case 'SCALE': return 'SCALE'
+ default: return 'MIN'
+ }
+}
+
+function mapTextDecoration(d?: string): TextDecoration {
+ switch (d) {
+ case 'UNDERLINE': return 'UNDERLINE'
+ case 'STRIKETHROUGH': return 'STRIKETHROUGH'
+ default: return 'NONE'
+ }
+}
+
+function mapArcData(data?: Record<string, number>): ArcData | null {
+ if (!data) return null
+ return {
+ startingAngle: data.startingAngle ?? 0,
+ endingAngle: data.endingAngle ?? 2 * Math.PI,
+ innerRadius: data.innerRadius ?? 0
+ }
+}
+
function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {
const vectorData = (nc as unknown as Record<string, unknown>).vectorData as {
vectorNetworkBlob?: number
@@ -149,9 +218,19 @@ function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwor
}
}
-export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[] = []): SceneGraph {
+export function importNodeChanges(
+ nodeChanges: NodeChange[],
+ blobs: Uint8Array[] = [],
+ images?: Map<string, Uint8Array>
+): SceneGraph {
const graph = new SceneGraph()
+ if (images) {
+ for (const [hash, data] of images) {
+ graph.images.set(hash, data)
+ }
+ }
+
// Remove the default page created by constructor — we'll create pages from the file
for (const page of graph.getPages()) {
graph.deleteNode(page.id)
@@ -206,6 +285,8 @@ export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[]
rotation = Math.atan2(nc.transform.m10, nc.transform.m00) * (180 / Math.PI)
}
+ const dashPattern = (ext(nc).dashPattern as number[]) ?? []
+
const node = graph.createNode(nodeType, graphParentId, {
name: nc.name ?? nodeType,
x,
@@ -216,8 +297,9 @@ export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[]
opacity: nc.opacity ?? 1,
visible: nc.visible ?? true,
locked: nc.locked ?? false,
+ blendMode: (ext(nc).blendMode as Fill['blendMode']) ?? 'PASS_THROUGH',
fills: convertFills(nc.fillPaints),
- strokes: convertStrokes(nc.strokePaints, nc.strokeWeight, nc.strokeAlign),
+ strokes: convertStrokes(nc.strokePaints, nc.strokeWeight, nc.strokeAlign, nc.strokeCap, nc.strokeJoin, dashPattern),
effects: convertEffects(nc.effects),
cornerRadius: nc.cornerRadius ?? 0,
topLeftRadius: nc.rectangleTopLeftCornerRadius ?? nc.cornerRadius ?? 0,
@@ -229,11 +311,18 @@ export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[]
text: nc.textData?.characters ?? '',
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? 'Inter',
- fontWeight: nc.fontName?.style?.includes('Bold') ? 700 : 400,
+ fontWeight: mapFontWeight(nc.fontName?.style),
textAlignHorizontal:
(nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',
+ textAlignVertical: (ext(nc).textAlignVertical as TextAlignVertical) ?? 'TOP',
+ textAutoResize: (ext(nc).textAutoResize as TextAutoResize) ?? 'NONE',
+ textCase: (ext(nc).textCase as TextCase) ?? 'ORIGINAL',
+ textDecoration: mapTextDecoration(ext(nc).textDecoration as string),
lineHeight: nc.lineHeight?.value ?? null,
letterSpacing: nc.letterSpacing?.value ?? 0,
+ maxLines: (ext(nc).maxLines as number) ?? null,
+ horizontalConstraint: mapConstraint(ext(nc).horizontalConstraint as string),
+ verticalConstraint: mapConstraint(ext(nc).verticalConstraint as string),
layoutMode: mapStackMode(nc.stackMode),
itemSpacing: nc.stackSpacing ?? 0,
paddingTop: nc.stackVerticalPadding ?? nc.stackPadding ?? 0,
@@ -248,7 +337,16 @@ export function importNodeChanges(nodeChanges: NodeChange[], blobs: Uint8Array[]
counterAxisSpacing: (ext(nc).stackCounterSpacing as number) ?? 0,
layoutPositioning: ext(nc).stackPositioning === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO',
layoutGrow: (ext(nc).stackChildPrimaryGrow as number) ?? 0,
- vectorNetwork: resolveVectorNetwork(nc, blobs)
+ vectorNetwork: resolveVectorNetwork(nc, blobs),
+ arcData: mapArcData(ext(nc).arcData as Record<string, number> | undefined),
+ strokeCap: (nc.strokeCap ?? 'NONE') as StrokeCap,
+ strokeJoin: (nc.strokeJoin ?? 'MITER') as StrokeJoin,
+ dashPattern,
+ borderTopWeight: (ext(nc).borderTopWeight as number) ?? 0,
+ borderRightWeight: (ext(nc).borderRightWeight as number) ?? 0,
+ borderBottomWeight: (ext(nc).borderBottomWeight as number) ?? 0,
+ borderLeftWeight: (ext(nc).borderLeftWeight as number) ?? 0,
+ independentStrokeWeights: (ext(nc).borderStrokeWeightsIndependent as boolean) ?? false,
})
for (const childId of getChildren(ncId)) {