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

docs: Update docs for q-component #65

Merged
merged 4 commits into from
Oct 19, 2021
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"test.e2e.open": "start-server-and-test integration.server.prod http://localhost:8081 \"cypress open --config-file cypress/cypress.json\"",
"integration.server": "node scripts --build --dev && node integration/devserver.js --port 8080 --mode development",
"integration.server.prod": "node scripts --tsc --build && node integration/devserver.js --port 8081 --mode production",
"docs.sync": "node scripts/docs_sync",
"jsx.types": "node scripts --jsx",
"prepare": "husky install",
"lint": "eslint \"**/*.ts*\" && npm run prettier-check",
Expand Down
14 changes: 14 additions & 0 deletions scripts/docs_sync/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* This is the root build scripts module (keep in commonjs). It's only a .js file
* but will handling registering typescript files with esbuild-register
* to allow NodeJS to build .ts files on-demand.
*/

const { join } = require('path');
const { register } = require('esbuild-register/dist/node');

const esmNode = parseInt(process.version.substr(1).split('.')[0], 10) >= 14;
register({ target: esmNode ? 'node14' : 'node10' });

const { main } = require('./main.ts');
main(join(process.cwd(), 'src'));
146 changes: 146 additions & 0 deletions scripts/docs_sync/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { dirname, join } from 'path';
import { readdir, stat, readFile, writeFile, linkSync } from 'fs';

export function main(dir: string) {
console.log('DOC SYNC', dir);
scanFiles(dir);
}

function scanFiles(dir: string) {
readdir(dir, (err, files) => {
if (err) throw err;
files.forEach((file) => {
const path = join(dir, file);
stat(path, (err, status) => {
if (err) throw err;
if (status.isDirectory()) {
scanFiles(path);
}
if (status.isFile() && file.endsWith('.ts')) {
readFileLines(join(dir, file)).then((lines) => scanForDocDirective(dir, file, lines));
}
});
});
});
}

async function scanForDocDirective(dir: string, file: string, lines: string[]) {
const output: string[] = [];
let row = 0;
let write = false;
while (row < lines.length) {
const line = lines[row++];
output.push(line);
const match = /^(\s*)\/\/ <docs markdown="(.*)">/.exec(line);
if (match) {
const prefix = match[1];
const ref = match[2];
output.push(prefix + `// !!DO NOT EDIT THIS COMMENT DIRECTLY!!! (edit ${ref} instead)`);
output.push(prefix + '/**');
(await resolveComment(dir, ref)).forEach((longLine) =>
breakLongLine(longLine).forEach((line) => output.push(prefix + ' * ' + line))
);
output.push(prefix + ' */');
while (row < lines.length) {
const line2 = lines[row++];
if (!isComment(line2)) {
throw new Error(
'Missing end `</doc>` tag. Got: ' + line2 + '\n' + join(dir, file) + '[' + row + ']'
);
}
if (line2.indexOf('// </docs>') != -1) {
output.push(line2);
break;
}
}
write = true;
}
}
if (write) {
await writeFileLines(join(dir, file), output);
}
}

function isComment(line: string) {
line = line.trim();
return line.startsWith('//') || line.startsWith('/**') || line.startsWith('*');
}

async function resolveComment(dir: string, ref: string): Promise<string[]> {
const lines = await readFileLines(join(dir, ref));
let row = 0;
let output: string[] = [];
while (row < lines.length) {
let line = lines[row++];
const match = /<docs code="\.\/(.*)#(.*)"\/>/.exec(line);
if (match) {
output.push('```typescript');
(await resolveCodeExample(join(dir, match[1]), match[2])).forEach((l) => output.push(l));
output.push('```');
} else {
output.push(line);
}
}
return output;
}

async function readFileLines(file: string): Promise<string[]> {
return new Promise((res, rej) =>
readFile(file, (err, data) => (err ? rej(err) : res(String(data).split('\n'))))
);
}

async function writeFileLines(file: string, lines: string[]) {
return new Promise((res, rej) =>
writeFile(file, lines.join('\n'), (err) => (err ? rej(err) : res(null)))
);
}

async function resolveCodeExample(file: string, anchor: string): Promise<string[]> {
const output: string[] = [];
const lines = await readFileLines(file);
let row = 0;
while (row < lines.length) {
const line = lines[row++];
const match = /^(\s*)\/\/ <docs anchor="(.*)">/.exec(line);
if (match && match[2] == anchor) {
while (row < lines.length) {
const offset = match[1].length;
const line2 = lines[row++].substr(offset);
const match2 = /\/\/ <\/docs>/.exec(line2);
if (match2) {
break;
}
output.push(line2);
}
}
}
return output;
}

