Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 16 additions & 18 deletions src/lib/actions/edits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { api } from '../api'
import { t } from '../i18n'
import { canEditOpenCanvas, pickedSelectors, useStore } from '../store'
import { currentPageCanvas } from '../pages'
import { LAYER_TEXT_PROPERTIES } from '../richText'
import { recordUpdates, trackSave } from '../history'
import { isCanvasElement } from '../drawing'
import {
Expand Down Expand Up @@ -511,19 +512,6 @@ const VISUAL_PROPERTIES = [
'mix-blend-mode',
] as const

const TEXT_PROPERTIES = [
'color',
'font-family',
'font-size',
'font-weight',
'font-style',
'line-height',
'letter-spacing',
'text-transform',
'text-decoration-line',
'text-align',
] as const

const STYLE_CLIP_KEY = 'doop:style-clip'

interface StyleClip {
Expand All @@ -538,12 +526,13 @@ export async function copyProperties(): Promise<boolean> {
const s = useStore.getState()
const picked = s.selectedElement
if (!picked) return false
const [visual, info] = await Promise.all([
computedStyles(picked.frameId, picked.selector, [...VISUAL_PROPERTIES, ...TEXT_PROPERTIES]),
const [visual, type, info] = await Promise.all([
computedStyles(picked.frameId, picked.selector, VISUAL_PROPERTIES),
computedStyles(picked.frameId, picked.selector, LAYER_TEXT_PROPERTIES, { fromTextRun: true }),
inspectElement(picked.frameId, picked.selector),
])
if (!visual || !info) return false
const text = info.hasText ? Object.fromEntries(TEXT_PROPERTIES.map((k) => [k, visual[k] ?? ''])) : null
if (!visual || !type || !info) return false
const text = info.hasText ? Object.fromEntries(LAYER_TEXT_PROPERTIES.map((k) => [k, type[k] ?? ''])) : null
const clip: StyleClip = { visual: Object.fromEntries(VISUAL_PROPERTIES.map((k) => [k, visual[k] ?? ''])), text }
try {
localStorage.setItem(STYLE_CLIP_KEY, JSON.stringify(clip))
Expand All @@ -569,7 +558,16 @@ export const hasStyleClip = () => !!styleClip()
export function pasteProperties(): boolean {
const clip = styleClip()
if (!clip) return false
return styleEach((info) => ({ ...clip.visual, ...(clip.text && info.hasText ? clip.text : {}) }))
const p = pickedLayers()
if (!p || p.frame.locked) return false
for (const selector of p.selectors) {
void inspectElement(p.frame.id, selector).then((info) => {
if (!info) return
const text = clip.text && info.hasText ? clip.text : null
void styleElement(p.frame.id, selector, { ...clip.visual, ...text }, { uniformText: !!text })
})
}
return true
}

/* ---- pick a colour from anywhere on screen ---- */
Expand Down
18 changes: 14 additions & 4 deletions src/lib/frameBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,15 @@ export async function inspectElement(frameId: string, selector: string): Promise
/** Write inline styles onto the element. The runtime saves the edited
* document through the frame's normal edit path and answers with the
* element's fresh properties. */
export async function styleElement(frameId: string, selector: string, styles: StylePatch): Promise<ElementInfo | null> {
return infoOf(await requestFrame(frameId, 'doop:style', { selector, styles }))
/** `uniformText` makes the patch's type the whole layer's: the inline runs
* under it drop their own values, and <b> / <i> / <u> runs their formatting. */
export async function styleElement(
frameId: string,
selector: string,
styles: StylePatch,
{ uniformText = false }: { uniformText?: boolean } = {},
): Promise<ElementInfo | null> {
return infoOf(await requestFrame(frameId, 'doop:style', { selector, styles, uniformText }))
}

/** Replace image content through the same live edit/undo path as styles. */
Expand Down Expand Up @@ -355,13 +362,16 @@ export async function formatElementText(
}

/** The element's computed values for `properties`, or null when the selector
* no longer resolves or the frame is not mounted. */
* no longer resolves or the frame is not mounted. `fromTextRun` reads them
* off the element's first text run instead, where a bold or italic run's
* formatting shows. */
export async function computedStyles(
frameId: string,
selector: string,
properties: readonly string[],
{ fromTextRun = false }: { fromTextRun?: boolean } = {},
): Promise<Record<string, string> | null> {
const reply = await requestFrame(frameId, 'doop:computed', { selector, properties: [...properties] })
const reply = await requestFrame(frameId, 'doop:computed', { selector, properties: [...properties], fromTextRun })
return reply && reply.values && typeof reply.values === 'object' ? (reply.values as Record<string, string>) : null
}

Expand Down
12 changes: 8 additions & 4 deletions src/lib/frameRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,7 @@ export const FRAME_BOOTSTRAP = `<!doctype html>
} else if (Object.keys(edit.touched).length || edit.runs.length || edit.created.length || edit.renamed.length) postEdited(true)
return true
}
function applyStyle(selector, styles) {
function applyStyle(selector, styles, uniformText) {
var el = styleTarget(selector)
if (!el || isLocked(el)) return false
var textPatch = isTextPatch(styles)
Expand Down Expand Up @@ -1291,6 +1291,7 @@ export const FRAME_BOOTSTRAP = `<!doctype html>
return true
}
if (textPatch) noteRuns(clearTextRuns(el, styles))
else if (uniformText) noteRuns(clearTextRuns(el, layerTextPatch(styles)))
if (styleEdit && styleEdit.selector === selector) {
Object.assign(styleEdit.styles, styles)
previewStyle(el, styles)
Expand Down Expand Up @@ -1319,9 +1320,12 @@ export const FRAME_BOOTSTRAP = `<!doctype html>
var computedEl = styleTarget(d.selector)
var values = null
if (computedEl) {
var cs = getComputedStyle(computedEl)
var run = d.fromTextRun === true ? firstTextRun(computedEl) : computedEl
var cs = getComputedStyle(run)
values = {}
d.properties.forEach(function (name) { values[name] = cs.getPropertyValue(name) })
d.properties.forEach(function (name) {
values[name] = name === 'text-decoration-line' && run !== computedEl ? runDecoration(run, computedEl) : cs.getPropertyValue(name)
})
}
parent.postMessage({ type: 'doop:computed-result', reqId: d.reqId, values: values }, '*')
}
Expand All @@ -1334,7 +1338,7 @@ export const FRAME_BOOTSTRAP = `<!doctype html>
parent.postMessage({ type: 'doop:settle-result', reqId: d.reqId }, '*')
}
if (d.type === 'doop:style' && d.styles && typeof d.styles === 'object') {
var applied = applyStyle(d.selector, d.styles)
var applied = applyStyle(d.selector, d.styles, d.uniformText === true)
parent.postMessage({ type: 'doop:style-result', reqId: d.reqId, ok: applied, info: applied ? inspect(d.selector) : null }, '*')
}
if (d.type === 'doop:replace-image') {
Expand Down
49 changes: 43 additions & 6 deletions src/lib/frameTextRuntime.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { TEXT_FORMAT_COMMANDS, TEXT_STYLE_PROPERTIES } from './richText'
import { LAYER_TEXT_PROPERTIES, TEXT_FORMAT_COMMANDS, TEXT_STYLE_PROPERTIES } from './richText'

/** Runs in FRAME_BOOTSTRAP's closure, sharing its active element and save path. */
export const FRAME_TEXT_RUNTIME = `
var textCommands = ${JSON.stringify(TEXT_FORMAT_COMMANDS)}
var textProps = ${JSON.stringify(TEXT_STYLE_PROPERTIES)}
var layerTextProps = ${JSON.stringify(LAYER_TEXT_PROPERTIES)}
var TEXT_RUN_MARK = 'doop-run'
var textRange = null
var lastTextSelection = ''
Expand Down Expand Up @@ -260,11 +261,44 @@ export const FRAME_TEXT_RUNTIME = `
run.remove()
}

/* The element whose computed type the layer's text shows: its first text
run's holder (a <b> made by ⌘B, say), else the layer itself. */
function firstTextRun(el) {
var node = textNodesIn(el, null)[0]
return node && node.parentElement ? node.parentElement : el
}

/* The lines a run's text is drawn with: text-decoration is not inherited
but painted across descendants, so an underline on the layer shows on its
<b> run though the run's own computed value is none. Every line set from
the run up to the layer counts. */
function runDecoration(run, layer) {
var lines = []
for (var el = run; el; el = el === layer ? null : el.parentElement) {
getComputedStyle(el).textDecorationLine.split(/\\s+/).forEach(function (line) {
if (line && line !== 'none' && lines.indexOf(line) === -1) lines.push(line)
})
}
return lines.length ? lines.join(' ') : 'none'
}

/* The type properties of a patch, for clearing a layer's runs under it. */
function layerTextPatch(styles) {
var text = {}
for (var key in styles) if (layerTextProps.indexOf(key) !== -1) text[key] = styles[key]
return text
}

/* The formatting tags a layer-wide value replaces: a weight set over <b>
runs takes their boldness with it, a style their italics, a decoration
their underline or strike. */
var FORMAT_TAGS = { 'font-weight': /^(B|STRONG)$/, 'font-style': /^(I|EM)$/, 'text-decoration-line': /^(U|S|STRIKE)$/ }

/* A value set on the whole layer makes it uniform: the inline runs under it
drop their own copy of the property, and a weight set over <b> / <strong>
runs takes their boldness with it (the tag becomes a span with the same
attributes), as Figma applies a layer-wide value over its mixed runs.
Returns what a cancelled gesture must undo. */
drop their own copy of the property, and the formatting tags it replaces
(FORMAT_TAGS) become spans with the same attributes, as Figma applies a
layer-wide value over its mixed runs. Returns what a cancelled gesture
must undo. */
function clearTextRuns(el, styles) {
var before = []
var renamed = []
Expand All @@ -276,7 +310,10 @@ export const FRAME_TEXT_RUNTIME = `
before.push({ el: run, cssText: cssText })
if (!run.getAttribute('style')) run.removeAttribute('style')
}
if (!Object.prototype.hasOwnProperty.call(styles, 'font-weight') || !/^(B|STRONG)$/.test(run.tagName)) return
var replaced = Object.keys(FORMAT_TAGS).some(function (key) {
return Object.prototype.hasOwnProperty.call(styles, key) && FORMAT_TAGS[key].test(run.tagName)
})
if (!replaced) return
var span = document.createElement('span')
Array.prototype.forEach.call(run.attributes, function (attr) { span.setAttribute(attr.name, attr.value) })
while (run.firstChild) span.appendChild(run.firstChild)
Expand Down
17 changes: 17 additions & 0 deletions src/lib/richText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,20 @@ export type TextFormatState = Partial<Record<TextFormatCommand, boolean>>
/** Design panel text properties a selection inside an edited element scopes
* to its own runs; set on the whole layer, they override its runs. */
export const TEXT_STYLE_PROPERTIES = ['font-family', 'font-size', 'font-weight', 'color'] as const

/** The type a pasted look (⌥⌘V) carries from one text layer to another. It
* is read off the source's first text run, since ⌘B / ⌘I / ⌘U format a
* layer by wrapping its text in <b> / <i> / <u>, and it replaces the
* target's runs' own values, so the pasted type is what shows. */
export const LAYER_TEXT_PROPERTIES = [
'color',
'font-family',
'font-size',
'font-weight',
'font-style',
'line-height',
'letter-spacing',
'text-transform',
'text-decoration-line',
'text-align',
] as const
57 changes: 57 additions & 0 deletions tests/richTextBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,63 @@ describe.skipIf(!findBrowserPath())('rich text editing', { timeout: 30_000 }, ()
expect((await inspect())?.textMixed).toEqual({})
})

it('copies the type of a layer formatted with ⌘B / ⌘I and pastes it over the formatting of another', async () => {
await send({
type: 'doop:html',
html:
'<p id="source" style="margin:0;font:24px Arial;text-decoration:underline"><b><i><s>Bold</s></i></b></p>' +
'<p id="text" style="margin:0;font:16px Arial;background:red">Plain <b>and</b> <u>marked</u></p>',
reqId: 'render',
})
await frame.waitForSelector('#source')
const reqId = `computed-${++nextReq}`
await send({
type: 'doop:computed',
selector: '#source',
properties: ['font-weight', 'font-style', 'font-size', 'text-decoration-line'],
fromTextRun: true,
reqId,
})
await page.waitForFunction(
(reqId) => (window as unknown as Fixture).messages.some((m) => m.reqId === reqId),
{},
reqId,
)
const copied = await page.evaluate(
(reqId) =>
(
(window as unknown as Fixture).messages.find((m) => m.reqId === reqId) as unknown as {
values: Record<string, string>
}
).values,
reqId,
)
// The paragraph's underline is painted on the run too, though not inherited.
expect(copied).toEqual({
'font-weight': '700',
'font-style': 'italic',
'font-size': '24px',
'text-decoration-line': 'line-through underline',
})

await ask('doop:style', {
selector: '#text',
styles: {
'background-color': 'blue',
'font-weight': '400',
'font-style': 'italic',
'text-decoration-line': 'none',
},
uniformText: true,
})
expect(await frame.$eval('#text', (el) => el.innerHTML)).toBe('Plain <span>and</span> <span>marked</span>')
expect(await frame.$$eval('#text span', (runs) => runs.map((r) => getComputedStyle(r).fontWeight))).toEqual([
'400',
'400',
])
expect(await frame.$eval('#text', (el) => getComputedStyle(el).backgroundColor)).toBe('rgb(0, 0, 255)')
})

it('restores a cancelled size scrub on selected words and saves a committed one once', async () => {
await render('<p id="text" style="margin:0;font:24px Arial">Hello world</p>')
await select(0, 5)
Expand Down
Loading