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

feat(overlay): Add click to go to editor for audits #9016

Merged
merged 8 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
5 changes: 5 additions & 0 deletions .changeset/calm-shirts-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Add ability to "Click to go editor" on auditted elements in the dev overlay
2 changes: 1 addition & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
"test:e2e:match": "playwright test -g"
},
"dependencies": {
"@astrojs/compiler": "^2.1.0",
"@astrojs/compiler": "^2.3.0",
"@astrojs/internal-helpers": "workspace:*",
"@astrojs/markdown-remark": "workspace:*",
"@astrojs/telemetry": "workspace:*",
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/core/compile/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export async function compile({
scopedStyleStrategy: astroConfig.scopedStyleStrategy,
resultScopedSlot: true,
transitionsAnimationURL: 'astro/components/viewtransitions.css',
annotateSourceFile: viteConfig.command === 'serve' && astroConfig.experimental.devOverlay,
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
preprocessStyle: createStylePreprocessor({
filename,
viteConfig,
Expand Down
34 changes: 24 additions & 10 deletions packages/astro/src/runtime/client/dev-overlay/plugins/audit.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DevOverlayPlugin } from '../../../../@types/astro.js';
import type { DevOverlayMetadata, DevOverlayPlugin } from '../../../../@types/astro.js';
import type { DevOverlayHighlight } from '../ui-library/highlight.js';
import { getIconElement } from '../ui-library/icons.js';
import { attachTooltipToHighlight, createHighlight, positionHighlight } from './utils/highlight.js';
Expand Down Expand Up @@ -121,15 +121,16 @@ export default {

const rect = originalElement.getBoundingClientRect();
const highlight = createHighlight(rect, 'warning');
const tooltip = buildAuditTooltip(rule);
const tooltip = buildAuditTooltip(rule, originalElement);
attachTooltipToHighlight(highlight, tooltip, originalElement);

canvas.append(highlight);
audits.push({ highlightElement: highlight, auditedElement: originalElement as HTMLElement });
}

function buildAuditTooltip(rule: AuditRule) {
function buildAuditTooltip(rule: AuditRule, element: Element) {
const tooltip = document.createElement('astro-dev-overlay-tooltip');

tooltip.sections = [
{
icon: 'warning',
Expand All @@ -138,15 +139,28 @@ export default {
{
content: rule.message,
},
// TODO: Add a link to the file
// Needs https://github.com/withastro/compiler/pull/375
// {
// content: '/src/somewhere/component.astro',
// clickDescription: 'Click to go to file',
// clickAction() {},
// },
];

const elementFile = element.getAttribute('data-astro-source-file');
const elementPosition = element.getAttribute('data-astro-source-loc');

if (elementFile) {
const elementFileWithPosition =
elementFile + (elementPosition ? ':' + elementPosition : '');

tooltip.sections.push({
content: elementFileWithPosition.slice(
(window as DevOverlayMetadata).__astro_dev_overlay__.root.length - 1 // We want to keep the final slash, so minus one.
),
clickDescription: 'Click to go to file',
async clickAction() {
// NOTE: The path here has to be absolute and without any errors (no double slashes etc)
// or Vite will silently fail to open the file. Quite annoying.
await fetch('/__open-in-editor?file=' + encodeURIComponent(elementFileWithPosition));
},
});
}

return tooltip;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sequence, defineMiddleware } from 'astro:middleware';
import { defineMiddleware, sequence } from 'astro:middleware';

const first = defineMiddleware(async (context, next) => {
if (context.request.url.includes('/lorem')) {
Expand All @@ -24,7 +24,7 @@ const first = defineMiddleware(async (context, next) => {
const response = await next();
const newResponse = response.clone();
const /** @type {string} */ html = await newResponse.text();
const newhtml = html.replace('<h1>testing</h1>', '<h1>it works</h1>');
const newhtml = html.replace('testing', 'it works');
return new Response(newhtml, { status: 200, headers: response.headers });
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this is a bit awkward. But since we now add attributes, those kind of naive replacements don't work in dev.

In my humble, informed, opinion, you shouldn't rely on string replaces like this anyway, because whitespaces, minification etc etc could ruin it anyway. Typically, I'd recommend people to use a real tool for this, like https://github.com/cloudflare/lol-html

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow, such shade 🌨

} else if(context.url.pathname === '/return-response-cookies') {
const response = await next();
Expand Down
8 changes: 4 additions & 4 deletions packages/astro/test/middleware.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { loadFixture } from './test-utils.js';
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import testAdapter from './test-adapter.js';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { readFileSync, existsSync } from 'node:fs';
import testAdapter from './test-adapter.js';
import { loadFixture } from './test-utils.js';

describe('Middleware in DEV mode', () => {
/** @type {import('./test-utils').Fixture} */
Expand Down Expand Up @@ -77,7 +77,7 @@ describe('Middleware in DEV mode', () => {
it('should be able to clone the response', async () => {
let res = await fixture.fetch('/clone');
let html = await res.text();
expect(html).to.contain('<h1>it works</h1>');
expect(html).to.contain('it works');
});

it('should forward cookies set in a component when the middleware returns a new response', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/partials.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('Partials', () => {

it('is only the written HTML', async () => {
const html = await fixture.fetch('/partials/item/').then((res) => res.text());
expect(html.startsWith('<li>')).to.equal(true);
expect(html.startsWith('<li')).to.equal(true);
});
});

Expand Down
9 changes: 5 additions & 4 deletions packages/astro/test/units/dev/dev.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { fileURLToPath } from 'node:url';
import {
createFs,
createRequestAndResponse,
triggerFSEvent,
runInContainer,
triggerFSEvent,
} from '../test-utils.js';

const root = new URL('../../fixtures/alias/', import.meta.url);
Expand Down Expand Up @@ -199,7 +199,8 @@ describe('dev container', () => {
container.handle(r.req, r.res);
await r.done;
const doc = await r.text();
expect(doc).to.match(/<h1>Regular page<\/h1>/);
console.log(doc);
expect(doc).to.match(/Regular page/);
expect(r.res.statusCode).to.equal(200);
}
{
Expand All @@ -208,7 +209,7 @@ describe('dev container', () => {
container.handle(r.req, r.res);
await r.done;
const doc = await r.text();
expect(doc).to.match(/<h1>Custom 404<\/h1>/);
expect(doc).to.match(/Custom 404/);
expect(r.res.statusCode).to.equal(404);
}
{
Expand All @@ -217,7 +218,7 @@ describe('dev container', () => {
container.handle(r.req, r.res);
await r.done;
const doc = await r.text();
expect(doc).to.match(/<h1>Custom 404<\/h1>/);
expect(doc).to.match(/Custom 404/);
expect(r.res.statusCode).to.equal(404);
}
}
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

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

Loading