Skip to content

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

Rich text style runs with per-selection bold/italic/underline

Danila Poyarkov88bfacdc9edf
diff --git a/components.d.ts b/components.d.ts
index 983c76702..2df71cea2 100644
--- a/components.d.ts
+++ b/components.d.ts
@@ -33,6 +33,7 @@ declare module 'vue' {
IconLucideAlignVerticalJustifyStart: typeof import('~icons/lucide/align-vertical-justify-start')['default']
IconLucideBaseline: typeof import('~icons/lucide/baseline')['default']
IconLucideBlend: typeof import('~icons/lucide/blend')['default']
+ IconLucideBold: typeof import('~icons/lucide/bold')['default']
IconLucideCheck: typeof import('~icons/lucide/check')['default']
IconLucideChevronDown: typeof import('~icons/lucide/chevron-down')['default']
IconLucideChevronRight: typeof import('~icons/lucide/chevron-right')['default']
@@ -45,6 +46,7 @@ declare module 'vue' {
IconLucideFolderPlus: typeof import('~icons/lucide/folder-plus')['default']
IconLucideHash: typeof import('~icons/lucide/hash')['default']
IconLucideImage: typeof import('~icons/lucide/image')['default']
+ IconLucideItalic: typeof import('~icons/lucide/italic')['default']
IconLucideLink: typeof import('~icons/lucide/link')['default']
IconLucidePlus: typeof import('~icons/lucide/plus')['default']
IconLucideRadius: typeof import('~icons/lucide/radius')['default']
@@ -52,8 +54,10 @@ declare module 'vue' {
IconLucideRotateCw: typeof import('~icons/lucide/rotate-cw')['default']
IconLucideSearch: typeof import('~icons/lucide/search')['default']
IconLucideSettings2: typeof import('~icons/lucide/settings2')['default']
+ IconLucideStrikethrough: typeof import('~icons/lucide/strikethrough')['default']
IconLucideToggleLeft: typeof import('~icons/lucide/toggle-left')['default']
IconLucideType: typeof import('~icons/lucide/type')['default']
+ IconLucideUnderline: typeof import('~icons/lucide/underline')['default']
IconLucideUnlink: typeof import('~icons/lucide/unlink')['default']
IconLucideX: typeof import('~icons/lucide/x')['default']
LayersPanel: typeof import('./src/components/LayersPanel.vue')['default']
diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.ts
index ffa2f36a2..1a3f8df8a 100644
--- a/packages/core/src/fig-export.ts
+++ b/packages/core/src/fig-export.ts
@@ -7,7 +7,7 @@ import { renderThumbnail } from './render-image'
import { encodeVectorNetworkBlob } from './vector'
import type { SkiaRenderer } from './renderer'
-import type { SceneGraph, SceneNode } from './scene-graph'
+import type { SceneGraph, SceneNode, CharacterStyleOverride } from './scene-graph'
import type { NodeChange, Paint } from './kiwi/codec'
import type { CanvasKit } from 'canvaskit-wasm'
@@ -155,14 +155,18 @@ function sceneNodeToKiwi(
nc.fontSize = node.fontSize
nc.fontName = {
family: node.fontFamily,
- style: node.fontWeight >= 700 ? 'Bold' : 'Regular',
+ style: fontStyleLabel(node.fontWeight, node.italic),
postscript: ''
}
- nc.textData = { characters: node.text }
+ nc.textData = exportTextData(node)
nc.textAutoResize = 'WIDTH_AND_HEIGHT'
nc.textAlignHorizontal = node.textAlignHorizontal
if (node.lineHeight != null) nc.lineHeight = { value: node.lineHeight, units: 'PIXELS' }
if (node.letterSpacing !== 0) nc.letterSpacing = { value: node.letterSpacing, units: 'PIXELS' }
+ if (node.textDecoration !== 'NONE') {
+ ;(nc as Record<string, unknown>).textDecoration =
+ node.textDecoration === 'UNDERLINE' ? 'UNDERLINE' : 'STRIKETHROUGH'
+ }
}
if (node.type === 'FRAME' || node.type === 'GROUP') {
@@ -335,3 +339,67 @@ export async function exportFigFile(
'meta.json': new TextEncoder().encode(metaJson)
})
}
+
+function fontStyleLabel(weight: number, italic: boolean): string {
+ let label = 'Regular'
+ if (weight >= 900) label = 'Black'
+ else if (weight >= 800) label = 'ExtraBold'
+ else if (weight >= 700) label = 'Bold'
+ else if (weight >= 600) label = 'SemiBold'
+ else if (weight >= 500) label = 'Medium'
+ else if (weight >= 300) label = 'Light'
+ else if (weight >= 200) label = 'ExtraLight'
+ else if (weight >= 100) label = 'Thin'
+ if (italic) label += ' Italic'
+ return label
+}
+
+function exportTextData(node: SceneNode): NodeChange['textData'] {
+ const runs = node.styleRuns
+ if (runs.length === 0) {
+ return { characters: node.text }
+ }
+
+ const charIds = new Array<number>(node.text.length).fill(0)
+ const styleMap = new Map<string, { id: number; style: CharacterStyleOverride }>()
+ let nextId = 1
+
+ for (const run of runs) {
+ const key = JSON.stringify(run.style)
+ let entry = styleMap.get(key)
+ if (!entry) {
+ entry = { id: nextId++, style: run.style }
+ styleMap.set(key, entry)
+ }
+ for (let i = run.start; i < run.start + run.length && i < charIds.length; i++) {
+ charIds[i] = entry.id
+ }
+ }
+
+ const overrideTable: NodeChange[] = []
+ for (const { id, style } of styleMap.values()) {
+ const override: Record<string, unknown> = { styleID: id }
+ const weight = style.fontWeight ?? node.fontWeight
+ const italic = style.italic ?? node.italic
+ override.fontName = {
+ family: style.fontFamily ?? node.fontFamily,
+ style: fontStyleLabel(weight, italic),
+ postscript: ''
+ }
+ if (style.fontSize !== undefined) override.fontSize = style.fontSize
+ if (style.letterSpacing !== undefined) {
+ override.letterSpacing = { value: style.letterSpacing, units: 'PIXELS' }
+ }
+ if (style.lineHeight !== undefined && style.lineHeight !== null) {
+ override.lineHeight = { value: style.lineHeight, units: 'PIXELS' }
+ }
+ if (style.textDecoration) override.textDecoration = style.textDecoration
+ overrideTable.push(override as unknown as NodeChange)
+ }
+
+ return {
+ characters: node.text,
+ characterStyleIDs: charIds,
+ styleOverrideTable: overrideTable
+ }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3eeac2f19..5f69cd8e4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -43,7 +43,9 @@ export {
type VariableValue,
type Variable,
type VariableCollection,
- type VariableCollectionMode
+ type VariableCollectionMode,
+ type CharacterStyleOverride,
+ type StyleRun
} from './scene-graph'
export { SkiaRenderer, type RenderOverlays } from './renderer'
@@ -55,6 +57,13 @@ export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob,
export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'
export { UndoManager } from './undo'
export { TextEditor, type TextCaret, type TextEditorState } from './text-editor'
+export {
+ toggleBoldInRange,
+ toggleItalicInRange,
+ toggleDecorationInRange,
+ adjustRunsForInsert,
+ adjustRunsForDelete
+} from './style-runs'
export { renderNodesToImage, renderThumbnail, type ExportFormat } from './render-image'
export { exportFigFile } from './fig-export'
export {
diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.ts
index 2ae170eb6..7425790e1 100644
--- a/packages/core/src/kiwi/codec.ts
+++ b/packages/core/src/kiwi/codec.ts
@@ -260,7 +260,12 @@ export interface NodeChange {
textAlignHorizontal?: string
textAlignVertical?: string
textAutoResize?: string
- textData?: { characters: string; lines?: unknown[] }
+ textData?: {
+ characters: string
+ lines?: unknown[]
+ characterStyleIDs?: number[]
+ styleOverrideTable?: NodeChange[]
+ }
lineHeight?: { value: number; units: string }
letterSpacing?: { value: number; units: string }
// Symbol/Instance
diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.ts
index 6abbfd44e..cda4506a7 100644
--- a/packages/core/src/kiwi/fig-import.ts
+++ b/packages/core/src/kiwi/fig-import.ts
@@ -24,7 +24,9 @@ import type {
TextCase,
TextDecoration,
ArcData,
- VectorNetwork
+ VectorNetwork,
+ StyleRun,
+ CharacterStyleOverride
} from '../scene-graph'
function ext(nc: NodeChange): Record<string, unknown> {
@@ -285,6 +287,54 @@ function mapArcData(data?: Record<string, number>): ArcData | null {
}
}
+function importStyleRuns(nc: NodeChange): StyleRun[] {
+ const td = nc.textData
+ if (!td?.characterStyleIDs || !td.styleOverrideTable) return []
+
+ const ids = td.characterStyleIDs
+ const table = td.styleOverrideTable
+ if (ids.length === 0 || table.length === 0) return []
+
+ const styleMap = new Map<number, CharacterStyleOverride>()
+ for (const override of table) {
+ const id = (override as unknown as Record<string, unknown>).styleID as number | undefined
+ if (id === undefined) continue
+ const style: CharacterStyleOverride = {}
+ if (override.fontName) {
+ style.fontFamily = override.fontName.family
+ style.fontWeight = mapFontWeight(override.fontName.style)
+ style.italic = override.fontName.style?.toLowerCase().includes('italic') ?? false
+ }
+ if (override.fontSize !== undefined) style.fontSize = override.fontSize
+ if (override.letterSpacing) style.letterSpacing = override.letterSpacing.value
+ if (override.lineHeight) style.lineHeight = override.lineHeight.value
+ const deco = ext(override).textDecoration as string | undefined
+ if (deco) style.textDecoration = mapTextDecoration(deco)
+ if (Object.keys(style).length > 0) styleMap.set(id, style)
+ }
+
+ if (styleMap.size === 0) return []
+
+ const runs: StyleRun[] = []
+ let currentId = ids[0]
+ let start = 0
+
+ for (let i = 1; i <= ids.length; i++) {
+ if (i === ids.length || ids[i] !== currentId) {
+ if (currentId !== 0) {
+ const style = styleMap.get(currentId)
+ if (style) runs.push({ start, length: i - start, style })
+ }
+ if (i < ids.length) {
+ currentId = ids[i]
+ start = i
+ }
+ }
+ }
+
+ return runs
+}
+
function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {
const vectorData = (nc as unknown as Record<string, unknown>).vectorData as
| {
@@ -405,6 +455,7 @@ export function importNodeChanges(
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? 'Inter',
fontWeight: mapFontWeight(nc.fontName?.style),
+ italic: nc.fontName?.style?.toLowerCase().includes('italic') ?? false,
textAlignHorizontal:
(nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',
textAlignVertical: (ext(nc).textAlignVertical as TextAlignVertical) ?? 'TOP',
@@ -414,6 +465,7 @@ export function importNodeChanges(
lineHeight: nc.lineHeight?.value ?? null,
letterSpacing: nc.letterSpacing?.value ?? 0,
maxLines: (ext(nc).maxLines as number) ?? null,
+ styleRuns: importStyleRuns(nc),
horizontalConstraint: mapConstraint(ext(nc).horizontalConstraint as string),
verticalConstraint: mapConstraint(ext(nc).verticalConstraint as string),
layoutMode: mapStackMode(nc.stackMode),
diff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.ts
index 794f78679..c4ee7762d 100644
--- a/packages/core/src/renderer.ts
+++ b/packages/core/src/renderer.ts
@@ -1542,31 +1542,96 @@ export class SkiaRenderer {
if (!text) return
if (this.fontsLoaded && this.fontProvider) {
- const paraStyle = new this.ck.ParagraphStyle({
- textAlign: this.getTextAlign(node.textAlignHorizontal),
- textStyle: {
- color: this.fillPaint.getColor(),
- fontFamilies: [node.fontFamily || 'Inter'],
- fontSize: node.fontSize || DEFAULT_FONT_SIZE,
- fontStyle: { weight: { value: node.fontWeight || 400 } as FontWeight },
- letterSpacing: node.letterSpacing || 0,
- heightMultiplier: node.lineHeight
- ? node.lineHeight / (node.fontSize || DEFAULT_FONT_SIZE)
- : undefined
- }
- })
- const builder = this.ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, this.fontProvider)
- builder.addText(text)
- const paragraph = builder.build()
- paragraph.layout(node.width || 1e6)
+ const paragraph = this.buildParagraph(node, this.fillPaint.getColor())
canvas.drawParagraph(paragraph, 0, 0)
paragraph.delete()
- builder.delete()
} else if (this.textFont) {
canvas.drawText(text, 0, node.fontSize || DEFAULT_FONT_SIZE, this.fillPaint, this.textFont)
}
}
+ buildParagraph(
+ node: SceneNode,
+ color?: Float32Array
+ ): import('canvaskit-wasm').Paragraph {
+ const ck = this.ck
+ const baseColor = color ?? ck.BLACK
+ const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
+
+ const paraStyle = new ck.ParagraphStyle({
+ textAlign: this.getTextAlign(node.textAlignHorizontal),
+ textStyle: {
+ color: baseColor,
+ fontFamilies: [node.fontFamily || 'Inter'],
+ fontSize: baseFontSize,
+ fontStyle: {
+ weight: { value: node.fontWeight || 400 } as FontWeight,
+ slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright
+ },
+ letterSpacing: node.letterSpacing || 0,
+ decoration: this.textDecorationValue(node.textDecoration),
+ heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined
+ }
+ })
+
+ const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, this.fontProvider!)
+ const runs = node.styleRuns
+ const text = node.text
+
+ if (runs.length === 0) {
+ builder.addText(text)
+ } else {
+ let pos = 0
+ for (const run of runs) {
+ if (pos < run.start) {
+ builder.addText(text.slice(pos, run.start))
+ }
+ const s = run.style
+ builder.pushStyle(
+ new ck.TextStyle({
+ color: baseColor,
+ fontFamilies: [s.fontFamily ?? (node.fontFamily || 'Inter')],
+ fontSize: s.fontSize ?? baseFontSize,
+ fontStyle: {
+ weight: { value: (s.fontWeight ?? node.fontWeight) || 400 } as FontWeight,
+ slant: (s.italic ?? node.italic)
+ ? ck.FontSlant.Italic
+ : ck.FontSlant.Upright
+ },
+ letterSpacing: s.letterSpacing ?? (node.letterSpacing || 0),
+ decoration: this.textDecorationValue(s.textDecoration ?? node.textDecoration),
+ heightMultiplier: (s.lineHeight !== undefined ? s.lineHeight : node.lineHeight)
+ ? ((s.lineHeight !== undefined ? s.lineHeight : node.lineHeight)! /
+ (s.fontSize ?? baseFontSize))
+ : undefined
+ })
+ )
+ builder.addText(text.slice(run.start, run.start + run.length))
+ builder.pop()
+ pos = run.start + run.length
+ }
+ if (pos < text.length) {
+ builder.addText(text.slice(pos))
+ }
+ }
+
+ const paragraph = builder.build()
+ paragraph.layout(node.width || 1e6)
+ builder.delete()
+ return paragraph
+ }
+
+ private textDecorationValue(decoration: string): number {
+ switch (decoration) {
+ case 'UNDERLINE':
+ return this.ck.UnderlineDecoration
+ case 'STRIKETHROUGH':
+ return this.ck.LineThroughDecoration
+ default:
+ return this.ck.NoDecoration
+ }
+ }
+
private getTextAlign(align: string) {
switch (align) {
case 'CENTER':
diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.ts
index cc018e4ba..0d6c99992 100644
--- a/packages/core/src/scene-graph.ts
+++ b/packages/core/src/scene-graph.ts
@@ -128,6 +128,22 @@ export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'
export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'
export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'
+export interface CharacterStyleOverride {
+ fontWeight?: number
+ italic?: boolean
+ textDecoration?: TextDecoration
+ fontSize?: number
+ fontFamily?: string
+ letterSpacing?: number
+ lineHeight?: number | null
+}
+
+export interface StyleRun {
+ start: number
+ length: number
+ style: CharacterStyleOverride
+}
+
export interface ArcData {
startingAngle: number
endingAngle: number
@@ -176,6 +192,7 @@ export interface SceneNode {
fontSize: number
fontFamily: string
fontWeight: number
+ italic: boolean
textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
textAlignVertical: TextAlignVertical
textAutoResize: TextAutoResize
@@ -184,6 +201,7 @@ export interface SceneNode {
lineHeight: number | null
letterSpacing: number
maxLines: number | null
+ styleRuns: StyleRun[]
horizontalConstraint: ConstraintType
verticalConstraint: ConstraintType
@@ -290,6 +308,7 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):
fontSize: 14,
fontFamily: 'Inter',
fontWeight: 400,
+ italic: false,
textAlignHorizontal: 'LEFT',
lineHeight: null,
letterSpacing: 0,
@@ -316,6 +335,7 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):
textCase: 'ORIGINAL',
textDecoration: 'NONE',
maxLines: null,
+ styleRuns: [],
horizontalConstraint: 'MIN',
verticalConstraint: 'MIN',
strokeCap: 'NONE',
diff --git a/packages/core/src/style-runs.ts b/packages/core/src/style-runs.ts
new file mode 100644
index 000000000..bb8334905
--- /dev/null
+++ b/packages/core/src/style-runs.ts
@@ -0,0 +1,217 @@
+import type { CharacterStyleOverride, StyleRun, TextDecoration } from './scene-graph'
+
+export function getStyleAt(runs: StyleRun[], index: number): CharacterStyleOverride {
+ for (const run of runs) {
+ if (index >= run.start && index < run.start + run.length) {
+ return run.style
+ }
+ }
+ return {}
+}
+
+export function applyStyleToRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ patch: CharacterStyleOverride,
+ textLength: number
+): StyleRun[] {
+ const chars: (CharacterStyleOverride | null)[] = new Array(textLength).fill(null)
+
+ for (const run of runs) {
+ for (let i = run.start; i < run.start + run.length && i < textLength; i++) {
+ chars[i] = { ...(chars[i] ?? {}), ...run.style }
+ }
+ }
+
+ for (let i = start; i < end && i < textLength; i++) {
+ chars[i] = { ...(chars[i] ?? {}), ...patch }
+ }
+
+ return compactRuns(chars)
+}
+
+export function removeStyleFromRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ keys: (keyof CharacterStyleOverride)[],
+ textLength: number
+): StyleRun[] {
+ const chars: (CharacterStyleOverride | null)[] = new Array(textLength).fill(null)
+
+ for (const run of runs) {
+ for (let i = run.start; i < run.start + run.length && i < textLength; i++) {
+ chars[i] = { ...(chars[i] ?? {}), ...run.style }
+ }
+ }
+
+ for (let i = start; i < end && i < textLength; i++) {
+ if (chars[i]) {
+ const copy = { ...chars[i]! }
+ for (const k of keys) delete copy[k]
+ chars[i] = Object.keys(copy).length > 0 ? copy : null
+ }
+ }
+
+ return compactRuns(chars)
+}
+
+export function selectionHasStyle(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ key: keyof CharacterStyleOverride,
+ value: unknown
+): boolean {
+ for (let i = start; i < end; i++) {
+ const style = getStyleAt(runs, i)
+ if (style[key] !== value) return false
+ }
+ return true
+}
+
+function stylesEqual(a: CharacterStyleOverride | null, b: CharacterStyleOverride | null): boolean {
+ if (a === b) return true
+ if (!a || !b) return a === b
+ const aKeys = Object.keys(a) as (keyof CharacterStyleOverride)[]
+ const bKeys = Object.keys(b) as (keyof CharacterStyleOverride)[]
+ if (aKeys.length !== bKeys.length) return false
+ for (const k of aKeys) {
+ if (a[k] !== b[k]) return false
+ }
+ return true
+}
+
+function isEmptyStyle(style: CharacterStyleOverride | null): boolean {
+ return !style || Object.keys(style).length === 0
+}
+
+function compactRuns(chars: (CharacterStyleOverride | null)[]): StyleRun[] {
+ const result: StyleRun[] = []
+ let i = 0
+ while (i < chars.length) {
+ if (isEmptyStyle(chars[i])) {
+ i++
+ continue
+ }
+ const start = i
+ const style = chars[i]!
+ while (i < chars.length && stylesEqual(chars[i], style)) i++
+ result.push({ start, length: i - start, style: { ...style } })
+ }
+ return result
+}
+
+export function adjustRunsForInsert(runs: StyleRun[], pos: number, insertLength: number): StyleRun[] {
+ return runs.map((run) => {
+ if (pos <= run.start) {
+ return { ...run, start: run.start + insertLength }
+ }
+ if (pos > run.start && pos < run.start + run.length) {
+ return { ...run, length: run.length + insertLength }
+ }
+ return run
+ })
+}
+
+export function adjustRunsForDelete(runs: StyleRun[], start: number, deleteLength: number): StyleRun[] {
+ const end = start + deleteLength
+ const result: StyleRun[] = []
+ for (const run of runs) {
+ const runEnd = run.start + run.length
+ if (runEnd <= start) {
+ result.push(run)
+ } else if (run.start >= end) {
+ result.push({ ...run, start: run.start - deleteLength })
+ } else {
+ const newStart = Math.max(run.start, start)
+ const newEnd = Math.min(runEnd, end)
+ const removed = newEnd - newStart
+ const newLength = run.length - removed
+ if (newLength > 0) {
+ result.push({
+ ...run,
+ start: Math.min(run.start, start),
+ length: newLength
+ })
+ }
+ }
+ }
+ return result
+}
+
+export function toggleBoldInRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ nodeWeight: number,
+ textLength: number
+): { runs: StyleRun[]; newWeight: number } {
+ const allBold = selectionAllBold(runs, start, end, nodeWeight)
+ const targetWeight = allBold ? 400 : 700
+ const newRuns = allBold
+ ? removeStyleFromRange(runs, start, end, ['fontWeight'], textLength)
+ : applyStyleToRange(runs, start, end, { fontWeight: 700 }, textLength)
+ return { runs: newRuns, newWeight: targetWeight }
+}
+
+function selectionAllBold(runs: StyleRun[], start: number, end: number, nodeWeight: number): boolean {
+ for (let i = start; i < end; i++) {
+ const style = getStyleAt(runs, i)
+ const weight = style.fontWeight ?? nodeWeight
+ if (weight < 700) return false
+ }
+ return true
+}
+
+export function toggleItalicInRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ nodeItalic: boolean,
+ textLength: number
+): { runs: StyleRun[]; newItalic: boolean } {
+ const allItalic = selectionAllItalic(runs, start, end, nodeItalic)
+ const newRuns = allItalic
+ ? removeStyleFromRange(runs, start, end, ['italic'], textLength)
+ : applyStyleToRange(runs, start, end, { italic: true }, textLength)
+ return { runs: newRuns, newItalic: !allItalic }
+}
+
+function selectionAllItalic(runs: StyleRun[], start: number, end: number, nodeItalic: boolean): boolean {
+ for (let i = start; i < end; i++) {
+ const style = getStyleAt(runs, i)
+ if (!(style.italic ?? nodeItalic)) return false
+ }
+ return true
+}
+
+export function toggleDecorationInRange(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ deco: TextDecoration,
+ nodeDeco: TextDecoration,
+ textLength: number
+): { runs: StyleRun[]; newDeco: TextDecoration } {
+ const allHave = selectionAllHasDecoration(runs, start, end, deco, nodeDeco)
+ const newRuns = allHave
+ ? removeStyleFromRange(runs, start, end, ['textDecoration'], textLength)
+ : applyStyleToRange(runs, start, end, { textDecoration: deco }, textLength)
+ return { runs: newRuns, newDeco: allHave ? 'NONE' : deco }
+}
+
+function selectionAllHasDecoration(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ deco: TextDecoration,
+ nodeDeco: TextDecoration
+): boolean {
+ for (let i = start; i < end; i++) {
+ const style = getStyleAt(runs, i)
+ if ((style.textDecoration ?? nodeDeco) !== deco) return false
+ }
+ return true
+}
diff --git a/packages/core/src/text-editor.ts b/packages/core/src/text-editor.ts
index 7386ad8a0..f23167c69 100644
--- a/packages/core/src/text-editor.ts
+++ b/packages/core/src/text-editor.ts
@@ -1,4 +1,5 @@
-import type { CanvasKit, Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'
+import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
+import type { SkiaRenderer } from './renderer'
import type { SceneNode } from './scene-graph'
import type { Rect } from './types'
@@ -18,7 +19,7 @@ export interface TextEditorState {
export class TextEditor {
private ck: CanvasKit
- private fontProvider: TypefaceFontProvider | null = null
+ private renderer: SkiaRenderer | null = null
private _state: TextEditorState | null = null
caretVisible = true
@@ -38,8 +39,8 @@ export class TextEditor {
return this._state?.nodeId ?? null
}
- setFontProvider(provider: TypefaceFontProvider | null): void {
- this.fontProvider = provider
+ setRenderer(renderer: SkiaRenderer | null): void {
+ this.renderer = renderer
}
start(node: SceneNode): void {
@@ -63,28 +64,9 @@ export class TextEditor {
rebuildParagraph(node: SceneNode): void {
const s = this._state
- if (!s || !this.fontProvider) return
-
+ if (!s || !this.renderer) return
s.paragraph?.delete()
-
- const paraStyle = new this.ck.ParagraphStyle({
- textAlign: this.getTextAlign(node.textAlignHorizontal),
- textStyle: {
- color: this.ck.BLACK,
- fontFamilies: [node.fontFamily || 'Inter'],
- fontSize: node.fontSize || 14,
- fontStyle: { weight: { value: node.fontWeight || 400 } },
- letterSpacing: node.letterSpacing || 0,
- heightMultiplier: node.lineHeight
- ? node.lineHeight / (node.fontSize || 14)
- : undefined
- }
- })
- const builder = this.ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, this.fontProvider)
- builder.addText(s.text)
- s.paragraph = builder.build()
- s.paragraph.layout(node.width || 1e6)
- builder.delete()
+ s.paragraph = this.renderer.buildParagraph(node)
}
hasSelection(): boolean {
@@ -353,18 +335,6 @@ export class TextEditor {
})
}
- private getTextAlign(align: string) {
- switch (align) {
- case 'CENTER':
- return this.ck.TextAlign.Center
- case 'RIGHT':
- return this.ck.TextAlign.Right
- case 'JUSTIFIED':
- return this.ck.TextAlign.Justify
- default:
- return this.ck.TextAlign.Left
- }
- }
}
function isWordBoundary(ch: string): boolean {
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 55b69de1c..b72d4a8d2 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -44,6 +44,26 @@ function setAlign(align: TextAlign) {
store.requestRender()
}
+function toggleBold() {
+ const n = node.value
+ selectWeight(n.fontWeight >= 700 ? 400 : 700)
+}
+
+function toggleItalic() {
+ store.updateNodeWithUndo(node.value.id, { italic: !node.value.italic }, 'Toggle italic')
+ store.requestRender()
+}
+
+function toggleDecoration(deco: 'UNDERLINE' | 'STRIKETHROUGH') {
+ const current = node.value.textDecoration
+ store.updateNodeWithUndo(
+ node.value.id,
+ { textDecoration: current === deco ? 'NONE' : deco },
+ `Toggle ${deco.toLowerCase()}`
+ )
+ store.requestRender()
+}
+
onMounted(async () => {
await loadFont(node.value.fontFamily, currentWeightLabel.value)
})
@@ -102,23 +122,75 @@ onMounted(async () => {
</ScrubInput>
</div>
- <!-- Text alignment -->
- <div class="flex gap-0.5">
- <button
- v-for="align in ['LEFT', 'CENTER', 'RIGHT'] as TextAlign[]"
- :key="align"
- class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"
- :class="
- node.textAlignHorizontal === align
- ? 'border-accent bg-accent text-white'
- : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
- "
- @click="setAlign(align)"
- >
- <icon-lucide-align-left v-if="align === 'LEFT'" class="size-3.5" />
- <icon-lucide-align-center v-else-if="align === 'CENTER'" class="size-3.5" />
- <icon-lucide-align-right v-else class="size-3.5" />
- </button>
+ <!-- Text alignment + formatting -->
+ <div class="flex items-center gap-3">
+ <div class="flex gap-0.5">
+ <button
+ v-for="align in ['LEFT', 'CENTER', 'RIGHT'] as TextAlign[]"
+ :key="align"
+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"
+ :class="
+ node.textAlignHorizontal === align
+ ? 'border-accent bg-accent text-white'
+ : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
+ "
+ @click="setAlign(align)"
+ >
+ <icon-lucide-align-left v-if="align === 'LEFT'" class="size-3.5" />
+ <icon-lucide-align-center v-else-if="align === 'CENTER'" class="size-3.5" />
+ <icon-lucide-align-right v-else class="size-3.5" />
+ </button>
+ </div>
+ <div class="flex gap-0.5">
+ <button
+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1 font-bold"
+ :class="
+ node.fontWeight >= 700
+ ? 'border-accent bg-accent text-white'
+ : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
+ "
+ title="Bold (⌘B)"
+ @click="toggleBold"
+ >
+ <icon-lucide-bold class="size-3.5" />
+ </button>
+ <button
+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"
+ :class="
+ node.italic
+ ? 'border-accent bg-accent text-white'
+ : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
+ "
+ title="Italic (⌘I)"
+ @click="toggleItalic"
+ >
+ <icon-lucide-italic class="size-3.5" />
+ </button>
+ <button
+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"
+ :class="
+ node.textDecoration === 'UNDERLINE'
+ ? 'border-accent bg-accent text-white'
+ : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
+ "
+ title="Underline (⌘U)"
+ @click="toggleDecoration('UNDERLINE')"
+ >
+ <icon-lucide-underline class="size-3.5" />
+ </button>
+ <button
+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"
+ :class="
+ node.textDecoration === 'STRIKETHROUGH'
+ ? 'border-accent bg-accent text-white'
+ : 'border-border bg-input text-muted hover:bg-hover hover:text-surface'
+ "
+ title="Strikethrough"
+ @click="toggleDecoration('STRIKETHROUGH')"
+ >
+ <icon-lucide-strikethrough class="size-3.5" />
+ </button>
+ </div>
</div>
</div>
</template>
diff --git a/src/composables/use-text-edit.ts b/src/composables/use-text-edit.ts
index cb815f683..89384b76d 100644
--- a/src/composables/use-text-edit.ts
+++ b/src/composables/use-text-edit.ts
@@ -1,6 +1,15 @@
import { useEventListener } from '@vueuse/core'
import { shallowRef, watch, type Ref } from 'vue'
+import {
+ adjustRunsForDelete,
+ adjustRunsForInsert,
+ toggleBoldInRange,
+ toggleDecorationInRange,
+ toggleItalicInRange
+} from '@/engine/style-runs'
+
+import type { SceneNode } from '@/engine/scene-graph'
import type { EditorStore } from '@/stores/editor'
const CARET_BLINK_MS = 530
@@ -27,11 +36,48 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
store.requestRepaint()
}
- function syncText(nodeId: string, text: string) {
- store.graph.updateNode(nodeId, { text })
+ function syncText(nodeId: string, text: string, runs?: SceneNode['styleRuns']) {
+ const changes: Partial<SceneNode> = { text }
+ if (runs !== undefined) changes.styleRuns = runs
+ store.graph.updateNode(nodeId, changes)
store.requestRender()
}
+ function insertText(text: string, node: SceneNode) {
+ const editor = store.textEditor
+ if (!editor) return
+ const range = editor.getSelectionRange()
+ let runs = node.styleRuns
+ if (range) {
+ runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])
+ runs = adjustRunsForInsert(runs, range[0], text.length)
+ } else {
+ runs = adjustRunsForInsert(runs, editor.state?.cursor ?? 0, text.length)
+ }
+ editor.insert(text, node)
+ syncText(node.id, editor.state?.text ?? '', runs)
+ }
+
+ function deleteText(node: SceneNode, forward: boolean) {
+ const editor = store.textEditor
+ if (!editor) return
+ const range = editor.getSelectionRange()
+ let runs = node.styleRuns
+ if (range) {
+ runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])
+ } else if (forward && editor.state && editor.state.cursor < node.text.length) {
+ runs = adjustRunsForDelete(runs, editor.state.cursor, 1)
+ } else if (!forward && editor.state && editor.state.cursor > 0) {
+ runs = adjustRunsForDelete(runs, editor.state.cursor - 1, 1)
+ }
+ if (forward) {
+ editor.delete(node)
+ } else {
+ editor.backspace(node)
+ }
+ syncText(node.id, editor.state?.text ?? '', runs)
+ }
+
function onCompositionStart() {
isComposing = true
}
@@ -39,11 +85,9 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
function onCompositionEnd(e: CompositionEvent) {
isComposing = false
if (!e.data) return
- const editor = store.textEditor
const node = getEditingNode()
- if (!editor || !node) return
- editor.insert(e.data, node)
- syncText(node.id, editor.state?.text ?? '')
+ if (!node) return
+ insertText(e.data, node)
if (textareaRef.value) textareaRef.value.value = ''
resetBlink()
}
@@ -55,11 +99,9 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
if (!text) return
el.value = ''
- const editor = store.textEditor
const node = getEditingNode()
- if (!editor || !node) return
- editor.insert(text, node)
- syncText(node.id, editor.state?.text ?? '')
+ if (!node) return
+ insertText(text, node)
resetBlink()
}
@@ -79,31 +121,25 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
e.preventDefault()
return
case 'Enter':
- editor.insert('\n', node)
+ insertText('\n', node)
textChanged = true
break
case 'Backspace':
if (isMeta) {
editor.moveToLineStart(true)
- editor.backspace(node)
} else if (e.altKey) {
editor.moveWordLeft(true)
- editor.backspace(node)
- } else {
- editor.backspace(node)
}
+ deleteText(node, false)
textChanged = true
break
case 'Delete':
if (isMeta) {
editor.moveToLineEnd(true)
- editor.delete(node)
} else if (e.altKey) {
editor.moveWordRight(true)
- editor.delete(node)
- } else {
- editor.delete(node)
}
+ deleteText(node, true)
textChanged = true
break
case 'ArrowLeft':
@@ -160,19 +196,98 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
e.preventDefault()
}
return
+ case 'b':
+ if (isMeta) {
+ toggleBold(node)
+ e.preventDefault()
+ }
+ return
+ case 'i':
+ if (isMeta) {
+ toggleItalic(node)
+ e.preventDefault()
+ }
+ return
+ case 'u':
+ if (isMeta) {
+ toggleUnderline(node)
+ e.preventDefault()
+ }
+ return
default:
return
}
- if (textChanged) {
- syncText(node.id, editor.state?.text ?? '')
- } else {
+ if (!textChanged) {
store.requestRender()
}
resetBlink()
e.preventDefault()
}
+ function applyFormatting(nodeId: string, changes: Partial<SceneNode>, label: string) {
+ store.updateNodeWithUndo(nodeId, changes, label)
+ const updated = store.graph.getNode(nodeId)
+ if (updated) store.textEditor?.rebuildParagraph(updated)
+ store.requestRender()
+ }
+
+ function toggleBold(node: SceneNode) {
+ const editor = store.textEditor
+ const range = editor?.getSelectionRange()
+ if (range) {
+ const { runs } = toggleBoldInRange(
+ node.styleRuns,
+ range[0],
+ range[1],
+ node.fontWeight,
+ node.text.length
+ )
+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle bold')
+ } else {
+ applyFormatting(node.id, { fontWeight: node.fontWeight >= 700 ? 400 : 700 }, 'Toggle bold')
+ }
+ }
+
+ function toggleItalic(node: SceneNode) {
+ const editor = store.textEditor
+ const range = editor?.getSelectionRange()
+ if (range) {
+ const { runs } = toggleItalicInRange(
+ node.styleRuns,
+ range[0],
+ range[1],
+ node.italic,
+ node.text.length
+ )
+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle italic')
+ } else {
+ applyFormatting(node.id, { italic: !node.italic }, 'Toggle italic')
+ }
+ }
+
+ function toggleUnderline(node: SceneNode) {
+ const editor = store.textEditor
+ const range = editor?.getSelectionRange()
+ if (range) {
+ const { runs } = toggleDecorationInRange(
+ node.styleRuns,
+ range[0],
+ range[1],
+ 'UNDERLINE',
+ node.textDecoration,
+ node.text.length
+ )
+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle underline')
+ } else {
+ applyFormatting(
+ node.id,
+ { textDecoration: node.textDecoration === 'UNDERLINE' ? 'NONE' : 'UNDERLINE' },
+ 'Toggle underline'
+ )
+ }
+ }
+
function handleCopy() {
const editor = store.textEditor
if (!editor) return
@@ -186,8 +301,7 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
const text = editor.getSelectedText()
if (text) {
navigator.clipboard.writeText(text)
- editor.backspace(node)
- syncText(node.id, editor.state?.text ?? '')
+ deleteText(node, false)
resetBlink()
}
}
@@ -198,8 +312,7 @@ export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Edi
try {
const text = await navigator.clipboard.readText()
if (text) {
- editor.insert(text, node)
- syncText(node.id, editor.state?.text ?? '')
+ insertText(text, node)
resetBlink()
}
} catch {
diff --git a/src/engine/style-runs.ts b/src/engine/style-runs.ts
new file mode 100644
index 000000000..add633218
--- /dev/null
+++ b/src/engine/style-runs.ts
@@ -0,0 +1,7 @@
+export {
+ toggleBoldInRange,
+ toggleItalicInRange,
+ toggleDecorationInRange,
+ adjustRunsForInsert,
+ adjustRunsForDelete
+} from '@open-pencil/core'
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index aa60dde43..903f61a29 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -474,7 +474,7 @@ export function createEditorStore() {
if (!node) return
state.editingTextId = nodeId
if (_textEditor) {
- _textEditor.setFontProvider(_renderer?.getFontProvider() ?? null)
+ _textEditor.setRenderer(_renderer)
_textEditor.start(node)
}
requestRender()