Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Make web components form-friendly #20

Merged
merged 4 commits into from
Jun 12, 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: 4 additions & 1 deletion package/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ <h2>Web component</h2>
</div>
</div>
<button class="btn" style="width: max-content;">Open search</button>
<prism-editor line-numbers language="javascript" theme="github-dark"></prism-editor>
<form id="form">
<prism-editor name="editor" line-numbers language="javascript" theme="github-dark"></prism-editor>
</form>
<button class="btn" form="form" style="width: max-content;" type="submit">Send as form data</button>
</section>
<section>
<readonly-editor readonly line-numbers language="markdown" theme="github-dark"></readonly-editor>
Expand Down
9 changes: 9 additions & 0 deletions package/src/testsite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,13 @@ document.querySelector<HTMLElement>("button.btn")!.onclick = () => {
editor2.extensions.searchWidget!.open()
}

document.querySelector<HTMLFormElement>("#form")!.onsubmit = e => {
e.preventDefault()
const data = new FormData(e.target as HTMLFormElement)
console.info(`===
Form submission results:
===
${data.get("editor")}`)
}

setTimeout(() => import("../prism/languages"), 500)
10 changes: 10 additions & 0 deletions package/src/webComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,19 @@ const addComponent = (name: string, createEditor: typeof basicEditor) => {
name,
class extends HTMLElement {
static observedAttributes = attributes
static formAssociated = true

editor: PrismEditor

constructor() {
super()
const internals = this.attachInternals?.()
this.editor = createEditor(this, getOptions(this), () =>
this.dispatchEvent(new CustomEvent("ready")),
)
if (internals) {
this.editor.addListener("update", internals.setFormValue.bind(internals))
}

for (const attr in attributeMap)
Object.defineProperty(this, attributeMap[<keyof typeof attributeMap>attr][1] || attr, {
Expand All @@ -63,6 +69,10 @@ const addComponent = (name: string, createEditor: typeof basicEditor) => {
this.editor.setOptions({ value })
}

formResetCallback() {
this.value = this.editor.options.value
}

attributeChangedCallback(
name: keyof typeof attributeMap,
oldValue: string | null,
Expand Down