CifraNETMúsicas
para
Missa
CifraNET
Connect

e-cifras - www.ecifras.cjb.net - U2

U2

Encontre suas cifras favoritas no Telegram!

Pesquise músicas e artistas gratuitamente pelo bot do CifraNET. Rápido, simples e direto no Telegram.

Buscar cifras no Telegram
Compartilhar
✉Enviar cifra ◉WhatsApp fFacebook Connect
Mais

Cifra de e-cifras - www.ecifras.cjb.net - U2

Veja os acordes de e-cifras - www.ecifras.cjb.net, de U2, e use os controles desta página para mudar o tom, ajustar a leitura e acompanhar a música enquanto toca. Ver mais cifras de U2 →

Primeiro acorde: Dm 10 acordes identificados
INTRO (spoken):
Dm Cadd9
And love it's not the easy thing
G
The only baggage That you can bring
Dm
Love It's not the easy thing
Cadd9
The only baggage you can bring
G
Is all that you can't leave behind
 
then gtr1 plays:
D Asus4 G Em7
D Asus4 G E
 
gtr2 plays the following 7x:
--------------12----
-----------------10-
--------11----------
-12--12----12-------
--------------------
--------------------
 
then the following 1x:
--------------12----
-----------------12-
--------13----------
-12--12----12-------
--------------------
--------------------
 
VERSE:
D A G Em7
And if the darkness is to keep us apart
D A G Em7
And if the daylight feels like it's a long way off
D A G
And if your glass heart should crack
Em7 D
Before the second you turn back
A E
Oh no, be strong ... ohhh
 
CHORUS:
D
Walk on
Asus4
Walk on
G
What you got, they can't steal it
Em7
No they can't even feel it
D
Walk on
Asus4
Walk on
G E
Stay safe tonight
 
VERSE 2:
D Asus4 G
You're packing a suitcase for a place
Em7
None of us has been
D Asus4
A place that has to be believed
G Em7
To be seen
D Asus4
You could have flown away
G
A singing bird
Em7
In an open cage
D
Who will only fly
Asus4 E
Only fly for freedom ... Ohhh
 
CHORUS
 
D
And I know it aches
Asus4
How your heart it breaks
E
You can only take so much
Bm G Em7 A
Walk on
Bm G Em7 A (then stay on A)
Walk on
 
D A/C#
Home
G
Hard to know what it is if you never had one
D A/C#
Home
G
I can't say where it is but I know I'm going
D A/C#
Home
E
That's where the heart is
D
And I know it aches
Asus4
How your heart it breaks
E
You can only take so much
Em7 G D Asus4
Walk on
Em7 G D Asus4
Leave it behind..you've got to leave it behind
 
Em7 G
All that you fashion.. all that you make
D A
All that you build.. all that you break
Em7 G
All that you measure.. all that you feel
D A
All this you can leave behind
(repeat and fade)
 
CHORDS USED:
Dm (xx0231)
Cadd9(x32033)
G (320033)
Em7 (022030)
Asus4(x02230)
E (022100)
A (x02220)
Bm (x24432)
A/C# (x4222x)
<!-- text below generated by server. PLEASE REMOVE --></table></script></style></noscript>

🎸 Continue tocando

U2
Acordes usados nesta música

Perguntas frequentes sobre e-cifras - www.ecifras.cjb.net (U2)

Qual é o tom da cifra de e-cifras - www.ecifras.cjb.net?

Use o botão de tonalidade para subir ou descer meio tom — a letra continua igual, só os acordes mudam.

Preciso de capotraste para tocar e-cifras - www.ecifras.cjb.net?

Não é obrigatório. O capotraste serve para simplificar os acordes: colocando na casa indicada, você toca formas mais fáceis e continua no mesmo tom.

Como ouvir a música enquanto toco?

Use o botão de vídeo: o player abre ao lado da cifra para você tocar junto, sem sair da página.

A cifra de e-cifras - www.ecifras.cjb.net é gratuita?

Sim. A cifra, a mudança de tom, o capotraste, a rolagem automática e o PDF são gratuitos no CifraNET, sem cadastro.

Mais cifras de U2

Toque “e-cifras - www.ecifras.cjb.net” com a gente

O CifraNET Connect é a rede de quem vive música: aulas, salas e gente para tocar junto.

Quem toca esta cifra

Ninguém marcou esta cifra ainda. Seja o primeiro — é um clique.

Eu toco esta cifra

Aulas e salas sobre esta música

Nenhuma sala falou desta música ainda. Você pode abrir a primeira.

