From 9390067c2dba65cd182b18964c2b1db03f73a85a Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Sat, 7 Nov 2026 16:38:22 +0200 Subject: [PATCH] fix(author): measure slide text as Course Presentation draws it, and set it larger where there is room The slide layout measured text at the slide's 16 px in lines of 1.5, but Course Presentation draws a paragraph at 10.8 px per 640 in lines of 1.25em, so a text box came out about twice as tall as its text and a slide of text alone showed small text in its top part. Text is now measured at the sizes Course Presentation 1.27's stylesheet gives each block, and on a slide with room and no question it is set larger, in steps up to twice, as large as fits with its pictures whole. The size goes on each block, written as the content check writes a style, so the lines grow with it and an untrusted play changes nothing. Text whose source sets a size keeps it. Closes #145. --- design/author.md | 11 +- packages/author/README.md | 9 +- packages/author/lib/types.mjs | 133 ++++++++++++++++-- packages/author/tests/layout.test.ts | 44 ++++++ .../types/H5P.CoursePresentation.md | 4 +- 5 files changed, 181 insertions(+), 20 deletions(-) diff --git a/design/author.md b/design/author.md index 5c1fda4d..3a0b49d4 100644 --- a/design/author.md +++ b/design/author.md @@ -49,8 +49,15 @@ to 3,000. Eleven things the code does not say by itself: Map and Branching Scenario are edited on a slide, a video, a map and a tree of their own, which set fields the form hides (`widget: "none"`). `lib/types.mjs` does each one's work on the generated content, wherever the type appears: a slide's unplaced elements stacked, text as tall as its lines - on CP's 16:9 slide at 16 px per 640, pictures shrunk in shape, a question in what is left, with a - note when a slide holds too much; interactions placed apart, clear of what shows at the same + as CP 1.27's stylesheet draws them, pictures shrunk in shape, a question in what is left, with a + note when a slide holds too much. Text is measured at the sizes CP draws, a paragraph at 10.8 px + per 640 in lines of 1.25em (`SLIDE_TEXT`), and on a slide with room and no question it is set + larger, in steps up to twice, as large as fits with its pictures whole (#145): measured at the + slide's 16 px before, a text box was twice as tall as its text, and a slide of text alone showed + small text in its top part. The size goes on each block, not on a span inside, since CP gives a + paragraph's lines in em and a span would inherit them as a length, so its lines would overlap; + and it is written as the content check writes a style, so an untrusted play changes nothing. + Text whose source sets a size keeps it. Interactions placed apart, clear of what shows at the same time, and named by their library; a poster sized by what it holds, in IV's em (a 16:9 video is 40 by 22.5): a picture in its shape, as the editor's own widget does, a text as wide as keeps it short, a question 17 by 16. The editor starts every interaction at 10 by 10 and leaves the diff --git a/packages/author/README.md b/packages/author/README.md index 5aa09add..bc7e0a9e 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -73,10 +73,11 @@ What `params` takes is what H5P's editor would let an author save in the same fo and the command lists what stayed English. A source may still set one by name. Some content types have a widget of their own in the editor, which sets fields the form hides. -The build does what those widgets do: it lays out a Course Presentation slide's elements, places -Interactive Video interactions, joins Game Map stages and sets their ids, numbers Branching -Scenario end screens, and names untitled Question Set questions. It refuses what they would not -let pass: a scenario path with no end, a map with no start, a hotspot question with no right area. +The build does what those widgets do: it lays out a Course Presentation slide's elements, setting +the text larger where a slide has room and no question, places Interactive Video interactions, +joins Game Map stages and sets their ids, numbers Branching Scenario end screens, and names +untitled Question Set questions. It refuses what they would not let pass: a scenario path with no +end, a map with no start, a hotspot question with no right area. A source with problems writes nothing and lists every problem by its path at once: diff --git a/packages/author/lib/types.mjs b/packages/author/lib/types.mjs index a95998b6..016d696c 100644 --- a/packages/author/lib/types.mjs +++ b/packages/author/lib/types.mjs @@ -97,18 +97,100 @@ const interactiveBook = { /* ---------------------------------------------------------------- Course Presentation */ /** - * The slide Course Presentation draws, 16:9, and the text it draws on it at that size: 16 px on a - * slide 640 px wide, about 8.5 px a character, 1.5 lines. Positions and sizes are percentages of - * the slide's width (`x`, `width`) and height (`y`, `height`). + * The slide Course Presentation draws, 16:9, 640 by 360 px at the size its stylesheet is written + * for. Positions and sizes are percentages of the slide's width (`x`, `width`) and height (`y`, + * `height`). `font`, `char` and `line` are the text Interactive Video's layout measures with + * (`textLines`): 16 px, about 8.5 px a character, lines of 1.5. */ const SLIDE = { width: 640, height: 360, font: 16, char: 8.5, line: 1.5 } const MARGIN_X = 4 const MARGIN_Y = 5 const GAP = 2 +/** + * Text as Course Presentation 1.27 draws it on that slide, from its stylesheet and Advanced + * Text's (#145): an element at .75em of the slide's 16 px, 12 px; a paragraph at .9em of that, + * 10.8 px, in lines of 1.25em with 1em after it; `h2` at 1.667em and `h3` at 1.333em, in lines of + * 1.5em with .5em after; a list item at the element's size in lines of 1.25em, 1em apart. `em` is + * a block's size in em of the element's, `size` the same in px, `line` and `after` in em of the + * block's own size; `pre` takes no style, so it is never set larger. Measured at the slide's + * 16 px in lines of 1.5, as before, a text box came out about twice as tall as its text. These are + * the minor the pack carries, as the editor rules the other layouts follow are pinned. + */ +const SLIDE_TEXT = { + p: { em: 0.9, size: 10.8, line: 1.25, after: 1, sized: true }, + h2: { em: 1.667, size: 20, line: 1.5, after: 0.5, sized: true }, + h3: { em: 1.333, size: 16, line: 1.5, after: 0.5, sized: true }, + li: { em: 1, size: 12, line: 1.25, after: 1, sized: true }, + pre: { em: 1, size: 12, line: 1.25, after: 1, sized: false } +} +/** A list's room above and below it, in px: 1em of the element's 12 px each way. */ +const LIST_MARGIN = 24 +/** About how wide a character is, as a part of the font's size, in H5P's sans. */ +const CHARACTER = 0.53 +/** Larger text, tried largest first, on a slide with room for it (#145). */ +const TEXT_STEPS = [2, 1.75, 1.5, 1.25] + +/** + * How much of the slide's height markup takes, in percent, as Course Presentation draws it in a + * box `pixels` wide with every block that takes a size `step` times as large: each paragraph, + * heading and list item by its lines and the room after it, each list by the room around it, and + * a little to spare. Text in no block is measured as a paragraph. + * @param {string} html + * @param {number} pixels + * @param {number} [step] + */ +function slideTextHeight(html, pixels, step = 1) { + /** @type {Array<{ tag: keyof typeof SLIDE_TEXT, inner: string }>} */ + const blocks = [...html.matchAll(/<(p|h2|h3|li|pre)\b[^>]*>([\s\S]*?)<\/\1>/gi)].map((match) => ({ + tag: /** @type {keyof typeof SLIDE_TEXT} */ (match[1].toLowerCase()), + inner: match[2] + })) + if (!blocks.length && textOf(html)) blocks.push({ tag: 'p', inner: html }) + let height = (html.match(/<(?:ul|ol)\b/gi) ?? []).length * LIST_MARGIN + for (const { tag, inner } of blocks) { + const metric = SLIDE_TEXT[tag] + const size = metric.size * (metric.sized ? step : 1) + const perLine = Math.max(8, Math.floor(pixels / (size * CHARACTER))) + const lines = inner.split(//i).reduce((sum, piece) => sum + Math.max(1, Math.ceil(textOf(piece).length / perLine)), 0) + height += lines * size * metric.line + size * metric.after + } + return Math.min(95, (height / SLIDE.height) * 100 + 2) +} + +/** + * Markup with each block that takes a size set `step` times as large: a `font-size` on the block + * itself, in em of the element's, so the lines, which the stylesheet gives in em, grow with it. A + * span inside a paragraph would inherit the paragraph's line height as a length, and its lines + * would overlap. The content check keeps it: Advanced Text allows `font.size`, and a style may + * sit on a paragraph, a heading or a list item; one the block has already is kept beside it. + * Written as the content check writes a style it keeps, so an untrusted play changes nothing: + * each declaration trimmed, in the order of its patterns, joined by `;` and ended with one. + * @param {string} html + * @param {number} step + */ +function sizedText(html, step) { + const blocks = /<(?:p|h2|h3|li|pre)\b/i.test(html) ? html : `

