Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
66 changes: 66 additions & 0 deletions src/components/Checkbox.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
import { z } from "astro:schema";

const props = z.object({
label: z.string(),
});

const { label } = props.parse(Astro.props);
---

<check-box>
<label class="block">
<input type="checkbox" />
{label}
</label>
</check-box>

<script>
function getStorage() {
const raw = localStorage.getItem("checkboxes");

if (!raw) return [];

let json;
try {
json = JSON.parse(raw);
} catch (e) {
localStorage.removeItem("checkboxes");
return [];
}

return json;
}

function updateStorage(label: string, checked: boolean) {
const key = `${window.location.pathname}${label}`;
const storage = getStorage();

if (checked) {
storage.push(key);
} else {
storage.splice(storage.indexOf(key), 1);
}

localStorage.setItem("checkboxes", JSON.stringify(storage));
}

class Checkbox extends HTMLElement {
connectedCallback() {
const input = this.querySelector("input") as HTMLInputElement;
const label = (
this.querySelector("label") as HTMLLabelElement
).innerText.trim();

input.checked = getStorage().includes(
`${window.location.pathname}${label}`,
);

input.addEventListener("change", () => {
updateStorage(label, input.checked);
});
}
}

customElements.define("check-box", Checkbox);
</script>
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export { Icon as AstroIcon } from "astro-icon/components";
export { default as AnchorHeading } from "./AnchorHeading.astro";
export { default as APIRequest } from "./APIRequest.astro";
export { default as AvailableNotifications } from "./AvailableNotifications.astro";
export { default as Checkbox } from "./Checkbox.astro";
export { default as CompatibilityFlag } from "./CompatibilityFlag.astro";
export { default as CompatibilityFlags } from "./CompatibilityFlags.astro";
export { default as ComponentUsage } from "./ComponentUsage.astro";
Expand Down
23 changes: 23 additions & 0 deletions src/content/docs/style-guide/components/checkbox.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: Checkbox
styleGuide:
component: Checkbox
---

import { Type, MetaInfo } from "~/components";

The `Checkbox` component is a custom checkbox that persists its state in local storage.

```mdx live
import { Checkbox } from "~/components";

<Checkbox label="Step one" />
<Checkbox label="Step two" />
<Checkbox label="Step three" />
```

## Props

- `label` <Type text="string" /> <MetaInfo text="required" />

The label for the checkbox.
Loading