"; const playSongTitle = "e-cifras - www.ecifras.cjb.net"; const playSongArtist = "U2"; const playSiteUrl = 'www.cifranet.com.br'; const playPageLang = "pt-BR"; const playWindowLabel = "Tocar Cifra"; const playStartLabel = "Play"; const playStopLabel = "Stop"; const playFastLabel = "Mais rapido"; const playSlowLabel = "Mais lento"; const playSpeedLabel = "Velocidade"; const playControlsLabel = "Controles da leitura"; const playRaiseToneLabel = "Subir tom"; const playLowerToneLabel = "Descer tom"; const playToneUpShortLabel = "Tom +"; const playToneDownShortLabel = "Tom -"; const playFontUpLabel = 'A+'; const playFontDownLabel = 'A-'; const cifraAutoScrollState = {running:false,timerId:0,lastTime:0,scrollPosition:0,speed:21.6}; const roots = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']; const flats = {'Db':'C#','Eb':'D#','Gb':'F#','Ab':'G#','Bb':'A#'}; let chordGalleryController = null; window.CifraNetChordDiagrams = (function(){ const noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']; const flatNames = {'Db':'C#','Eb':'D#','Gb':'F#','Ab':'G#','Bb':'A#'}; const svgNs = 'http://www.w3.org/2000/svg'; const exactShapeOverrides = { 'C': 'x32010', 'Cm': 'x35543', 'C7': 'x32310', 'Cmaj7': 'x32000', 'D': 'xx0232', 'Dm': 'xx0231', 'D7': 'xx0212', 'Dsus2': 'xx0230', 'Dsus4': 'xx0233', 'E': '022100', 'Em': '022000', 'E7': '020100', 'Esus4': '022200', 'Eadd9': '024100', 'F': '133211', 'Fm': '133111', 'G': '320003', 'Gm': '355333', 'G7': '320001', 'A': 'x02220', 'Am': 'x02210', 'A7': 'x02020', 'Asus2': 'x02200', 'Asus4': 'x02230', 'B': 'x24442', 'Bm': 'x24432', 'B7': 'x21202' }; const shapeFamilies = { major: [ { openRoot: 'E', positions: [0, 2, 2, 1, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 2, 2, 0] } ], minor: [ { openRoot: 'E', positions: [0, 2, 2, 0, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 2, 1, 0] } ], dominant7: [ { openRoot: 'E', positions: [0, 2, 0, 1, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 0, 2, 0] } ], minor7: [ { openRoot: 'E', positions: [0, 2, 0, 0, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 0, 1, 0] } ], major7: [ { openRoot: 'E', positions: [0, 2, 1, 1, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 1, 2, 0] } ], sus4: [ { openRoot: 'E', positions: [0, 2, 2, 2, 0, 0] }, { openRoot: 'A', positions: ['x', 0, 2, 2, 3, 0] } ], sus2: [ { openRoot: 'A', positions: ['x', 0, 2, 2, 0, 0] }, { openRoot: 'E', positions: [0, 2, 4, 4, 0, 0] } ], add9: [ { openRoot: 'A', positions: ['x', 0, 2, 4, 2, 0] }, { openRoot: 'E', positions: [0, 2, 4, 1, 0, 2] } ], diminished: [ { openRoot: 'E', positions: [0, 1, 2, 0, 2, 0] }, { openRoot: 'A', positions: ['x', 0, 1, 2, 1, 2] } ], augmented: [ { openRoot: 'E', positions: [0, 3, 2, 1, 1, 0] }, { openRoot: 'A', positions: ['x', 0, 3, 2, 2, 1] } ] }; function normalizeNote(root){ return flatNames[root] || root; } function escapeText(value){ return String(value == null ? '' : value); } function transposeChordName(chord, steps){ /* Deslocamento zero devolve o nome que está no banco (ver transposeChord). */ if(!steps){ return String(chord || ''); } const match = String(chord || '').match(/^([A-G](?:#|b)?)(.*)$/); if(!match){ return String(chord || ''); } const root = normalizeNote(match[1]); const rest = match[2] || ''; const index = noteNames.indexOf(root); if(index < 0){ return String(chord || ''); } return noteNames[(index + Number(steps || 0) + 120) % 12] + rest; } function parseChord(chord){ const value = String(chord || '').trim(); const match = value.match(/^([A-G](?:#|b)?)([^\/]*)(?:\/([A-G](?:#|b)?))?$/i); if(!match){ return null; } const suffix = String(match[2] || '').trim(); return { name: value, root: normalizeNote(match[1]), suffix: suffix, slash: match[3] ? normalizeNote(match[3]) : '', family: resolveFamily(suffix) }; } function resolveFamily(suffix){ const clean = String(suffix || '') .replace(/\s+/g, '') .replace(/min/gi, 'm') .replace(/major/gi, 'maj'); if (/maj7|M7|7M/i.test(clean)) { return 'major7'; } if (/m7/i.test(clean)) { return 'minor7'; } if (/sus2/i.test(clean)) { return 'sus2'; } if (/sus4/i.test(clean) || /sus/i.test(clean)) { return 'sus4'; } if (/add9|9/i.test(clean)) { return 'add9'; } if (/dim/i.test(clean)) { return 'diminished'; } if (/aug|\+/i.test(clean)) { return 'augmented'; } if (/7/i.test(clean)) { return 'dominant7'; } if (/^m(?!aj)/i.test(clean)) { return 'minor'; } return 'major'; } function noteIndex(root){ return noteNames.indexOf(normalizeNote(root)); } function buildAbsolutePositions(shape, targetRoot){ const origin = noteIndex(shape.openRoot); const target = noteIndex(targetRoot); if(origin < 0 || target < 0){ return null; } const fretShift = (target - origin + 120) % 12; return shape.positions.map(function(position){ if(position === 'x'){ return 'x'; } return fretShift + Number(position || 0); }); } function exactPositionsForChord(chordName){ const shape = exactShapeOverrides[String(chordName || '').trim()]; if(!shape){ return null; } return String(shape).split('').map(function(char){ if(char.toLowerCase() === 'x'){ return 'x'; } return Number(char); }); } function chooseShape(parsed){ const exactShape = exactPositionsForChord(parsed.name); if(exactShape){ return exactShape; } const candidates = shapeFamilies[parsed.family] || shapeFamilies.major; let best = null; candidates.forEach(function(candidate){ const absolute = buildAbsolutePositions(candidate, parsed.root); if(!absolute){ return; } const numeric = absolute.filter(function(value){ return typeof value === 'number' && value > 0; }); if(!numeric.length){ return; } const minFret = Math.min.apply(Math, numeric); const maxFret = Math.max.apply(Math, numeric); const openCount = absolute.filter(function(value){ return value === 0; }).length; const score = (maxFret * 10) + minFret - openCount; if(!best || score < best.score){ best = { score: score, positions: absolute }; } }); return best ? best.positions : null; } function buildDiagramData(chordName){ const parsed = parseChord(chordName); if(!parsed){ return null; } const positions = chooseShape(parsed); if(!positions){ return null; } const numeric = positions.filter(function(value){ return typeof value === 'number' && value > 0; }); const displayBase = numeric.length ? Math.max(1, Math.min.apply(Math, numeric)) : 1; const dots = []; const markers = []; positions.forEach(function(position, index){ if(position === 'x'){ markers.push({ string: index, label: 'x' }); return; } if(position === 0){ markers.push({ string: index, label: 'o' }); return; } dots.push({ string: index, fret: Math.max(1, position - displayBase + 1) }); }); return { chordName: escapeText(chordName), displayBase: displayBase, markers: markers, dots: dots }; } function svgEl(doc, name){ return doc.createElementNS(svgNs, name); } function createSvg(doc, data, options){ const darkMode = !!(options && options.darkMode); const large = !!(options && options.large); const width = large ? 320 : 104; const height = large ? 400 : 134; const marginLeft = data.displayBase > 1 ? (large ? 42 : 22) : (large ? 24 : 12); const top = large ? 56 : 28; const boardWidth = width - marginLeft - (large ? 22 : 10); const boardHeight = height - top - (large ? 26 : 14); const stringGap = boardWidth / 5; const fretGap = boardHeight / 5; const stroke = darkMode ? '#94a3b8' : '#111111'; const fill = darkMode ? '#f9fafb' : '#111111'; const accent = darkMode ? '#60a5fa' : '#111111'; const markerColor = darkMode ? '#cbd5e1' : '#475569'; const dotRadius = large ? 12 : 4.5; const fontSize = large ? 22 : 10; const svg = svgEl(doc, 'svg'); svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height); svg.setAttribute('aria-hidden', 'true'); if(data.displayBase > 1){ const baseText = svgEl(doc, 'text'); baseText.setAttribute('x', String(2)); baseText.setAttribute('y', String(top + fretGap * 0.7)); baseText.setAttribute('fill', markerColor); baseText.setAttribute('font-size', String(large ? 22 : 11)); baseText.setAttribute('font-weight', '700'); baseText.textContent = String(data.displayBase); svg.appendChild(baseText); } for(let column = 0; column < 6; column += 1){ const line = svgEl(doc, 'line'); const x = marginLeft + (column * stringGap); line.setAttribute('x1', String(x)); line.setAttribute('y1', String(top)); line.setAttribute('x2', String(x)); line.setAttribute('y2', String(top + boardHeight)); line.setAttribute('stroke', stroke); line.setAttribute('stroke-width', String(large ? 2.4 : 1.4)); svg.appendChild(line); } for(let row = 0; row <= 5; row += 1){ const line = svgEl(doc, 'line'); const y = top + (row * fretGap); line.setAttribute('x1', String(marginLeft)); line.setAttribute('y1', String(y)); line.setAttribute('x2', String(marginLeft + boardWidth)); line.setAttribute('y2', String(y)); line.setAttribute('stroke', stroke); line.setAttribute('stroke-width', String((data.displayBase === 1 && row === 0) ? (large ? 5 : 2.6) : (large ? 2.2 : 1.2))); svg.appendChild(line); } data.markers.forEach(function(marker){ const text = svgEl(doc, 'text'); text.setAttribute('x', String(marginLeft + (marker.string * stringGap))); text.setAttribute('y', String(top - (large ? 16 : 9))); text.setAttribute('fill', markerColor); text.setAttribute('font-size', String(fontSize)); text.setAttribute('font-weight', '800'); text.setAttribute('text-anchor', 'middle'); text.textContent = marker.label; svg.appendChild(text); }); data.dots.forEach(function(dot){ const circle = svgEl(doc, 'circle'); circle.setAttribute('cx', String(marginLeft + (dot.string * stringGap))); circle.setAttribute('cy', String(top + ((dot.fret - 0.5) * fretGap))); circle.setAttribute('r', String(dotRadius)); circle.setAttribute('fill', accent); svg.appendChild(circle); }); return svg; } function closeModal(modal){ if(!modal){ return; } const doc = modal.ownerDocument; modal.classList.remove('is-open'); modal.setAttribute('aria-hidden', 'true'); if(doc && doc.body && modal.dataset.prevOverflow !== undefined){ doc.body.style.overflow = modal.dataset.prevOverflow; } } function ensureModalBindings(modal){ if(!modal || modal.dataset.bound === '1'){ return; } const doc = modal.ownerDocument; modal.dataset.bound = '1'; modal.addEventListener('click', function(event){ if(event.target === modal || event.target.closest('[data-chord-close]')){ closeModal(modal); } }); doc.addEventListener('keydown', function(event){ if(event.key === 'Escape' && modal.classList.contains('is-open')){ closeModal(modal); } }); } function openModal(modal, originalChord, semitoneOffset, options){ if(!modal){ return; } ensureModalBindings(modal); const doc = modal.ownerDocument; const darkMode = !!(options && options.darkMode); const title = modal.querySelector('[data-chord-modal-title]'); const holder = modal.querySelector('[data-chord-modal-diagram]'); const displayName = transposeChordName(originalChord, semitoneOffset || 0); const data = buildDiagramData(displayName); if(title){ title.textContent = displayName; } if(holder){ holder.innerHTML = ''; if(data){ holder.appendChild(createSvg(doc, data, { darkMode: darkMode, large: true })); } else { const empty = doc.createElement('div'); empty.className = 'chord-gallery-empty'; empty.textContent = 'Sem desenho'; holder.appendChild(empty); } } modal.dataset.originalChord = originalChord; modal.dataset.prevOverflow = doc && doc.body ? doc.body.style.overflow || '' : ''; if(doc && doc.body){ doc.body.style.overflow = 'hidden'; } modal.classList.add('is-open'); modal.setAttribute('aria-hidden', 'false'); } function renderGrid(container, modal, chordNames, semitoneOffset, options){ if(!container){ return; } const doc = container.ownerDocument; const darkMode = !!(options && options.darkMode); const list = Array.isArray(chordNames) ? chordNames : []; container.innerHTML = ''; list.forEach(function(originalChord){ const button = doc.createElement('button'); const name = transposeChordName(originalChord, semitoneOffset || 0); const data = buildDiagramData(name); const title = doc.createElement('span'); const preview = doc.createElement('span'); button.type = 'button'; button.className = 'chord-gallery-card'; button.setAttribute('aria-label', name); title.className = 'chord-gallery-name'; title.textContent = name; preview.className = 'chord-gallery-preview'; if(data){ preview.appendChild(createSvg(doc, data, { darkMode: darkMode, large: false })); } else { const empty = doc.createElement('span'); empty.className = 'chord-gallery-empty'; empty.textContent = 'Sem desenho'; preview.appendChild(empty); } button.appendChild(title); button.appendChild(preview); button.addEventListener('click', function(){ openModal(modal, originalChord, semitoneOffset || 0, options || {}); }); container.appendChild(button); }); if(modal && modal.classList.contains('is-open') && modal.dataset.originalChord){ openModal(modal, modal.dataset.originalChord, semitoneOffset || 0, options || {}); } } function bindGrid(container, modal, chordNames, getSemitoneOffset, options){ ensureModalBindings(modal); return { render: function(){ renderGrid( container, modal, chordNames, typeof getSemitoneOffset === 'function' ? getSemitoneOffset() : 0, options || {} ); } }; } return { bindGrid: bindGrid, transposeChordName: transposeChordName }; })(); function normalizeRoot(r){ return flats[r] || r; } function escapePlayHtml(value){ return String(value) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function transposeChord(chord, steps){ /* 13/10/2026 — DESLOCAMENTO ZERO = CIFRA DO BANCO, LETRA POR LETRA. Sem esta guarda o acorde passava pela tabela de sustenidos e saía reescrito (Bb virava A#) mesmo sem ninguém pedir transposição — quem abria a cifra no celular via acordes diferentes dos cadastrados. */ if(!steps) return chord; const m = chord.match(/^([A-G](?:#|b)?)(.*)$/); if(!m) return chord; let root = normalizeRoot(m[1]); let rest = m[2] || ''; let idx = roots.indexOf(root); if(idx < 0) return chord; let novo = roots[(idx + steps + 120) % 12]; return novo + rest; } function alignPracticeVideo(){ const video = document.getElementById('cifraPracticeVideo'); if(!video) return; video.style.marginTop = '0px'; } function togglePracticeVideo(){ const video = document.getElementById('cifraPracticeVideo'); const frame = document.getElementById('cifraPracticeFrame'); const button = document.querySelector('.cifra-playalong-card'); if(!video || !frame) return; if(video.classList.contains('is-open')){ closePracticeVideo(); return; } const source = frame.dataset.src || ''; if(source && !frame.getAttribute('src')){ frame.setAttribute('src', source + (source.indexOf('?') >= 0 ? '&' : '?') + 'autoplay=1'); } video.classList.add('is-open'); try{ const eventData = new URLSearchParams(); eventData.set('cifranet_event', 'ouvir_tocar'); fetch(window.location.href, {method:'POST',body:eventData,credentials:'same-origin',keepalive:true}).catch(function(){}); }catch(error){} if(button) button.setAttribute('aria-expanded', 'true'); showCifraAutoScrollControls(); requestAnimationFrame(function(){ alignPracticeVideo(); const cifraBox = document.querySelector('#cifraPracticeLayout .cifra-box'); if(cifraBox){ const targetTop = cifraBox.getBoundingClientRect().top + window.scrollY - 88; window.scrollTo({top: Math.max(0, targetTop), behavior: 'smooth'}); } window.setTimeout(startCifraAutoScroll, 700); }); if(typeof gtag === 'function') gtag('event', 'video_play_along_open', {item_name: playSongTitle}); } function showCifraAutoScrollControls(){ const controls = document.getElementById('cifraAutoScrollControls'); if(controls) controls.hidden = false; updateCifraAutoScrollControls(); } function updateCifraAutoScrollControls(){ const toggle = document.getElementById('cifraAutoScrollToggle'); const speed = document.getElementById('cifraAutoScrollSpeed'); const rehearsalToggle = document.getElementById('rehearsalScrollToggle'); const rehearsalSpeed = document.getElementById('rehearsalSpeed'); if(toggle){ toggle.textContent = cifraAutoScrollState.running ? playStopLabel : playStartLabel; toggle.title = cifraAutoScrollState.running ? playStopLabel : playStartLabel; toggle.setAttribute('aria-pressed', cifraAutoScrollState.running ? 'true' : 'false'); } if(speed) speed.textContent = playSpeedLabel + ' ' + (cifraAutoScrollState.speed / 72).toFixed(1) + 'x'; if(rehearsalToggle){ rehearsalToggle.textContent = cifraAutoScrollState.running ? '⏸ Parar' : '▶ Rolar'; rehearsalToggle.setAttribute('aria-pressed', cifraAutoScrollState.running ? 'true' : 'false'); } if(rehearsalSpeed) rehearsalSpeed.innerHTML = playSpeedLabel + '
' + (cifraAutoScrollState.speed / 72).toFixed(1) + 'x'; } function stopCifraAutoScroll(){ cifraAutoScrollState.running = false; cifraAutoScrollState.lastTime = 0; cifraAutoScrollState.scrollPosition = window.scrollY || window.pageYOffset || 0; if(cifraAutoScrollState.timerId){ window.clearInterval(cifraAutoScrollState.timerId); cifraAutoScrollState.timerId = 0; } updateCifraAutoScrollControls(); } function cifraAutoScrollStep(){ if(!cifraAutoScrollState.running) return; const now = Date.now(); if(!cifraAutoScrollState.lastTime){ cifraAutoScrollState.lastTime = now; return; } const elapsed = now - cifraAutoScrollState.lastTime; cifraAutoScrollState.lastTime = now; cifraAutoScrollState.scrollPosition += (cifraAutoScrollState.speed * elapsed) / 1000; const root = document.scrollingElement || document.documentElement; const limit = Math.max(0, Math.max(root.scrollHeight, document.body.scrollHeight) - window.innerHeight); if(cifraAutoScrollState.scrollPosition >= limit){ window.scrollTo(0, limit); stopCifraAutoScroll(); return; } window.scrollTo(0, cifraAutoScrollState.scrollPosition); } function startCifraAutoScroll(){ showCifraAutoScrollControls(); if(cifraAutoScrollState.running) return; const root = document.scrollingElement || document.documentElement; const limit = Math.max(0, Math.max(root.scrollHeight, document.body.scrollHeight) - window.innerHeight); if((window.scrollY || window.pageYOffset || 0) >= limit) window.scrollTo(0, 0); cifraAutoScrollState.running = true; cifraAutoScrollState.lastTime = 0; cifraAutoScrollState.scrollPosition = window.scrollY || window.pageYOffset || 0; updateCifraAutoScrollControls(); cifraAutoScrollState.timerId = window.setInterval(cifraAutoScrollStep, 16); } function toggleCifraAutoScroll(){ if(cifraAutoScrollState.running) stopCifraAutoScroll(); else { cifraEvento('rolagem'); startCifraAutoScroll(); } } function adjustCifraAutoScrollSpeed(direction){ cifraAutoScrollState.speed += direction > 0 ? 7.2 : -7.2; cifraAutoScrollState.speed = Math.min(270, Math.max(7.2, cifraAutoScrollState.speed)); try{ localStorage.setItem('cifranet_cifra_scroll_speed', String(cifraAutoScrollState.speed)); }catch(error){} updateCifraAutoScrollControls(); } function toggleRehearsalAutoScroll(){ const willStart = !cifraAutoScrollState.running; toggleCifraAutoScroll(); if(willStart && typeof gtag === 'function') gtag('event', 'modo_ensaio_rolagem', {cifra_id: currentCifraId}); } window.addEventListener('beforeunload', stopCifraAutoScroll); function closePracticeVideo(){ const video = document.getElementById('cifraPracticeVideo'); const frame = document.getElementById('cifraPracticeFrame'); const button = document.querySelector('.cifra-playalong-card'); if(video){ video.classList.remove('is-open'); video.style.marginTop = ''; } if(frame) frame.removeAttribute('src'); if(button) button.setAttribute('aria-expanded', 'false'); } window.addEventListener('resize', function(){ const video = document.getElementById('cifraPracticeVideo'); if(video && video.classList.contains('is-open')) alignPracticeVideo(); }); function openVideoModal(){ const modal = document.getElementById('cifraVideoModal'); const frame = document.getElementById('cifraVideoFrame'); if(!modal || !frame) return; if(!frame.getAttribute('src')){ const source = frame.dataset.src || ''; frame.setAttribute('src', source + (source.indexOf('?') >= 0 ? '&' : '?') + 'autoplay=1'); } modal.classList.add('is-open'); modal.setAttribute('aria-hidden', 'false'); document.body.style.overflow = 'hidden'; const closeButton = modal.querySelector('.video-modal-close'); if(closeButton) closeButton.focus(); if(typeof gtag === 'function') gtag('event', 'video_modal_open', {item_name: playSongTitle}); } function closeVideoModal(){ const modal = document.getElementById('cifraVideoModal'); const frame = document.getElementById('cifraVideoFrame'); if(!modal) return; modal.classList.remove('is-open'); modal.setAttribute('aria-hidden', 'true'); document.body.style.overflow = ''; if(frame) frame.removeAttribute('src'); } document.addEventListener('click', function(event){ const modal = document.getElementById('cifraVideoModal'); if(modal && event.target === modal) closeVideoModal(); }); document.addEventListener('keydown', function(event){ if(event.key === 'Escape'){ exitRehearsalMode(); closeVideoModal(); closePracticeVideo(); } }); /* ── Funcionalidades exigem conta (25/09/2026) ─────────────────────────────── */ function cfAbrirLogin(oQue){ var veu = document.getElementById('cfLoginVeu'); if(!veu) return; var texto = document.getElementById('cfLoginTexto'); if(texto){ texto.textContent = oQue ? 'Para ' + oQue + ' você precisa de uma conta — é grátis e leva menos de um minuto.' : 'As ferramentas da cifra são para quem tem conta — é grátis e leva menos de um minuto.'; } veu.hidden = false; veu.setAttribute('aria-hidden', 'false'); document.body.style.overflow = 'hidden'; var primeiro = document.getElementById('cfLoginCriar'); if(primeiro && primeiro.focus) primeiro.focus(); } function cfFecharLogin(){ var veu = document.getElementById('cfLoginVeu'); if(!veu) return; veu.hidden = true; veu.setAttribute('aria-hidden', 'true'); document.body.style.overflow = ''; } /* Clique em qualquer funcionalidade: sem conta, a tela abre ANTES do que o botão faria (fase de captura, então o onclick do botão nem roda). */ document.addEventListener('click', function(evento){ if(cifraLogado) return; var alvo = evento.target && evento.target.closest ? evento.target.closest('[data-cfn-login]') : null; if(!alvo) return; evento.preventDefault(); evento.stopPropagation(); if(evento.stopImmediatePropagation) evento.stopImmediatePropagation(); cfAbrirLogin(alvo.getAttribute('data-cfn-login') || ''); }, true); document.addEventListener('keydown', function(evento){ if(evento.key === 'Escape') cfFecharLogin(); }); /* Uso das funcionalidades entra nas estatísticas (um envio por tipo em cada carregamento; o servidor também limita a um por cifra a cada 30 minutos). */ var cifraEventosEnviados = {}; function cifraEvento(nome){ nome = String(nome || ''); if(!cifraLogado || nome === '' || cifraEventosEnviados[nome]) return; cifraEventosEnviados[nome] = true; try{ const dadosEvento = new URLSearchParams(); dadosEvento.set('cifranet_event', nome); fetch(window.location.href, {method:'POST', body:dadosEvento, credentials:'same-origin', keepalive:true}).catch(function(){}); }catch(erro){} } /* Ações que são de outra área (favoritar) ou links de compartilhar. */ document.addEventListener('click', function(evento){ var alvo = evento.target && evento.target.closest ? evento.target.closest('[data-cfn-evento]') : null; if(!alvo) return; if(alvo.getAttribute('data-cfn-evento') === 'favorito'){ cfAlternarFavorito(alvo); return; } cifraEvento(alvo.getAttribute('data-cfn-evento')); }); /* ── FAZER O FAVORITO FUNCIONAR (30/09/2026) ──────────────────────────────── O clique grava (ou desfaz) o favorito no servidor — /social/favoritar.php — e o botão é pintado conforme a RESPOSTA, nunca antes: assim a tela e o painel ("Meu perfil" › Favoritos) nunca discordam. Enquanto o pedido viaja o botão fica travado, para dois cliques rápidos não virarem dois pedidos. */ function cfPintarFavorito(botao, ativo){ botao.classList.toggle('is-favorite', !!ativo); botao.setAttribute('aria-pressed', ativo ? 'true' : 'false'); var rotulo = ativo ? botao.getAttribute('data-label-saved') : botao.getAttribute('data-label-save'); var texto = botao.querySelector('span'); if(texto && rotulo) texto.textContent = rotulo; if(rotulo) botao.setAttribute('title', rotulo); } function cfAlternarFavorito(botao){ if(!botao || botao.getAttribute('data-cfn-ocupado') === '1') return; botao.setAttribute('data-cfn-ocupado', '1'); try{ const dados = new URLSearchParams(); dados.set('alvo_tipo', botao.getAttribute('data-alvo-tipo') || 'CIFRA'); dados.set('alvo_id', botao.getAttribute('data-alvo-id') || '0'); dados.set('alvo_titulo', botao.getAttribute('data-alvo-titulo') || ''); dados.set('alvo_url', botao.getAttribute('data-alvo-url') || window.location.href); fetch('/favoritos-api.php', {method:'POST', body:dados, credentials:'same-origin'}) .then(function(resposta){ return resposta.json().catch(function(){ return {ok:false, erro:'Resposta inesperada do servidor.'}; }); }) .then(function(dadosResposta){ botao.removeAttribute('data-cfn-ocupado'); if(!dadosResposta.ok){ cfAvisarFavorito(dadosResposta.erro || 'Não consegui guardar nos favoritos agora.', false); return; } cfPintarFavorito(botao, dadosResposta.ativo); cfAvisarFavorito( dadosResposta.ativo ? 'Guardado nos favoritos! Veja em Meu perfil › Favoritos.' : 'Tirado dos favoritos.', true ); cifraEvento('favorito'); }) .catch(function(){ botao.removeAttribute('data-cfn-ocupado'); cfAvisarFavorito('Sem resposta do servidor. Confira a conexão e tente de novo.', false); }); }catch(erro){ botao.removeAttribute('data-cfn-ocupado'); cfAvisarFavorito('Não consegui falar com o servidor agora.', false); } } /* Aviso do favorito: some sozinho, mas fica mais tempo quando é erro. */ function cfAvisarFavorito(mensagem, ok){ var aviso = document.getElementById('cfFavoritoAviso'); if(!aviso) return; aviso.textContent = mensagem || ''; aviso.className = 'cifra-favorito-aviso' + (ok ? ' ok' : ''); aviso.hidden = !mensagem; if(cfAvisarFavorito.timer) window.clearTimeout(cfAvisarFavorito.timer); if(mensagem) cfAvisarFavorito.timer = window.setTimeout(function(){ aviso.hidden = true; }, ok ? 4000 : 9000); } function transpose(step){ semitones += step; cifraEvento('tom'); document.querySelectorAll('.chord').forEach(function(el){ const original = el.dataset.original; el.textContent = transposeChord(original, cfCapoPassosExibidos()); }); if(chordGalleryController){ chordGalleryController.render(); } /* 13/10/2026 — O TOM VALE SÓ NESTA VISITA. Antes, cada clique no Tom ± gravava o deslocamento no aparelho e a página o reaplicava na abertura seguinte. Agora nada é guardado: a cifra sempre abre como está no banco de dados e o tom só muda quando a pessoa pede (aqui ou no capotraste). */ if(typeof gtag === 'function') gtag('event', 'transpose_chord_chart', {steps: step, total_steps: semitones}); } /* 06/11/2026 — leitura do tom pela página "lembrar onde parei" (opcional, só para quem liga o botão). Não muda o comportamento padrão: a cifra continua abrindo no tom do banco. */ window.cfTomAtualPassos = function(){ return (typeof semitones === 'number') ? semitones : 0; }; /* 25/09/2026 (imagem 04): o botao PDF baixa a cifra no tom que esta na tela. O arquivo e montado no servidor a partir do banco (nunca do navegador), entao so os semitons viajam na URL. */ function cfBaixarPdf(){ cifraEvento('pdf'); const passo = (typeof semitones === 'number') ? semitones : 0; const endereco = '/cifra-pdf.php?id=' + encodeURIComponent(currentCifraId) + '&passos=' + encodeURIComponent(passo); if(typeof gtag === 'function') gtag('event', 'baixar_pdf_cifra', {cifra_id: currentCifraId, semitons: passo}); window.location.href = endereco; } /* ── ARTE DA CIFRA PARA TIKTOK E INSTAGRAM (15/10/2026) ───────────────────── Pedido do responsavel: dois botoes ao lado do Facebook. Cada um monta, no proprio navegador, uma arte com a foto da pagina ao fundo, "APRENDA A TOCAR", o nome da musica, o artista em italico, cifranet.com.br em destaque e um trecho da cifra com os acordes. Tamanhos: TikTok 1080x1920 (9:16, o formato de foto do app) e Instagram 1080x1350 (4:5, o que ocupa mais tela no feed). O terceiro botao nao abre rede nenhuma: BAIXA a mesma arte do TikTok, no tamanho do TikTok. Como a imagem chega na rede: · CELULAR — navigator.share com o ARQUIVO abre a bandeja do sistema: a pessoa escolhe TikTok ou Instagram e a imagem entra no app. E o unico caminho que existe hoje para publicar imagem por link. · COMPUTADOR — nenhuma das duas redes aceita arquivo por link (o TikTok so publica pela pagina de upload dele e o Instagram nao publica foto pelo site). Entao a imagem e BAIXADA, a legenda vai para a area de transferencia e a pagina de publicacao abre em outra aba. O aviso na tela diz exatamente isso — nenhum passo pode falhar calado. */ var CF_SOCIAL_ARTE = { tiktok: { largura: 1080, altura: 1920, rotulo: 'TikTok', pagina: 'https://www.tiktok.com/upload', sufixo: 'tiktok', topo: .14 }, instagram: { largura: 1080, altura: 1350, rotulo: 'Instagram', pagina: 'https://www.instagram.com/', sufixo: 'instagram', topo: .09 }, /* O terceiro botao BAIXA a MESMA arte do TikTok (1080x1920) e nao abre rede nenhuma: e para quem vai publicar na mao ou usar a imagem em outro lugar (pedido de 15/10/2026, no lugar do antigo botao do YouTube). */ baixar: { largura: 1080, altura: 1920, rotulo: 'imagem', pagina: '', sufixo: 'tiktok', topo: .14, baixar: true } }; var CF_SOCIAL_LARANJA = '#f97300'; function cfSocialAviso(mensagem, demorado){ var caixa = document.getElementById('cfSocialAviso'); if(!caixa) return; caixa.textContent = mensagem || ''; caixa.hidden = !mensagem; if(cfSocialAviso.timer) window.clearTimeout(cfSocialAviso.timer); if(mensagem) cfSocialAviso.timer = window.setTimeout(function(){ caixa.hidden = true; }, demorado ? 14000 : 5000); } /* Mesma regra da pagina para saber se a linha e so de acordes (assim a arte pinta os acordes como a tela pinta). */ function cfSocialLinhaSoAcordes(no){ var acordes = no.querySelectorAll('.chord'); if(!acordes.length) return false; var resto = no.textContent || ''; for(var i = 0; i < acordes.length; i++){ var texto = (acordes[i].textContent || '').trim(); if(texto !== '') resto = resto.replace(texto, ' '); } return resto.replace(/[\s\u00a0]/g, '') === ''; } /* Tudo o que a arte precisa, lido da PROPRIA pagina aberta: nome, artista, endereco, a foto do cartaz e o trecho da cifra (no tom que esta na tela). */ function cfSocialDados(){ var caixa = document.getElementById('cifra'); if(!caixa) return null; var nome = (caixa.getAttribute('data-cifra-nome') || '').trim(); var artista = (caixa.getAttribute('data-cifra-artista') || '').trim(); var tom = (caixa.getAttribute('data-cifra-tom') || '').trim(); var url = (caixa.getAttribute('data-cifra-url') || '').trim(); if(url === '') url = window.location.href.split('#')[0]; var foto = ''; var cartaz = document.querySelector('.song-summary'); if(cartaz){ var valor = window.getComputedStyle(cartaz).getPropertyValue('--cn-capa') || ''; var achado = valor.match(/url\((['"]?)(.*?)\1\)/); if(achado && achado[2]) foto = achado[2]; } if(foto === ''){ var alternativa = document.querySelector('.song-cover, .song-video img'); if(alternativa) foto = alternativa.getAttribute('src') || ''; } var linhas = []; var nos = caixa.querySelectorAll('.cifra-line'); for(var i = 0; i < nos.length && linhas.length < 60; i++){ var bruto = (nos[i].textContent || '').replace(/[\u00a0]/g, ' ').replace(/\s+$/, ''); if(bruto.replace(/\s/g, '') === ''){ if(linhas.length === 0) continue; // as linhas vazias do comeco nao entram linhas.push({ texto: '', acordes: false }); continue; } linhas.push({ texto: bruto, acordes: cfSocialLinhaSoAcordes(nos[i]) }); } while(linhas.length && linhas[linhas.length - 1].texto === '') linhas.pop(); return { nome: nome, artista: artista, tom: tom, url: url, foto: foto, linhas: linhas }; } /* A foto do cartaz vem do YouTube (img.youtube.com), que libera CORS para origens de fora. O crossOrigin e obrigatorio: sem ele o canvas fica "sujo" e o navegador se recusa a gerar o arquivo da imagem. Se a foto falhar, a arte sai com o fundo em degrade — nunca sem imagem. */ function cfSocialCarregarFoto(endereco){ return new Promise(function(resolver){ if(!endereco){ resolver(null); return; } var imagem = new Image(); var terminou = false; var fechar = function(resultado){ if(terminou) return; terminou = true; resolver(resultado); }; imagem.crossOrigin = 'anonymous'; imagem.onload = function(){ fechar(imagem.naturalWidth ? imagem : null); }; imagem.onerror = function(){ fechar(null); }; window.setTimeout(function(){ fechar(imagem.naturalWidth ? imagem : null); }, 7000); imagem.src = endereco; }); } function cfSocialCaixa(ctx, x, y, largura, altura, raio){ var r = Math.min(raio, largura / 2, altura / 2); ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + largura, y, x + largura, y + altura, r); ctx.arcTo(x + largura, y + altura, x, y + altura, r); ctx.arcTo(x, y + altura, x, y, r); ctx.arcTo(x, y, x + largura, y, r); ctx.closePath(); } function cfSocialQuebrar(ctx, texto, largura){ var palavras = String(texto).split(/\s+/); var linhas = []; var atual = ''; for(var i = 0; i < palavras.length; i++){ var tentativa = atual === '' ? palavras[i] : atual + ' ' + palavras[i]; if(atual !== '' && ctx.measureText(tentativa).width > largura){ linhas.push(atual); atual = palavras[i]; } else { atual = tentativa; } } if(atual !== '') linhas.push(atual); return linhas; } function cfSocialQuebrarCifra(ctx, texto, largura){ var saida = []; var resto = String(texto); while(resto !== '' && saida.length < 4){ if(ctx.measureText(resto).width <= largura){ saida.push(resto); break; } var corte = resto.length; while(corte > 1 && ctx.measureText(resto.slice(0, corte)).width > largura) corte--; var espaco = resto.lastIndexOf(' ', corte); if(espaco > corte * 0.6) corte = espaco; saida.push(resto.slice(0, corte).replace(/\s+$/, '')); resto = resto.slice(corte).replace(/^\s+/, ''); } return saida; } function cfSocialDesenhar(ctx, rede, dados, foto){ var ajuste = CF_SOCIAL_ARTE[rede]; var L = ajuste.largura; var A = ajuste.altura; var margem = Math.round(L * 0.0667); ctx.clearRect(0, 0, L, A); /* Fundo PRETO com a capa do YouTube da pagina a 50% de transparencia — pedido de 15/10/2026: a imagem da cifra (a capa do video) por cima do preto, SEM desfoque, na parte de cima. As letras brancas levam uma sombra preta pequena para continuarem legiveis por cima dessa foto. */ ctx.fillStyle = '#000'; ctx.fillRect(0, 0, L, A); if(foto){ var escala = Math.max(L / foto.naturalWidth, A / foto.naturalHeight); var largura = foto.naturalWidth * escala; var altura = foto.naturalHeight * escala; ctx.globalAlpha = 0.5; ctx.drawImage(foto, (L - largura) / 2, (A - altura) / 2, largura, altura); ctx.globalAlpha = 1; } /* Da metade para baixo o preto cresce de leve; o escurecimento forte atrás do painel da cifra é aplicado mais abaixo, quando já se sabe onde ele começa. */ var veu = ctx.createLinearGradient(0, 0, 0, A); veu.addColorStop(0, 'rgba(0,0,0,.04)'); veu.addColorStop(.5, 'rgba(0,0,0,.28)'); veu.addColorStop(1, 'rgba(0,0,0,.55)'); ctx.fillStyle = veu; ctx.fillRect(0, 0, L, A); ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; var comEspaco = ('letterSpacing' in ctx); var sombraLetra = function(ligar){ ctx.shadowColor = ligar ? 'rgba(0,0,0,.75)' : 'rgba(0,0,0,0)'; ctx.shadowBlur = ligar ? 9 : 0; ctx.shadowOffsetY = ligar ? 3 : 0; }; /* APRENDA A TOCAR / musica / artista — as letras brancas com a sombra. O bloco começa dentro da ÁREA SEGURA do topo (ajuste.topo): no TikTok o campo de busca cobre a parte de cima e a arte ficava escondida atrás dele (15/10/2026). Tudo aqui também ficou mais compacto, para sobrar mais espaço para a cifra. */ var y = Math.round(A * ajuste.topo); sombraLetra(true); ctx.font = '800 34px Arial, Helvetica, sans-serif'; ctx.fillStyle = 'rgba(255,255,255,.92)'; if(comEspaco) ctx.letterSpacing = '6px'; ctx.fillText('APRENDA A TOCAR', margem, y); if(comEspaco) ctx.letterSpacing = '0px'; y += 52; var tamanhoNome = dados.nome.length > 34 ? 54 : (dados.nome.length > 22 ? 64 : 76); ctx.font = '900 ' + tamanhoNome + 'px Arial, Helvetica, sans-serif'; var linhasNome = cfSocialQuebrar(ctx, dados.nome, L - margem * 2); ctx.fillStyle = '#fff'; var alturaNome = Math.round(tamanhoNome * 1.06); for(var i = 0; i < linhasNome.length && i < 3; i++){ ctx.fillText(linhasNome[i], margem, y + alturaNome / 2); y += alturaNome; } y += 10; if(dados.artista !== ''){ ctx.font = 'italic 700 44px Georgia, "Times New Roman", serif'; ctx.fillStyle = '#ffd9b8'; ctx.fillText(dados.artista, margem, y + 22); y += 44; } y += 24; /* Selo do site, DEPOIS do nome do artista: pílula com gradiente laranja, brilho de vidro no alto, contorno claro e halo — é o endereço que precisa chamar a atenção na arte (pedido de 15/10/2026). A sombra das letras brancas termina aqui: o painel da cifra desenha com o contexto limpo. */ sombraLetra(false); var alturaSelo = 68; ctx.font = '900 40px Arial, Helvetica, sans-serif'; var selo = 'cifranet.com.br'; var larguraSelo = ctx.measureText(selo).width + 56; var seloGradiente = ctx.createLinearGradient(margem, y, margem + larguraSelo, y + alturaSelo); seloGradiente.addColorStop(0, '#ff9d1f'); seloGradiente.addColorStop(.55, CF_SOCIAL_LARANJA); seloGradiente.addColorStop(1, '#e85d00'); ctx.save(); ctx.shadowColor = 'rgba(249,115,0,.5)'; ctx.shadowBlur = 30; ctx.shadowOffsetY = 8; cfSocialCaixa(ctx, margem, y, larguraSelo, alturaSelo, alturaSelo / 2); ctx.fillStyle = seloGradiente; ctx.fill(); ctx.restore(); ctx.save(); cfSocialCaixa(ctx, margem, y, larguraSelo, alturaSelo, alturaSelo / 2); ctx.clip(); var brilhoSelo = ctx.createLinearGradient(0, y, 0, y + alturaSelo); brilhoSelo.addColorStop(0, 'rgba(255,255,255,.34)'); brilhoSelo.addColorStop(.55, 'rgba(255,255,255,0)'); ctx.fillStyle = brilhoSelo; ctx.fillRect(margem, y, larguraSelo, alturaSelo); ctx.restore(); cfSocialCaixa(ctx, margem, y, larguraSelo, alturaSelo, alturaSelo / 2); ctx.strokeStyle = 'rgba(255,255,255,.45)'; ctx.lineWidth = 2; ctx.stroke(); ctx.fillStyle = '#fff'; ctx.fillText(selo, margem + 28, y + alturaSelo / 2 + 1); y += alturaSelo + 26; /* O trecho da cifra fica sobre um escurecimento mais suave: a capa continua aparecendo de leve atrás das notas (pedido de 15/10/2026), sem atrapalhar a leitura dos acordes. */ var escurecer = ctx.createLinearGradient(0, y - 48, 0, A); escurecer.addColorStop(0, 'rgba(0,0,0,0)'); escurecer.addColorStop(.17, 'rgba(0,0,0,.76)'); escurecer.addColorStop(1, 'rgba(0,0,0,.9)'); ctx.fillStyle = escurecer; ctx.fillRect(0, y - 48, L, A - (y - 48)); /* Trecho da cifra: acordes em laranja (linha de acordes inteira) e a letra em branco, dentro de um painel — o mesmo desenho da pagina. As margens do rodape sao FIXAS (em pixels), nao proporcionais: no 9:16 do TikTok o proporcional deixava um vazio grande embaixo. */ var painelFim = A - 240; var fonteCifra = ajuste.altura > 1400 ? 38 : 36; var alturaLinha = fonteCifra + 20; var mostra = []; if(dados.linhas.length){ ctx.font = '700 ' + fonteCifra + 'px "Courier New", Courier, monospace'; var cabem = Math.floor(((painelFim - y) - 84) / alturaLinha); for(var j = 0; j < dados.linhas.length && mostra.length < cabem; j++){ var pedacos = cfSocialQuebrarCifra(ctx, dados.linhas[j].texto, L - margem * 2 - 96); for(var k = 0; k < pedacos.length && mostra.length < cabem; k++){ mostra.push({ texto: pedacos[k], acordes: dados.linhas[j].acordes }); } } } if(mostra.length){ cfSocialCaixa(ctx, margem, y, L - margem * 2, painelFim - y, 30); ctx.fillStyle = 'rgba(4,10,20,.68)'; ctx.fill(); ctx.strokeStyle = 'rgba(255,255,255,.16)'; ctx.lineWidth = 2; ctx.stroke(); cfSocialCaixa(ctx, margem, y, 12, painelFim - y, 6); ctx.fillStyle = CF_SOCIAL_LARANJA; ctx.fill(); var linhaY = y + 42 + alturaLinha / 2; for(var m = 0; m < mostra.length; m++){ ctx.font = (mostra[m].acordes ? '700 ' : '400 ') + fonteCifra + 'px "Courier New", Courier, monospace'; ctx.fillStyle = mostra[m].acordes ? '#ffb066' : '#eaf0f8'; ctx.fillText(mostra[m].texto, margem + 44, linhaY); linhaY += alturaLinha; } } /* Chamada do rodape: a cifra completa esta no site. */ var rodape = A - 180; ctx.font = '600 34px Arial, Helvetica, sans-serif'; ctx.fillStyle = 'rgba(255,255,255,.72)'; ctx.fillText('Cifra completa, com todos os acordes, em', margem, rodape); ctx.font = '900 46px Arial, Helvetica, sans-serif'; ctx.fillStyle = CF_SOCIAL_LARANJA; ctx.fillText('cifranet.com.br', margem, rodape + 65); } function cfSocialApelido(texto){ var limpo = String(texto).toLowerCase(); if(limpo.normalize) limpo = limpo.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); limpo = limpo.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60); return limpo || 'cifra'; } function cfSocialGerar(rede){ var ajuste = CF_SOCIAL_ARTE[rede]; var dados = cfSocialDados(); if(!ajuste || !dados) return Promise.reject(new Error('dados indisponiveis')); return cfSocialCarregarFoto(dados.foto).then(function(foto){ var tela = document.createElement('canvas'); tela.width = ajuste.largura; tela.height = ajuste.altura; cfSocialDesenhar(tela.getContext('2d'), rede, dados, foto); return new Promise(function(resolver, rejeitar){ try{ tela.toBlob(function(imagem){ if(!imagem){ rejeitar(new Error('imagem vazia')); return; } resolver({ imagem: imagem, dados: dados, ajuste: ajuste, nomeArquivo: 'cifra-' + cfSocialApelido(dados.nome + ' ' + dados.artista) + '-' + (ajuste.sufixo || rede) + '.png' }); }, 'image/png'); }catch(erro){ rejeitar(erro); } }); }); } /* O texto que acompanha a arte nos TRES botoes: dados da musica, o endereco da cifra e as etiquetas. Ele vai junto no compartilhamento do celular (o app pode usar como legenda) e SEMPRE fica copiado, para colar quando o app nao preencher sozinho (pedido de 15/10/2026). */ function cfSocialLegenda(dados, rede){ var convite = dados.tom !== '' ? '🎼 Cifra completa em ' + dados.tom + ', grátis, com todos os acordes:' : '🎼 Cifra completa, grátis, com todos os acordes:'; var etiquetas = rede === 'tiktok' ? '#cifranet #cifra #aprendaatocar #tiktok' : '#cifranet #cifra #aprendaatocar #instagram'; return '🎸 APRENDA A TOCAR "' + dados.nome + '" — ' + dados.artista + '\n' + convite + '\n' + dados.url + '\n' + etiquetas; } function cfSocialBaixar(imagem, nomeArquivo){ var endereco = URL.createObjectURL(imagem); var link = document.createElement('a'); link.href = endereco; link.download = nomeArquivo; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.setTimeout(function(){ URL.revokeObjectURL(endereco); }, 60000); } /* Copia o texto da legenda. Usado pelo caminho do computador e pelo botao de baixar; devolve o resultado para o aviso dizer a verdade ao usuario. */ function cfSocialCopiar(texto, retorno){ if(navigator.clipboard && navigator.clipboard.writeText){ navigator.clipboard.writeText(texto).then(function(){ retorno(true); }, function(){ retorno(false); }); return; } try{ var campo = document.createElement('textarea'); campo.value = texto; campo.setAttribute('readonly', 'readonly'); campo.style.position = 'fixed'; campo.style.top = '-1000px'; document.body.appendChild(campo); campo.select(); var deu = document.execCommand('copy'); document.body.removeChild(campo); retorno(deu); }catch(erro){ retorno(false); } } /* Saida do computador: baixa o arquivo, copia a legenda e confirma na tela. */ function cfSocialEntregarBaixando(arquivo, nomeArquivo, legenda, ajuste, janela){ cfSocialBaixar(arquivo, nomeArquivo); var onde = janela ? 'a página de publicação abriu em outra aba' : 'abra ' + ajuste.pagina; var recado = 'Imagem baixada! Publique no ' + ajuste.rotulo + ' (' + onde + ').'; cfSocialCopiar(legenda, function(copiou){ cfSocialAviso(recado + (copiou ? ' O texto com os dados da música, o link e as hashtags já está copiado.' : ''), true); }); } function cfCompartilharSocial(rede){ var ajuste = CF_SOCIAL_ARTE[rede]; if(!ajuste) return; if(!cfSocialDados()){ cfSocialAviso('Não consegui ler os dados desta cifra para montar a arte.', true); return; } cfSocialAviso('Montando a arte da cifra…'); /* Botao de BAIXAR: monta a arte no tamanho do TikTok e entrega o arquivo, sem abrir rede nenhuma (é o que a pessoa quer quando vai publicar na mão). */ if(ajuste.baixar){ cfSocialGerar(rede).then(function(pacote){ cfSocialBaixar(pacote.imagem, pacote.nomeArquivo); cfSocialCopiar(cfSocialLegenda(pacote.dados, 'tiktok'), function(copiou){ cfSocialAviso('Imagem baixada no tamanho do TikTok (1080x1920).' + (copiou ? ' O texto com os dados da música, o link e as hashtags já está copiado.' : ''), true); }); }).catch(function(){ cfSocialAviso('Não consegui montar a imagem agora. Tente de novo em instantes.', true); }); return; } /* A bandeja do aparelho e decidida AGORA, no clique (no computador a aba da rede precisa abrir aqui: janela aberta depois de uma espera e bloqueada pelo navegador). So vale no CELULAR: no Windows o navegador tambem tem navigator.share, mas ele abre a bandeja do sistema — onde TikTok e Instagram nao estao — e a pessoa ficaria sem saber o que fazer. */ var ehAparelho = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent || ''); var temBandeja = false; try{ temBandeja = ehAparelho && !!(navigator.share && navigator.canShare && window.File) && navigator.canShare({ files: [new File([new Blob(['x'])], 'arte.png', { type: 'image/png' })] }); }catch(erro){ temBandeja = false; } var janela = null; if(!temBandeja){ janela = window.open(ajuste.pagina, '_blank'); if(janela) janela.opener = null; } if(typeof gtag === 'function') gtag('event', 'arte_cifra_social', {rede: rede, cifra_id: currentCifraId}); cfSocialGerar(rede).then(function(pacote){ var legenda = cfSocialLegenda(pacote.dados, rede); if(temBandeja){ var arquivo = new File([pacote.imagem], pacote.nomeArquivo, { type: pacote.imagem.type }); /* O texto com os dados da musica, o link e as etiquetas vai JUNTO no compartilhamento (o app pode usar como legenda) e, de qualquer forma, fica copiado: se o app nao preencher sozinho, e so colar. */ cfSocialCopiar(legenda, function(){}); navigator.share({ files: [arquivo], text: legenda, title: pacote.dados.nome + ' - ' + pacote.dados.artista }) .then(function(){ cfSocialAviso('Imagem enviada para ' + ajuste.rotulo + '. Se o texto não vier preenchido lá, é só colar — ele já está copiado.', true); }) .catch(function(erro){ if(erro && erro.name === 'AbortError') return; // a pessoa desistiu cfSocialEntregarBaixando(pacote.imagem, pacote.nomeArquivo, legenda, ajuste, janela); }); return; } cfSocialEntregarBaixando(pacote.imagem, pacote.nomeArquivo, legenda, ajuste, janela); }).catch(function(){ if(janela) janela.close(); cfSocialAviso('Não consegui montar a imagem agora. Tente de novo em instantes.', true); }); } function fontSize(step){ currentFont += step; cifraEvento('texto'); if(currentFont < 12) currentFont = 12; if(currentFont > 30) currentFont = 30; document.getElementById('cifra').style.fontSize = currentFont + 'px'; try{ localStorage.setItem('cifranet_cifra_font', String(currentFont)); }catch(error){} if(window.matchMedia('(max-width: 640px)').matches){ renderResponsiveCifra(); } } function restoreCifraPreferences(){ try{ const storedFont = localStorage.getItem('cifranet_cifra_font'); const savedFont = Number(storedFont || '0'); if(storedFont !== null && savedFont >= 12 && savedFont <= 30){ currentFont = savedFont; const cifra = document.getElementById('cifra'); if(cifra) cifra.style.fontSize = currentFont + 'px'; } /* 13/10/2026 — A CIFRA ABRE COMO ESTÁ NO BANCO DE DADOS. Aqui havia a leitura de 'cifranet_tom_': a página reaplicava na abertura o deslocamento que alguém havia escolhido antes, e os acordes apareciam diferentes do cadastro — a música parecia errada. O tom transposto passa a existir só enquanto a pessoa está na página: ele começa em zero (o que está no banco) e só muda no clique do Tom ±/capotraste. A chave antiga é apagada para que nenhum valor gravado por versões anteriores volte a valer. */ try{ localStorage.removeItem('cifranet_tom_' + currentCifraId); }catch(error){} const storedSpeed = Number(localStorage.getItem('cifranet_cifra_scroll_speed') || '0'); if(Number.isFinite(storedSpeed) && storedSpeed >= 7.2 && storedSpeed <= 270) cifraAutoScrollState.speed = storedSpeed; localStorage.removeItem('cifranet_cifra_dark'); }catch(error){} updateCifraAutoScrollControls(); } function rehearsalCifraOffset(){ const cifra = document.getElementById('cifra'); if(!cifra) return 0; return (window.scrollY || window.pageYOffset || 0) - (cifra.getBoundingClientRect().top + (window.scrollY || window.pageYOffset || 0)); } function restoreRehearsalScroll(offset){ const cifra = document.getElementById('cifra'); if(!cifra) return; const top = cifra.getBoundingClientRect().top + (window.scrollY || window.pageYOffset || 0); window.scrollTo(0, Math.max(0, top + offset)); } async function requestRehearsalWakeLock(){ if(!document.body.classList.contains('rehearsal-mode') || document.visibilityState !== 'visible' || !('wakeLock' in navigator)) return; try{ rehearsalWakeLock = await navigator.wakeLock.request('screen'); rehearsalWakeLock.addEventListener('release', function(){ rehearsalWakeLock = null; }); }catch(error){ rehearsalWakeLock = null; } } async function releaseRehearsalWakeLock(){ const lock = rehearsalWakeLock; rehearsalWakeLock = null; if(lock){ try{ await lock.release(); }catch(error){} } } function enterRehearsalMode(){ if(document.body.classList.contains('rehearsal-mode')) return; const offset = rehearsalCifraOffset(); closePracticeVideo(); document.body.classList.add('rehearsal-mode'); try{ const eventData = new URLSearchParams(); eventData.set('cifranet_event', 'modo_ensaio'); fetch(window.location.href, {method:'POST',body:eventData,credentials:'same-origin',keepalive:true}).catch(function(){}); }catch(error){} requestAnimationFrame(function(){ renderResponsiveCifra(); restoreRehearsalScroll(offset); }); requestRehearsalWakeLock(); if(typeof gtag === 'function') gtag('event', 'modo_ensaio_ativado', {cifra_id: currentCifraId, artista: playSongArtist}); } function exitRehearsalMode(){ if(!document.body.classList.contains('rehearsal-mode')) return; const offset = rehearsalCifraOffset(); document.body.classList.remove('rehearsal-mode'); requestAnimationFrame(function(){ renderResponsiveCifra(); restoreRehearsalScroll(offset); }); releaseRehearsalWakeLock(); if(typeof gtag === 'function') gtag('event', 'modo_ensaio_encerrado', {cifra_id: currentCifraId, artista: playSongArtist}); } function recommendationEvent(type, targetId, position, originId){ if(!smartRecommendationsEnabled) return; const payload = JSON.stringify({type:type,origin_id:Number(originId)||currentCifraId,destination_id:Number(targetId)||0,position:Number(position)||0}); try{ if(navigator.sendBeacon && (type === 'click')) navigator.sendBeacon('/recommendation-event.php', new Blob([payload], {type:'application/json'})); else fetch('/recommendation-event.php',{method:'POST',headers:{'Content-Type':'application/json'},body:payload,credentials:'same-origin',keepalive:true}).catch(function(){}); }catch(error){} } function trackContinuePlaying(kind, targetId, position, element){ recommendationEvent('click', targetId, position); try{ sessionStorage.setItem('cifranet_recommendation_context', JSON.stringify({origin_id:currentCifraId,destination_id:Number(targetId),position:Number(position),at:Date.now()})); }catch(error){} if(typeof gtag !== 'function') return; const eventName = kind === 'principal' ? 'recommendation_next_song' : (kind === 'explore' ? 'recommendation_explore_click' : 'recommendation_click'); gtag('event', eventName, { cifra_id_atual: currentCifraId, cifra_id_destino: Number(targetId) || 0, artista_origem: playSongArtist, artista_destino: element ? String(element.dataset.destinationArtist || '') : '', posicao: Number(position) || 0, tipo_recomendacao: kind }); } function initSmartRecommendationTracking(){ const shown = new Set(); const observer = 'IntersectionObserver' in window ? new IntersectionObserver(function(entries){ entries.forEach(function(entry){ if(!entry.isIntersecting || entry.intersectionRatio < .5) return; const el=entry.target, target=Number(el.dataset.destinationId)||0, position=Number(el.dataset.position)||0; const key=target+':'+position; if(shown.has(key)) return; shown.add(key); observer.unobserve(el); recommendationEvent('impression',target,position); if(typeof gtag==='function') gtag('event','recommendation_impression',{cifra_origem:currentCifraId,cifra_destino:target,artista_origem:playSongArtist,artista_destino:String(el.dataset.destinationArtist||''),posicao:position,tipo_recomendacao:String(el.dataset.recommendationType||'related')}); }); },{threshold:[.5]}) : null; if(observer) document.querySelectorAll('.smart-recommendation').forEach(function(el){observer.observe(el);}); let context=null; try{context=JSON.parse(sessionStorage.getItem('cifranet_recommendation_context')||'null');}catch(error){} if(!context || Number(context.destination_id)!==currentCifraId || Date.now()-Number(context.at)>1800000) return; const emit=function(type){recommendationEvent(type,context.destination_id,context.position,context.origin_id);}; emit('open'); window.setTimeout(function(){emit('time_30');},30000); let half=false,ninety=false; window.addEventListener('scroll',function(){const root=document.documentElement;const ratio=(window.scrollY+window.innerHeight)/Math.max(1,root.scrollHeight);if(ratio>=.5&&!half){half=true;emit('scroll_50');}if(ratio>=.9&&!ninety){ninety=true;emit('scroll_90');}},{passive:true}); document.querySelectorAll('[onclick*="transpose("]').forEach(function(el){el.addEventListener('click',function(){emit('transpose');},{once:true});}); document.querySelectorAll('[onclick*="PracticeVideo"],[onclick*="VideoModal"]').forEach(function(el){el.addEventListener('click',function(){emit('player');},{once:true});}); document.querySelectorAll('[onclick*="enterRehearsalMode"]').forEach(function(el){el.addEventListener('click',function(){emit('rehearsal');},{once:true});}); document.querySelectorAll('[data-cifranet-favorite]').forEach(function(el){el.addEventListener('click',function(){emit('save');},{once:true});}); } document.addEventListener('visibilitychange', function(){ if(document.visibilityState === 'visible' && document.body.classList.contains('rehearsal-mode')) requestRehearsalWakeLock(); }); function updateCifraProgress(){ const bar = document.getElementById('cifraProgressBar'); const cifra = document.getElementById('cifra'); if(!bar || !cifra) return; const rect = cifra.getBoundingClientRect(); const total = Math.max(1, cifra.offsetHeight + window.innerHeight); const passed = Math.min(total, Math.max(0, window.innerHeight - rect.top)); bar.style.width = Math.round((passed / total) * 100) + '%'; } function renderResponsiveCifra(){ const holder = document.getElementById('cifra'); if(!holder || !window.matchMedia('(max-width: 640px)').matches) return; const available = Math.max(180, holder.clientWidth || holder.parentElement.clientWidth || 300); const probe = document.createElement('span'); probe.textContent = '0000000000'; probe.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;font:inherit'; holder.appendChild(probe); const charWidth = Math.max(6, probe.getBoundingClientRect().width / 10); probe.remove(); // Reserva uma margem interna real e limita o comprimento das linhas no // celular. Assim o último acorde não fica encostado na borda nem separado // do trecho da letra ao qual pertence. const usableWidth = Math.max(160, available - 30); const columns = Math.max(18, Math.min(24, Math.floor(usableWidth / charWidth))); const lines = String(originalCifraText || '').split(/\r\n|\n|\r/); const chordToken = /^[A-G](?:#|b)?(?:m|maj|min|dim|aug|sus|add)?[0-9]*(?:M)?(?:\/[A-G](?:#|b)?)?$/; const chordLine = /^\s*(?:[A-G](?:#|b)?(?:m|maj|min|dim|aug|sus|add)?[0-9]*(?:M)?(?:\/[A-G](?:#|b)?)?\s*)+$/; function splitAtWidth(value){ const pieces = []; let remaining = String(value || ''); while(remaining.length > columns){ let cut = remaining.lastIndexOf(' ', columns); if(cut < Math.floor(columns * .55)) cut = columns; else cut += 1; pieces.push(remaining.slice(0, cut)); remaining = remaining.slice(cut); } pieces.push(remaining); return pieces; } function appendLine(value, isChordRow){ const row = document.createElement('div'); row.className = 'cifra-line' + (isChordRow ? ' cifra-line-chords' : ''); row.dataset.responsive = '1'; if(value === ''){ row.innerHTML = ' '; holder.appendChild(row); return; } String(value).split(/(\s+)/).forEach(function(part){ if(!part) return; if(chordToken.test(part)){ const chord = document.createElement('span'); chord.className = 'chord'; chord.dataset.original = part; chord.textContent = transposeChord(part, cfCapoPassosExibidos()); row.appendChild(chord); }else{ row.appendChild(document.createTextNode(part)); } }); holder.appendChild(row); } holder.innerHTML = ''; for(let index = 0; index < lines.length; index += 1){ const current = lines[index] || ''; const next = index + 1 < lines.length ? lines[index + 1] : null; if(chordLine.test(current) && next !== null && next.trim() !== '' && !chordLine.test(next)){ const lyricParts = splitAtWidth(next); let offset = 0; lyricParts.forEach(function(lyricPart){ const length = lyricPart.length; const chordPart = current.slice(offset, offset + length); if(chordPart.trim() !== '') appendLine(chordPart, true); appendLine(lyricPart, false); offset += length; }); if(current.slice(offset).trim() !== '') appendLine(current.slice(offset), true); index += 1; continue; } splitAtWidth(current).forEach(function(part){ appendLine(part, chordLine.test(current)); }); } } function initChordGallery(){ const gallery = document.getElementById('cifraChordGallery'); const modal = document.getElementById('cifraChordModal'); if(!gallery || !modal || !Array.isArray(chordGallerySource) || !chordGallerySource.length || !window.CifraNetChordDiagrams){ return; } chordGalleryController = window.CifraNetChordDiagrams.bindGrid( gallery, modal, chordGallerySource, function(){ return semitones; }, { darkMode: document.body.classList.contains('darkmode') } ); chordGalleryController.render(); } restoreCifraPreferences(); renderResponsiveCifra(); initChordGallery(); updateCifraProgress(); initSmartRecommendationTracking(); window.addEventListener('scroll', updateCifraProgress, {passive:true}); let responsiveCifraResizeTimer = 0; window.addEventListener('resize', function(){ updateCifraProgress(); window.clearTimeout(responsiveCifraResizeTimer); responsiveCifraResizeTimer = window.setTimeout(renderResponsiveCifra, 180); }); function openPlayView(){ const cifra = document.getElementById('cifra'); if(!cifra){ return; } const cifraAtualHtml = cifra.innerHTML; const cifraFont = window.getComputedStyle(cifra); const cifraFontSize = cifraFont.fontSize || (currentFont + 'px'); const cifraLineHeight = cifraFont.lineHeight || '1.72'; const cifraFontFamily = cifraFont.fontFamily || '"Courier New",monospace'; const safeFontSize = /^[-0-9.]+(px|rem|em|%)$/.test(cifraFontSize) ? cifraFontSize : (currentFont + 'px'); const safeLineHeight = /^[-0-9.a-zA-Z]+(px|rem|em|%)?$/.test(cifraLineHeight) ? cifraLineHeight : '1.72'; const safeFontFamily = cifraFontFamily.replace(/[<>]/g, ''); const darkModeActive = document.body.classList.contains('darkmode'); const playWindow = window.open('', '_blank', 'width=1100,height=760'); if(!playWindow){ return; } const playHtml = ` ${escapePlayHtml(playSongTitle)} - ${escapePlayHtml(playWindowLabel)} | CifraNET

CIFRANET

${escapePlayHtml(playSiteUrl)}

${escapePlayHtml(playSongTitle)}

${escapePlayHtml(playSongArtist)}

${cifraAtualHtml.replace(/cifra-line/g, 'play-cifra-line')}
1.0x