${html}

` + return blocks.replace(/<(p|h2|h3|li)\b([^>]*)>/gi, (_, /** @type {string} */ tag, /** @type {string} */ attributes) => { + const style = /\sstyle\s*=\s*(["'])([\s\S]*?)\1/i.exec(attributes) + const declarations = (style?.[2] ?? '').split(';').map((each) => each.trim()).filter(Boolean) + declarations.push(`font-size:${round(SLIDE_TEXT[/** @type {'p' | 'h2' | 'h3' | 'li'} */ (tag.toLowerCase())].em * step)}em`) + const rank = (/** @type {string} */ declaration) => { + const at = STYLE_ORDER.indexOf(declaration.slice(0, declaration.indexOf(':')).trim().toLowerCase()) + return at < 0 ? STYLE_ORDER.length : at + } + const value = `style="${declarations.sort((a, b) => rank(a) - rank(b)).join(';')};"` + return style ? `<${tag}${attributes.replace(style[0], ` ${value}`)}>` : `<${tag}${attributes} ${value}>` + }) +} + +/** The order the content check writes a kept style's declarations in, its patterns' (`stylePatterns`). */ +const STYLE_ORDER = ['text-align', 'font-size', 'font-family', 'color', 'background-color', 'letter-spacing', 'line-height'] + /** * How many lines markup takes at 16 px in a width, at about 8.5 px a character: a heading's at - * its size, and a little between blocks. + * its size, and a little between blocks. Interactive Video's measure; Course Presentation's is + * `slideTextHeight`. * @param {string} html * @param {number} pixels */ @@ -134,10 +216,7 @@ function wanted(element, width) { const library = machineName(element?.action?.library) const params = element?.action?.params ?? {} const pixels = (width / 100) * SLIDE.width - if (library === 'H5P.AdvancedText') { - const lines = textLines(String(params.text ?? ''), pixels) - return { height: Math.min(95, (lines * SLIDE.font * SLIDE.line / SLIDE.height) * 100 + 3), flexible: false, min: 8 } - } + if (library === 'H5P.AdvancedText') return { height: slideTextHeight(String(params.text ?? ''), pixels), flexible: false, min: 8 } if (library === 'H5P.Image') { const file = params.file ?? {} const ratio = file.width && file.height ? file.height / file.width : 9 / 16 @@ -149,10 +228,38 @@ function wanted(element, width) { return { height: 0, flexible: true, min: element?.displayAsButton ? 12 : 40 } } +/** + * On a slide with room left and no question to give it to, its text set larger, in steps, the + * largest that fits with every picture at its full size (#145): Course Presentation draws text + * small, a paragraph at 10.8 px on a slide 640 px wide, and a slide of text alone showed it in its + * top part. Only text nobody sized: one that sets a `font-size` anywhere keeps its own. + * @param {any[]} free the elements being stacked + * @param {Array<{ kind: string, height: number, min: number }>} kinds what each wants, in the same order + * @param {number} spare percent of the slide's height left over + * @param {number} width percent of the slide's width each takes + */ +function growText(free, kinds, spare, width) { + const texts = free.flatMap((element, i) => + kinds[i].kind === 'fixed' && machineName(element?.action?.library) === 'H5P.AdvancedText' && + typeof element.action.params?.text === 'string' && !/font-size/i.test(element.action.params.text) ? [i] : []) + if (!texts.length || spare <= 0) return + const pixels = (width / 100) * SLIDE.width + for (const step of TEXT_STEPS) { + const heights = texts.map((i) => slideTextHeight(free[i].action.params.text, pixels, step)) + if (heights.reduce((sum, height, n) => sum + height - kinds[texts[n]].height, 0) > spare) continue + texts.forEach((i, n) => { + kinds[i].height = kinds[i].min = heights[n] + free[i].action.params.text = sizedText(free[i].action.params.text, step) + }) + return + } +} + /** * Elements without a position are stacked down the slide, full width, below any placed by hand. - * Text keeps the height its lines need; a picture or a video shrinks, keeping its shape, to leave - * a question the room it needs; a question takes what is left. + * Text keeps the height its lines need, set larger where the slide has room and no question; + * a picture or a video shrinks, keeping its shape, to leave a question the room it needs; a + * question takes what is left. * @param {any[]} elements * @param {string} path * @param {LayoutContext} context @@ -172,15 +279,17 @@ function stackSlide(elements, path, context) { return { kind: 'fixed', height: want.height, min: want.height } }) const room = 100 - MARGIN_Y - top - GAP * (free.length - 1) - const fixed = kinds.filter((each) => each.kind === 'fixed' || each.kind === 'button').reduce((sum, each) => sum + each.height, 0) + const fixedHeight = () => kinds.filter((each) => each.kind === 'fixed' || each.kind === 'button').reduce((sum, each) => sum + each.height, 0) const flexible = kinds.filter((each) => each.kind === 'flexible') const pictures = kinds.filter((each) => each.kind === 'picture') - const needed = fixed + flexible.reduce((sum, each) => sum + each.min, 0) + pictures.reduce((sum, each) => sum + each.min, 0) + const needed = fixedHeight() + flexible.reduce((sum, each) => sum + each.min, 0) + pictures.reduce((sum, each) => sum + each.min, 0) if (needed > room + 0.5) { context.note(path, flexible.length ? 'likely holds more than fits on one slide: split it, or show the question as a button ("displayAsButton": true)' : 'likely holds more than fits on one slide: split it') } + if (!flexible.length) growText(free, kinds, room - fixedHeight() - pictures.reduce((sum, each) => sum + each.height, 0), width) + const fixed = fixedHeight() let rest = Math.max(0, room - fixed) // Pictures first get what they want, up to an equal share of what is left after the questions' minimum. const forPictures = Math.max(0, rest - flexible.reduce((sum, each) => sum + each.min, 0)) diff --git a/packages/author/tests/layout.test.ts b/packages/author/tests/layout.test.ts index c32d0a2b..47d62189 100644 --- a/packages/author/tests/layout.test.ts +++ b/packages/author/tests/layout.test.ts @@ -48,6 +48,50 @@ describe('Course Presentation', () => { expect(second[1].y).toBeGreaterThanOrEqual(30) }) + const text = (html: string) => ({ action: { library: 'H5P.AdvancedText', params: { text: html } } }) + const slides = async (...elements: unknown[][]) => + (await build('H5P.CoursePresentation', { presentation: { slides: elements.map((each) => ({ elements: each })) } })).presentation.slides.map( + (slide: { elements: Array<{ y: number, height: number, action: { params: { text?: string } } }> }) => slide.elements + ) + + it('measures text as Course Presentation draws it, so a text box is about as tall as its text (#145)', async () => { + // An h2 in lines of 30 px with 10 after, a paragraph in lines of 13.5 px with 10.8 after: 64 px + // of the slide's 360. At the slide's 16 px in lines of 1.5, as before, the box was 25. + const [[box]] = await slides([text('

Rivers

Water runs down to the sea.

'), { action: question }]) + expect(box.height).toBeGreaterThan(17) + expect(box.height).toBeLessThan(21) + // Beside a question, the text keeps its size and the question the room. + expect(box.action.params.text).toBe('

Rivers

Water runs down to the sea.

') + }) + + it('sets text larger on a slide with room and no question, as large as fits (#145)', async () => { + const long = Array.from({ length: 5 }, (_, i) => `

