Skip to content

Commit

Permalink
feat(vdom): add textContent attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
jacott committed Apr 19, 2020
1 parent f8b71fd commit 374c3dd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/lambda-shared/src/__test__/vdom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ o.spec('VDom', () => {
o(res.toString()).equals('<div>\n <b>\n <span style="color:red">text</span>\n </b>\n</div>');
});

o('should get set textContent', () => {
const span = V('span', { style: 'color:red' }, 'in span');
const res = V('div', {}, V('b', [span, 'more text', V('b')]));
o(span.textContent).equals('in span');

span.textContent = 'changed';
o(res.textContent).equals('changedmore text');

res.textContent = 'replace';
o(res.textContent).equals('replace');
o(res.children.length).equals(1);
o(res.children[0] instanceof VNodeText).equals(true);
});

o('should find tags', () => {
const res = V('div', {}, V('b', [V('span', { style: 'color:red' }, 'text'), V('b'), V('i'), V('b')]));

Expand Down
23 changes: 23 additions & 0 deletions packages/lambda-shared/src/vdom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export abstract class VNode {
*tags(tag: string): Generator<VNode, void, void> {
return;
}

abstract get textContent(): string;
abstract set textContent(v: string);
}

/**
Expand All @@ -35,6 +38,14 @@ export class VNodeText extends VNode {
toString(level = 0): string {
return indent(level) + this.text;
}

get textContent(): string {
return this.text;
}

set textContent(v: string) {
this.text = v;
}
}

/**
Expand All @@ -52,6 +63,18 @@ export class VNodeElement extends VNode {
this.children = children;
}

get textContent(): string {
if (this.children.length == 0) return '';
if (this.children.length == 1) {
return this.children[0].textContent;
}
return this.children.map((c) => c.textContent).join('');
}

set textContent(v: string) {
this.children = [new VNodeText(v)];
}

toString(level = 0): string {
const attrs = this.toStringAttrs();
const padding = indent(level);
Expand Down

0 comments on commit 374c3dd

Please sign in to comment.