const LINE_WIDTH = 95;

function breakLongLine(longLine: string): string[] {
if (longLine.length < LINE_WIDTH) return [longLine];
const output: string[] = [];
while (longLine) {
if (longLine.length < LINE_WIDTH) {
output.push(longLine);
break;
}
let index = 0;
let lastWhitespace = index;
while (index < longLine.length && index < LINE_WIDTH) {
if (longLine[index++].match(/\s/)) {
lastWhitespace = index;
}
}
if (lastWhitespace == 0) {
output.push(longLine);
break;
}
output.push(longLine.substr(0, lastWhitespace - 1));
longLine = longLine.substr(lastWhitespace).trim();
}
return output;
}
108 changes: 108 additions & 0 deletions src/core/component/LIFE_CYCLE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
Describes component lifecycle hooks.

In typical development, when discussing object lifespan, it is clear that objects either exist or they do not. Either an object has been instantiated, or it has not yet been instantiated (or it has been instantiated and has since been garbage collected. Hence it no longer exists.)

When discussing the lifespan of Qwik component, it is necessary to expand the definition into
three states: `Void`, `dehydrated`, and `Hydrated`.

1. `Void`: Component does not exist. Nothing has been created yet. This is equivalent to an object not being instantiated or an object not existing.
2. `Hydrated`: Component exists in VM heap and can be passed around as a reference. This is equivalent to how developers normally think of objects.
3. `Dehydrated`: An in-between state between `Void` and `Hydrated`. A component has been created, but it is not represented in the VM heap as an actual object which can be passed around as a reference. In this state, the component state is serialized in the DOM/HTML but does not have the VM heap representation.

## A Typical lifecycle of a component in an SSR scenario.

