M9.9: text style runs + paragraph settings

TextDoc gains character style runs (font, size, colours, tracking, leading,
baseline shift, h/v scale, tsume, faux styles, caps, super/subscript, kerning
metrics/optical/manual, ligatures) and per-paragraph settings (justification
with last-line modes, indents, space before/after, direction, composer,
hanging punctuation), serde-compatible with single-style documents. Layout
handles mixed runs on a line (shared baseline, largest leading), every-line
composer, editing geometry (carets, hit testing, selection quads) and basic
vertical type. Renderer colours per run. Expressions get the sourceText style
API (style, getStyleAt, createStyle, setters with character ranges).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 10:34:13 -04:00
co-authored by Claude Opus 5.5
parent ea1bd0e0c4
commit f78435927b
11 changed files with 2278 additions and 253 deletions
+21
View File
@@ -49,6 +49,17 @@ pub enum Req {
SourceRect { comp: u64, layer: u64, t: Secs, extents: bool },
/// `[[time, duration, comment, chapter, url], …]` for a layer, or the comp when `layer` is None.
Markers { comp: u64, layer: Option<u64> },
/// A Source Text value as JSON `{doc, text, runs: [{len, style}], paras}` (styles as
/// `layer.setText` keys), or null for other properties.
Doc { comp: u64, layer: u64, path: String, t: Secs, pre: bool },
}
/// A text document as the style API's JSON.
pub fn doc_json(d: &effectcraft_keyframe::TextDoc) -> String {
use effectcraft_keyframe::text_doc::{char_style_json, para_style_json};
let runs: Vec<serde_json::Value> = d.runs().iter().map(|r| serde_json::json!({"len": r.len, "style": char_style_json(&r.style)})).collect();
let paras: Vec<serde_json::Value> = d.paras().iter().map(para_style_json).collect();
serde_json::json!({"doc": d, "text": d.text, "runs": runs, "paras": paras}).to_string()
}
/// Plain data answer, converted to a JS value by the runtime.
@@ -292,6 +303,16 @@ impl<'a> Resolver<'a> {
let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) };
value_resp(&v, prop_dims(l, p))
}
Req::Doc { comp, layer, path, t, pre } => {
let (l, p) = self.prop(*comp, *layer, path)?;
let t = f64::from_bits(*t);
let v = if *pre { p.value_at(l.layer_time(Tick::from_seconds_f64(t))) } else { self.ctx_at(*comp, t)?.value(l, p) };
match v {
Value::Text(d) => Resp::Str(doc_json(&d)),
Value::Str(s) => Resp::Str(doc_json(&effectcraft_keyframe::TextDoc::plain(&s))),
_ => Resp::Null,
}
}
Req::Xform { comp, layer, t } => {
let l = self.layer(*comp, *layer)?;
let ctx = self.ctx_at(*comp, f64::from_bits(*t))?;
+146 -1
View File
@@ -17,7 +17,7 @@ var textTotal = 1;
var selectorValue = [100, 100, 100];
// Request ops (must match runtime.rs).
var __COMP = 0, __COMPNAME = 1, __LAYER = 2, __LINFO = 3, __CHILD = 4, __PINFO = 5, __VALUE = 6, __XFORM = 7, __RECT = 8, __MARKERS = 9;
var __COMP = 0, __COMPNAME = 1, __LAYER = 2, __LINFO = 3, __CHILD = 4, __PINFO = 5, __VALUE = 6, __XFORM = 7, __RECT = 8, __MARKERS = 9, __DOC = 10;
function __begin(t, v, c, l, path, uid, idx, fd, ti, tt, sv) {
time = t;
@@ -34,6 +34,7 @@ function __begin(t, v, c, l, path, uid, idx, fd, ti, tt, sv) {
function __finish(r) {
r = __v(r);
if (r !== null && typeof r === 'object' && r.__isLayer) return r.index;
if (r !== null && typeof r === 'object' && r.__isTextStyle) return r.__out();
// `[temp, temp]` where temp is a property (pick-whip 1D → 2D): read the values here, while
// host requests can still be answered and the script re-run.
if (Array.isArray(r)) return r.map(function (x) { return __v(x); });
@@ -640,6 +641,18 @@ Prop.prototype = {
inTangents: function (t) { return this.valueAtTime(t === undefined ? time : t).inTangents(); },
outTangents: function (t) { return this.valueAtTime(t === undefined ? time : t).outTangents(); },
isClosed: function () { return this.value.isClosed(); },
// Source Text style API.
__docAt: function (t) {
var d = __h(__DOC, this.__c, this.__l, this.__p, t, this.__self);
if (d === null) __err('Property "' + this.name + '" is not a Source Text property');
return JSON.parse(d);
},
get style() { return this.getStyleAt(0); },
getStyleAt: function (i, t) {
if (t === undefined) t = time;
return new __TextStyle(this.__docAt(__v(t)), i === undefined ? 0 : Math.floor(__v(i)), [], false);
},
createStyle: function () { return new __TextStyle(this.__docAt(time), 0, [], true); },
valueOf: function () { return this.value; },
toString: function () { return String(this.value); },
};
@@ -658,6 +671,138 @@ function __mkProp(c, l, path) {
return new Proxy(new Prop(c, l, path), __propHandler);
}
// Text styles (the Source Text style API) ------------------------------------------------------
// A TextStyle is the source document (as JSON from the host), the character index it reads its
// attributes at, and the setter calls made on it ([key, value, start, count]). Setters return
// new objects; returning a style from a Source Text expression applies it.
function __TextStyle(doc, idx, ops, empty) { this.__d = doc; this.__i = idx; this.__ops = ops; this.__empty = empty; }
function __styleSetter(key, conv) {
return function (v, start, count) {
v = __v(v);
if (conv) v = conv(v, this);
var s = start === undefined ? -1 : Math.max(0, Math.floor(__v(start)));
var n = count === undefined ? -1 : Math.max(0, Math.floor(__v(count)));
return new __TextStyle(this.__d, this.__i, this.__ops.concat([[key, v, s, n]]), this.__empty);
};
}
function __colorIn(c) {
if (typeof c === 'string') return c;
return [c[0], c[1], c[2]];
}
__TextStyle.prototype = {
__isTextStyle: true,
__base: function () {
var runs = this.__d.runs, pos = 0, i = this.__i;
for (var k = 0; k < runs.length; k++) {
if (i < pos + runs[k].len || k === runs.length - 1) return runs[k].style;
pos += runs[k].len;
}
return {};
},
__para: function () {
var t = this.text, p = 0;
for (var k = 0; k < Math.min(this.__i, t.length); k++) if (t[k] === '\n' || t[k] === '\r') p++;
var paras = this.__d.paras;
return paras[Math.min(p, paras.length - 1)];
},
__get: function (key, para) {
for (var k = this.__ops.length - 1; k >= 0; k--) {
var o = this.__ops[k];
if (o[0] !== key) continue;
if (o[2] < 0 || (this.__i >= o[2] && (o[3] < 0 || this.__i < o[2] + o[3]))) return o[1];
}
return (para ? this.__para() : this.__base())[key];
},
get text() {
var t = this.__d.text;
for (var k = 0; k < this.__ops.length; k++) {
var o = this.__ops[k];
if (o[0] !== 'text') continue;
if (o[2] < 0) t = String(o[1]);
else t = t.slice(0, o[2]) + String(o[1]) + (o[3] < 0 ? '' : t.slice(o[2] + o[3]));
}
return t;
},
get font() { return this.__get('font'); },
get fontSize() { return this.__get('size'); },
get isFauxBold() { return this.__get('fauxBold'); },
get isFauxItalic() { return this.__get('fauxItalic'); },
get isAllCaps() { return this.__get('allCaps'); },
get isSmallCaps() { return this.__get('smallCaps'); },
get tracking() { return this.__get('tracking'); },
get autoLeading() { return this.__get('leading') === 'auto'; },
get leading() { var l = this.__get('leading'); return l === 'auto' ? this.fontSize * 1.2 : l; },
get baselineShift() { return this.__get('baselineShift'); },
get applyFill() { return this.__get('applyFill'); },
get fillColor() { var c = this.__get('fill'); return [c[0], c[1], c[2]]; },
get applyStroke() { return this.__get('applyStroke'); },
get strokeColor() { var c = this.__get('stroke'); return [c[0], c[1], c[2]]; },
get strokeWidth() { return this.__get('strokeWidth'); },
get horizontalScaling() { return this.__get('hScale'); },
get verticalScaling() { return this.__get('vScale'); },
get tsume() { return this.__get('tsume'); },
get baselineOption() { return this.__get('baseline'); },
get isSuperscript() { return this.__get('baseline') === 'superscript'; },
get isSubscript() { return this.__get('baseline') === 'subscript'; },
get kerningType() { var k = this.__get('kerning'); return typeof k === 'number' ? 'manual' : k; },
get kerning() { var k = this.__get('kerning'); return typeof k === 'number' ? k : 0; },
get isLigature() { return this.__get('ligatures'); },
get justification() { return this.__get('justify', true); },
get firstLineIndent() { return this.__get('indentFirst', true); },
get startIndent() { return this.__get('indentLeft', true); },
get endIndent() { return this.__get('indentRight', true); },
get spaceBefore() { return this.__get('spaceBefore', true); },
get spaceAfter() { return this.__get('spaceAfter', true); },
get direction() { return this.__get('direction', true); },
get isEveryLineComposer() { return this.__get('composer', true) === 'everyLine'; },
get isHangingRoman() { return this.__get('hangingPunctuation', true); },
setText: __styleSetter('text', function (v) { return String(v); }),
replaceText: __styleSetter('text', function (v) { return String(v); }),
setFont: __styleSetter('font', function (v) { return String(v); }),
setFontSize: __styleSetter('size'),
setFauxBold: __styleSetter('fauxBold', Boolean),
setFauxItalic: __styleSetter('fauxItalic', Boolean),
setAllCaps: __styleSetter('allCaps', Boolean),
setSmallCaps: __styleSetter('smallCaps', Boolean),
setTracking: __styleSetter('tracking'),
setLeading: __styleSetter('leading'),
setAutoLeading: __styleSetter('leading', function (v, s) { return v ? 'auto' : s.leading; }),
setBaselineShift: __styleSetter('baselineShift'),
setApplyFill: __styleSetter('applyFill', Boolean),
setFillColor: __styleSetter('fill', __colorIn),
setApplyStroke: __styleSetter('applyStroke', Boolean),
setStrokeColor: __styleSetter('stroke', __colorIn),
setStrokeWidth: __styleSetter('strokeWidth'),
setHorizontalScaling: __styleSetter('hScale'),
setVerticalScaling: __styleSetter('vScale'),
setTsume: __styleSetter('tsume'),
setBaselineOption: __styleSetter('baseline', function (v) { return String(v).toLowerCase().replace('_baseline', ''); }),
setSuperscript: __styleSetter('superscript', Boolean),
setSubscript: __styleSetter('subscript', Boolean),
setKerningType: __styleSetter('kerning', function (v) { v = String(v).toLowerCase(); return v === 'manual' ? 0 : v; }),
setKerning: __styleSetter('kerning', Number),
setLigature: __styleSetter('ligatures', Boolean),
setJustification: __styleSetter('justify', function (v) { return String(v); }),
setFirstLineIndent: __styleSetter('indentFirst'),
setStartIndent: __styleSetter('indentLeft'),
setEndIndent: __styleSetter('indentRight'),
setSpaceBefore: __styleSetter('spaceBefore'),
setSpaceAfter: __styleSetter('spaceAfter'),
setDirection: __styleSetter('direction', function (v) { v = String(v).toLowerCase(); return v.indexOf('right') === 0 || v === 'rtl' ? 'rtl' : 'ltr'; }),
setEveryLineComposer: __styleSetter('composer', function (v) { return v ? 'everyLine' : 'singleLine'; }),
setHangingRoman: __styleSetter('hangingPunctuation', Boolean),
__out: function () {
return { __style: true, __json: JSON.stringify({ doc: this.__empty ? null : this.__d.doc, ops: this.__ops }) };
},
toString: function () { return this.text; },
valueOf: function () { return this.text; },
};
Object.defineProperty(__TextStyle.prototype, 'length', { get: function () { return this.text.length; } });
// Markers ---------------------------------------------------------------------------------------
function Markers(c, l) { this.__c = c; this.__l = l; this.__m = null; }
+75 -6
View File
@@ -70,7 +70,14 @@ pub enum Out {
Num(f64),
Str(String),
Arr(Vec<Out>),
Path { points: Vec<[f64; 2]>, ins: Vec<[f64; 2]>, outs: Vec<[f64; 2]>, closed: bool },
Path {
points: Vec<[f64; 2]>,
ins: Vec<[f64; 2]>,
outs: Vec<[f64; 2]>,
closed: bool,
},
/// A text style object: JSON `{doc: TextDoc | null, ops: [[key, value, start, count], …]}`.
Style(String),
Object(String),
}
@@ -131,6 +138,13 @@ fn native_host(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsV
let l = num(args, 2, ctx)?;
Req::Markers { comp: id(args, 1, ctx)?, layer: (l >= 0.0).then_some(l as u64) }
}
10 => Req::Doc {
comp: id(args, 1, ctx)?,
layer: id(args, 2, ctx)?,
path: string(args, 3, ctx)?,
t: secs(num(args, 4, ctx)?),
pre: arg(args, 5).to_boolean(),
},
_ => return Err(JsNativeError::typ().with_message("unknown host request").into()),
};
let found = FRAMES.with(|f| {
@@ -278,6 +292,10 @@ fn detach(v: &JsValue, ctx: &mut Context, depth: usize) -> Result<Out, String> {
}
return Ok(Out::Arr(out));
}
if o.get(js_string!("__style"), ctx).map_err(err)?.to_boolean() {
let j = o.get(js_string!("__json"), ctx).map_err(err)?;
return Ok(Out::Style(j.as_string().map(|s| s.to_std_string_escaped()).unwrap_or_default()));
}
if o.get(js_string!("__path"), ctx).map_err(err)?.to_boolean() {
let pts = |name: JsString, ctx: &mut Context| -> Result<Vec<[f64; 2]>, String> {
let v = o.get(name, ctx).map_err(err)?;
@@ -408,6 +426,9 @@ pub fn to_value(out: &Out, current: &Value) -> Result<Value, String> {
Out::Arr(a) => a.iter().map(|x| if let Out::Num(n) = x { js_number(*n) } else { String::new() }).collect::<Vec<_>>().join(","),
Out::Undefined | Out::Null => String::new(),
Out::Path { .. } => "[object Path]".into(),
Out::Style(j) => {
serde_json::from_str::<serde_json::Value>(j).ok().map(|v| styled_doc(&v, &effectcraft_keyframe::TextDoc::default()).text).unwrap_or_default()
}
Out::Object(s) => s.clone(),
}
};
@@ -428,11 +449,17 @@ pub fn to_value(out: &Out, current: &Value) -> Result<Value, String> {
}
Value::Bool(_) => Value::Bool(truthy(out)),
Value::Enum(_) => Value::Enum((finite(numeric(out).unwrap_or(1.0))? - 1.0).round().max(0.0) as u32),
Value::Text(doc) => {
let mut d = doc.clone();
d.text = text(out);
Value::Text(d)
}
Value::Text(doc) => match out {
Out::Style(j) => {
let v: serde_json::Value = serde_json::from_str(j).map_err(|e| format!("Error: bad text style: {e}"))?;
Value::Text(Box::new(styled_doc(&v, doc)))
}
_ => {
let mut d = doc.clone();
d.set_text(&text(out));
Value::Text(d)
}
},
Value::Str(_) => Value::Str(text(out)),
Value::Path(_) => match out {
Out::Path { points, ins, outs, closed } => {
@@ -450,6 +477,48 @@ pub fn to_value(out: &Out, current: &Value) -> Result<Value, String> {
})
}
/// Apply a returned text style (`{doc, ops}`) to the property's own document `own`: the style's
/// source document (another layer's, or this one's) gives the formatting, then the setter calls
/// apply in order. Without `setText` the text stays `own`'s.
pub fn styled_doc(v: &serde_json::Value, own: &effectcraft_keyframe::TextDoc) -> effectcraft_keyframe::TextDoc {
use effectcraft_keyframe::TextDoc;
let mut d = own.clone();
if let Some(src) = v.get("doc").filter(|s| !s.is_null()).and_then(|s| serde_json::from_value::<TextDoc>(s.clone()).ok()) {
if src.text == own.text {
// The same text (this layer's own style, or an identical one): every run carries over.
d = TextDoc { box_size: own.box_size, box_pos: own.box_pos, vertical: own.vertical, ..src };
} else {
let first = src.style_at(0);
d.runs.clear();
d.apply_style_all(|s| *s = first.clone());
let p0 = src.para(0);
d.set_paras(vec![p0; d.para_count()]);
d.stroke_over_fill = src.stroke_over_fill;
}
}
for op in v.get("ops").and_then(|o| o.as_array()).into_iter().flatten() {
let Some(key) = op.get(0).and_then(|k| k.as_str()) else { continue };
let val = op.get(1).cloned().unwrap_or_default();
let start = op.get(2).and_then(|x| x.as_i64()).unwrap_or(-1);
let count = op.get(3).and_then(|x| x.as_i64()).unwrap_or(-1);
let n = d.char_len();
let range = (start >= 0).then(|| {
let a = (start as usize).min(n);
a..if count < 0 { n } else { (a + count as usize).min(n) }
});
if key == "text" {
let s = val.as_str().unwrap_or_default();
match range {
Some(r) => d.replace_range(r, s, None),
None => d.set_text(s),
}
continue;
}
let _ = d.set_attr(key, &val, range);
}
d
}
/// Number → string like JS (`3`, not `3.0`).
fn js_number(x: f64) -> String {
if x.is_finite() && x == x.trunc() && x.abs() < 1e21 { format!("{}", x as i64) } else { format!("{x}") }
+54
View File
@@ -723,6 +723,60 @@ fn source_text_reading_and_string_methods() {
assert_close!(f.num("thisComp.layer('Title').text.sourceText.length", 0.0), 5.0);
}
#[test]
fn source_text_style_api() {
let mut f = fx();
let doc = |f: &Fx, e: &str| -> TextDoc {
match f.ev(f.title, "text/sourceText", e, 0.0) {
Ok(Value::Text(d)) => *d,
r => panic!("{e}: {r:?}"),
}
};
// Getters read the first character's style.
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.fontSize", 0.0), 40.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.isAllCaps ? 1 : 0", 0.0), 0.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.autoLeading ? 1 : 0", 0.0), 1.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.leading", 0.0), 48.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.fillColor[1]", 0.0), 1.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.setFontSize(12).fontSize", 0.0), 12.0);
// Setters chain and return a styled document.
let d = doc(&f, "text.sourceText.style.setFontSize(80).setFillColor([1, 0, 0]).setAllCaps(true)");
assert_eq!(d.text, "Hello");
assert!(d.is_uniform());
assert_eq!((d.size, d.fill, d.all_caps), (80.0, [1.0, 0.0, 0.0, 1.0], true));
// Character ranges create runs; setText replaces the text.
let d = doc(&f, "text.sourceText.style.setText('Hi there').setFontSize(20, 3, 5).setFauxBold(true, 0, 2)");
assert_eq!(d.text, "Hi there");
let sizes: Vec<(usize, f64, bool)> = d.runs().iter().map(|r| (r.len, r.style.size, r.style.faux_bold)).collect();
assert_eq!(sizes, vec![(2, 40.0, true), (1, 40.0, false), (5, 20.0, false)]);
// getStyleAt reads a styled document per character (and at a time).
{
let l = f.layer_mut(f.title);
let p = l.props.prop_mut("text/sourceText").unwrap();
let Value::Text(d) = &mut p.value else { panic!() };
d.apply_style(1..3, |s| s.size = 99.0);
}
assert_close!(f.num("thisComp.layer('Title').text.sourceText.getStyleAt(2, 0).fontSize", 0.0), 99.0);
assert_close!(f.num("thisComp.layer('Title').text.sourceText.getStyleAt(4).fontSize", 0.0), 40.0);
// Returning the own style keeps its runs; plain strings keep the first character's style.
let d = doc(&f, "text.sourceText.style");
assert_eq!(d.runs().len(), 3);
let d = doc(&f, "'Bye'");
assert_eq!((d.text.as_str(), d.size), ("Bye", 40.0));
// Paragraph setters.
let d = doc(&f, "text.sourceText.style.setJustification('CENTER_JUSTIFY').setStartIndent(12).setSpaceBefore(4).setEveryLineComposer(false)");
assert_eq!(d.justify, effectcraft_keyframe::Justify::Center);
assert_eq!((d.indent_left, d.space_before), (12.0, 4.0));
assert_close!(f.num("thisComp.layer('Title').text.sourceText.style.setStartIndent(7).startIndent", 0.0), 7.0);
// createStyle sets only what's given and keeps the existing runs.
let d = doc(&f, "thisComp.layer('Title').text.sourceText.createStyle().setTsume(50).setBaselineOption('superscript')");
assert_eq!(d.text, "Hello");
assert!(d.runs().iter().all(|r| r.style.tsume == 50.0 && r.style.baseline == effectcraft_keyframe::BaselineOption::Superscript));
assert_eq!(d.runs().len(), 3);
// Non-text properties have no style.
assert!(f.ev(f.a, ROT, "transform.rotation.style.fontSize", 0.0).is_err());
}
#[test]
fn numbers_to_source_text() {
let f = fx();