Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Media in slides: video + audio element (hybrid embed + budget)
nyblnete758020f46e6
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 598f90dc..e5b1fbab 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -4,7 +4,8 @@import type { Store } from '../store'import {FORMAT_VERSION,- applyChartPalette, applyLayout, builtinLayouts, defaultChart, defaultImage, defaultShape, defaultTable, defaultText,+ MEDIA_EMBED_BUDGET,+ applyChartPalette, applyLayout, builtinLayouts, defaultChart, defaultImage, defaultMedia, defaultShape, defaultTable, defaultText,instantiateLayout, layoutElementIds, newDocId, syncLinkedChart, uid,type ChartElement, type ShapeKind, type Slide, type SlideElement, type TableElement,} from '../model'@@ -193,6 +194,8 @@ export class Editor {this.shapeDropdown(),btn(ICONS.image, t('Image'), () => this.pickImage(),t('Add an image — or just paste one (⌘V) straight onto the slide')),+ btn(ICONS.media, t('Media'), () => this.pickMedia(),+ t('Add video or audio — small clips embed in the file; for big ones, paste a hosted URL in the panel to keep the deck small')),btn(ICONS.table, t('Table'), () => this.canvas.insert(defaultTable()),t('Add a table — edit cells inline; turn it into a live chart from the panel')),btn(ICONS.chart, t('Chart'), () => this.canvas.insert(defaultChart(applyChartPalette(CHART_PRESETS.bar(), this.store.doc.theme))),@@ -993,6 +996,53 @@ export class Editor {input.click()}+ // --- insert media (video / audio) --------------------------------------------------++ private pickMedia() {+ const input = document.createElement('input')+ input.type = 'file'+ input.accept = 'video/*,audio/*'+ input.addEventListener('change', () => {+ const file = input.files?.[0]+ if (!file) return+ const kind: 'video' | 'audio' = file.type.startsWith('audio') ? 'audio' : 'video'+ if (file.size > MEDIA_EMBED_BUDGET) {+ const mb = Math.round(file.size / (1024 * 1024))+ const ok = confirm(t(+ 'This {kind} is {mb} MB. Embedding keeps it inside the .bento.html but makes the file large and slow to open and save.\n\nEmbed anyway? (Cancel, then paste a hosted URL in the panel to keep the deck small.)',+ { kind, mb },+ ))+ if (!ok) { this.insertMedia(kind, ''); return } // empty element → panel URL field+ }+ const reader = new FileReader()+ reader.onload = () => this.insertMedia(kind, String(reader.result))+ reader.readAsDataURL(file)+ })+ input.click()+ }++ /** Insert a media element, sizing video to its intrinsic aspect when known. */+ private insertMedia(kind: 'video' | 'audio', src: string) {+ const { width: dw, height: dh } = this.store.doc.size+ if (kind === 'audio' || !src) {+ const w = kind === 'audio' ? 460 : 560+ const h = kind === 'audio' ? 56 : 315+ this.canvas.insert(defaultMedia(kind, src, { w, h, x: (dw - w) / 2, y: (dh - h) / 2 }))+ return+ }+ const probe = document.createElement('video')+ const place = (w: number, h: number) =>+ this.canvas.insert(defaultMedia('video', src, { w: Math.round(w), h: Math.round(h), x: (dw - w) / 2, y: (dh - h) / 2 }))+ probe.preload = 'metadata'+ probe.onloadedmetadata = () => {+ const ar = probe.videoWidth && probe.videoHeight ? probe.videoWidth / probe.videoHeight : 16 / 9+ const w = Math.min(dw * 0.6, 640)+ place(w, w / ar)+ }+ probe.onerror = () => place(560, 315)+ probe.src = src+ }+// --- present & save ------------------------------------------------------------------present(fromStart = false, fullscreen = true) {diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.tsindex b60eba56..e9f7531e 100644--- a/slides/src/editor/panels.ts+++ b/slides/src/editor/panels.ts@@ -3,7 +3,7 @@// into a single undo checkpoint.import type { Store } from '../store'-import { applyChartPalette, defaultChart, uid, type ChartElement, type LineEnding, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind } from '../model'+import { MEDIA_EMBED_BUDGET, applyChartPalette, defaultChart, uid, type ChartElement, type LineEnding, type MediaElement, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind } from '../model'import { grantScreens, screensCached, secondScreen, windowManagementSupported } from '../screens'import { CHART_PRESETS } from '../charts'import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'@@ -327,7 +327,7 @@ export class PropsPanel {}private buildElementPanel(el: SlideElement) {- this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram', chart: 'Chart', table: 'Table' }[el.type])+ this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram', chart: 'Chart', table: 'Table', media: el.type === 'media' && el.kind === 'audio' ? 'Audio' : 'Video' }[el.type])this.opsRow([el])this.section(t('Arrange'))@@ -397,6 +397,7 @@ export class PropsPanel {if (el.type === 'image') this.buildImageProps(el)if (el.type === 'chart') this.buildChartProps(el)if (el.type === 'table') this.buildTableProps(el)+ if (el.type === 'media') this.buildMediaProps(el)this.buildPresentingProps(el)@@ -1279,6 +1280,82 @@ export class PropsPanel {this.mutate(el.id, (e) => { (e as any).radius = Math.max(v, 0) }, fin)))}+ private buildMediaProps(el: MediaElement) {+ this.section(t('Source & playback'))++ // source status: embedded (with size) / linked / none+ const status = document.createElement('p')+ status.className = 'ed-hint'+ if (!el.src) status.textContent = t('No source yet — choose a file or paste a URL.')+ else if (el.src.startsWith('data:')) {+ const kb = Math.round((el.src.length * 3) / 4 / 1024)+ status.innerHTML = t('Embedded in the file') + ` · <b>${kb >= 1024 ? (kb / 1024).toFixed(1) + ' MB' : kb + ' KB'}</b>`+ } else status.textContent = t('Linked — the deck stays small but needs this URL to play.')+ this.host.appendChild(status)++ // replace / choose file (embeds; warns over budget)+ const replace = document.createElement('button')+ replace.className = 'ed-btn ed-btn-block'+ replace.textContent = el.src ? t('Replace file…') : t('Choose file…')+ replace.addEventListener('click', () => {+ const input = document.createElement('input')+ input.type = 'file'+ input.accept = el.kind === 'audio' ? 'audio/*' : 'video/*'+ input.addEventListener('change', () => {+ const file = input.files?.[0]+ if (!file) return+ if (file.size > MEDIA_EMBED_BUDGET) {+ const mb = Math.round(file.size / (1024 * 1024))+ if (!confirm(t('This file is {mb} MB. Embedding makes the .bento.html large and slow to open and save. Embed anyway?', { mb }))) return+ }+ const reader = new FileReader()+ reader.onload = () => this.mutate(el.id, (e) => { (e as MediaElement).src = String(reader.result) }, true)+ reader.readAsDataURL(file)+ })+ input.click()+ })+ this.host.appendChild(replace)++ // URL (reference) — clears an embed when set+ const url = document.createElement('input')+ url.type = 'text'+ url.placeholder = t('…or paste a media URL')+ url.value = el.src && !el.src.startsWith('data:') ? el.src : ''+ url.addEventListener('change', () =>+ this.mutate(el.id, (e) => { (e as MediaElement).src = url.value.trim() }, true))+ this.row(t('URL'), url)++ // playback+ const toggle = (label: string, on: boolean, set: (v: boolean) => void) =>+ this.row(label, this.select(['off', 'on'], on ? 'on' : 'off', (v) => set(v === 'on')))+ toggle(t('Controls'), el.controls !== false, (v) => this.mutate(el.id, (e) => { (e as MediaElement).controls = v ? undefined : false }, true))+ toggle(t('Autoplay'), !!el.autoplay, (v) => this.mutate(el.id, (e) => { (e as MediaElement).autoplay = v || undefined }, true))+ toggle(t('Loop'), !!el.loop, (v) => this.mutate(el.id, (e) => { (e as MediaElement).loop = v || undefined }, true))+ toggle(t('Muted'), !!el.muted, (v) => this.mutate(el.id, (e) => { (e as MediaElement).muted = v || undefined }, true))+ const note = document.createElement('p')+ note.className = 'ed-hint'+ note.textContent = t('Autoplay runs only while presenting; browsers require “muted” for video to autoplay.')+ this.host.appendChild(note)++ if (el.kind === 'video') {+ this.row(t('Fit'), this.select(['contain', 'cover', 'fill'], el.fit ?? 'contain', (v) =>+ this.mutate(el.id, (e) => { (e as MediaElement).fit = v as MediaElement['fit'] }, true)))+ this.row(t('Corner radius'), this.number(el.radius ?? 0, 1, (v, fin) =>+ this.mutate(el.id, (e) => { (e as MediaElement).radius = Math.max(v, 0) }, fin)))+ const poster = document.createElement('input')+ poster.type = 'text'+ poster.placeholder = t('Poster image URL (optional)')+ poster.value = el.poster && !el.poster.startsWith('data:') ? el.poster : ''+ poster.addEventListener('change', () =>+ this.mutate(el.id, (e) => {+ const m = e as MediaElement+ const v = poster.value.trim()+ if (v) m.poster = v; else delete m.poster+ }, true))+ this.row(t('Poster'), poster)+ }+ }+// --- element ops --------------------------------------------------------------private opsRow(els: SlideElement[]) {diff --git a/slides/src/icons.ts b/slides/src/icons.tsindex eb93465a..cea30337 100644--- a/slides/src/icons.ts+++ b/slides/src/icons.ts@@ -7,6 +7,7 @@ export const ICONS = {text: svg('<polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/>'),shapes: svg('<rect x="3" y="3" width="10" height="10" rx="1.5"/><circle cx="16.5" cy="16.5" r="4.5"/>'),image: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.5-3.5L6 23"/>'),+ media: svg('<rect x="2" y="4" width="20" height="16" rx="2"/><polygon points="10 9 15 12 10 15" fill="currentColor" stroke="none"/>'),comment: svg('<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>'),chart: svg('<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/>'),undo: svg('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>'),diff --git a/slides/src/model.ts b/slides/src/model.tsindex 917e7dec..a53156b6 100644--- a/slides/src/model.ts+++ b/slides/src/model.ts@@ -230,8 +230,31 @@ export interface TableElement extends ElementBase {style: TableStyle}+/**+ * Audio or video. Hybrid storage: `src` is a data: URI (embedded — travels+ * inside the .bento.html), an external URL / relative path (referenced — keeps+ * the file small but needs the network / a sibling file), or "asset:<key>".+ * The editor embeds small clips and warns above MEDIA_EMBED_BUDGET, offering a+ * URL instead. Autoplay only fires in PRESENT mode (never on the canvas or in+ * thumbnails).+ */+export interface MediaElement extends ElementBase {+ type: 'media'+ kind: 'video' | 'audio'+ src: string+ /** video only: a still shown before playback (data:/asset:/URL) */+ poster?: string+ /** video only: fit within the element box */+ fit?: 'contain' | 'cover' | 'fill'+ radius?: number+ autoplay?: boolean+ loop?: boolean+ muted?: boolean+ controls?: boolean+}+export type SlideElement =- | TextElement | ShapeElement | ImageElement | SvgElement | ChartElement | TableElement+ | TextElement | ShapeElement | ImageElement | SvgElement | ChartElement | TableElement | MediaElement/*** A review comment thread. Editor-only metadata: never rendered while@@ -559,6 +582,35 @@ export function defaultImage(src: string, partial: Partial<ImageElement> = {}):}}+/** Soft ceiling for embedding media as a data URI (bytes). Above this the+ * editor warns — a big embed makes the .bento.html slow to open and save. */+export const MEDIA_EMBED_BUDGET = 8 * 1024 * 1024 // 8 MB++export function defaultMedia(+ kind: 'video' | 'audio',+ src: string,+ partial: Partial<MediaElement> = {},+): MediaElement {+ const audio = kind === 'audio'+ return {+ id: uid('m'),+ type: 'media',+ kind,+ x: 440, y: 210,+ w: audio ? 460 : 560, h: audio ? 56 : 315,+ rotation: 0, opacity: 1,+ src,+ fit: 'contain',+ radius: audio ? 12 : 8,+ controls: true,+ // video defaults muted so present-mode autoplay is permitted by browsers+ muted: !audio,+ loop: false,+ autoplay: false,+ ...partial,+ }+}+export function emptySlide(partial: Partial<Slide> = {}): Slide {return {id: uid('slide'),diff --git a/slides/src/present.ts b/slides/src/present.tsindex f9be00dd..652bf7ff 100644--- a/slides/src/present.ts+++ b/slides/src/present.ts@@ -43,7 +43,7 @@ export function startPresentation(// Morph slides swap instantly; the Flip animation supplies the motion.section.dataset.transition = slide.transition === 'morph' ? 'none' : slide.transitionif (slide.stateOf) section.dataset.bentoState = '1' // dimmed in overview- const surface = renderSlide(slide, doc, { hidePlaceholders: true })+ const surface = renderSlide(slide, doc, { hidePlaceholders: true, liveMedia: true })// reveal slides start with only the default hover set visibleif (slide.hover?.type === 'reveal') applyRevealSet(surface, slide.hover.default ?? null, slide.hover.default)section.appendChild(surface)@@ -273,6 +273,7 @@ export function startPresentation(const exit = () => {if (exited) returnexited = true+ pauseMediaIn(slidesEl) // stop any playing clip before teardownif (document.fullscreenElement) document.exitFullscreen().catch(() => {})const last = deck.getIndices().htry {@@ -385,6 +386,8 @@ export function startPresentation(wireHoverFocus(doc.slides[toIdx], to)if (from) disposeLiveCharts(doc.slides[fromIdx], from)mountLiveCharts(doc.slides[toIdx], to, morphing ? doc.slides[fromIdx] : undefined)+ if (from) pauseMediaIn(from)+ startMediaIn(to)updateSpeaker()}) as any)@@ -414,12 +417,29 @@ export function startPresentation(restartSvgAnimations(first)wireHoverFocus(doc.slides[startIndex], first)mountLiveCharts(doc.slides[startIndex], first)+ startMediaIn(first)}})return { exit }}+// --- media playback -----------------------------------------------------------++// Autoplay is intentionally NOT set at render time (it would fire on the editor+// canvas and in every thumbnail). Present mode starts flagged media on entry+// and pauses everything on exit so a paused clip doesn't keep playing off-slide.+function startMediaIn(section: HTMLElement) {+ section.querySelectorAll<HTMLMediaElement>('video[data-autoplay="1"], audio[data-autoplay="1"]').forEach((m) => {+ try { m.currentTime = 0 } catch { /* not seekable yet */ }+ void m.play().catch(() => { /* blocked (e.g. un-muted video) — leave paused */ })+ })+}++function pauseMediaIn(section: HTMLElement) {+ section.querySelectorAll<HTMLMediaElement>('video, audio').forEach((m) => { m.pause() })+}+// --- live charts --------------------------------------------------------------// Present mode swaps chart snapshots for live ECharts instances (tooltips,diff --git a/slides/src/render.ts b/slides/src/render.tsindex ab4a49cf..776cd582 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -11,6 +11,9 @@ export interface RenderOpts {svgAsImage?: boolean/** hide empty placeholder text entirely — present mode and print */hidePlaceholders?: boolean+ /** media (video/audio) accepts pointer input — PRESENT only. On the editor+ * canvas it stays inert so its native controls don't swallow selection. */+ liveMedia?: boolean/** dynamic-field values ({{page}} etc.) for this slide; auto-filled by renderSlide */fields?: FieldContext}@@ -425,6 +428,62 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsnode.appendChild(img)break}+ case 'media': {+ const radius = el.radius ?? 0+ if (opts.svgAsImage) {+ // thumbnails: a cheap still — poster (video) or an icon chip, never a+ // live media element.+ const still = document.createElement('div')+ still.style.cssText = `width:100%;height:100%;border-radius:${radius}px;display:flex;align-items:center;justify-content:center;overflow:hidden;background:${el.kind === 'video' ? '#0b0f14' : '#e7edf4'}`+ if (el.kind === 'video' && el.poster) {+ const img = document.createElement('img')+ img.src = resolveAsset(doc, el.poster)+ img.style.cssText = `width:100%;height:100%;object-fit:${el.fit ?? 'contain'};display:block`+ still.appendChild(img)+ } else {+ still.style.color = el.kind === 'video' ? '#ffffff' : '#5e7699'+ still.style.fontSize = '24px'+ still.textContent = el.kind === 'video' ? '▶' : '♪'+ }+ node.appendChild(still)+ break+ }+ const inert = opts.liveMedia ? '' : ';pointer-events:none'+ if (el.kind === 'audio') {+ const audio = document.createElement('audio')+ if (el.src) audio.src = resolveAsset(doc, el.src)+ audio.controls = el.controls !== false+ audio.loop = !!el.loop+ audio.preload = 'metadata'+ audio.dataset.autoplay = el.autoplay ? '1' : ''+ audio.style.cssText = 'width:100%;display:block' + inert+ const wrap = document.createElement('div')+ wrap.style.cssText = `width:100%;height:100%;display:flex;align-items:center;padding:0 6px;box-sizing:border-box;border-radius:${radius}px;background:#eef2f7`+ if (!el.src) { wrap.style.color = '#93a2b6'; wrap.style.fontSize = '13px'; wrap.style.justifyContent = 'center'; wrap.textContent = '♪ ' + 'No audio source' }+ else wrap.appendChild(audio)+ node.appendChild(wrap)+ break+ }+ const video = document.createElement('video')+ if (el.src) video.src = resolveAsset(doc, el.src)+ if (el.poster) video.poster = resolveAsset(doc, el.poster)+ video.controls = el.controls !== false+ video.loop = !!el.loop+ video.muted = el.muted !== false+ video.playsInline = true+ video.preload = 'metadata'+ video.dataset.autoplay = el.autoplay ? '1' : ''+ video.style.cssText = `width:100%;height:100%;object-fit:${el.fit ?? 'contain'};border-radius:${radius}px;display:block;background:#0b0f14` + inert+ if (!el.src) {+ const ph = document.createElement('div')+ ph.style.cssText = `width:100%;height:100%;border-radius:${radius}px;display:flex;align-items:center;justify-content:center;background:#0b0f14;color:#8fa0b6;font-size:14px`+ ph.textContent = '▶ No video source'+ node.appendChild(ph)+ } else {+ node.appendChild(video)+ }+ break+ }case 'chart': {// Static SVG snapshot everywhere; present mode swaps in a live ECharts// instance (mountLiveCharts) for tooltips/zoom. Kept as innerHTML so