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

toString #12

Open
fabiancook opened this issue Nov 5, 2021 · 2 comments
Open

toString #12

fabiancook opened this issue Nov 5, 2021 · 2 comments

Comments

@fabiancook
Copy link
Contributor

🚀 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
Copy link
Contributor Author

fabiancook commented Nov 5, 2021

The initial implementation of toString is available here

export function toString(node: VNode): IterablePromise<string>

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
Copy link
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant