virtualstate / x

Bring your own JavaScript tooling.
https://virtualstate.dev
MIT License
23 stars 0 forks source link

toString #12

Open fabiancook opened 3 years ago

fabiancook commented 3 years ago

🚀 Feature Proposal

Produce a string from any vnode

Motivation

To output a vnode as a string for client usage.

Example

const node = (
  <container>
    <text>Left</text>
    <text>Right</text>
  </container>
);

Consuming the result iteratively as it is generated:

for await (const iteration of toString(node)) {
  console.log({ iteration });
}

Resolving the complete string:

const value = await toString(node);
fabiancook commented 3 years ago

The initial implementation of toString is available here

https://github.com/virtualstate/x/blob/6db6e3c2038727307aab6a8b5efb82498019fbcb/packages/fringe/src/string.ts#L95

It it marked as experimental.

It includes support for "this" to be bound to, which allows for customisation of how the string is generated. An example of this is the quirks of HTML, including script requiring to contain a body

Usage of this can be seen here:

https://github.com/opennetwork/environment/blob/415ce57c430422278b5f316a74db76e8ff556526/src/example/fetch.ts#L18-L32

function isScalar(node: VNode) {
    if (!node.scalar) return false;
    const tags: unknown[] = ["script", "link", "meta"];
    return !tags.includes(node.source);
}

function getBody(node: VNode, body: string) {
    if (body) {
        return `\n${body.split("\n").map(value => `  ${value}`).join("\n")}\n`;
    }
    if (node.source !== "script") {
        return ""
    }
    return "\n";
}

https://github.com/opennetwork/environment/blob/415ce57c430422278b5f316a74db76e8ff556526/src/example/fetch.ts#L57

const string = await toString.call({ isScalar, getBody }, view);
fabiancook commented 2 years ago

By default deno's typescript doesn't like the usage of a .then function that isn't a "real promise", so this API may be unusable there. Potentially we can use a real promise, and assign our async iterator to it.