1. Component is created on the server. It is in the `Hydrated` state and can be passed around by reference (the normal way of passing objects in JS.)
2. Server completes rendering and `dehydrate’s all of the components. This serializes all of the component states into the DOM attributes. Once the state is serialized in the DOM the server can convert the DOM into HTML and send the HTML to the client.
3. At this point, the VM no longer has a reference to the component instances. However, It would be incorrect to say that the component no longer exists. Instead, the component is in a `dehydrated` state. It is somewhere between non-existing and fully existing.
4. Client receives the HTML and turns it back to DOM. The DOM contains the component’s state, but the component is not yet hydrated.
5. Some action is performed which requires that the component is fully hydrated. It is at this point that the component can be re-created. Obviously, from the reference point, the object on the server and on the client are different instances. But logically, we can say that it is the same component.

For the above reasons, it is important to differentiate between a logical component and a component instance. A logical component is a component that can span creation on the server and execution on the client. A logical component survives dehydration/re-hydration events
(component instance does not.)

To describe the whole lifecycle of the component, refer to the diagram and explanation below.

```
logical || || private || transient || component ||
component || DOM || state || state || instance ||
JSX || || STATE || TRANSIENT || (VM ref) ||
======================================================================
(1)
<MyComp> (2)
|| <my-comp/> (3) new
|| || QComponent()
|| || new (4) |
|| || STATE() <---------[OnMount]----------- |
|| || || |
|| || || - - - - - - - (5) - - - - - - -> ||
|| || || new (6) ||
|| || || TRANSIENT() <---[OnHydrate]--- ||
|| || || || ||
|| || || || - - - - - -(7)- - - - > |||
|| || || || |||
|| || || || (8) |||
|| <my-comp> <=======================[OnRender]========= |||
|| (9) <view/> || || |||
|| </my-comp> || || |||
|| || || || |||
|| || || (10) || |||
---------------------------- dehydrate(document) -----------------------+
|| || || || ||| |
|| || || || (11) ||| |
|| || (12) || XX <-----[OnDehydrate]---- XXX <-+
|| <my-comp {STATE}> <-- XX (13)|
|| =================== Serialized to HTML ===================== <-+
|| == (14) HTTP ==
|| =================== Deserialize from HTML =================
|| <my-comp {STATE}>
|| <view/> (15)
|| </my-comp>
|| || (16) (17) new
|| || JSON QComponent()
|| || - - - - -> (parse) - - - - - - - - - - - - - - >||
|| || || ||
|| || || new (18) ||
|| || || TRANSIENT() <---[OnHydrate]--- ||
|| || || || ||
|| || || || - - - - - (19) - - - -> |||
|| || || || |||
|| || || || |||
|| || || || (20) |||
|| <my-comp> <=======================[OnRender]========= |||
|| (21) <view/> || || |||
|| </my-comp> || || |||
|| || || || |||
(removed) || || || (24) |||
(22) +-->(removed) ---------------------------[OnUnmount]----> |||
(23) || || (25) |||
XX<------XX <-----[OnDehydrate]---- XXX
```

Please match the numbers in the diagram above the explanation below.

1. A logic component is created when the parent component’s render function creates a `<MyComp>` node.
2. The result of executing the parent’s component JSX is that `<my-comp>` host-element is created in the DOM, and the`<MyComp>`’s view is scheduled for rendering.
3. Before rendering can start, the component instance needs to be created. This is equivalent to `new QComponent()`. The newly created `QComponent` is missing the private and transient state, and so it fires `[OnMount]` (and a bit later `[OnHydrate]`)
4. `[OnMount]`: Allows the `[OnMount]` hook to create the state of the component.
5. The new `STATE` is assigned into `QComponent`. This allows the `[OnHydrate]` hook to run.
6. `[OnHydrate]`: Responsible for creating `TRANSIENT` state. A transient state is a state which can’t be serialized (ie. promises, observables, closures, streams.) It is separated from `[OnMount]` because `[OnMount]` runs only once for the logical component. The application needs a way to be notified every time the component is deserialized.
7. The new `TRANSIENT` state is assigned to `QComponent`. At this point, the component is fully re-hydrated and can be used for rendering or event handling.
8. `[OnRender]`: This invokes the `MyComp’s render function, which produces JSX nodes to be reconciled against the DOM.
9. The result of `[OnRender]` and reconciliation is that the `<my-comp>` host-element now contains `MyComp’s view fully rendered..
10. `dehydrate()`: At some point, the server determines that the SSR is finished and the rendered applications should be sent to the client. The first step is to serialize all of the data into the DOM. This method locates all of the components and triggers the `[OnDehydrate]` hook.
11. `[OnDehydrate]` is responsible for doing the reverse of `[OnHydrate]`. The method is
responsible for releasing any resources which the `[OnHydrate]` acquired and which are stored in `TRANSIENT` state.
12. Qwik serializes the `STATE` of the component into the DOM. At this point, the `QComponent` is released and is available for garbage collection.
13. After `dehydrate()` completes, the DOM can be serialized to HTML and sent to the client.
14. The client receives the HTML and deserializes it into DOM.
15. The deserialized DOM contains the `<my-comp {STATE}>` element along with its serialized state. The components are deserialized lazily. Only when `QComponent` instance is needed does it go through the deserialization process.
16. If a component is needed, it can go through a re-hydration process. First, the component’s state is parsed from the DOM and passed to the `QComponent`
17. A new `QComponent` is created, and the deserialized state is assigned to it.
18. `[OnHydrate]`: `[OnHydrate]` hook runs which creates a transient state for the component. This is also a good place to recreate any non-serializable objects, such as promises, observables, closures, and streams.
19. The new `TRANSIENT` state is assigned to the `QComponent`. At this point, the `QComponent` is ready to be used in rendering.
20. `[OnRender]`: On render, the method can execute, which can create new JSX nodes.
21. The rendered DOM is updated to reflect the changes from `<MyComp>`. The update process does not force child or parent components to be re-rendered unless the update changes props of those components.
22. At some point, the parent component removes the `<MyComp>` from ins JSX tree. This triggers the destroy process.
23. The DOM is updated, and `<my-comp>` is removed.
24. `[OnUnmount]`: lifecycle hook is invoked to let the component know that it is being removed.
25. `[OnDehydrate]`: lifecycle hook is invoked to clean up the transient state of the component.
13 changes: 13 additions & 0 deletions src/core/component/props-of.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Infers `Props` from `QComponent`.

Given:

```
type MyComponent = qComponent<{propA: string}>({...});
```

Then:

```
const myProps: PropsOf<typeof MyComponent> = ...; // Same as `{propA: string}`
```
26 changes: 26 additions & 0 deletions src/core/component/q-component-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Defines `QComponent` type definition.

`QComponent` is a type returned by the `qComponent` method and is used to verify type-safety throughout the component definition.

`QComponent` contains type information about:

- `PROPS` public interfaces for props (to be used in `<MyComponent propA ...>`)
- `STATE` private state. This will be serialized into HTML on dehydration, therefore it must be JSON serializable. (`OnRender` typically uses both `PROPS` and `STATE`.)

### Example

A simple example with no `STATE` only `PROPS`

<docs code="./q-component.docs.tsx#component"/>

The above allows one to use `Counter` like so:

<docs code="./q-component.docs.tsx#component-usage"/>

## Referring to types

Normally `QComponent` is used in the application for type-safety as is. At times it is required to refer to the types of `PROPS` and, `STATE`directly. In such a case, one can use `PropsOf` and `StateOf`.

See: `PropsOf`, `StateOf`.

@public
Loading