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

Allow a single stream response to update multiple elements #113

Merged
merged 17 commits into from
Jun 17, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
14 changes: 7 additions & 7 deletions src/core/streams/stream_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@ import { StreamElement } from "../../elements/stream_element"

export const StreamActions: { [action: string]: (this: StreamElement) => void } = {
append() {
this.targetElement?.append(this.templateContent)
this.targetElements?.forEach(e => e.append(this.templateContent))
},

prepend() {
this.targetElement?.prepend(this.templateContent)
this.targetElements?.forEach(e => e.prepend(this.templateContent))
},

remove() {
this.targetElement?.remove()
this.targetElements?.forEach(e => e.remove())
},

replace() {
this.targetElement?.replaceWith(this.templateContent)
this.targetElements?.forEach(e => e.replaceWith(this.templateContent))
},

update() {
if (this.targetElement) {
this.targetElement.innerHTML = ""
this.targetElement.append(this.templateContent)
if (this.targetElements) {
this.targetElements.forEach(e => e.innerHTML = "")
this.targetElements.forEach(e => e.append(this.templateContent))
}
}
}
20 changes: 15 additions & 5 deletions src/elements/stream_element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,25 @@ export class StreamElement extends HTMLElement {
this.raise("action attribute is missing")
}

get targetElement() {
if (this.target) {
return this.ownerDocument?.getElementById(this.target)
get targetElements(): Array<Element> {
// Try to get the target node by first looking it up by ID.
// If that fails, try using the target as a CSS Selector.
if (!this.target) {
this.raise("target attribute is missing")
}
this.raise("target attribute is missing")
const idTarget = this.ownerDocument?.getElementById(this.target)
if (idTarget !== null) {
return [idTarget]
}
const cssTarget = this.ownerDocument?.querySelectorAll(this.target)
if (cssTarget.length !== 0) {
return Array.prototype.slice.call(cssTarget)
}
this.raise(`target "${this.target}" not found`)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've added this exception. I'm assuming not finding the target is a programming error, but maybe that's too strict?

Copy link
Member

Choose a reason for hiding this comment

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

Too strict, yeah. And a breaking change. You may well stream an update to something that's no longer there.

}

get templateContent() {
return this.templateElement.content
return this.templateElement.content.cloneNode(true)
}

get templateElement() {
Expand Down
10 changes: 9 additions & 1 deletion src/tests/fixtures/stream.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
<meta charset="utf-8">
<title>Turbo Streams</title>
<script src="/dist/turbo.es2017-umd.js" data-turbo-track="reload"></script>
<script>Turbo.connectStreamSource(new EventSource("/__turbo/messages"))</script>
<script>
Turbo.connectStreamSource(new EventSource("/__turbo/messages"));
</script>
</head>
<body>
<form id="create" method="post" action="/__turbo/messages">
Expand All @@ -15,5 +17,11 @@
<div id="messages">
<div class="message">First</div>
</div>
<div class="messages">
<div class="message">Second</div>
</div>
<div class="messages">
<div class="message">Third</div>
</div>
</body>
</html>
26 changes: 26 additions & 0 deletions src/tests/functional/stream_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ export class StreamTests extends FunctionalTestCase {
element = await this.querySelector(selector)
this.assert.equal(await element.getVisibleText(), "Hello world!")
}

async "test receiving a stream message with css selector target"() {
let element
const selector = ".messages div.message:last-child"

element = await this.querySelectorAll(selector)
this.assert.equal(await element[0].getVisibleText(), "Second")
this.assert.equal(await element[1].getVisibleText(), "Third")

await this.createMessage("Hello CSS!", ".messages")
await this.nextBeat

element = await this.querySelectorAll(selector)
this.assert.equal(await element[0].getVisibleText(), "Hello CSS!")
this.assert.equal(await element[1].getVisibleText(), "Hello CSS!")
}

async createMessage(content: string, target?: string) {
return this.post("/__turbo/messages", { content , target})
}

async post(path: string, params: any = {}) {
await this.evaluate((path, method, params) => {
fetch(location.origin + path, { method, body: new URLSearchParams(params) })
}, path, "POST", params)
}
}

StreamTests.registerSuite()
4 changes: 4 additions & 0 deletions src/tests/helpers/functional_test_case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export class FunctionalTestCase extends InternTestCase {
return this.remote.findByCssSelector(selector)
}

async querySelectorAll(selector: string) {
return this.remote.findAllByCssSelector(selector)
}

async clickSelector(selector: string): Promise<void> {
return this.remote.findByCssSelector(selector).click()
}
Expand Down
14 changes: 7 additions & 7 deletions src/tests/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ router.post("/reject", (request, response) => {
})

router.post("/messages", (request, response) => {
const { content, status, type } = request.body
const { content, status, type, target } = request.body
if (typeof content == "string") {
receiveMessage(content)
receiveMessage(content, target)
if (type == "stream" && acceptsStreams(request)) {
response.type("text/vnd.turbo-stream.html; charset=utf-8")
response.send(renderMessage(content))
response.send(renderMessage(content, target))
} else {
response.sendStatus(parseInt(status || "201", 10))
}
Expand Down Expand Up @@ -91,17 +91,17 @@ router.get("/messages", (request, response) => {
streamResponses.add(response)
})

function receiveMessage(content: string) {
const data = renderSSEData(renderMessage(content))
function receiveMessage(content: string, target?: string) {
const data = renderSSEData(renderMessage(content, target))
for (const response of streamResponses) {
intern.log("delivering message to stream", response.socket?.remotePort)
response.write(data)
}
}

function renderMessage(content: string) {
function renderMessage(content: string, target = "messages") {
return `
<turbo-stream action="append" target="messages"><template>
<turbo-stream action="append" target="${target}"><template>
<div class="message">${escapeHTML(content)}</div>
</template></turbo-stream>
`
Expand Down