From 4faf8a44dbc1d73cdb0271af5e740cf5978faf3f Mon Sep 17 00:00:00 2001 From: Carl Richter Date: Thu, 29 Jul 2021 12:56:53 +0200 Subject: [PATCH] fix: refactor code block resizing to support window resizing --- client/themes/tyclipso/plugins/prism.js | 41 +++++++++++++++++-------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/client/themes/tyclipso/plugins/prism.js b/client/themes/tyclipso/plugins/prism.js index 04255aa0..efbe1b5c 100644 --- a/client/themes/tyclipso/plugins/prism.js +++ b/client/themes/tyclipso/plugins/prism.js @@ -57,35 +57,50 @@ function expandButton() { const codeBlock = env.element.closest('.code-toolbar') const container = env.element.closest('.page-col-content.ty-max-width') - const codeBlockWidth = codeBlock.style.width = `${codeBlock.offsetWidth}px`; const applyInlineStyles = (marginLeft, width) => { - codeBlock.style.marginLeft = expanded ? `${marginLeft}px` : '0px' - codeBlock.style.width = expanded ? `${width}px` : codeBlockWidth + codeBlock.style.width = `${codeBlock.closest('.contents').offsetWidth}px` + codeBlock.style.marginLeft = '0px' + + if (expanded) { + window.requestAnimationFrame(() => { + codeBlock.style.marginLeft = `${marginLeft}px` + codeBlock.style.width = `${width}px` + }) + } else { + setTimeout(() => { + codeBlock.style.marginLeft = codeBlock.style.width = null + }, 500) + } + } + + const recalculateWidth = () => { + const containerMargin = parseFloat(window.getComputedStyle(container).marginLeft) + const containerPadding = parseFloat(window.getComputedStyle(container).paddingLeft) + + // compute expanded size + const expandedWidth = container.offsetWidth - containerPadding * 2 + containerMargin * 2; + + // apply inline styles to code block + applyInlineStyles(-containerMargin, expandedWidth) } - applyInlineStyles() const expandButton = document.createElement('button') expandButton.innerHTML = expandIcon expandButton.addEventListener('click', () => { - const containerMargin = parseFloat(window.getComputedStyle(container).marginLeft) - const containerPadding = parseFloat(window.getComputedStyle(container).paddingLeft) - expanded = !expanded + recalculateWidth() + // switch icon expandButton.innerHTML = expanded ? collapseIcon : expandIcon - // compute expanded size - const expandedWidth = container.offsetWidth - containerPadding * 2 + containerMargin * 2; - - // apply inline styles to code block - applyInlineStyles(-containerMargin, expandedWidth) - document.activeElement.blur() }) + window.addEventListener('resize', recalculateWidth) + return expandButton }) }