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

refactor: ready -> $.ready #72

Merged
merged 2 commits into from
Jul 22, 2024
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
5 changes: 5 additions & 0 deletions .changeset/neat-chefs-provide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"simple-stack-query": minor
---

Change from a global `ready()` block from client scripts to a namespaced `$.ready()` block. Should be safer to avoid collisions with any local variables called `ready`.
18 changes: 9 additions & 9 deletions packages/query/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ A simple library to query the DOM from your Astro components.
<button data-target={$('btn')}>Click me</button>

<script>
ready(() => {
$.ready(() => {
$('btn').addEventListener('click', () => {
console.log("It's like JQuery but not!");
});
Expand Down Expand Up @@ -41,15 +41,15 @@ From your client script, the query result will be a plain HTML element. No, it's
$('btn').addEventListener(() => { /* ... */ });
```

You can also pass an `HTMLElement` or `SVGElement` type to access specific properties. For example, use `$<HTMLInputElement>` to access `.value`:
You can also pass an `HTMLElement` or `SVGElement` type to access specific properties. For example, use `$<HTMLInputElement>()` to access `.value`:

```ts
$<HTMLInputElement>('input').value = '';
```

### `$.optional` selector
### `$.optional()` selector

`$` throws when no matching element is found. To avoid this behavior, use `$.optional`:
`$()` throws when no matching element is found. To avoid this behavior, use `$.optional()`:

```astro
---
Expand All @@ -67,9 +67,9 @@ ready(() => {
</script>
```

### `$.all` selector
### `$.all()` selector

You may want to select multiple targets with the same name. You can use `$.all` to query for an array of results:
You may want to select multiple targets with the same name. You can use `$.all()` to query for an array of results:

```astro
---
Expand All @@ -87,13 +87,13 @@ ready(() => {
</script>
```

## Global `ready()` function
## Global `$.ready()` function

All `$` queries must be nested in a `ready()` block. This opts in to using the global `$` from client scripts. `ready()` also ensures your code reruns on every page [when view transitions are enabled.](https://docs.astro.build/en/guides/view-transitions/)
All `$` queries must be nested in a `$.ready()` block. This opts in to using the global `$` from client scripts. `$.ready()` also ensures your code reruns on every page [when view transitions are enabled.](https://docs.astro.build/en/guides/view-transitions/)

```astro
<script>
ready(() => {
$.ready(() => {
// ✅ Allowed
$('element').textContent = 'hey';
})
Expand Down
3 changes: 1 addition & 2 deletions packages/query/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@ declare namespace $ {
function optional<T extends Element = HTMLElement>(
selector: string,
): T | undefined;
function ready(callback: () => void): void;
}

declare function ready(callback: () => void): void;
8 changes: 7 additions & 1 deletion packages/query/fixtures/basic/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,10 @@ import WithContext from "./WithContext.astro";

<h1 data-target={$('test')}>Hey</h1>
<Nested />
<WithContext $context={$} />
<WithContext $context={$} />

<script>
$.ready(() => {
$('test').textContent = 'Hello';
});
</script>
3 changes: 1 addition & 2 deletions packages/query/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ function vitePlugin(): VitePlugin {
import { scope as __scope } from 'simple:scope';
import * as __queryInternals from "simple-stack-query/internal";

const $ = __queryInternals.create$(__scope);
const ready = __queryInternals.createReady(__scope);\n${code}`;
const $ = __queryInternals.create$(__scope);\n${code}`;
},
};
}
44 changes: 19 additions & 25 deletions packages/query/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import type { scope as scopeFn } from "simple:scope";
import { transitionEnabledOnThisPage } from "astro/virtual-modules/transitions-router.js";

export function create$(scope: typeof scopeFn) {
const anyMatchSelector = `[data-target$=${JSON.stringify(scope())}`;
function hasScopeElement() {
return Boolean(document.querySelector(anyMatchSelector));
}
function getSelector(scopeId: string) {
return `[data-target=${JSON.stringify(scope(scopeId))}]`;
}
Expand All @@ -20,33 +24,23 @@ export function create$(scope: typeof scopeFn) {
const selector = getSelector(scopeId);
return [...document.querySelectorAll(selector)];
},
ready(callback: () => MaybePromise<undefined | (() => void)>) {
if (transitionEnabledOnThisPage()) {
let cleanup: (() => void) | undefined;

document.addEventListener("astro:page-load", async () => {
if (cleanup) cleanup();
if (!hasScopeElement()) return;

cleanup = await callback();
});
} else {
if (!hasScopeElement()) return;
callback();
}
},
});
return $;
}

type MaybePromise<T> = T | Promise<T>;

export function createReady(scope: typeof scopeFn) {
const selector = `[data-target$=${JSON.stringify(scope())}`;
function hasScopeElement() {
return Boolean(document.querySelector(selector));
}

return function ready(
callback: () => MaybePromise<undefined | (() => void)>,
) {
if (transitionEnabledOnThisPage()) {
let cleanup: (() => void) | undefined;

document.addEventListener("astro:page-load", async () => {
if (cleanup) cleanup();
if (!hasScopeElement()) return;

cleanup = await callback();
});
} else {
if (!hasScopeElement()) return;
callback();
}
};
}
18 changes: 9 additions & 9 deletions www/src/content/docs/query.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A simple library to query the DOM from your Astro components.
<button data-target={$('btn')}>Click me</button>

<script>
ready(() => {
$.ready(() => {
$('btn').addEventListener('click', () => {
console.log("It's like JQuery but not!");
});
Expand Down Expand Up @@ -44,15 +44,15 @@ From your client script, the query result will be a plain HTML element. No, it's
$('btn').addEventListener(() => { /* ... */ });
```

You can also pass an `HTMLElement` or `SVGElement` type to access specific properties. For example, use `$<HTMLInputElement>` to access `.value`:
You can also pass an `HTMLElement` or `SVGElement` type to access specific properties. For example, use `$<HTMLInputElement>()` to access `.value`:

```ts
$<HTMLInputElement>('input').value = '';
```

### `$.optional` selector
### `$.optional()` selector

`$` throws when no matching element is found. To avoid this behavior, use `$.optional`:
`$()` throws when no matching element is found. To avoid this behavior, use `$.optional()`:

```astro
---
Expand All @@ -70,9 +70,9 @@ ready(() => {
</script>
```

### `$.all` selector
### `$.all()` selector

You may want to select multiple targets with the same name. You can use `$.all` to query for an array of results:
You may want to select multiple targets with the same name. You can use `$.all()` to query for an array of results:

```astro
---
Expand All @@ -90,13 +90,13 @@ ready(() => {
</script>
```

## Global `ready()` function
## Global `$.ready()` function

All `$` queries must be nested in a `ready()` block. This opts in to using the global `$` from client scripts. `ready()` also ensures your code reruns on every page [when view transitions are enabled.](https://docs.astro.build/en/guides/view-transitions/)
All `$` queries must be nested in a `$.ready()` block. This opts in to using the global `$` from client scripts. `$.ready()` also ensures your code reruns on every page [when view transitions are enabled.](https://docs.astro.build/en/guides/view-transitions/)

```astro
<script>
ready(() => {
$.ready(() => {
// ✅ Allowed
$('element').textContent = 'hey';
})
Expand Down
Loading