Skip to content

Commit

Permalink
feat: svelte inspector updates and promote from experimental (#631)
Browse files Browse the repository at this point in the history
* fix(inspector): move inspector host out of body to decrease risk of it getting removed by something overwriting body content

* feat(inspector): promote from experimental to regular, warn users to update config

* feat(inspector): enable inspector by default

* feat(inspector): enable holdMode by default

* fix(inspector): automatically disable on leave after a file has been opened

* fix(inspector): prepend vite base when calling __openInEditor

* feat(inspector): allow configuration via environment

* fix: disable inspector in CI and use eager disable if found via env

* fix: revert previous change, fix testcase and make sure inspector is only enabled for devserver

* fix: don't enable inspector by default

* fix(inspector): return void if no environment option is set

* fix: remove extra check for serve mode, it is already covered by apply: serve

* fix(inspector): remove keyup listener on destroy
  • Loading branch information
dominikg committed May 1, 2023
1 parent 5202b0a commit 40558dc
Show file tree
Hide file tree
Showing 15 changed files with 340 additions and 176 deletions.
5 changes: 5 additions & 0 deletions .changeset/bright-fans-count.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

feat(inspector): Promote experimental.inspector to regular option
5 changes: 5 additions & 0 deletions .changeset/cold-tips-lay.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

feat(inspector): allow configuration via environment SVELTE_INSPECTOR_OPTIONS or SVELTE_INSPECTOR_TOGGLE
5 changes: 5 additions & 0 deletions .changeset/funny-suits-grin.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

fix(inspector): prepend vite base when calling \_\_openInEditor
5 changes: 5 additions & 0 deletions .changeset/green-rats-cry.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

fix(inspector): after a file has been opened, automatically disable inspector on leaving browser
5 changes: 5 additions & 0 deletions .changeset/orange-lobsters-cross.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

fix(inspector): use control-shift as default keycombo on linux to avoid problems in firefox
5 changes: 5 additions & 0 deletions .changeset/perfect-nails-rescue.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

feat(inspector): enable holdMode by default
5 changes: 5 additions & 0 deletions .changeset/weak-crabs-type.md
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

fix(svelte-inspector): mount outside body to avoid hydration claiming body removing it
170 changes: 95 additions & 75 deletions docs/config.md
Expand Up @@ -212,81 +212,16 @@ A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patt

See the [FAQ](./faq.md#what-is-going-on-with-vite-and-pre-bundling-dependencies) for details and how to fine-tune it for huge libraries.

## Experimental options

These options are considered experimental and breaking changes to them can occur in any release! Specify them under the `experimental` option.

Either in Vite config:

```js
// vite.config.js
export default defineConfig({
plugins: [
svelte({
experimental: {
// experimental options
}
})
]
});
```

or in Svelte config:

```js
// svelte.config.js
export default {
vitePlugin: {
experimental: {
// experimental options
}
}
};
```

### dynamicCompileOptions

- **Type:**

```ts
type DynamicCompileOptions = (data: {
filename: string; // The file to be compiled
code: string; // The preprocessed Svelte code
compileOptions: Partial<CompileOptions>; // The current compiler options
}) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
```

A function to update the `compilerOptions` before compilation. To change part of the compiler options, return an object with the changes you need.

**Example:**

```js
// vite.config.js
export default defineConfig({
plugins: [
svelte({
experimental: {
dynamicCompileOptions({ filename, compileOptions }) {
// Dynamically set hydration per Svelte file
if (compileWithHydratable(filename) && !compileOptions.hydratable) {
return { hydratable: true };
}
}
}
})
]
});
```

### inspector

- **Type:**`InspectorOptions | boolean`
- **Default:** `unset` for dev, always `false` for build

```ts
interface InspectorOptions {
/**
* define a key combo to toggle inspector,
* @default 'control-shift' on windows, 'meta-shift' on other os
* @default 'meta-shift' on mac, 'control-shift' on other os
*
* any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by -
* examples: control-shift, control-o, control-alt-s meta-x control-meta
Expand Down Expand Up @@ -318,7 +253,7 @@ export default {

/**
* inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress
* @default false
* @default true
*/
holdMode?: boolean;

Expand All @@ -341,9 +276,94 @@ export default {
}
```

Set to `true` or customized `InspectorOptions` to enable svelte inspector during development.
Set to `true` or options object to enable svelte inspector during development.

Inspector mode shows you the file location where the element under cursor is defined and you can click to quickly open your code editor at this location.

**Example:**

```js
// vite.config.js
export default defineConfig({
plugins: [
svelte({
inspector: {
toggleKeyCombo: 'meta-shift',
holdMode: true,
showToggleButton: 'always',
toggleButtonPos: 'bottom-right'
}
})
]
});
```

#### Customizing Inspector options via environment

Svelte Inspector toggle keys and other options are personal preferences. As such it isn't always convenient to define them in a shared svelte config file.
To allow you to use your own setup, svelte inspector can be configured via environment variables, both from shell and dotenv files.

```shell
# just keycombo, unquoted string
SVELTE_INSPECTOR_TOGGLE=control-shift

# options object as json, all options except appendTo are supported
SVELTE_INSPECTOR_OPTIONS='{"holdMode": false, "toggleButtonPos": "bottom-left"}'

# disable completely
SVELTE_INSPECTOR_OPTIONS=false

# force default options
SVELTE_INSPECTOR_OPTIONS=true
```

When enabled, inspector mode shows you the file location where the element under cursor is defined and you can click to quickly open your code editor at this location.
> Inspector options set on the environment take precedence over values set in svelte config and automatically enable svelte inspector during dev.
## Experimental options

These options are considered experimental and breaking changes to them can occur in any release! Specify them under the `experimental` option.

Either in Vite config:

```js
// vite.config.js
export default defineConfig({
plugins: [
svelte({
experimental: {
// experimental options
}
})
]
});
```

or in Svelte config:

```js
// svelte.config.js
export default {
vitePlugin: {
experimental: {
// experimental options
}
}
};
```

### dynamicCompileOptions

- **Type:**

```ts
type DynamicCompileOptions = (data: {
filename: string; // The file to be compiled
code: string; // The preprocessed Svelte code
compileOptions: Partial<CompileOptions>; // The current compiler options
}) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
```

A function to update the `compilerOptions` before compilation. To change part of the compiler options, return an object with the changes you need.

**Example:**

Expand All @@ -353,11 +373,11 @@ export default {
plugins: [
svelte({
experimental: {
inspector: {
toggleKeyCombo: 'meta-shift',
holdMode: true,
showToggleButton: 'always',
toggleButtonPos: 'bottom-right'
dynamicCompileOptions({ filename, compileOptions }) {
// Dynamically set hydration per Svelte file
if (compileWithHydratable(filename) && !compileOptions.hydratable) {
return { hydratable: true };
}
}
}
})
Expand Down
Expand Up @@ -16,7 +16,7 @@ test('should apply css compiled from scss', async () => {

if (!isBuild) {
test('should generate sourcemap', async () => {
const style = await getText('style');
const style = await getText('style[data-vite-dev-id*="App.svelte"]');
const lines = style.split(`\n`).map((l) => l.trim());
const css = lines[0];
const mapComment = lines[1];
Expand Down
6 changes: 3 additions & 3 deletions packages/vite-plugin-svelte/src/index.ts
Expand Up @@ -273,10 +273,10 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin[] {
);
}
}
}
},
svelteInspector()
];
plugins.push(svelteInspector());
return plugins.filter(Boolean);
return plugins;
}

export { vitePreprocess } from './preprocess';
Expand Down
23 changes: 21 additions & 2 deletions packages/vite-plugin-svelte/src/ui/inspector/Inspector.svelte
Expand Up @@ -6,6 +6,7 @@
const toggle_combo = options.toggleKeyCombo?.toLowerCase().split('-');
const nav_keys = Object.values(options.navKeys).map((k) => k.toLowerCase());
let enabled = false;
let hasOpened = false;
const icon = `data:image/svg+xml;base64,${btoa(
`
Expand Down Expand Up @@ -123,7 +124,8 @@
function open_editor(event) {
if (file_loc) {
stop(event);
fetch(`/__open-in-editor?file=${encodeURIComponent(file_loc)}`);
fetch(`${options.__internal.base}/__open-in-editor?file=${encodeURIComponent(file_loc)}`);
hasOpened = true;
if (options.holdMode && is_holding()) {
disable();
}
Expand Down Expand Up @@ -247,6 +249,7 @@
function disable() {
enabled = false;
hasOpened = false;
enabled_ts = null;
const b = document.body;
listeners(b, enabled);
Expand All @@ -257,6 +260,18 @@
active_el = null;
}
function visibilityChange() {
if (document.visibilityState === 'hidden') {
onLeave();
}
}
function onLeave() {
if (hasOpened) {
disable();
}
}
onMount(() => {
const s = document.createElement('style');
s.setAttribute('type', 'text/css');
Expand All @@ -269,6 +284,8 @@
document.body.addEventListener('keyup', keyup);
}
}
document.addEventListener('visibilitychange', visibilityChange);
document.documentElement.addEventListener('mouseleave', onLeave);
return () => {
// make sure we get rid of everything
disable();
Expand All @@ -279,9 +296,11 @@
if (toggle_combo) {
document.body.removeEventListener('keydown', keydown);
if (options.holdMode) {
document.body.addEventListener('keyup', keyup);
document.body.removeEventListener('keyup', keyup);
}
}
document.removeEventListener('visibilitychange', visibilityChange);
document.documentElement.removeEventListener('mouseleave', onLeave);
};
});
</script>
Expand Down
Expand Up @@ -8,7 +8,7 @@ function create_inspector_host() {
}
const el = document.createElement('div');
el.setAttribute('id', id);
document.getElementsByTagName('body')[0].appendChild(el);
document.documentElement.appendChild(el);
return el;
}

Expand Down

0 comments on commit 40558dc

Please sign in to comment.