Skip to content

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

fix(text): align editing overlays with vertical text (#543)

Danila Poyarkov15bd0ba19f02
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0684578d..adff3b329 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,6 +58,7 @@
### Fixed
+- Keep text-editing carets, hit testing, and selection highlights aligned with vertically centered or bottom-aligned text. (#539)
- Match AI chat code-block syntax colors and backgrounds to the active light or dark theme. (#537)
- Let desktop users select and copy AI chat text without replacing it with the selected canvas layers. (#538)
- Restore visible above, below, and child drop feedback while dragging layers in the Layers panel.
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index 3cc126de3..c15d65b65 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -34,6 +34,20 @@ export class TextEditor {
this.ck = ck
}
+ private paragraphVerticalOffset(): number {
+ const s = this._state
+ const node = this.paragraphNode
+ if (!s?.paragraph || !node) return 0
+ const available = Math.max(0, node.height - s.paragraph.getHeight())
+ if (node.textAlignVertical === 'CENTER') return available / 2
+ if (node.textAlignVertical === 'BOTTOM') return available
+ return 0
+ }
+
+ private paragraphY(y: number): number {
+ return y - this.paragraphVerticalOffset()
+ }
+
private prepareMove(extend: boolean): TextEditorState | null {
const s = this._state
if (!s) return null
@@ -170,7 +184,7 @@ export class TextEditor {
setCursorAt(x: number, y: number, extend = false): void {
const s = this._state
if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, y).pos
+ const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
if (extend) {
if (s.selectionAnchor === null) s.selectionAnchor = s.cursor
} else {
@@ -193,14 +207,14 @@ export class TextEditor {
selectWordAt(x: number, y: number): void {
const s = this._state
if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, y).pos
+ const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
this.selectWord(pos)
}
selectLineAt(x: number, y: number): void {
const s = this._state
if (!s?.paragraph) return
- const pos = s.paragraph.getGlyphPositionAtCoordinate(x, y).pos
+ const pos = s.paragraph.getGlyphPositionAtCoordinate(x, this.paragraphY(y)).pos
this.selectLine(pos)
}
@@ -256,7 +270,7 @@ export class TextEditor {
if (!caret) return
const fontSize = s.paragraph.getLineMetrics()[0]?.height ?? 14
const y = edge === 'up' ? caret.y0 - fontSize / 2 : caret.y1 + fontSize / 2
- s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, y).pos
+ s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, this.paragraphY(y)).pos
}
moveUp(extend = false): void {
@@ -338,7 +352,8 @@ export class TextEditor {
const metrics = s.paragraph.getLineMetrics()
if (metrics.length === 0) return null
const line = metrics[0]
- return { x: line.left, y0: 0, y1: line.height }
+ const offsetY = this.paragraphVerticalOffset()
+ return { x: line.left, y0: offsetY, y1: offsetY + line.height }
}
let lo: number
@@ -366,10 +381,11 @@ export class TextEditor {
)
if (rects.length === 0) return null
const [left, top, right, bottom] = rects[0].rect
+ const offsetY = this.paragraphVerticalOffset()
return {
x: useRight ? right : left,
- y0: top,
- y1: bottom
+ y0: top + offsetY,
+ y1: bottom + offsetY
}
}
@@ -385,9 +401,10 @@ export class TextEditor {
this.ck.RectHeightStyle.Max,
this.ck.RectWidthStyle.Tight
)
+ const offsetY = this.paragraphVerticalOffset()
return rects.map((r) => {
const [left, top, right, bottom] = r.rect
- return { x: left, y: top, width: right - left, height: bottom - top }
+ return { x: left, y: top + offsetY, width: right - left, height: bottom - top }
})
}
}
diff --git a/tests/e2e/text/aligned-selection.spec.ts b/tests/e2e/text/aligned-selection.spec.ts
new file mode 100644
index 000000000..ae9f55bc7
--- /dev/null
+++ b/tests/e2e/text/aligned-selection.spec.ts
@@ -0,0 +1,45 @@
+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
+import { expectDefined } from '#tests/helpers/assert'
+
+const editor = useEditorSetup()
+
+test('centered and bottom-aligned text selection follows the rendered text', async () => {
+ for (const [textAlignHorizontal, textAlignVertical] of [
+ ['CENTER', 'CENTER'],
+ ['RIGHT', 'CENTER'],
+ ['LEFT', 'BOTTOM']
+ ] as const) {
+ const geometry = await editor.page.evaluate(
+ ({ horizontal, vertical }) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const id = store.createShape('TEXT', 300, 250, 220, 120)
+ store.graph.updateNode(id, {
+ text: 'Aligned text',
+ fontSize: 24,
+ textAlignHorizontal: horizontal,
+ textAlignVertical: vertical
+ })
+ store.select([id])
+ store.startTextEditing(id)
+ store.textEditor?.selectAll()
+ store.requestRender()
+ return { rects: store.textEditor?.getSelectionRects() ?? [] }
+ },
+ { horizontal: textAlignHorizontal, vertical: textAlignVertical }
+ )
+ const selection = expectDefined(geometry.rects[0], `${textAlignVertical} selection rectangle`)
+ expect(selection.y).toBeGreaterThan(textAlignVertical === 'BOTTOM' ? 80 : 35)
+ expect(selection.y + selection.height).toBeLessThanOrEqual(120)
+ if (textAlignHorizontal === 'CENTER') expect(selection.x).toBeGreaterThan(20)
+ if (textAlignHorizontal === 'RIGHT') expect(selection.x).toBeGreaterThan(40)
+
+ await editor.page.keyboard.press('Escape')
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const selectedId = store?.state.selectedIds.values().next().value
+ if (selectedId) store?.graph.deleteNode(selectedId)
+ store?.clearSelection()
+ })
+ }
+})
diff --git a/tests/engine/text/editor.test.ts b/tests/engine/text/editor.test.ts
index e0602ed06..1e20a0466 100644
--- a/tests/engine/text/editor.test.ts
+++ b/tests/engine/text/editor.test.ts
@@ -1,12 +1,16 @@
import { describe, test, expect } from 'bun:test'
-import type { CanvasKit } from 'canvaskit-wasm'
+import type { CanvasKit, Paragraph, RectWithDirection } from 'canvaskit-wasm'
import { TextEditor, type SceneNode } from '@open-pencil/core'
+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { expectDefined } from '#tests/helpers/assert'
-const mockCk = {} as CanvasKit
+const mockCk = {
+ RectHeightStyle: { Max: 0 },
+ RectWidthStyle: { Tight: 0 }
+} as Pick<CanvasKit, 'RectHeightStyle' | 'RectWidthStyle'> as CanvasKit
function createEditor(text = 'Hello World') {
const editor = new TextEditor(mockCk)
@@ -19,6 +23,51 @@ function editorState(editor: TextEditor) {
return expectDefined(editor.state, 'text editor state')
}
+function createParagraphEditor(textAlignVertical: SceneNode['textAlignVertical']) {
+ const hitTestYs: number[] = []
+ const rects = [{ rect: [4, 2, 14, 12] }] as RectWithDirection[]
+ const lineMetrics = {
+ endExcludingWhitespaces: 5,
+ height: 10,
+ left: 3,
+ startIndex: 0
+ }
+ const paragraph = {
+ delete: () => undefined,
+ getGlyphPositionAtCoordinate: (_x: number, y: number) => {
+ hitTestYs.push(y)
+ return { pos: Math.round(y) }
+ },
+ getHeight: () => 20,
+ getLineMetrics: () => [lineMetrics],
+ getLineMetricsAt: () => lineMetrics,
+ getLineNumberAt: () => 0,
+ getRectsForRange: () => rects
+ } as Pick<
+ Paragraph,
+ | 'delete'
+ | 'getGlyphPositionAtCoordinate'
+ | 'getHeight'
+ | 'getLineMetrics'
+ | 'getLineMetricsAt'
+ | 'getLineNumberAt'
+ | 'getRectsForRange'
+ > as Paragraph
+ const renderer = {
+ buildParagraph: () => paragraph,
+ fontGeneration: 1
+ }
+ const editor = new TextEditor(mockCk)
+ editor.setRenderer(renderer as Parameters<TextEditor['setRenderer']>[0])
+ const node = createDefaultNode(() => 'aligned-text', 'TEXT', {
+ height: 100,
+ text: 'Hello',
+ textAlignVertical
+ })
+ editor.start(node)
+ return { editor, hitTestYs }
+}
+
describe('TextEditor', () => {
test('start initializes state', () => {
const { editor } = createEditor()
@@ -111,6 +160,51 @@ describe('TextEditor', () => {
expect(editor.state?.text).toBe(' World')
})
+ test('offsets hit testing, caret, and selection for vertical alignment', () => {
+ for (const [alignment, offset] of [
+ ['TOP', 0],
+ ['CENTER', 40],
+ ['BOTTOM', 80]
+ ] as const) {
+ const { editor, hitTestYs } = createParagraphEditor(alignment)
+ editorState(editor).selectionAnchor = 0
+ editorState(editor).cursor = 5
+
+ expect(editor.getSelectionRects()).toEqual([{ x: 4, y: 2 + offset, width: 10, height: 10 }])
+ editorState(editor).selectionAnchor = null
+ expect(editor.getCaretRect()).toEqual({ x: 14, y0: 2 + offset, y1: 12 + offset })
+
+ editor.setCursorAt(4, offset + 3)
+ expect(hitTestYs.at(-1)).toBe(3)
+ expect(editorState(editor).cursor).toBe(3)
+
+ editor.selectWordAt(4, offset + 2)
+ expect(hitTestYs.at(-1)).toBe(2)
+ expect(editor.getSelectionRange()).toEqual([0, 5])
+
+ editor.selectLineAt(4, offset + 4)
+ expect(hitTestYs.at(-1)).toBe(4)
+ expect(editor.getSelectionRange()).toEqual([0, 5])
+
+ editorState(editor).selectionAnchor = null
+ editorState(editor).cursor = 1
+ editor.moveUp()
+ expect(hitTestYs.at(-1)).toBe(-3)
+
+ editorState(editor).cursor = 1
+ editor.moveDown()
+ expect(hitTestYs.at(-1)).toBe(17)
+ }
+ })
+
+ test('offsets the empty-text caret for vertical alignment', () => {
+ const { editor } = createParagraphEditor('BOTTOM')
+ editorState(editor).text = ''
+ editorState(editor).cursor = 0
+
+ expect(editor.getCaretRect()).toEqual({ x: 3, y0: 80, y1: 90 })
+ })
+
test('moveLeft', () => {
const { editor } = createEditor()
editor.moveLeft()