Skip to content
Open
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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ What changed for the people who use AnnoTinder: researchers, coders and
those who run a server. Server, client and contracts are released together
under one version.

## Unreleased

- **Audio and video in unit layouts.** `$unit.clip::audio` and
`$unit.clip::video` (or a `::: audio` / `::: video` block) show a player
for the media file at an `https://` URL in the unit. Nothing is uploaded:
the files are hosted elsewhere. Clips don't autoplay, and their controls
don't swipe the card.
- **Unit fields of type `image`, `audio` and `video`**: links to such files.
A CSV column of https links ending in `.jpg`, `.mp3`, `.mp4` and the like
is suggested as one; the upload checks that every value is an `https://`
link. The simple layout puts these fields in the body as a picture or a
player. API: `POST /units` takes `fields` with the types of new link
columns.

## 0.10.0 (2026-12-04)

**Licence: AGPL-3.0 (or later), was MIT.** A server running a changed version
Expand Down
17 changes: 13 additions & 4 deletions docs/api/researcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -813,15 +813,20 @@ Schemas: [`contracts/src/unit.ts`](../../packages/contracts/src/unit.ts), [`unit
Implementation: [`researcher/units*.ts`](../../packages/server/src/researcher/), [`sets.ts`](../../packages/server/src/researcher/sets.ts).

**Unit fields.** All units of a study have the same fields, each `text`,
`number` or `boolean`; values are stored typed (`42`, not `"42"`), and `null`
is an empty value of any type. The first upload sets the fields
`number`, `boolean`, `list`, or `image`, `audio` or `video`; values are
stored typed (`42`, not `"42"`), and `null` is an empty value of any type.
An `image`, `audio` or `video` value is text: an `https://` link to such a
file (or a `data:` URL of that kind; `mediaUrl` in `media.ts`), checked on
upload and when retyped. The first upload sets the fields
(`fieldsOfUnits` in `unitFields.ts`). A later upload must give every
existing field a fitting value (`checkUnitData`; `null` for empty) and may
add fields (`addedFields`): they are appended, and units already stored
have no value for them. New field names are letters, digits and `_`, not
starting with a digit (`UNIT_FIELD_NAME`), so designs can refer to them
as `$unit.<name>`. Deleting all units resets the fields. Clients infer the
types of CSV columns (`inferFieldType`) and send typed values. The role
types of CSV columns (`inferFieldType`; a column of https links to image,
audio or video files by their extension) and send typed values, with the
types of new link columns in `fields`. The role
columns (`coder_set`, `condition_set`, `part_set`, `test_set`) aren't
unit data: the client's CSV upload writes them with
[putSetGroup](#putsetgroup).
Expand Down Expand Up @@ -872,7 +877,11 @@ units by id, the units with the [unit ids given](#filtering-by-unit)
`POST /study/:studyId/units` → `UnitResponseSchema[]` (201). Up to 200 per
call, all or nothing. Every unit's data must fit the study's fields (400 with
the first problem, e.g. `Unit 'u3': Field 'n' is number, got text`); the
first upload sets them, later ones may add fields. An existing external id is a 409, unless
first upload sets them, later ones may add fields. A new field's type comes
from its values; `fields` (`UnitFieldSchema[]`, optional) can give a new
column of text as `image`, `audio` or `video` (every value must then be a
link: `Field 'clip' is audio: "a.mp3" isn't an https:// link`). Other types
given there are ignored. An existing external id is a 409, unless
`overwrite: true`; a unit that was coded (`coded`) also needs
`overwriteCoded: true`. Its answers keep the unit version their coder saw
([listUnitVersions](#listunitversions)); spans may no longer fit the new
Expand Down
6 changes: 4 additions & 2 deletions docs/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ after the slot, never inside `{{ }}`:
| `::text` (default) | literal text, never parsed as markdown (`**x**` stays `**x**`) |
| `::markdown` | rendered markdown (no blocks or values inside) |
| `::image` | an image from the URL |
| `::audio` | an `<audio controls>` player for an `https:` (or `data:audio/`) URL |
| `::video` | a `<video controls playsinline>` player for an `https:` (or `data:video/`) URL |
| `::html` | HTML in a sandboxed iframe (below) |

`$unit.text` equals `{{$unit.text}}`. `\$` is a literal `$`; references in
Expand All @@ -271,7 +273,7 @@ but ours, which reports the content height. A default style copied from the
app (colours, font size, light or dark) makes plain HTML fit in; the HTML's
own CSS overrides it.

**Typed blocks**: `::: text|markdown|html|image [name]` … `:::` show their
**Typed blocks**: `::: text|markdown|html|image|audio|video [name]` … `:::` show their
content (values inserted as they are) as one thing of that kind. A suffix is
the short form of a typed block. Typed blocks don't nest.

Expand Down Expand Up @@ -310,7 +312,7 @@ Pandoc's fenced divs.
only.
- `style <css>`: the content in a `<div>` with inline CSS (per property;
`position: fixed/sticky` refused).
- `text|markdown|html|image [name]`: typed blocks (above).
- `text|markdown|html|image|audio|video [name]`: typed blocks (above).
- A bare `:::` closes the innermost block and needs as many colons as its
opening fence, so outer blocks use more colons.

Expand Down
22 changes: 22 additions & 0 deletions packages/client/src/lib/admin/csv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,28 @@ describe("csvToUnits", () => {
expect(result.errors).toEqual([]);
});

it("types a column of links to audio or video files as such, and says which values aren't links", () => {
const h = ["id", "clip", "page"];
const r = [
["1", "https://x.org/a.mp3", "https://x.org/1"],
["2", " https://x.org/b.ogg", "https://x.org/2"],
];
const mapping = assignAllColumns(h, r, initialMapping(h, r, []), [], 0);
expect(mapping.map((m) => m.type)).toEqual(["number", "audio", "text"]);
expect(csvToUnits(h, r, 0, mapping).units[1].data).toEqual({
clip: "https://x.org/b.ogg",
page: "https://x.org/2",
});
// Chosen as video: every value must be an https link
const asVideo = mapping.map((m) => (m.column === 2 ? { ...m, type: "video" as const } : m));
expect(csvToUnits(h, r, 0, asVideo).errors).toEqual([]);
const bad = [...r, ["3", "x.mp3", "http://x.org/3"]];
expect(csvToUnits(h, bad, 0, asVideo).errors).toEqual([
"clip: 1 value isn't an https:// link ('x.mp3')",
"page: 1 value isn't an https:// link ('http://x.org/3')",
]);
});

it("links columns to the study's fields, leaves unmapped fields empty, and reports what doesn't fit", () => {
const studyFields = [
{ name: "text", type: "text" as const },
Expand Down
6 changes: 5 additions & 1 deletion packages/client/src/lib/admin/csv.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
inferFieldType,
isMediaKind,
isAnswerColumn,
parseFieldValue,
toUnitFieldName,
Expand Down Expand Up @@ -175,8 +176,11 @@ export function mappingProblems(
return `Two columns are uploaded as ${m.field}`;
const type = existing?.type ?? m.type;
const { count, examples } = badValues(rows, m.column, type);
const shown = examples.map((e) => `'${e}'`).join(", ");
if (count > 0 && isMediaKind(type))
return `${count} value${count === 1 ? " isn't an https:// link" : "s aren't https:// links"} (${shown})`;
if (count > 0)
return `${count} value${count === 1 ? " isn't a" : "s aren't"} ${type === "text" ? "text" : `${type}${count === 1 ? "" : "s"}`} (${examples.map((e) => `'${e}'`).join(", ")})`;
return `${count} value${count === 1 ? " isn't a" : "s aren't"} ${type === "text" ? "text" : `${type}${count === 1 ? "" : "s"}`} (${shown})`;
return null;
});
}
Expand Down
10 changes: 9 additions & 1 deletion packages/client/src/lib/admin/uploadUnits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ export type JoinMode = "distribute" | "new";

export interface UnitsUpload {
units: UnitCreate[];
/** The types of new link columns (image, audio, video), which their values can't tell the server. */
fields?: UnitField[];
overwrite: boolean;
overwriteCoded: boolean;
/** The file's role columns: each replaces what the column had. */
Expand All @@ -162,7 +164,12 @@ export interface UnitsUpload {

/** The server calls an upload makes. */
export interface UploadApi {
createUnits(body: { units: UnitCreate[]; overwrite: boolean; overwriteCoded: boolean }): Promise<unknown>;
createUnits(body: {
units: UnitCreate[];
overwrite: boolean;
overwriteCoded: boolean;
fields?: UnitField[];
}): Promise<unknown>;
listUnits(): Promise<{ id: number; externalId: string }[]>;
putSetGroup(group: string, body: SetGroupWrite): Promise<unknown>;
}
Expand Down Expand Up @@ -191,6 +198,7 @@ export async function uploadUnits(
overwrite: upload.overwrite,
overwriteCoded: upload.overwrite && upload.overwriteCoded,
units: upload.units.slice(uploaded, uploaded + UPLOAD_BATCH),
...(upload.fields?.length ? { fields: upload.fields } : {}),
});
}
uploaded = upload.units.length;
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/lib/codebook/renderTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export function staticTemplate(source: string): RenderedTemplate {
markdown,
values: expressions.map((e) => ({
...toValue(e, source.slice(e.start, e.end)),
suffix: e.suffix === "image" || e.suffix === "html" ? "text" : e.suffix,
suffix: e.suffix === "markdown" ? "markdown" : "text",
})),
};
}
25 changes: 25 additions & 0 deletions packages/client/src/lib/components/TemplateMarkdown.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,29 @@ describe("TemplateMarkdown blocks", () => {
expect(html).toContain("ABOUT CLIMATE");
expect(rendered.values.at(-1)).toEqual({ suffix: "text", text: "about", block: true, field: "summary" });
});

it("plays ::audio and ::video values and blocks with controls, no autoplay, and no swipe from their controls", async () => {
const s: ReferenceScope = {
$unit: { clip: "https://example.org/clip.mp3", film: "https://example.org/film.mp4" },
$var: {},
};
const rendered = await renderTemplate("$unit.clip::audio\n\n::: video film\n$unit.film\n:::", s);
const html = renderToStaticMarkup(<TemplateMarkdown rendered={rendered} />);
expect(html).toContain(
'<div data-no-swipe="" data-field="unit.clip"><audio controls="" preload="metadata" src="https://example.org/clip.mp3" class="w-full"></audio></div>',
);
expect(html).toContain(
'<div data-no-swipe="" data-field="film"><video controls="" playsInline="" preload="metadata" src="https://example.org/film.mp4"',
);
expect(html).not.toContain("autoplay");
});

it("says when it can't play a clip's link, and shows nothing for an empty one", async () => {
const s: ReferenceScope = { $unit: { a: "javascript:alert(1)", b: "http://example.org/b.mp4", c: "" }, $var: {} };
const html = renderToStaticMarkup(
<TemplateMarkdown rendered={await renderTemplate("$unit.a::audio\n\n$unit.b::video\n\n$unit.c::audio", s)} />,
);
expect(html).not.toMatch(/<audio|<video|javascript:|http:/);
expect(html.match(/its link must start with https:\/\//g)).toHaveLength(2);
});
});
32 changes: 31 additions & 1 deletion packages/client/src/lib/components/TemplateMarkdown.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { CSSProperties, ReactNode } from "react";
import { mediaUrl } from "@annotinder/contracts";
import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import type { RenderedTemplate, TemplateValue } from "../codebook/renderTemplate";
Expand All @@ -12,7 +13,7 @@ import { markBackground, markedPieces, type Mark, type Marks } from "../codebook
* instruction text. The markdown is rendered with `react-markdown` (no raw
* HTML), and each value by its suffix: `text` as a React text node (never
* parsed as markdown), `markdown` as nested markdown, `image` as an image,
* `html` in a sandboxed iframe; a unit field span questions select in as
* `audio` and `video` as a player, `html` in a sandboxed iframe; a unit field span questions select in as
* selectable text.
*/
export function TemplateMarkdown({
Expand Down Expand Up @@ -71,6 +72,32 @@ function styleComponents(styles: Record<string, string>[] | undefined): Componen
} as Components;
}

/**
* An `::audio` or `::video` value: a player for the file at its URL, with its
* own controls (no autoplay). Scrubbing or setting the volume is no swipe
* (`data-no-swipe`). A URL it can't play says so, for the researcher.
*/
function MediaPlayer({ kind, text, field }: { kind: "audio" | "video"; text: string; field?: string }) {
if (!text.trim()) return null;
const src = mediaUrl(text, kind);
const marked = field ? { "data-field": field } : {};
if (!src)
return (
<div className="text-sm text-muted-foreground" {...marked}>
Can't play this {kind}: its link must start with https://
</div>
);
return (
<div data-no-swipe="" {...marked}>
{kind === "audio" ? (
<audio controls preload="metadata" src={src} className="w-full" />
) : (
<video controls playsInline preload="metadata" src={src} className="h-auto max-h-[60vh] max-w-full" />
)}
</div>
);
}

function TemplateValueView({
value,
block,
Expand Down Expand Up @@ -98,6 +125,9 @@ function TemplateValueView({
switch (value.suffix) {
case "image":
return value.text ? <img src={value.text} alt={value.field ?? ""} className="max-w-full" {...field} /> : null;
case "audio":
case "video":
return <MediaPlayer kind={value.suffix} text={value.text} field={value.field} />;
case "html":
// Researchers' or units' own HTML, in a sandbox (SandboxedHtml.tsx)
return value.text ? (
Expand Down
13 changes: 12 additions & 1 deletion packages/client/src/lib/components/admin/ItemForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import type { ResearcherApi } from "../../api/httpResearcherApi";
import type { AnyVariableType, DesignItem, SetGroupResponse, DesignIssue, UrlParam } from "@annotinder/contracts";
import type {
AnyVariableType,
DesignItem,
SetGroupResponse,
DesignIssue,
UnitFieldType,
UrlParam,
} from "@annotinder/contracts";
import { UnitLoopForm } from "./UnitLoopForm";
import { LayoutForm } from "./unitLoop/LayoutForm";
import { SessionItemForm } from "./SessionItemForm";
Expand Down Expand Up @@ -27,6 +34,8 @@ interface ItemFormProps {
loopItems?: DesignItem[];
/** The study's unit fields (completions in a layout's template). */
unitFields?: string[];
/** Their types (a layout shows image, audio and video fields as such). */
unitFieldTypes?: Partial<Record<string, UnitFieldType>>;
/** The unit fields of type list (a question can take its options from one). */
listFields?: string[];
/** For a question in a loop: what the layouts before it show ("Show field"), and what span questions can select in. */
Expand Down Expand Up @@ -69,6 +78,7 @@ function ItemFields({
inLoop = false,
loopItems = [],
unitFields = [],
unitFieldTypes,
listFields = [],
loopNames,
readOnly = false,
Expand Down Expand Up @@ -130,6 +140,7 @@ function ItemFields({
layout={item}
loopItems={loopItems}
unitFields={unitFields}
unitFieldTypes={unitFieldTypes}
coderQuestions={availableQuestions}
issues={validationIssues}
readOnly={readOnly}
Expand Down
14 changes: 14 additions & 0 deletions packages/client/src/lib/components/admin/LayoutDesigner.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ describe("LayoutDesigner", () => {
expect(html).toContain('aria-label="Body: add a field"');
});

it("offers image, audio and video fields for the body only, and shows them there as such", () => {
const html = renderToStaticMarkup(
<LayoutDesigner
layout={{ body: ["clip"] }}
fields={["headline", "clip", "photo"]}
types={{ headline: "text", clip: "audio", photo: "image" }}
onChange={() => {}}
/>,
);
expect(html).toContain('aria-label="Body: clip"');
expect(html).toContain("(audio URL)");
expect(html).toContain('aria-label="Add photo to the body"');
});

it("says when every field is shown", () => {
const html = renderToStaticMarkup(
<LayoutDesigner
Expand Down
Loading
Loading