AI-native design editor. Open-source Figma alternative.
fix(core): keep character colours when text is inserted, deleted or replaced (#1201)
Niraj Sanganie615efc75722
diff --git a/changes/1201/fixed.md b/changes/1201/fixed.mdnew file mode 100644index 000000000..9e0891d89--- /dev/null+++ b/changes/1201/fixed.md@@ -0,0 +1 @@+- Inserting and deleting characters through the plugin API, `openpencil eval` or MCP keeps each colour and other character style on the letters it was applied to, and `insertCharacters` takes Figma's `useStyle` to copy the style of the character before or after. Setting `characters` resets range styles to the first character's, as in Figma. A position outside the text is refused instead of corrupting the styles.diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.tsindex 61ce03ab9..6f3f5cd09 100644--- a/packages/core/src/figma-api/accessors/text/index.ts+++ b/packages/core/src/figma-api/accessors/text/index.ts@@ -19,6 +19,7 @@ import {letterSpacingValue,lineHeightValue,paragraphStylesForCharacters,+ styleRunsForCharacters,spacingProblem,type FigmaLetterSpacing,type FigmaLineHeight@@ -100,7 +101,8 @@ export function installTextNodeProxyAccessors(},set(this: ProxyThis, value: string) {const textParagraphs = paragraphStylesForCharacters(raw(this, internals), value)- updateNode(this, internals, { text: value, textParagraphs })+ const styleRuns = styleRunsForCharacters(raw(this, internals), value)+ updateNode(this, internals, { text: value, textParagraphs, styleRuns })}},fontName: characterStyle<FigmaFontName>(internals, 'fontName', mixed, (_node, value) => {diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 680018ff9..2ab733dda 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -292,8 +292,12 @@ export class FigmaNodeProxy {return n}- insertCharacters(start: number, characters: string): void {- TextProxy.insertCharacters(this[INTERNAL_GRAPH], this._raw(), start, characters)+ insertCharacters(+ start: number,+ characters: string,+ useStyle: TextProxy.InsertStyleSource = 'BEFORE'+ ): void {+ TextProxy.insertCharacters(this[INTERNAL_GRAPH], this._raw(), start, characters, useStyle)}deleteCharacters(start: number, end: number): void {diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.tsindex 7261dac00..9e4671445 100644--- a/packages/core/src/figma-api/text/index.ts+++ b/packages/core/src/figma-api/text/index.ts@@ -3,6 +3,7 @@ import { upperFirst } from 'es-toolkit/string'import type {SceneGraph,SceneNode,+ StyleRun,TextParagraphSpacingField,TextParagraphStyle} from '@open-pencil/scene-graph'@@ -21,6 +22,9 @@ import {withParagraphSpacing} from '@open-pencil/scene-graph/text'+import { invalid } from '#core/figma-api/accessors/text/messages'+import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'+import { assertTextRange } from './style'/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */@@ -53,12 +57,48 @@ export function letterSpacingValue(node: SceneNode, value: FigmaLetterSpacing |return typeof value === 'number' ? value : pixels(value, node.fontSize)}+/** Which neighbour inserted characters copy their style from, as Figma's `insertCharacters` takes it. */+export type InsertStyleSource = 'BEFORE' | 'AFTER'++const INSERT_STYLE_SOURCES: ReadonlySet<string> = new Set(['BEFORE', 'AFTER'])++/**+ * The style inserted characters take, as Figma gives it: the preceding character's for `BEFORE`+ * and the following one's for `AFTER`, or the closest character's at either end of the text.+ */+function insertedStyle(node: SceneNode, start: number, useStyle: InsertStyleSource) {+ if (node.text.length === 0) return {}+ const preferred = useStyle === 'BEFORE' ? start - 1 : start+ const index = Math.min(Math.max(preferred, 0), node.text.length - 1)+ return getStyleAt(node.styleRuns, index)+}++/**+ * A text's style runs once its characters are replaced. Figma resets the styles applied to+ * character ranges, so the whole text keeps the style of its first character.+ */+export function styleRunsForCharacters(node: SceneNode, characters: string): StyleRun[] {+ const first = node.text.length > 0 ? getStyleAt(node.styleRuns, 0) : {}+ if (characters.length === 0 || Object.keys(first).length === 0) return []+ return [{ start: 0, length: characters.length, style: { ...first } }]+}+export function insertCharacters(graph: SceneGraph,node: SceneNode,start: number,- characters: string+ characters: string,+ useStyle: InsertStyleSource = 'BEFORE'): void {+ // Scripts are not type-checked, so the value is checked as Figma checks it.+ if (!INSERT_STYLE_SOURCES.has(useStyle)) {+ throw invalid(+ 'insertCharacters',+ 'Invalid option: expected one of "BEFORE"|"AFTER"',+ 'useStyle'+ )+ }+ assertEditPosition('insertCharacters', node, 'start', start)const text = node.text.slice(0, start) + characters + node.text.slice(start)const textParagraphs = paragraphStylesAfterEdit(node.textParagraphs,@@ -67,8 +107,34 @@ export function insertCharacters(start,characters)- graph.updateNode(node.id, { text, textParagraphs })- recordInstanceOverride(graph, node.id, ['text', 'textParagraphs'])+ const styleRuns = insertRunsWithStyle(+ node.styleRuns,+ start,+ characters.length,+ insertedStyle(node, start, useStyle)+ )+ graph.updateNode(node.id, { text, textParagraphs, styleRuns })+ recordInstanceOverride(graph, node.id, ['text', 'textParagraphs', 'styleRuns'])+}++/**+ * A position an edit can use: an integer from 0 through the text length, the end included,+ * refused with Figma's messages.+ */+function assertEditPosition(+ method: 'insertCharacters' | 'deleteCharacters',+ node: SceneNode,+ name: string,+ value: number+) {+ if (!Number.isInteger(value)) throw invalid(method, 'Expected int, received number', name)+ if (value < 0) throw invalid(method, 'Too small: expected number to be >=0', name)+ if (value > node.text.length) {+ const verb = method === 'insertCharacters' ? 'insert' : 'delete'+ throw new Error(+ `in ${method}: Cannot ${verb} characters at index greater than the length of the text`+ )+ }}export function deleteCharacters(@@ -77,10 +143,16 @@ export function deleteCharacters(start: number,end: number): void {+ assertEditPosition('deleteCharacters', node, 'start', start)+ assertEditPosition('deleteCharacters', node, 'end', end)+ if (end < start) {+ throw new Error('in deleteCharacters: deleteCharacters must have (start <= end)')+ }const text = node.text.slice(0, start) + node.text.slice(end)const textParagraphs = paragraphStylesAfterEdit(node.textParagraphs, node.text, start, end, '')- graph.updateNode(node.id, { text, textParagraphs })- recordInstanceOverride(graph, node.id, ['text', 'textParagraphs'])+ const styleRuns = adjustRunsForDelete(node.styleRuns, start, end - start)+ graph.updateNode(node.id, { text, textParagraphs, styleRuns })+ recordInstanceOverride(graph, node.id, ['text', 'textParagraphs', 'styleRuns'])}type ListType = TextListOptions['type']diff --git a/packages/core/src/text/style-runs.ts b/packages/core/src/text/style-runs.tsindex 241106259..4da0de6f2 100644--- a/packages/core/src/text/style-runs.ts+++ b/packages/core/src/text/style-runs.ts@@ -116,6 +116,41 @@ export function adjustRunsForInsert(})}+/**+ * The runs after `length` characters are inserted at `pos`, the new characters all in `style`+ * and every other character keeping its own. Works on the runs, not on each character, so a+ * long insert costs no more than a short one.+ */+export function insertRunsWithStyle(+ runs: StyleRun[],+ pos: number,+ length: number,+ style: CharacterStyleOverride+): StyleRun[] {+ const moved: StyleRun[] = []+ for (const run of runs) {+ const end = run.start + run.length+ if (end <= pos) moved.push(run)+ else if (run.start >= pos) moved.push({ ...run, start: run.start + length })+ else {+ // The insert splits this run in two around the new characters.+ moved.push({ ...run, length: pos - run.start })+ moved.push({ ...run, start: pos + length, length: end - pos })+ }+ }+ if (length > 0 && !isEmptyStyle(style)) moved.push({ start: pos, length, style: { ...style } })+ moved.sort((first, second) => first.start - second.start)+ // Runs that meet with the same style become one, as compactRuns leaves them.+ const merged: StyleRun[] = []+ for (const run of moved) {+ const last = merged.at(-1)+ if (last && last.start + last.length === run.start && isEqual(last.style, run.style)) {+ merged[merged.length - 1] = { ...last, length: last.length + run.length }+ } else merged.push(run)+ }+ return merged+}+export function adjustRunsForDelete(runs: StyleRun[],start: number,diff --git a/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts b/packages/core/tests/figma-api/text/edit-keeps-colour.test.tsnew file mode 100644index 000000000..bba06d642--- /dev/null+++ b/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from 'bun:test'++import { createAPI } from '#core-tests/helpers/figma-api'++const RED = [{ type: 'SOLID' as const, color: { r: 1, g: 0, b: 0 } }]++function coloured(characters: string, start: number, end: number) {+ const api = createAPI()+ const text = api.createText()+ text.characters = characters+ text.setRangeFills(start, end, RED)+ return text+}++function redCharacters(text: ReturnType<typeof coloured>) {+ return text+ .getStyledTextSegments(['fills'])+ .filter((segment) => {+ const [fill] = segment.fills as typeof RED+ return fill?.color.r === 1 && fill.color.g === 0+ })+ .map((segment) => segment.characters)+}++// Recorded with the same scripts in Figma 126.+describe('editing coloured text through the plugin API', () => {+ test('inserting before a coloured run moves the run with its characters', () => {+ const text = coloured('one two three', 4, 7)+ text.insertCharacters(0, 'zero ')++ expect(text.characters).toBe('zero one two three')+ expect(redCharacters(text)).toEqual(['two'])+ })++ test('inserted characters copy the preceding character, so typing on after a run extends it', () => {+ const text = coloured('one two three', 4, 7)+ text.insertCharacters(7, 's')++ expect(redCharacters(text)).toEqual(['twos'])+ })++ test('with AFTER, inserted characters copy the following character', () => {+ const text = coloured('one two three', 4, 7)+ text.insertCharacters(4, 'big ', 'AFTER')+ text.insertCharacters(11, '!', 'AFTER')++ expect(text.characters).toBe('one big two! three')+ expect(redCharacters(text)).toEqual(['big two'])+ })++ test('at the start of the text, inserted characters copy the closest character', () => {+ const text = coloured('two three', 0, 3)+ text.insertCharacters(0, 'one ')++ expect(redCharacters(text)).toEqual(['one two'])+ })++ test('a long insert keeps the styles around it', () => {+ const text = coloured('one two three', 4, 7)+ const long = 'x'.repeat(200_000)+ text.insertCharacters(4, long, 'AFTER')++ expect(text.characters.length).toBe(13 + long.length)+ // Read back a few ranges: listing every segment of 200,000 characters is slow in itself.+ const red = (start: number, end: number) =>+ (text.getRangeFills(start, end) as typeof RED)[0]?.color.r+ expect([red(4, 5), red(4 + long.length, 7 + long.length)]).toEqual([1, 1])+ // Before the run, the text keeps its own black.+ expect(red(0, 4)).toBe(0)+ })++ test('deleting before a coloured run moves the run with its characters', () => {+ const text = coloured('one two three', 8, 13)+ text.deleteCharacters(0, 4)++ expect(redCharacters(text)).toEqual(['three'])+ })++ test('deleting across the start of a coloured run keeps the characters left in it', () => {+ const text = coloured('one two three', 8, 13)+ text.deleteCharacters(6, 10)++ expect(text.characters).toBe('one twree')+ expect(redCharacters(text)).toEqual(['ree'])+ })++ test('deleting inside a coloured run shortens the run and keeps the rest coloured', () => {+ const text = coloured('one seven three', 4, 9)+ text.deleteCharacters(5, 7)++ expect(text.characters).toBe('one sen three')+ expect(redCharacters(text)).toEqual(['sen'])+ })++ test('setting characters resets range styles, leaving the style of the first character', () => {+ const middle = coloured('one two three', 4, 7)+ middle.characters = 'one six three'+ expect(redCharacters(middle)).toEqual([])++ const first = coloured('one two three', 0, 3)+ first.characters = 'six seven'+ expect(redCharacters(first)).toEqual(['six seven'])+ })++ // Messages recorded in Figma 126.+ test('an unknown useStyle is refused', () => {+ const text = coloured('one', 0, 1)+ expect(() => text.insertCharacters(0, 'x', 'MIDDLE' as never)).toThrow(+ 'in insertCharacters: Property "useStyle" failed validation: Invalid option: expected one of "BEFORE"|"AFTER"'+ )+ })++ test('insert and delete positions outside the text are refused and change nothing', () => {+ const text = coloured('one two three', 4, 7)++ expect(() => text.insertCharacters(14, 'x')).toThrow(+ 'in insertCharacters: Cannot insert characters at index greater than the length of the text'+ )+ expect(() => text.insertCharacters(-1, 'x')).toThrow(+ 'in insertCharacters: Property "start" failed validation: Too small: expected number to be >=0'+ )+ expect(() => text.insertCharacters(1.5, 'x')).toThrow(+ 'in insertCharacters: Property "start" failed validation: Expected int, received number'+ )+ expect(() => text.deleteCharacters(-1, 3)).toThrow(+ 'in deleteCharacters: Property "start" failed validation: Too small: expected number to be >=0'+ )+ expect(() => text.deleteCharacters(0, 14)).toThrow(+ 'in deleteCharacters: Cannot delete characters at index greater than the length of the text'+ )+ expect(() => text.deleteCharacters(5, 3)).toThrow(+ 'in deleteCharacters: deleteCharacters must have (start <= end)'+ )++ expect(text.characters).toBe('one two three')+ expect(redCharacters(text)).toEqual(['two'])+ })++ test('the end of the text is a valid place to insert and to end a deletion', () => {+ const text = coloured('one two three', 4, 7)+ text.insertCharacters(13, '!')+ text.deleteCharacters(12, 14)++ expect(text.characters).toBe('one two thre')+ expect(redCharacters(text)).toEqual(['two'])+ })+})