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

fix: image devtools #4626

Merged
merged 1 commit into from
Jun 27, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
position: absolute !important;
top: 0 !important;
left: 0 !important;
width: 100svw !important;
overflow: hidden !important;
height: 100svh !important;
width: 0 !important;
overflow: visible !important;
height: 0 !important;
pointer-events: none !important;
contain: strict;
contain: size layout style content;
z-index: 1;
}
</style>
<template id="qwik-image-warning-template">
Expand Down
127 changes: 71 additions & 56 deletions packages/qwik/src/optimizer/src/plugins/image-size-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,12 @@ export async function getInfoForSrc(src: string) {
}
}

export const getImageSizeServer = (sys: OptimizerSystem, rootDir: string, srcDir: string) => {
const handler: Connect.NextHandleFunction = async (req, res, next) => {
export const getImageSizeServer = (
sys: OptimizerSystem,
rootDir: string,
srcDir: string
): Connect.NextHandleFunction => {
return async (req, res, next) => {
const fs: typeof import('fs') = await sys.dynamicImport('node:fs');
const path: typeof import('path') = await sys.dynamicImport('node:path');

Expand Down Expand Up @@ -155,75 +159,86 @@ export const getImageSizeServer = (sys: OptimizerSystem, rootDir: string, srcDir
}
}

if (text.slice(offset, offset + 4) === '<img') {
const end = text.indexOf('>', offset) + 1;
const extensionSupportsImport = ['.ts', '.tsx', '.js', '.jsx', '.mdx'].includes(
extension
if (text.slice(offset, offset + 4) !== '<img') {
console.error(
'Could not apply auto fix, because it was not possible to find the original <img> tag'
);
let imgTag = text.slice(offset, end);
if (src && currentHref && extensionSupportsImport) {
const urlSrc = new URL(src);
const urlCurrent = new URL(currentHref);
if (urlSrc.origin === urlCurrent.origin) {
const publicImagePath = path.join(rootDir, 'public', urlSrc.pathname);
const rootImagePath = path.join(rootDir, urlSrc.pathname);
let relativeLocation: string;
if (fs.existsSync(publicImagePath)) {
const mediaSrc = path.join(srcDir, 'media', path.dirname(urlSrc.pathname));
await fs.promises.mkdir(mediaSrc, { recursive: true });
await fs.promises.copyFile(
publicImagePath,
path.join(srcDir, 'media', urlSrc.pathname)
);
relativeLocation = '~/media' + urlSrc.pathname;
} else if (fs.existsSync(rootImagePath)) {
relativeLocation = urlSrc.pathname.replace('/src/', '~/');
} else {
res.statusCode = 500;
return;
}

const end = text.indexOf('>', offset) + 1;
if (end < offset) {
console.error(
'Could not apply auto fix, because it was not possible to find the original <img> tag'
);
res.statusCode = 500;
return;
}

const extensionSupportsImport = ['.ts', '.tsx', '.js', '.jsx', '.mdx'].includes(extension);
let imgTag = text.slice(offset, end);
if (src && currentHref && extensionSupportsImport) {
const urlSrc = new URL(src);
const urlCurrent = new URL(currentHref);
if (urlSrc.origin === urlCurrent.origin) {
const publicImagePath = path.join(rootDir, 'public', urlSrc.pathname);
const rootImagePath = path.join(rootDir, urlSrc.pathname);
let relativeLocation: string;
if (fs.existsSync(publicImagePath)) {
const mediaSrc = path.join(srcDir, 'media', path.dirname(urlSrc.pathname));
await fs.promises.mkdir(mediaSrc, { recursive: true });
await fs.promises.copyFile(
publicImagePath,
path.join(srcDir, 'media', urlSrc.pathname)
);
relativeLocation = '~/media' + urlSrc.pathname;
} else if (fs.existsSync(rootImagePath)) {
relativeLocation = urlSrc.pathname.replace('/src/', '~/');
} else {
return;
}
const importIdent = imgImportName(urlSrc.pathname);
const importSrc = `${relativeLocation}?jsx`;
imgTag = imgTag.replace(/^<img/, `<${importIdent}`);
imgTag = imgTag.replace(/\bwidth=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);
imgTag = imgTag.replace(/\bheight=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);
imgTag = imgTag.replace(/\bsrc=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);

let insertImport = 0;
if (extension === '.mdx' && text.startsWith('---')) {
insertImport = text.indexOf('---', 4) + 3;
if (insertImport === -1) {
return;
}
const importIdent = imgImportName(urlSrc.pathname);
const importSrc = `${relativeLocation}?jsx`;
imgTag = imgTag.replace(/^<img/, `<${importIdent}`);
imgTag = imgTag.replace(/\bwidth=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);
imgTag = imgTag.replace(/\bheight=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);
imgTag = imgTag.replace(/\bsrc=(({[^}]*})|('[^']*')|("[^"]*"))\s*/, ``);

let insertImport = 0;
if (extension === '.mdx' && text.startsWith('---')) {
insertImport = text.indexOf('---', 4) + 3;
if (insertImport === -1) {
return;
}
}
const newImport = `\nimport ${importIdent} from '${importSrc}';`;
text = `${text.slice(0, insertImport)}${newImport}${text.slice(
insertImport,
offset
)}${imgTag}${text.slice(end)}`;
fs.writeFileSync(filePath, text);
}
const newImport = `\nimport ${importIdent} from '${importSrc}';`;
text = `${text.slice(0, insertImport)}${newImport}${text.slice(
insertImport,
offset
)}${imgTag}${text.slice(end)}`;
fs.writeFileSync(filePath, text);
return;
}
}

imgTag = imgTag.replace(/\bwidth=(({[^}]*})|('[^']*')|("[^"]*"))/, `width="${width}"`);
imgTag = imgTag.replace(/\bheight=(({[^}]*})|('[^']*')|("[^"]*"))/, `height="${height}"`);
if (!imgTag.includes('height=')) {
imgTag = imgTag.replace(/<img/, `<img height="${height}"`);
}
if (!imgTag.includes('width=')) {
imgTag = imgTag.replace(/<img/, `<img width="${width}"`);
}
text = text.slice(0, offset) + imgTag + text.slice(end);
fs.writeFileSync(filePath, text);
imgTag = imgTag.replace(/\bwidth=(({[^}]*})|('[^']*')|("[^"]*"))/, `width="${width}"`);
imgTag = imgTag.replace(/\bheight=(({[^}]*})|('[^']*')|("[^"]*"))/, `height="${height}"`);
if (!imgTag.includes('height=')) {
imgTag = imgTag.replace(/<img/, `<img height="${height}"`);
}
if (!imgTag.includes('width=')) {
imgTag = imgTag.replace(/<img/, `<img width="${width}"`);
}
text = text.slice(0, offset) + imgTag + text.slice(end);
fs.writeFileSync(filePath, text);
} catch (e) {
console.error('Error auto fixing image', e, url);
}
} else {
next();
}
};
return handler;
};

function imgImportName(value: string) {
Expand Down