Initializing paragraph with styles

following a lead from https://discuss.prosemirror.net/t/adding-style-on-the-fly/703/11I came up with this plugin:

appendTransaction(trs, oldState, newState) {
	if (trs.length !== 1 || trs[0].steps.length !== 1 || !trs[0].steps[0].slice.content.firstChild || trs[0].steps[0].slice.content.firstChild.marks.length > 0) return;

	const { fontFamily, fontSize } = getCurrFont();
	const schema = trs[0].doc.type.schema;
	const familyMark = schema.marks.fontFamily.create({ fontFamily }), sizeMark=schema.marks.fontSize.create({ fontSize });

	let newTr = newState.tr
	trs.forEach(tr => {
		tr.steps.forEach(step => {
			step.getMap().forEach((oldStart, oldEnd, newStart, newEnd) => {
				newState.doc.nodesBetween(newStart, newEnd, (parentNode, parentPos) => {
					parentNode.forEach((childNode, childOffset) => {
						if (childNode.isText) newTr = newTr.addMark(newStart, newEnd, familyMark).addMark(newStart, newEnd, sizeMark)
					})
				})
			})
		})
	})

	newTr=newTr.removeStoredMark(schema.marks.fontFamily).removeStoredMark(schema.marks.fontSize);
	newTr=newTr.addStoredMark(familyMark).addStoredMark(sizeMark);
	return newTr;
}

The good news is that it works :slight_smile: but

  • I am not confident about the test in the beginning, how do I safely recognize that I am in a the transaction of a newly created paragraph with no marks ?

  • it’s terribly involved, is there no simpler way ?

thx!

1 Like