Skip to content

Commit

Permalink
feat: 0.0.30
Browse files Browse the repository at this point in the history
  • Loading branch information
theajack3 committed Sep 18, 2023
1 parent 2f011b8 commit 056534d
Show file tree
Hide file tree
Showing 17 changed files with 253 additions and 53 deletions.
29 changes: 29 additions & 0 deletions a.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!--
* @Author: chenzhongsheng
* @Date: 2023-09-18 08:38:50
* @Description: Coding something
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <script src='https://cdn.jsdelivr.net/npm/alins-standalone'></script> -->
<script src='./packages/client-standalone/dist/alins-standalone.iife.min.js'></script>
<script>
const {react, computed, Dom} = window.Alins
let count = react(1);
let countAdd1 = computed(()=>count.v+1);
Dom('button', {
$mount: document.body,
onclick: ()=>count.v++,
}, [
react`count is ${count}; countAdd1 is ${countAdd1}`
// 'count is ', count, ';'
]);
</script>
</body>
</html>
3 changes: 2 additions & 1 deletion packages/client-reactive/src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ const age1 = age++;
cache = v;

if (isDepReactive()) {
proxy = createProxy(wrapReactive(v, true), { set, get, isProp });
// todo check return cache
proxy = createProxy(wrapReactive(v, true), { set, get: () => cache, isProp });
return proxy;
}
// ! 此处是为了兼容编译时将未知类型的import常量进行表达式计算时进行的统一computed处理的开销
Expand Down
4 changes: 2 additions & 2 deletions packages/client-reactive/src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export function createProxy<T extends IJson> (data: T, {
const proxy = new Proxy(data, {
// ! 闭包
get (target: IJson, property, receiver) {
// console.log('debug: Get property', property);
// if (property === 'label') console.warn('proxy get', property);
const isFunc = typeof target[property] === 'function';
if (isArray && isFunc) {
Expand All @@ -182,7 +183,6 @@ export function createProxy<T extends IJson> (data: T, {
}
if (typeof property !== 'symbol' && !isFunc) {
// ! 收集依赖
debugger;
if (currentFn) {
if (!depReactive) depReactive = true;
// console.warn('COLLECT------ ', property, '=', target[property]);
Expand All @@ -199,7 +199,7 @@ export function createProxy<T extends IJson> (data: T, {
},
// ! 闭包
set (target: IJson, property, v, receiver) {
// console.log('Set property', property, v);
// console.log('debug: Set property', property, v);
const originSet = () => {
const value = Reflect.set(target, property, v, receiver);
if (isArray && property !== 'length' && lns.length?.size) {
Expand Down
5 changes: 5 additions & 0 deletions packages/client-standalone/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ type IDomGenerator = ()=>IGeneralElement|IGeneralElement[];
export { react, watch, computed } from 'alins';
import { react, watch, computed } from 'alins';

export function ref<T> (v: T) {
return react({ v });
}

// alins.Dom('div', {

// }, [
Expand Down Expand Up @@ -164,6 +168,7 @@ export function Show (condition: IBoolCond, generator: IDomGenerator) {
}

export const alins = {
ref,
react,
watch,
computed,
Expand Down
10 changes: 5 additions & 5 deletions packages/compiler-core/src/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import type { Node, VariableDeclaration, VariableDeclarator } from '@babel/types';

function parseComment (node: Node) {
function parseComment (node: Node, onlyHead = false) {
const comments: string[] = [];
const nodeLine = node.loc?.start.line || 0;
const before = node.leadingComments?.[node.leadingComments.length - 1];
Expand All @@ -23,7 +23,7 @@ function parseComment (node: Node) {
}
const after = node.trailingComments?.[0];

if (after && after.loc?.start.line === nodeLine) {
if (!onlyHead && after && after.loc?.start.line === nodeLine) {
commentEls.push(before);
comments.push(after.value);
}
Expand All @@ -32,7 +32,7 @@ function parseComment (node: Node) {
if (node)node.value = node.value.replace(reg, (str: string) => str.replace('@', '$$'));
};
replace(before);
replace(after);
if (!onlyHead) replace(after);
} };
}

Expand All @@ -56,8 +56,8 @@ export function parseCommentMulti (node: Node, reg = RegMap.React) {
return result[2].split(',').map(s => s.trim());
}

export function parseCommentSingle (node: Node, reg = RegMap.Shallow) {
const { comment, clear } = parseComment(node);
export function parseCommentSingle (node: Node, reg = RegMap.Shallow, onlyHead?: boolean) {
const { comment, clear } = parseComment(node, onlyHead);
if (!comment) return false;
if (!reg.test(comment)) return false;
clear(reg);
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler-core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class Module {
if (this.isInStaticScope) return;
const node = path.node;

const comment = parseCommentSingle(node, RegMap.StaticScope);
const comment = parseCommentSingle(node, RegMap.StaticScope, true);
const markStatic = () => {
this.isInStaticScope = true;
// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler-core/src/controller/import-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const ImportManager = (() => {

let addUse: (name: AlinsVar)=>void = () => {};

let clear: any;
let clear: any = () => {};

return {
exitModule () {
Expand Down
6 changes: 3 additions & 3 deletions packages/compiler-core/src/is.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,15 +248,15 @@ export function isArrayMapCall (node: CallExpression) {
return node.callee?.property?.name === 'map';
}

export function isBlockBreak (elements: any[]) {
export function isBlockBreak (elements: any[], onBreakNode: (node: any)=>void) {
for (let i = elements.length - 1; i >= 0; i--) {
const node = elements[i];
if (node.type === 'BreakStatement') {
// ! break 换成 return;
node.type = 'ReturnStatement';
onBreakNode(node);
return true;
} else if (node.type === 'BlockStatement') {
if (isBlockBreak(node.body)) {
if (isBlockBreak(node.body, onBreakNode)) {
return true;
}
}
Expand Down
8 changes: 7 additions & 1 deletion packages/compiler-core/src/parse-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ export function traverseSwitchStatement (node: SwitchStatement) {
const discr = t.arrowFunctionExpression([], node.discriminant);
let isReturnJsx = false;

const breakList: any = [];

let childrenList: any[][] = [];
let isLastBreak = true;
Expand All @@ -367,7 +368,7 @@ export function traverseSwitchStatement (node: SwitchStatement) {
isReturnJsx = (returnType === BlockReturnType.Jsx);
}

const isBreak = !!returnType || isBlockBreak(bodyArr);
const isBreak = !!returnType || isBlockBreak(bodyArr, node => {breakList.push(node);});
if (!isLastBreak) {
childrenList.forEach(item => {item.push(...bodyArr);});
}
Expand All @@ -390,6 +391,11 @@ export function traverseSwitchStatement (node: SwitchStatement) {
}));

const endFunc = createSetAsyncArrowFunc(t.blockStatement([]));

if (isReturnJsx) {
breakList.forEach(node => {node.type = 'ReturnStatement';});
}

return {
endFunc,
isReturnJsx,
Expand Down
8 changes: 6 additions & 2 deletions packages/compiler-core/src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,11 @@ export function createNodeVisitor (t: IBabelType, useImport = true) {
},
BreakStatement (path) {
// console.log(ctx.curScope);
if (ctx.curScope.inIf || ctx.curScope.inSwitch) {
const scope = ctx.curScope;
if (
(scope.inIf && scope.ifScope?.isReturnJsx) ||
(scope.inSwitch && scope.switchScope?.isReturnJsx)
) {
// if (ctx.curScope.inSwitch) {
// if (path.parent.type === 'SwitchCase') {
// // @ts-ignore
Expand All @@ -420,7 +424,7 @@ export function createNodeVisitor (t: IBabelType, useImport = true) {
}
}
} as TraverseOptions<Node>;
}
};

export function createBabelPluginAlins () {
return (data: any, args?: {useImport?: boolean}) => { // {import: boolean}
Expand Down
6 changes: 3 additions & 3 deletions packages/compiler-web/src/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ function onDOMContentLoaded () {
// @ts-ignore
for (const item of scripts) {
// @ts-ignore
onSingleScript(item, !item.hasAttribute('node'), item.hasAttribute('ts'));
onSingleScript(item, item.hasAttribute('import'), item.hasAttribute('ts'));
}
}
}

async function onSingleScript (script: HTMLScriptElement, web = true, ts = false) {
async function onSingleScript (script: HTMLScriptElement, useImport = false, ts = false) {
// __DEV__ && console.log(`web=${web}; ts=${ts}`);
let code = '';
if (script.innerText.trim() === '') {
Expand All @@ -39,7 +39,7 @@ async function onSingleScript (script: HTMLScriptElement, web = true, ts = false
} else {
code = script.innerText;
}
const output = parseWebAlins(code, { useImport: !web, ts });
const output = parseWebAlins(code, { useImport, ts });
// console.warn(code);
// console.warn('============>');
if (__DEV__) console.warn('Compiler output:', output);
Expand Down
133 changes: 133 additions & 0 deletions packages/compiler-web/src/test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { IElement, defineRenderer, ILifeListener } from 'alins';

const ElementType = {
Element: 0,
Text: 1,
Empty: 2,
Frag: 3,
};

defineRenderer({
querySelector (selector) {return selector === '#Root' ? LogElement.Root : null;},
createElement (tag = '') {
return new LogElement(ElementType.Element, '', tag);
},
createTextNode (text) {
return new LogElement(ElementType.Text, text);
},
createEmptyMountNode () {
return new LogElement(ElementType.Empty);
},
createFragment () {
return new LogElement(ElementType.Frag);
},
isFragment (node) {
return node.type === ElementType.Frag;
},
isElement (node) {
return node.type === ElementType.Element || node.type === ElementType.Text;
},
onMounted (parent: LogElement, node: LogElement, mounted: ILifeListener<void|ILifeListener>) {
node.mountCallList.push(mounted);
},
onRemoved (parent: LogElement, node: LogElement, removed: ILifeListener) {
node.removeCallList.push(removed);
},
});

class LogElement implements IElement {
static Root: null|LogElement = null;
type = ElementType.Element;
style = {}; // mock
tagName = '';
className = '';
innerText = '';
get textContent () {return this.innerText;};
set textContent (v) {this.innerText = v;}
deep = 0;
get prefix () {
return new Array(this.deep).fill('--').join('');
}
addEventListener () {};
removeEventListener () {};
setAttribute () {};
removeAttribute () {};
getAttribute () {return '';};
classList = {
add () {},
remove () {}
};
constructor (type, text = '', tag = '') {
this.type = type;
this.tagName = tag;
this.innerText = text;
if (tag === 'Root') LogElement.Root = this;
}
parentElement: LogElement|null = null;
get parentNode () {return this.parentElement;};
removeCallList: any[] = [];
remove () {
const children = this.parentElement?.children;
if (children) {
children.splice(children.indexOf(this), 1);
this.removeCallList.forEach(call => call(this));
}
}
get innerHTML () {return this.innerText;}
get outerHTML () {return this.innerText;}
children: LogElement[] = [];
get childNodes () {
return this.childNodes;
}
mountCallList: any[] = [];
appendChild (child: LogElement) {
this.children.push(child);
child.mountCallList.forEach(call => call(child));
}
get nextSibling () {
return this.parentElement?.children[this.index + 1] || null;
}
insertBefore (node, child) {
if (child.parentElement !== this) {
throw new Error('insertBefore error');
}
this.parentElement?.children.splice(child.index - 1, 0, node);
child.mountCallList.forEach(call => call(child));
return node;
}
get index () {
const parent = this.parentElement;
return !parent ? -1 : parent.children.indexOf(this);
}
render () {
const text = `${this.innerText}`;
if (this.type === ElementType.Text) {
text && console.log(`${this.prefix}text: ${text.trim()}`);
} else if (this.type === ElementType.Element) {
console.log(`${this.prefix}${this.tagName}: ${text.trim()}`);
this.children.forEach(item => {
item.deep = this.deep + 1;
item.render();
});
}
}
}

const Root = new LogElement(ElementType.Element, '', 'Root');

let v = 0;
const v2 = v * 2;

<div $$Root>
value = {v}
<div>value * 2 = {v2}</div>
</div>;

function loopRender () {
v ++;
console.clear();
Root.render();
setTimeout(() => {requestAnimationFrame(loopRender);}, 1000);
}

loopRender();
4 changes: 2 additions & 2 deletions playground/compare/react/src/count.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, {useState} from 'react';
import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Main () {
const [count, setCount] = useState(1);
const [ count, setCount ] = useState(1);
function increase () {
setCount(count + 1);
}
Expand Down
Loading

0 comments on commit 056534d

Please sign in to comment.