Paragraph ${i}: the sun warms the sea, and some of the water rises into the air as vapour.

`).join('') + const [[short], [longer], [full]] = await slides( + [text('

The water cycle

How water travels between the sea, the sky and the land.

')], + [text(`

Evaporation

${long}`)], + // Eleven one-line paragraphs: 74 % of the slide as written, 93 % at the smallest step, past the 90 there is. + [text(Array.from({ length: 11 }, () => '

The sun warms the sea, and some of the water rises into the air as vapour.

').join(''))] + ) + // Twice the size, the largest step, on the size each block has. + expect(short.action.params.text).toBe('

The water cycle

How water travels between the sea, the sky and the land.

') + expect(short.y + short.height).toBeLessThanOrEqual(95) + // More text, a smaller step. + expect(longer.action.params.text).toMatch(/^

Evaporation<\/h2>

/) + expect(longer.y + longer.height).toBeLessThanOrEqual(95) + // No room for even the smallest step: as written. + expect(full.action.params.text).not.toContain('font-size') + }) + + it('keeps a size the source set, and a block’s own style beside the one it adds (#145)', async () => { + const [[sized], [centred]] = await slides( + [text('

Already sized

')], + [text('

A centred line

')] + ) + expect(sized.action.params.text).toBe('

Already sized

') + // As the content check writes a style it keeps: text-align first, each ended with a semicolon. + expect(centred.action.params.text).toBe('

A centred line

') + }) + it('says when a slide holds more than fits', async () => { const long = Array.from({ length: 12 }, (_, i) => `

