aboutsummaryrefslogtreecommitdiff
path: root/static/scripts/resize.js
blob: 95b75c167a57582d5acff2c80ab1ee6f5b4c3718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function getAvailableHeight() {
    const navbar = document.querySelector('nav')
    const postBar = document.querySelector('.single-post-bar')
    const navbarHeight = navbar ? navbar.offsetHeight : 0
    const postBarHeight = postBar ? postBar.offsetHeight : 0
    const padding = 40
    return window.innerHeight - navbarHeight - postBarHeight - padding
}

function updateSizeSelection(selectedSize) {
    document.querySelectorAll('.single-post-bar-size-actions a').forEach((link) => {
        link.classList.remove('size-selected')
        if (link.onclick && link.onclick.toString().includes(selectedSize)) {
            link.classList.add('size-selected')
        }
    })
}

let currentSize = 'fitBoth'

function handleResize() {
    if (currentSize === 'fitHeight' || currentSize === 'fitBoth') {
        switchSize(currentSize)
    }
}

function switchSize(size) {
    currentSize = size
    const img = document.getElementById('post-image')
    const container = document.querySelector('.post-image-container')
    const sizeData = sizes[size]

    img.className = ''
    img.style.width = ''
    img.style.height = ''
    img.style.maxWidth = ''
    img.style.maxHeight = ''

    if (size === 'fitHeight') {
        const availableHeight = getAvailableHeight()
        img.style.maxHeight = availableHeight + 'px'
        img.style.width = 'auto'
        img.style.maxWidth = 'none'
        img.classList.add('fit-height')
    } else if (size === 'fitWidth') {
        img.style.width = '100%'
        img.style.height = 'auto'
        img.style.maxWidth = '100%'
        img.classList.add('fit-width')
    } else if (size === 'fitBoth') {
        const availableHeight = getAvailableHeight()
        const imageWidth = parseInt(sizeData.width || img.naturalWidth)
        const imageHeight = parseInt(sizeData.height || img.naturalHeight)

        if (imageHeight > imageWidth) {
            img.style.maxHeight = availableHeight + 'px'
            img.style.width = 'auto'
            img.style.maxWidth = 'none'
        } else {
            img.style.width = '100%'
            img.style.height = 'auto'
            img.style.maxWidth = '100%'
        }
        img.classList.add('fit-both')
    } else {
        img.style.maxWidth = 'none'
        if (sizeData.width) img.style.width = sizeData.width + 'px'
        if (sizeData.height) img.style.height = sizeData.height + 'px'
        img.classList.add('fixed-size')
    }

    img.src = sizeData.src
    updateSizeSelection(size)
}

window.addEventListener('resize', handleResize)

window.addEventListener('load', function () {
    switchSize(currentSize)
})