Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async images #186

Merged
merged 7 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions cosmoz-image-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ const renderCosmozImageViewer = ({
nextImage,
previousImage,
total,
first,
last,
currentImageIndex,
selectedImageNumber,
syncImageIndex,
Expand Down Expand Up @@ -71,10 +73,20 @@ const renderCosmozImageViewer = ({
${when(
shouldShow(host.showNav, total, 2),
() => html`
<button class="nav" name="prev" @click=${previousImage}>
<button
class="nav"
name="prev"
?disabled=${first}
@click=${previousImage}
>
${leftArrow}
</button>
<button class="nav" name="next" @click=${nextImage}>
<button
class="nav"
name="next"
?disabled=${last}
@click=${nextImage}
>
${rightArrow}
</button>
`,
Expand Down
23 changes: 18 additions & 5 deletions cosmoz-image-viewer.style.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,18 @@ button.nav {
border: none;
width: 40px;
height: 40px;
cursor: pointer;
transition: background-color 100ms;
}

button.nav:active {
button.nav:not([disabled]) {
cursor: pointer;
}

button.nav[disabled] {
opacity: 0.5;
}

button.nav:active:not([disabled]) {
background-color: rgba(0, 0, 0, 0.60);
}

Expand Down Expand Up @@ -108,7 +115,13 @@ button.nav:active {

cosmoz-slider {
min-height: 150px;
// overflow-y: auto !important;
overflow-y: auto !important;
height:100%;
overflow-y: hidden;
}`;
}

cz-spinner {
position: absolute;
top: 50%;
left: 50%;
}
`;
69 changes: 49 additions & 20 deletions lib/hooks/use-cosmoz-image-viewer.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import '@neovici/cosmoz-utils/elements/cz-spinner';

import { useSlideList } from '@neovici/cosmoz-slider';
import { useImperativeApi } from '@neovici/cosmoz-utils/hooks/use-imperative-api';
import { useNotifyProperty } from '@neovici/cosmoz-utils/hooks/use-notify-property';
import { useCallback, useEffect, useState } from 'haunted';
import { html } from 'lit-html';
import { useCallback, useEffect, useMemo, useState } from 'haunted';
import { html, nothing } from 'lit-html';
import { download } from '../pdf';
import { popout, hasWindow } from '../popout';
import { print } from '../print';
import { guard } from 'lit-html/directives/guard.js';
import { until } from 'lit-html/directives/until.js';
import { invoke } from '@neovici/cosmoz-utils/function';
import { memoize } from '@neovici/cosmoz-utils/memoize';

const onImageError = (e) => {
if (!e.currentTarget.parentElement) {
Expand All @@ -18,21 +24,32 @@ const onImageError = (e) => {
e.currentTarget.setAttribute('hidden', true);
},
onStatusChanged = (ev) => ev.detail.value === 'error' && onImageError(ev),
renderImage = ({ showZoom, image, isZoomed, _onZoomChanged }) =>
showZoom
? html`<haunted-pan-zoom
class="image-zoom"
.src=${image}
?disabled=${!isZoomed}
@zoom-changed=${_onZoomChanged}
@status-changed=${onStatusChanged}
></haunted-pan-zoom>`
: html`<img
class="image"
.src=${image}
style="width:100%"
@error=${onImageError}
/>`,
renderImage = ({ src$, showZoom, isZoomed, _onZoomChanged }) => {
const src = guard(src$, () => until(src$));

return [
showZoom
? html`<haunted-pan-zoom
class="image-zoom"
.src=${src}
?disabled=${!isZoomed}
@zoom-changed=${_onZoomChanged}
@status-changed=${onStatusChanged}
></haunted-pan-zoom>`
: html`<img
class="image"
.src=${src}
style="width:100%"
@error=${onImageError}
/>`,
guard(src$, () =>
until(
src$.then(() => nothing),
html`<cz-spinner></cz-spinner>`,
),
),
];
},
render = (opts) =>
html`<div>
<div hidden class="error">
Expand All @@ -52,10 +69,20 @@ const onImageError = (e) => {
} = host,
[isZoomed, setIsZoomed] = useState(false),
_onZoomChanged = (ev) => setIsZoomed(ev.detail.value > 1),
{ slide, next, prev, goto, index } = useSlideList(images, {
initial: images[host.currentImageIndex],
_invoke = useMemo(
() => memoize((image) => Promise.resolve(invoke(image))),
[],
),
{ slide, next, prev, goto, index, first, last } = useSlideList(images, {
loop,
initial: images?.[host.currentImageIndex],
render: (image) =>
render({ image, showZoom, isZoomed, _onZoomChanged }),
render({
src$: _invoke(image),
showZoom,
isZoomed,
_onZoomChanged,
}),
}),
[isFullscreen, setIsFullscreen] = useState(false),
openFullscreen = () => setIsFullscreen(true),
Expand Down Expand Up @@ -96,6 +123,8 @@ const onImageError = (e) => {
currentSlide: slide,
nextImage: next,
previousImage: prev,
first,
last,
total: images.length,
currentImageIndex: index,
selectedImageNumber: index + 1,
Expand Down
57 changes: 32 additions & 25 deletions lib/pdf.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
export const
fit = (rect, bounds) => {
import { invoke } from '@neovici/cosmoz-utils/function';

export const fit = (rect, bounds) => {
const rectRatio = rect.width / rect.height,
boundsRatio = bounds.width / bounds.height;

return rectRatio > boundsRatio
? {
width: bounds.width,
height: rect.height * (bounds.width / rect.width)
}
width: bounds.width,
height: rect.height * (bounds.width / rect.width),
}
: {
width: rect.width * (bounds.height / rect.height),
height: bounds.height
};
width: rect.width * (bounds.height / rect.height),
height: bounds.height,

Check warning on line 14 in lib/pdf.js

View check run for this annotation

Codecov / codecov/patch

lib/pdf.js#L13-L14

Added lines #L13 - L14 were not covered by tests
};
},

create = async (urls, credentials) => {
const options = { credentials: credentials ? 'include' : 'omit' },
[{ jsPDF }, ...responses$] = await Promise.all([import('jspdf'), ...urls.map(
async url => {
[{ jsPDF }, ...responses$] = await Promise.all([
import('jspdf'),
...urls.map(async (_url) => {
const url = await Promise.resolve(invoke(_url));
const response = await fetch(url, options);
return response.ok
? {
url,
data: new Uint8Array(await response.arrayBuffer())
}
url,
data: new Uint8Array(await response.arrayBuffer()),
}
: undefined;
}
)]),
}),
]),
responses = responses$.filter(Boolean);

if (responses.length < 1) {
Expand All @@ -36,32 +38,37 @@
const pdf = new jsPDF(); // eslint-disable-line new-cap

responses.filter(Boolean).forEach(({ url, data }, i) => {
const
padding = 2, //in mm
{ internal: { pageSize }} = pdf,
const padding = 2, //in mm
{
internal: { pageSize },
} = pdf,
{ width, height } = fit(pdf.getImageProperties(data), {
width: pageSize.getWidth() - padding * 2,
height: pageSize.getHeight() - padding * 2
height: pageSize.getHeight() - padding * 2,
});
if (i > 0) {
pdf.addPage();
}
pdf.addImage(data, url.split('.').pop().toUpperCase(), padding, padding, width, height);

pdf.addImage(
data,
url.split('.').pop().toUpperCase(),
padding,
padding,
width,
height,
);
});
return pdf.output('blob');
},

downloadBlob = (blob, filename) => {
const url = URL.createObjectURL(blob),
a = document.body.appendChild(document.createElement('a'));
a.href = url;
a.download = `${ filename }.pdf`;
a.download = `${filename}.pdf`;
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
},

download = async (urls, filename, credentials) => {
const blob = await create(urls, credentials);
if (blob) {
Expand Down
11 changes: 8 additions & 3 deletions lib/print.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { invoke } from '@neovici/cosmoz-utils/function';
import { html, render } from 'lit-html';
import { until } from 'lit-html/directives/until.js';

const waitFor = (condition) =>
new Promise((resolve) => {
Expand All @@ -20,14 +22,17 @@
page-break-after: always;
max-height: 100%;
width: 100%;
}</style
>${images.map((src) => html`<img src="${src}" />`)}`,
}
</style>
${images.map(
(src) => html`<img src="${until(Promise.resolve(invoke(src)))}" />`,
)}`,

Check warning on line 29 in lib/print.js

View check run for this annotation

Codecov / codecov/patch

lib/print.js#L25-L29

Added lines #L25 - L29 were not covered by tests
pout.document.body,
);

waitFor(() =>
Array.from(pout.document.querySelectorAll('img')).every(
(img) => img.complete,
(img) => img.src && img.complete,

Check warning on line 35 in lib/print.js

View check run for this annotation

Codecov / codecov/patch

lib/print.js#L35

Added line #L35 was not covered by tests
),
)
.then(() => pout.print())
Expand Down
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"dependencies": {
"@neovici/cfg": "^1.43.0",
"@neovici/cosmoz-i18next": "^3.2.2",
"@neovici/cosmoz-slider": "^4.0.0",
"@neovici/cosmoz-slider": "^4.5.0",
"@neovici/cosmoz-utils": "^5.0.0",
"haunted": "^5.0.0",
"jspdf": "^2.3.0",
Expand Down
40 changes: 5 additions & 35 deletions stories/data.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,9 @@
export const images = [
'stories/images/stockholm.jpg',
'this-is-a-loading-error.jpg',
'stories/images/a_size.png',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg',
'stories/images/strasbourg.jpg',
'stories/images/stockholm.jpg'
() => 'stories/images/a_size.png',
() =>
new Promise((resolve) =>
setTimeout(() => resolve('stories/images/strasbourg.jpg'), 500),
),
];
Loading