Paragraph ${i} about rivers, lakes, seas and the water cycle that joins them.

`).join('') const { notes } = await result('H5P.CoursePresentation', { presentation: { slides: [{ elements: [{ action: { library: 'H5P.AdvancedText', params: { text: long } } }, { action: question }] }] } }) diff --git a/skills/h5p-author/references/types/H5P.CoursePresentation.md b/skills/h5p-author/references/types/H5P.CoursePresentation.md index 5a9b158e..81e42741 100644 --- a/skills/h5p-author/references/types/H5P.CoursePresentation.md +++ b/skills/h5p-author/references/types/H5P.CoursePresentation.md @@ -3,9 +3,9 @@ Slides with text, pictures, video and questions; a summary slide with the score follows when there are questions. - `presentation.slides` is the list of slides; each slide's `elements` are sub-content under `action`: `{ "action": { "library": "H5P.AdvancedText", "params": { … } } }`. -- Leave out `x`, `y`, `width` and `height` and the build stacks a slide's elements top to bottom: text as tall as its lines, pictures in shape, a question in what is left. It notes a slide that holds too much; split it, or show its question as a button (`"displayAsButton": true`). To place an element by hand, give all four, in percent of the slide's width and height from the top left. +- Leave out `x`, `y`, `width` and `height` and the build stacks a slide's elements top to bottom: text as tall as its lines, pictures in shape, a question in what is left. On a slide with room and no question it sets the text larger, up to twice its size; text you give a `font-size` keeps it. It notes a slide that holds too much; split it, or show its question as a button (`"displayAsButton": true`). To place an element by hand, give all four, in percent of the slide's width and height from the top left. - A slide's `keywords` (`[{ "main": "…" }]`) name it in the outline. -- The slide is 16:9; at most a short heading, a paragraph and a picture, or a question, fit one slide. +- The slide is 16:9: a heading with a few short paragraphs or a list, or with a paragraph and a picture, or with a line of text and a question, fits one slide. Keep to one idea a slide. ## Example