Skip to content

Commit d1481d4

Browse files
feat(media): show an image, video or audio item on every question
A picture, a clip or a recording often belongs to the question it explains, not to a block of its own: "What do you see in this image?" needs the image right next to its answer field. Every question type now accepts the extra setting `media` that content blocks use, and shows it below the description, inside the question. The editor offers "Add image, video or audio" in the actions of a question, which shows the address field and moves the focus to it, and "Remove image, video or audio" to take it away again; content blocks keep the field always visible. The answer fields of a question name the item in their accessible description next to the question's description, so screen reader users hear it while answering. The results summary shows the item of a question as well, with the same consent notice for YouTube and Vimeo. The display and the fields move from the content block into a QuestionMedia component that Question renders for every type, and the media helpers of the e2e tests into a shared support file. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Andy Scherzinger <info@andy-scherzinger.de>
1 parent 618e04d commit d1481d4

25 files changed

Lines changed: 912 additions & 496 deletions

‎docs/DataStructure.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ Optional extra settings for some [Question Types](#question-types)
276276
| `ratingIcon` | `linearscale` with `questionType` `rating` | string | `'star', 'heart', 'thumb'` | Set the icon of the rating, default: `'star'` |
277277
| `goTo` | `dropdown, linearscale, multiple_unique` | Array | see [Jumps](#jumps) | Where to go next for an answer |
278278
| `next` | `color, content, date, file, grid, long, multiple, ranking, short, time` | Integer / string | question id, `'submit'` | Where to go after the question, see [Jumps](#jumps) |
279-
| `media` | `content` | Object / null | see [Media](#media) | The image, video or audio item the block shows |
279+
| `media` | all | Object / null | see [Media](#media) | The image, video or audio item shown below the description |
280280

281281
### Jumps
282282

@@ -297,7 +297,7 @@ The respondent's path starts at the first question and follows these targets. It
297297

298298
### Media
299299

300-
The extra setting `media` of a `content` block holds one image, video or audio item:
300+
The extra setting `media` of a question of any type holds one image, video or audio item, shown below the question's description:
301301

302302
```json
303303
"media": {
@@ -307,7 +307,7 @@ The extra setting `media` of a `content` block holds one image, video or audio i
307307
}
308308
```
309309

310-
- `url` is the `http` or `https` address of the item, `alt` its description for screen readers (images, and the players of shared videos and audio) or the text of the link to it (YouTube and Vimeo videos and other addresses). Both are strings or `null`; `media` itself may be `null` for a block with only title and description.
310+
- `url` is the `http` or `https` address of the item, `alt` its description for screen readers (images, and the players of shared videos and audio) or the text of the link to it (YouTube and Vimeo videos and other addresses). Both are strings or `null`; `media` itself may be `null` for a question without an item, such as a `content` block with only title and description.
311311
- `type` is `image`, `video`, `audio` or `null`, and the server sets it from `url` whenever `media` is saved with a new `url`, whatever the request sent, and keeps the stored type while `url` is unchanged: `video` for a YouTube or Vimeo video, the type of the file for a public share link of this instance (or its download address) to an image, video or audio file that can be downloaded without a password, and `null` for any other address. The server does not fetch other addresses. When the stored type differs from the type sent, the response header `X-Forms-Adjusted` holds `media-type` with the id of the question, see [Adjustments by the server](API_v3.md#adjustments-by-the-server).
312312
- Clients show shared images from their public preview (`/apps/files_sharing/publicpreview/<token>`) and other shared files from their download address (`/s/<token>/download`) without preloading them, load YouTube (`www.youtube-nocookie.com`) and Vimeo (`player.vimeo.com`, do not track) players only after the respondent agrees, and show other addresses as a link. The pages showing a form allow these two player origins as frames.
313313
- Other keys in `media`, values of other types and other media types are rejected with 400 "Invalid extraSettings".

‎lib/Constants.php‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,10 +290,16 @@ class Constants {
290290
* A content block shows a title, a description and optionally one image, video or audio item; it takes no answer.
291291
*/
292292
public const EXTRA_SETTINGS_CONTENT = [
293-
'media' => ['array', 'NULL'],
294293
'next' => ['integer', 'string'],
295294
];
296295

296+
/**
297+
* Extra settings of every question type: one image, video or audio item shown below the description
298+
*/
299+
public const EXTRA_SETTINGS_ALL_TYPES = [
300+
'media' => ['array', 'NULL'],
301+
];
302+
297303
/**
298304
* Keys of the extra setting `media` with the allowed types of their values; `type` is set by the server.
299305
*/

‎lib/Controller/PageController.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ protected function insertHeaderOnIos(): void {
300300
}
301301

302302
/**
303-
* Create the CSP for pages showing a form, allowing the players of video blocks as frames
303+
* Create the CSP for pages showing a form, allowing the video players of question media as frames
304304
*/
305305
protected function createPolicy(): ContentSecurityPolicy {
306306
$policy = new ContentSecurityPolicy();

‎lib/Service/FormsService.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -896,7 +896,10 @@ private function getSharesWithUser(int $formId, string $userId): array {
896896
* @return array<string, list<string>> the allowed value types by extra setting
897897
*/
898898
public static function getAllowedExtraSettings(string $questionType): array {
899-
return match ($questionType) {
899+
if (!in_array($questionType, Constants::ANSWER_TYPES, true)) {
900+
return [];
901+
}
902+
return Constants::EXTRA_SETTINGS_ALL_TYPES + match ($questionType) {
900903
Constants::ANSWER_TYPE_DROPDOWN => Constants::EXTRA_SETTINGS_DROPDOWN,
901904
Constants::ANSWER_TYPE_MULTIPLE => Constants::EXTRA_SETTINGS_MULTIPLE,
902905
Constants::ANSWER_TYPE_MULTIPLEUNIQUE => Constants::EXTRA_SETTINGS_MULTIPLEUNIQUE,

‎playwright/e2e/content-blocks.spec.ts‎

Lines changed: 1 addition & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { test as randomUserTest } from '../support/fixtures/random-user.ts'
1414
import { test as submitTest } from '../support/fixtures/submit.ts'
1515
import { test as topBarTest } from '../support/fixtures/topBar.ts'
1616
import { api } from '../support/helpers.ts'
17+
import { createAudio, createMedia, sharePublicly } from '../support/media.ts'
1718
import { QuestionType } from '../support/sections/QuestionType.ts'
1819
import { FormsView } from '../support/sections/TopBarSection.ts'
1920

@@ -66,110 +67,6 @@ async function interceptPlayers(page: Page): Promise<string[]> {
6667
return requests
6768
}
6869

69-
/**
70-
* Create a small PNG image or a one second WebM video in the browser.
71-
*
72-
* @param page the page to create the file in
73-
* @param type the type of file
74-
* @return the bytes of the file
75-
*/
76-
async function createMedia(page: Page, type: 'image' | 'video'): Promise<Buffer> {
77-
const bytes = await page.evaluate(async (type) => {
78-
const canvas = document.createElement('canvas')
79-
canvas.width = 64
80-
canvas.height = 48
81-
const context = canvas.getContext('2d')!
82-
context.fillStyle = '#0082c9'
83-
context.fillRect(0, 0, 64, 48)
84-
let blob: Blob
85-
if (type === 'image') {
86-
blob = await new Promise<Blob>((resolve) => {
87-
canvas.toBlob((result) => resolve(result!), 'image/png')
88-
})
89-
} else {
90-
const recorder = new MediaRecorder(canvas.captureStream(10), {
91-
mimeType: 'video/webm',
92-
})
93-
const chunks: Blob[] = []
94-
recorder.ondataavailable = (event) => chunks.push(event.data)
95-
const stopped = new Promise((resolve) => {
96-
recorder.onstop = resolve
97-
})
98-
recorder.start()
99-
const timer = setInterval(() => context.fillRect(0, 0, 64, 48), 100)
100-
await new Promise((resolve) => setTimeout(resolve, 1000))
101-
recorder.stop()
102-
await stopped
103-
clearInterval(timer)
104-
blob = new Blob(chunks, { type: 'video/webm' })
105-
}
106-
return Array.from(new Uint8Array(await blob.arrayBuffer()))
107-
}, type)
108-
return Buffer.from(bytes)
109-
}
110-
111-
/**
112-
* Create a half second 440 Hz tone as a WAV file.
113-
*
114-
* @return the bytes of the file
115-
*/
116-
function createAudio(): Buffer {
117-
const rate = 8000
118-
const samples = rate / 2
119-
const wav = Buffer.alloc(44 + samples * 2)
120-
wav.write('RIFF', 0)
121-
wav.writeUInt32LE(36 + samples * 2, 4)
122-
wav.write('WAVEfmt ', 8)
123-
wav.writeUInt32LE(16, 16)
124-
wav.writeUInt16LE(1, 20)
125-
wav.writeUInt16LE(1, 22)
126-
wav.writeUInt32LE(rate, 24)
127-
wav.writeUInt32LE(rate * 2, 28)
128-
wav.writeUInt16LE(2, 32)
129-
wav.writeUInt16LE(16, 34)
130-
wav.write('data', 36)
131-
wav.writeUInt32LE(samples * 2, 40)
132-
for (let i = 0; i < samples; i++) {
133-
wav.writeInt16LE(
134-
Math.round(Math.sin((2 * Math.PI * 440 * i) / rate) * 8000),
135-
44 + i * 2,
136-
)
137-
}
138-
return wav
139-
}
140-
141-
/**
142-
* Upload a file to the logged in user's files and share it by public link.
143-
*
144-
* @param page the page of the logged in user
145-
* @param name the file name
146-
* @param content the file content
147-
* @return the public link of the share
148-
*/
149-
async function sharePublicly(
150-
page: Page,
151-
name: string,
152-
content: Buffer,
153-
): Promise<string> {
154-
const headers = { 'OCS-APIRequest': 'true', Accept: 'application/json' }
155-
const user = await page.request.get('../ocs/v2.php/cloud/user', { headers })
156-
const userId = (await user.json()).ocs.data.id
157-
const upload = await page.request.put(
158-
`../remote.php/dav/files/${encodeURIComponent(userId)}/${name}`,
159-
{ headers, data: content },
160-
)
161-
expect(upload.ok()).toBeTruthy()
162-
const share = await page.request.post(
163-
'../ocs/v2.php/apps/files_sharing/api/v1/shares',
164-
{
165-
headers,
166-
form: { path: `/${name}`, shareType: 3 },
167-
},
168-
)
169-
expect(share.ok()).toBeTruthy()
170-
return (await share.json()).ocs.data.url
171-
}
172-
17370
test.describe('Content blocks', () => {
17471
test.beforeEach(async ({ page, appNavigation, form }) => {
17572
await page.goto('apps/forms')
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
/**
2+
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
3+
* SPDX-License-Identifier: AGPL-3.0-or-later
4+
*/
5+
6+
import { expect, mergeTests } from '@playwright/test'
7+
import { test as formTest } from '../support/fixtures/form.ts'
8+
import { test as appNavigationTest } from '../support/fixtures/navigation.ts'
9+
import { test as randomUserTest } from '../support/fixtures/random-user.ts'
10+
import { test as submitTest } from '../support/fixtures/submit.ts'
11+
import { test as topBarTest } from '../support/fixtures/topBar.ts'
12+
import { createAudio, createMedia, sharePublicly } from '../support/media.ts'
13+
import { QuestionType } from '../support/sections/QuestionType.ts'
14+
import { FormsView } from '../support/sections/TopBarSection.ts'
15+
16+
const test = mergeTests(
17+
randomUserTest,
18+
appNavigationTest,
19+
formTest,
20+
topBarTest,
21+
submitTest,
22+
)
23+
24+
const ADD_MEDIA = 'Add image, video or audio'
25+
const ADDRESS = 'Address of an image, video or audio'
26+
27+
test.describe('Media on questions', () => {
28+
test.beforeEach(async ({ page, appNavigation, form }) => {
29+
await page.goto('apps/forms')
30+
await page.waitForURL(/apps\/forms\/?$/)
31+
await appNavigation.clickNewForm()
32+
await form.fillTitle('Question media test form')
33+
})
34+
35+
test('Shows an image below the description of a question and in the summary', async ({
36+
page,
37+
form,
38+
topBar,
39+
submitView,
40+
}) => {
41+
const link = await sharePublicly(
42+
page,
43+
'scene.png',
44+
await createMedia(page, 'image'),
45+
)
46+
await form.addQuestion(QuestionType.ShortAnswer)
47+
const [question] = await form.getQuestions()
48+
await question.fillTitle('What do you see?')
49+
await question.fillDescription('Look at the picture first.')
50+
await expect(
51+
question.section.getByRole('textbox', { name: ADDRESS }),
52+
).toHaveCount(0)
53+
54+
await question.openActionsMenu()
55+
await page.getByRole('button', { name: ADD_MEDIA }).click()
56+
const address = question.section.getByRole('textbox', { name: ADDRESS })
57+
await expect(address).toBeFocused()
58+
await question.fillMediaField(ADDRESS, link)
59+
await question.fillMediaField(
60+
'Description for screen readers',
61+
'A blue square',
62+
)
63+
await expect(
64+
question.section.getByRole('img', { name: 'A blue square' }),
65+
).toBeVisible()
66+
await question.openActionsMenu()
67+
await expect(page.getByRole('button', { name: ADD_MEDIA })).toHaveCount(0)
68+
await page.keyboard.press('Escape')
69+
70+
await topBar.toggleView(FormsView.View)
71+
const shown = submitView.getQuestion('What do you see?')
72+
const image = shown.getByRole('img', { name: 'A blue square' })
73+
await expect(image).toHaveAttribute(
74+
'src',
75+
/\/apps\/files_sharing\/publicpreview\/[A-Za-z0-9-]+\?x=1280&y=800&a=1$/,
76+
)
77+
expect(
78+
await shown.evaluate((item) => {
79+
const [description, picture, input] = [
80+
'.question__header__description__output',
81+
'img',
82+
'input',
83+
].map((selector) => item.querySelector(selector)!)
84+
return (
85+
!!(
86+
description.compareDocumentPosition(picture)
87+
& Node.DOCUMENT_POSITION_FOLLOWING
88+
)
89+
&& !!(
90+
picture.compareDocumentPosition(input)
91+
& Node.DOCUMENT_POSITION_FOLLOWING
92+
)
93+
)
94+
}),
95+
).toBe(true)
96+
await expect(shown.getByRole('textbox')).toHaveAccessibleDescription(
97+
/^Look at the picture first\.\s*A blue square$/,
98+
)
99+
await submitView.fillText('What do you see?', 'A square')
100+
await submitView.submit()
101+
await expect(submitView.successMessage).toBeVisible()
102+
103+
await topBar.toggleView(FormsView.Results)
104+
await expect(page.getByRole('img', { name: 'A blue square' })).toBeVisible()
105+
})
106+
107+
test('Plays audio attached to a choice question', async ({
108+
page,
109+
form,
110+
topBar,
111+
submitView,
112+
}) => {
113+
const link = await sharePublicly(page, 'note.wav', createAudio())
114+
await form.addQuestion(QuestionType.Checkboxes)
115+
const [question] = await form.getQuestions()
116+
await question.fillTitle('Which instrument is it?')
117+
await question.addAnswer('Piano')
118+
await question.openActionsMenu()
119+
await page.getByRole('button', { name: ADD_MEDIA }).click()
120+
await question.fillMediaField(ADDRESS, link)
121+
await question.fillMediaField(
122+
'Description for screen readers',
123+
'Download the note',
124+
)
125+
await expect(
126+
question.section.getByText(
127+
'Add a transcript of the audio to the description',
128+
),
129+
).toBeVisible()
130+
131+
await topBar.toggleView(FormsView.View)
132+
const shown = submitView.getQuestion('Which instrument is it?')
133+
await expect(shown.locator('audio')).toHaveAccessibleName(
134+
'Download the note',
135+
)
136+
await expect(shown.getByRole('checkbox', { name: 'Piano' })).toBeVisible()
137+
})
138+
139+
test('Removes the image, video or audio item of a question', async ({
140+
page,
141+
form,
142+
}) => {
143+
await form.addQuestion(QuestionType.ShortAnswer)
144+
const [question] = await form.getQuestions()
145+
await question.fillTitle('Where is it?')
146+
await question.openActionsMenu()
147+
await page.getByRole('button', { name: ADD_MEDIA }).click()
148+
await question.fillMediaField(ADDRESS, 'https://example.com/map')
149+
150+
await question.openActionsMenu()
151+
const saved = page.waitForResponse(
152+
(response) =>
153+
response.request().method() === 'PATCH'
154+
&& response.url().includes('/questions/'),
155+
)
156+
await page
157+
.getByRole('button', { name: 'Remove image, video or audio' })
158+
.click()
159+
expect((await saved).request().postDataJSON()).toEqual({
160+
keyValuePairs: { extraSettings: { media: null } },
161+
})
162+
await expect(
163+
question.section.getByRole('textbox', { name: ADDRESS }),
164+
).toHaveCount(0)
165+
await expect(
166+
question.section.getByRole('button', { name: 'Actions', exact: true }),
167+
).toBeFocused()
168+
169+
await page.reload()
170+
const reloaded = page.getByRole('listitem', { name: 'Question number 1' })
171+
await expect(
172+
reloaded.getByRole('textbox', { name: 'Title of question number 1' }),
173+
).toHaveValue('Where is it?')
174+
await expect(reloaded.getByRole('textbox', { name: ADDRESS })).toHaveCount(0)
175+
await reloaded.getByRole('button', { name: 'Actions', exact: true }).click()
176+
await expect(page.getByRole('button', { name: ADD_MEDIA })).toBeVisible()
177+
})
178+
179+
test('Offers no extra media action on a content block', async ({
180+
page,
181+
form,
182+
}) => {
183+
await form.addQuestion(QuestionType.Content)
184+
const [block] = await form.getQuestions()
185+
await expect(
186+
block.section.getByRole('textbox', { name: ADDRESS }),
187+
).toBeVisible()
188+
await block.openActionsMenu()
189+
await expect(page.getByRole('button', { name: ADD_MEDIA })).toHaveCount(0)
190+
})
191+
})

0 commit comments

Comments
 (0)