feat: a video on several products, sound and expand on the floating player, upright vertical video, looping cards at the foot of the home (Rodada 5, D7)

site_videos.products (the old product column is kept and copied); one
floating video per product checks the overlap and names it. The floating
player starts muted, with a sound button that says its state and an
expand button to the large player. A vertical video stands upright on
the floating and the large player. The home's videos move to its foot as
muted looping cards that play only on screen, not at all with reduced
motion, and open the large player.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 16:03:51 -03:00
parent 22239f21d8
commit 21858b5764
7 changed files with 218 additions and 69 deletions

View File

@@ -24,15 +24,32 @@ CATALOG = {
}
VIDEO_MAX = 500 * 1024 * 1024
CAPTIONS_MAX = 1024 * 1024
PRODUCTS = ('file', 'avulsa', 'uvfile', 'uv')
PRODUCT_NAMES = {
'file': 'Arquivo por metro',
'avulsa': 'Artes avulsas',
'uvfile': 'Arquivo por metro · UV',
'uv': 'Artes avulsas · UV',
}
class VideoUpdate(StrictModel):
upload_id: UUID | None = None
captions_id: UUID | None = None
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
products: list[Literal['file', 'avulsa', 'uvfile', 'uv']] = Field(default_factory=list, max_length=4)
enabled: bool = False
def _products(body):
"""The chosen products, unique and in catalog order; the old single
`product` still works and means one product."""
chosen = set(body.products)
if not chosen and body.product:
chosen.add(body.product)
return [product for product in PRODUCTS if product in chosen]
class VideoUploadStart(StrictModel):
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
@@ -78,14 +95,19 @@ def manage_videos(user=Depends(operator)):
FROM dtf_local.site_videos v
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
return {'videos': [dict(id=id, title=title,
product=rows[id]['product'] if id in rows else None,
upload_id=rows[id]['upload_id'] if id in rows else None,
captions_id=rows[id]['captions_id'] if id in rows else None,
video_name=rows[id]['video_name'] if id in rows else None,
captions_name=rows[id]['captions_name'] if id in rows else None,
enabled=rows[id]['enabled'] if id in rows else False)
for id, title in CATALOG.items()]}
videos = []
for id, title in CATALOG.items():
row = rows.get(id)
products = list(row['products'] or []) if row else []
videos.append(dict(id=id, title=title,
product=products[0] if products else None,
products=products,
upload_id=row['upload_id'] if row else None,
captions_id=row['captions_id'] if row else None,
video_name=row['video_name'] if row else None,
captions_name=row['captions_name'] if row else None,
enabled=row['enabled'] if row else False))
return {'videos': videos}
@router.post('/api/operator/site-videos/{video_id}')
@@ -94,17 +116,20 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
raise HTTPException(404, 'Vídeo não encontrado.')
if body.enabled and not body.upload_id:
raise HTTPException(422, 'Envie o vídeo antes de publicar.')
products = _products(body)
with db.connect() as c:
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
(video_id,)).fetchone() or {}
# One floating video per product page; checked before any copy, and
# the refusal names the video that holds the product (DTF-WEB-G).
if body.enabled and body.product:
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
(video_id, body.product)).fetchone()
# the refusal names the video and the product it holds (DTF-WEB-G).
if body.enabled and products:
other = c.execute('''SELECT id,products FROM dtf_local.site_videos
WHERE id<>%s AND enabled AND products && %s''', (video_id, products)).fetchone()
if other:
raise HTTPException(409, f'Este produto já tem o vídeo "{CATALOG.get(other["id"], other["id"])}" '
'publicado. Tire esse do Site antes, ou escolha outro lugar.')
common = next(product for product in products if product in other['products'])
raise HTTPException(409, f'O produto "{PRODUCT_NAMES[common]}" já tem o vídeo '
f'"{CATALOG.get(other["id"], other["id"])}" publicado. '
'Tire esse do Site antes, ou escolha outro lugar.')
identity = operator_identity(user)
keys = []
for uid, expected, previous_id, previous_key in (
@@ -121,12 +146,14 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
Key=key, ContentType=mime, MetadataDirective='REPLACE')
keys.append(key)
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,products,enabled,updated_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''',
(video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user))
product=EXCLUDED.product,products=EXCLUDED.products,enabled=EXCLUDED.enabled,
updated_by=EXCLUDED.updated_by,updated_at=now()''',
(video_id, body.upload_id, body.captions_id, keys[0], keys[1],
products[0] if products else None, products, body.enabled, user))
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
if ids:
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
@@ -137,14 +164,18 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
@router.get('/api/site/videos')
def published_videos():
with db.connect() as c:
rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name
rows = c.execute('''SELECT v.id,v.products,v.video_key,v.captions_key,u.name AS video_name
FROM dtf_local.site_videos v
JOIN dtf_local.uploads u ON u.id=v.upload_id
WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall()
return {'videos': [dict(id=row['id'], product=row['product'],
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None)
for row in rows]}
videos = []
for row in rows:
products = list(row['products'] or [])
videos.append(dict(id=row['id'], product=products[0] if products else None,
products=products,
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None))
return {'videos': videos}
@router.get('/api/site/videos/{video_id}/captions')

View File

@@ -0,0 +1,8 @@
-- Round 5, D7: the same video can appear on more than one product page. The
-- old single `product` column stays for compatibility; the code reads
-- `products`. One floating video per product is still enforced in the API.
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS products text[] NOT NULL DEFAULT '{}';
UPDATE dtf_local.site_videos SET products=ARRAY[product] WHERE product IS NOT NULL AND products='{}';
ALTER TABLE dtf_local.site_videos DROP CONSTRAINT IF EXISTS site_videos_products_check;
ALTER TABLE dtf_local.site_videos ADD CONSTRAINT site_videos_products_check
CHECK (products <@ ARRAY['file','avulsa','uvfile','uv']::text[]);

View File

@@ -47,9 +47,22 @@ def run():
published = client.call('/site/videos')['videos']
entry = next(row for row in published if row['id'] == 'sala')
assert entry['product'] == 'file'
assert entry['products'] == ['file'], entry
assert entry['captions'] == '/api/site/videos/sala/captions'
# The same video can appear on more than one product; duplicates are
# dropped and the order follows the product catalog.
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'products': ['uv', 'file', 'uv'], 'enabled': True})
entry = next(row for row in client.call('/site/videos')['videos'] if row['id'] == 'sala')
assert entry['products'] == ['file', 'uv'], entry
assert entry['product'] == 'file', entry
# One floating video per product: a second one is refused before any
# copy, naming the video that holds the product (DTF-WEB-G).
# copy, naming the video and the product in conflict (DTF-WEB-G).
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
'products': ['uv'], 'enabled': True}, expected=409)
assert 'A sala às 3 da manhã' in refused['detail'], refused
assert 'Artes avulsas · UV' in refused['detail'], refused
# The old single `product` still works and is refused the same way.
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
'product': 'file', 'enabled': True}, expected=409)
assert 'A sala às 3 da manhã' in refused['detail'], refused

View File

@@ -753,15 +753,6 @@ h2 em{font-style:normal;color:var(--laranja)}
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
</div></section>
<!-- VÍDEOS -->
<section id="videos" class="videos2"><div class="w">
<div class="videosCab">
<div><div class="et">Vídeos</div><h2>A DTF por dentro</h2></div>
<p>O que acontece com a sua arte, do envio à retirada.</p>
</div>
<div class="videosGrid" id="videosGrid"></div>
</div></section>
<!-- ENVIO -->
<section id="envio">
<nav class="passos" id="passos" aria-label="Etapas do pedido" hidden>
@@ -1203,6 +1194,15 @@ h2 em{font-style:normal;color:var(--laranja)}
<a href="/carrinho" id="barraMBtn">Continuar</a>
</div>
<!-- VÍDEOS -->
<section id="videos" class="videos2"><div class="w">
<div class="videosCab">
<div><div class="et">Vídeos</div><h2>A DTF por dentro</h2></div>
<p>O que acontece com a sua arte, do envio à retirada.</p>
</div>
<div class="videosGrid" id="videosGrid"></div>
</div></section>
<footer><div class="w">
<div class="frow">
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>

View File

@@ -11,8 +11,8 @@ const SITE_TABS=[
{id:'grade',label:'Nota da arte',note:'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'},
{id:'videos',label:'Vídeos',note:'MP4 ou WebM até 500 MB; legenda VTT opcional. Só aparece no Site depois de publicado.'},
];
const SITE_VIDEO_PRODUCTS=[['','Só na categoria DTF'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']];
const SITE_VIDEO_PRODUCTS=[['','Só na página inicial'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro · UV'],['uv','Artes avulsas · UV']];
let siteTab=(()=>{
try{const saved=localStorage.getItem(SITE_TAB_KEY);return SITE_TABS.some(t=>t.id===saved)?saved:'products';}
catch(_){return 'products';}
@@ -548,8 +548,10 @@ function renderSiteGrade(){
}
// ---- Vídeos (S5, S6) ------------------------------------------------------
function videoProductLabel(product){
return (SITE_VIDEO_PRODUCTS.find(([value])=>value===(product||''))||SITE_VIDEO_PRODUCTS[0])[1];
function videoProductLabel(video){
const products=(video.products&&video.products.length?video.products:[video.product]).filter(Boolean);
if(!products.length)return 'Só na página inicial';
return products.map(product=>(SITE_VIDEO_PRODUCTS.find(([value])=>value===product)||[product])[1]).join(', ');
}
function renderSiteVideos(){
const host=$('site-videos-list');if(!host)return;
@@ -562,7 +564,7 @@ function siteVideoRow(video){
file.append(video.video_name?node('span',video.video_name,'siteFileName'):node('span','sem vídeo','muted'));
const captions=node('td');captions.dataset.label='Legenda';
captions.append(video.captions_name?node('span',video.captions_name,'siteFileName'):node('span','sem legenda','muted'));
const where=node('td',videoProductLabel(video.product));where.dataset.label='Onde aparece';
const where=node('td',videoProductLabel(video));where.dataset.label='Onde aparece';
const situation=node('td');situation.dataset.label='Situação';
situation.append(node('span',video.enabled?'Publicado':'Rascunho','tag'+(video.enabled?' ok':'')));
const action=node('td',undefined,'r siteAction');
@@ -604,29 +606,44 @@ function videoDialog(video){
videoInput.addEventListener('change',checkVideo);
captionsInput.addEventListener('change',checkCaptions);
// A product page shows one floating video: the products another published
// video holds are marked, and closed while this one is published (DTF-WEB-G).
const taken=new Map(siteVideos.filter(other=>other.id!==video.id&&other.enabled&&other.product)
.map(other=>[other.product,other.title]));
const product=node('select');
for(const [value,label] of SITE_VIDEO_PRODUCTS){
const option=node('option',taken.has(value)?label+' · já tem vídeo':label);option.value=value;product.append(option);
// video holds are marked, and locked while this one is published (DTF-WEB-G).
const taken=new Map();
for(const other of siteVideos){
if(other.id===video.id||!other.enabled)continue;
for(const value of (other.products&&other.products.length?other.products:[other.product])){
if(value&&!taken.has(value))taken.set(value,other.title);
}
}
product.value=video.product||'';
const where=field('Onde aparece',product,'Ou flutuando na página de um produto.');
const whereHint=where.querySelector('small');
const where=node('div',undefined,'fld');
where.append(node('span','Onde aparece'));
const productBoxes=[];
for(const [value,label] of SITE_VIDEO_PRODUCTS){
if(!value)continue;
const input=node('input');input.value=value;
input.checked=(video.products&&video.products.length?video.products:[video.product]).includes(value);
where.append(checkbox(taken.has(value)?label+' · já tem vídeo':label,input));
productBoxes.push([value,input]);
}
const whereHint=node('small');
where.append(whereHint);
const busyProduct=()=>productBoxes.find(([value,input])=>input.checked&&taken.has(value));
const paintWhere=()=>{
for(const option of product.options)option.disabled=published&&taken.has(option.value);
if(!taken.has(product.value))where.classList.remove('warn');
whereHint.textContent=taken.has(product.value)
?'Este produto já tem o vídeo "'+taken.get(product.value)+'" publicado. Tire esse do Site para publicar este aqui.'
:'Ou flutuando na página de um produto.';
for(const [value,input] of productBoxes)input.disabled=published&&taken.has(value);
const busy=busyProduct();
where.classList.toggle('warn',!!busy);
whereHint.textContent=busy
?'Este produto já tem o vídeo "'+taken.get(busy[0])+'" publicado. Tire esse do Site para publicar este aqui.'
:productBoxes.some(([,input])=>input.checked)
?'Aparece flutuando na página de cada produto marcado.'
:'Nenhum marcado: só na página inicial.';
};
product.onchange=paintWhere;
for(const [,input] of productBoxes)input.onchange=paintWhere;
const sw=node('button',undefined,'sw'+(published?' on':''));
sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(published));
sw.append(node('span',undefined,'t'),'Publicar no Site');
sw.onclick=()=>{
if(!published&&taken.has(product.value)){where.classList.add('warn');product.focus();return;}
const busy=busyProduct();
if(!published&&busy){paintWhere();busy[1].focus();return;}
published=!published;sw.classList.toggle('on',published);sw.setAttribute('aria-checked',String(published));
paintWhere();
};
@@ -644,8 +661,9 @@ function videoDialog(video){
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
const products=productBoxes.filter(([,input])=>input.checked).map(([value])=>value);
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
product:product.value||null,enabled:published});
products,enabled:published});
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
await loadSiteVideos();
}});

View File

@@ -64,17 +64,21 @@ section+section{border-top:0}
.videosCab h2{margin-top:8px;font-size:clamp(28px,3vw,38px);font-weight:800;letter-spacing:-.02em}
.videosCab p{margin-left:auto;max-width:440px;font-size:16.5px;color:var(--fraco)}
.videosGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
.videoCard{position:relative;display:flex;flex-direction:column;align-items:flex-start;gap:8px;min-height:170px;padding:20px;border:1px solid var(--linha);border-radius:14px;background:var(--cinza);color:var(--preto);text-align:left;font:inherit;cursor:pointer}
.videoCard{position:relative;display:flex;flex-direction:column;align-items:flex-start;gap:8px;padding:14px;border:1px solid var(--linha);border-radius:14px;background:var(--cinza);color:var(--preto);text-align:left;font:inherit;cursor:pointer}
.videoCard:hover{border-color:var(--laranja)}
.videoCard .vcPlay{display:flex;align-items:center;justify-content:center;width:38px;height:38px;border-radius:999px;background:var(--laranja);color:var(--preto);font-size:16px;font-weight:900}
.videoCard video{display:block;width:100%;height:auto;aspect-ratio:16/9;object-fit:cover;border-radius:10px;background:#000}
.videoCard b{font-family:"Inter",sans-serif;font-size:17px;line-height:1.25}
.videoCard span{font-size:14.5px;line-height:1.4;color:var(--fraco)}
.videoCard em{margin-top:auto;font-style:normal;font-size:12.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--laranja-escuro)}
.videoCard[data-soon="1"]{cursor:default;opacity:.72}
.videoCard[data-soon="1"]:hover{border-color:var(--linha)}
.videoFloat{position:fixed;right:max(22px,env(safe-area-inset-right));bottom:max(22px,env(safe-area-inset-bottom));z-index:70;width:min(280px,calc(100vw - 32px));border-radius:14px;overflow:hidden;background:var(--preto);box-shadow:0 14px 40px rgba(3,6,11,.35)}
.videoFloat video{display:block;width:100%;height:auto;aspect-ratio:16/9;background:#000}
.videoFloat .vfClose{position:absolute;top:8px;right:8px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:20px;line-height:1;cursor:pointer}
.videoFloat.vertical{width:min(180px,40vw);max-height:70vh}
.videoFloat.vertical video{aspect-ratio:9/16}
.videoFloat .vfActions{position:absolute;top:8px;right:8px;display:flex;gap:8px}
.videoFloat .vfActions button{width:44px;height:44px;padding:0;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center}
.videoFloat .vfActions button:focus-visible{outline:3px solid var(--laranja);outline-offset:2px}
.videoFloat .vfActions svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.videoFloat .vfLabel{padding:8px 12px;color:#fff;font-size:13px;line-height:1.3}
.videoFloat .vfLabel b{display:block;font-family:"Inter",sans-serif;font-size:14px}
.videoAberto{overflow:hidden}
@@ -82,6 +86,8 @@ section+section{border-top:0}
.videoModal[hidden]{display:none}
.videoModal .vmBox{position:relative;width:min(920px,100%);border-radius:16px;overflow:hidden;background:#000}
.videoModal video{display:block;width:100%;height:auto;max-height:82vh;background:#000}
.videoModal.vertical .vmBox{width:auto;max-width:100%}
.videoModal.vertical video{width:auto;max-width:100%;max-height:86vh}
.videoModal .vmClose{position:absolute;top:10px;right:10px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.65);color:#fff;font-size:22px;cursor:pointer}
@media(max-width:900px){.videosGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:620px){.videosGrid{grid-template-columns:1fr}.videos2{padding:36px 0}}

View File

@@ -20,6 +20,16 @@ const VIDEOS = [
src: null, captions: null},
];
// A video may appear on more than one product page; the old single `product`
// still stands for one product.
function videoProducts(video) {
return video.products && video.products.length ? video.products : [video.product].filter(Boolean);
}
const SOUND_OFF = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9h3l4-4v14l-4-4H4z"/><path d="M15 9l6 6M21 9l-6 6"/></svg>';
const SOUND_ON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9h3l4-4v14l-4-4H4z"/><path d="M15 8a5.5 5.5 0 0 1 0 8"/><path d="M18 5a9 9 0 0 1 0 14"/></svg>';
const EXPAND = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>';
function videoElement(video, {controls = false} = {}) {
const el = document.createElement('video');
el.src = video.src;
@@ -40,7 +50,29 @@ function videoElement(video, {controls = false} = {}) {
return el;
}
// The category shows only videos with a published file.
// The home cards: every published video plays muted, in loop, and opens the
// large player on click. Only the cards on screen play.
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
const cardPlayers = new WeakMap();
let cardObserver = null;
function observeCards() {
const grid = document.getElementById('videosGrid');
if (!grid) return;
if (!cardObserver) {
cardObserver = new IntersectionObserver(entries => {
for (const entry of entries) {
const player = cardPlayers.get(entry.target);
if (!player) continue;
if (entry.isIntersecting && !reduceMotion.matches) player.play().catch(() => {});
else player.pause();
}
}, {threshold: 0.5});
}
cardObserver.disconnect();
for (const card of grid.querySelectorAll('.videoCard')) cardObserver.observe(card);
}
// The section shows only videos with a published file.
function videosSection() {
const grid = document.getElementById('videosGrid');
if (!grid) return;
@@ -52,19 +84,23 @@ function videosSection() {
card.type = 'button';
card.className = 'videoCard';
card.dataset.video = video.id;
const play = document.createElement('span');
play.className = 'vcPlay';
play.textContent = '▶';
const player = videoElement(video);
player.loop = true;
player.addEventListener('loadedmetadata', () => {
if (player.videoHeight > player.videoWidth) card.classList.add('vertical');
});
// The loop stops at 30 s, like the rest of the catalog.
player.addEventListener('timeupdate', () => { if (player.currentTime >= 30) player.currentTime = 0; });
const title = document.createElement('b');
title.textContent = video.title;
const desc = document.createElement('span');
desc.textContent = video.desc;
const note = document.createElement('em');
note.textContent = 'Assistir · 30 s';
card.append(play, title, desc, note);
card.append(player, title, desc);
card.addEventListener('click', () => openVideo(video, card));
cardPlayers.set(card, player);
grid.append(card);
}
observeCards();
}
videosSection();
@@ -96,7 +132,11 @@ function openVideo(video, trigger=document.activeElement) {
}
const box = videoModal.querySelector('.vmBox');
box.querySelectorAll('video').forEach(el => el.remove());
videoModal.classList.remove('vertical');
const player = videoElement(video, {controls: true});
player.addEventListener('loadedmetadata', () => {
if (player.videoHeight > player.videoWidth) videoModal.classList.add('vertical');
});
player.addEventListener('timeupdate', () => { if (player.currentTime >= 30) player.pause(); });
box.append(player);
videoModal.hidden = false;
@@ -119,7 +159,7 @@ function closeVideo() {
let floating = null, floatingId = null;
function videoForProduct() {
if (document.documentElement.dataset.rota !== 'produto') return null;
return VIDEOS.find(video => video.src && video.product === modo) || null;
return VIDEOS.find(video => video.src && videoProducts(video).includes(modo)) || null;
}
function syncFloatingVideo() {
const video = videoForProduct();
@@ -132,6 +172,16 @@ function syncFloatingVideo() {
floatingId = video.id;
floating = document.createElement('div');
floating.className = 'videoFloat';
const actions = document.createElement('div');
actions.className = 'vfActions';
const sound = document.createElement('button');
sound.type = 'button';
sound.className = 'vfSound';
const expand = document.createElement('button');
expand.type = 'button';
expand.className = 'vfExpand';
expand.setAttribute('aria-label', 'Expandir vídeo');
expand.innerHTML = EXPAND;
const close = document.createElement('button');
close.type = 'button';
close.className = 'vfClose';
@@ -143,6 +193,28 @@ function syncFloatingVideo() {
player.loop = false;
// 30 segundos no máximo, como o PDF pede.
player.addEventListener('timeupdate', () => { if (player.currentTime >= 30) player.pause(); });
player.addEventListener('loadedmetadata', () => {
if (player.videoHeight > player.videoWidth) floating.classList.add('vertical');
});
// It starts muted; the button turns the sound on and off.
let muted = true;
const paintSound = () => {
sound.setAttribute('aria-pressed', String(!muted));
sound.setAttribute('aria-label', muted ? 'Ativar som' : 'Desativar som');
sound.innerHTML = muted ? SOUND_OFF : SOUND_ON;
};
paintSound();
sound.addEventListener('click', () => {
muted = !muted;
player.muted = muted;
paintSound();
desc.textContent = (muted ? 'Mudo' : 'Com som') + (video.captions ? ' · com legenda' : '') + ' · 30 s';
});
expand.addEventListener('click', () => {
player.pause();
openVideo(video, expand);
});
actions.append(sound, expand, close);
const label = document.createElement('div');
label.className = 'vfLabel';
const title = document.createElement('b');
@@ -150,7 +222,7 @@ function syncFloatingVideo() {
const desc = document.createElement('span');
desc.textContent = video.captions ? 'Mudo · com legenda · 30 s' : 'Mudo · 30 s';
label.append(title, desc);
floating.append(player, close, label);
floating.append(player, actions, label);
document.body.append(floating);
player.play().catch(() => {});
}
@@ -160,7 +232,8 @@ syncFloatingVideo();
window.siteVideosReady=fetch('/api/site/videos').then(response=>response.ok?response.json():null).then(data=>{
for(const published of data?.videos||[]){
const video=VIDEOS.find(item=>item.id===published.id);
if(video){video.src=published.src;video.captions=published.captions;video.product=published.product;}
if(video){video.src=published.src;video.captions=published.captions;
video.product=published.product;video.products=published.products||[];}
}
videosSection();
syncFloatingVideo();