Add SSR mode and test on Android

This commit is contained in:
pengfei.zhou 2022-11-02 14:29:07 +08:00 committed by osborn
parent 5782a0d161
commit c3b9638434
18 changed files with 313 additions and 61 deletions

View File

@ -35,6 +35,9 @@
<activity
android:name=".DoricEmbeddedActivity"
android:theme="@style/Theme.Design.Light.NoActionBar" />
<activity
android:name=".DoricSSRActivity"
android:theme="@style/Theme.Design.Light.NoActionBar" />
</application>
<uses-permission android:name="android.permission.INTERNET" />

View File

@ -0,0 +1,80 @@
/*
* Copyright [2019] [Doric.Pub]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pub.doric.demo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.github.pengfeizhou.jscore.JSDecoder;
import com.github.pengfeizhou.jscore.JSObject;
import org.json.JSONObject;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import pub.doric.DoricContext;
import pub.doric.DoricPanel;
import pub.doric.devkit.DoricDev;
import pub.doric.devkit.remote.ValueBuilder;
import pub.doric.navbar.BaseDoricNavBar;
import pub.doric.shader.RootNode;
import pub.doric.utils.DoricUtils;
/**
* @Description: pub.doric.demo
* @Author: pengfei.zhou
* @CreateDate: 2021/7/14
*/
public class DoricSSRActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug_timing);
BaseDoricNavBar doricNavBar = findViewById(R.id.doric_nav_bar);
TextView textView = new TextView(this);
textView.setText("Devkit");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoricDev.getInstance().openDevMode();
}
});
textView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
doricNavBar.setRight(textView);
final DoricPanel doricPanel = findViewById(R.id.doric_panel);
RootNode rootNode = new RootNode(DoricContext.MOCK_CONTEXT);
rootNode.setRootView(doricPanel);
String json = DoricUtils.readAssetFile("src/LayoutDemo.ssr.json");
try {
long start = System.currentTimeMillis();
JSONObject jsonObject = new JSONObject(json);
ValueBuilder vb = new ValueBuilder(jsonObject);
JSDecoder jsDecoder = new JSDecoder(vb.build());
JSObject jsObject = jsDecoder.decode().asObject();
Log.d("Timing", "Decode cost " + (System.currentTimeMillis() - start) + " ms");
rootNode.blend(jsObject.getProperty("props").asObject());
Log.d("Timing", "SSR cost " + (System.currentTimeMillis() - start) + " ms");
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -25,15 +25,14 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import pub.doric.devkit.DoricDev;
import pub.doric.refresh.DoricSwipeLayout;
import pub.doric.utils.DoricUtils;
@ -133,13 +132,22 @@ public class MainActivity extends AppCompatActivity {
tv.getContext().startActivity(intent);
}
});
}else {
tv.setText(data[position - 3]);
} else if (position == 3) {
tv.setText("SSR Example");
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(tv.getContext(), DoricSSRActivity.class);
tv.getContext().startActivity(intent);
}
});
} else {
tv.setText(data[position - 4]);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(tv.getContext(), DoricDebugTimingActivity.class);
intent.putExtra("source", "assets://src/" + data[position - 3]);
intent.putExtra("source", "assets://src/" + data[position - 4]);
//intent.putExtra("alias", data[position - 1].replace(".js", ""));
intent.putExtra("alias", "__dev__");
tv.getContext().startActivity(intent);
@ -150,7 +158,7 @@ public class MainActivity extends AppCompatActivity {
@Override
public int getItemCount() {
return data.length + 3;
return data.length + 4;
}
}
}

View File

@ -26,8 +26,6 @@ import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.github.pengfeizhou.jscore.ArchiveException;
import com.github.pengfeizhou.jscore.JSArray;
import com.github.pengfeizhou.jscore.JSDecoder;
@ -35,6 +33,7 @@ import com.github.pengfeizhou.jscore.JSObject;
import java.util.concurrent.Callable;
import androidx.annotation.NonNull;
import pub.doric.DoricContext;
import pub.doric.async.AsyncResult;
import pub.doric.devkit.R;
@ -156,7 +155,7 @@ public class DoricSnapshotView extends DoricFloatingView {
rootNode.setId(viewId);
rootNode.blend(jsObject.getProperty("props").asObject());
} else {
ViewNode viewNode = doricContext.targetViewNode(viewId);
ViewNode<?> viewNode = doricContext.targetViewNode(viewId);
if (viewNode != null) {
viewNode.blend(jsObject.getProperty("props").asObject());
}

View File

@ -17,13 +17,11 @@ package pub.doric;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.github.pengfeizhou.jscore.JSDecoder;
import com.github.pengfeizhou.jscore.JSONBuilder;
@ -39,6 +37,8 @@ import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import pub.doric.async.AsyncResult;
import pub.doric.engine.RetainedJavaValue;
import pub.doric.navbar.IDoricNavBar;
@ -72,6 +72,8 @@ public class DoricContext {
private final Map<String, Animator> animators = new HashMap<>();
private final Map<String, DoricResource> cachedResources = new WeakHashMap<>();
private final Set<SoftReference<RetainedJavaValue>> retainedJavaValues = new HashSet<>();
@SuppressLint("StaticFieldLeak")
public static final DoricContext MOCK_CONTEXT = new DoricContext(Doric.application(), "", "", "");
public Collection<ViewNode<?>> allHeadNodes(String type) {
Map<String, ViewNode<?>> headNode = mHeadNodes.get(type);

View File

@ -91,4 +91,25 @@ export async function mergeMap(mapFile: string) {
await fs.promises.unlink(lockFile)
}
}
export async function ssr() {
const ret = await build();
if (ret != 0) {
return ret;
}
console.log("Start generate ssr data");
const bundleFiles = await glob("bundle/**/*.js");
process.env["SSR_BUILD"] = "1";
for (let bundleFile of bundleFiles) {
console.log(bundleFile);
await Shell.exec("node", [bundleFile], {
env: process.env,
consoleHandler: (info) => {
console.log(info);
}
});
}
return 0;
}

View File

@ -1,7 +1,7 @@
#!/usr/bin/env node
import commander from "commander"
import { build, clean } from "./actions";
import { build, clean, ssr } from "./actions";
import { create, createLib } from "./create"
import dev from "./dev"
import { run } from "./run";
@ -41,7 +41,18 @@ commander
.action(async function () {
await clean();
})
commander
.command('ssr <action>')
.action(async function (action) {
if (action === 'build') {
const ret = await ssr();
if (ret != 0) {
process.exit(ret)
}
} else {
console.error("Do not support in ssr mode ", action)
}
})
commander
.command('run <platform>')
.action(async function (platform, cmd) {

View File

@ -87,6 +87,7 @@ class CounterVM extends ViewModel<CountModel, CounterView> {
log(`Current count is ${s.count}`);
logw(`Current count is ${s.count}`);
loge(`Current count is ${s.count}`);
console.log("This is from console.log")
}
}

View File

@ -17414,9 +17414,10 @@ var doric = (function (exports) {
};
}
var global$2 = Function('return this')();
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global$2.Envrionemnt &&
(Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global$2, "console", {
warn: logw,
error: loge,

View File

@ -1478,9 +1478,10 @@ var doric = (function (exports) {
};
}
const global$1 = Function('return this')();
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global$1.Environment
&& (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global$1, "console", {
warn: logw,
error: loge,

View File

@ -4,11 +4,13 @@ Object.defineProperty(exports, '__esModule', { value: true });
var WebSocket = require('ws');
var path = require('path');
var fs = require('fs');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var WebSocket__default = /*#__PURE__*/_interopDefaultLegacy(WebSocket);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
/*
* Copyright [2019] [Doric.Pub]
@ -1487,9 +1489,10 @@ function jsObtainEntry(contextId) {
};
}
const global$2 = Function('return this')();
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global$2.Environment
&& (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global$2, "console", {
warn: logw,
error: loge,
@ -5349,6 +5352,8 @@ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _argume
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
//Is in SSR Build Mode
const inSSRBuild = process.env["SSR_BUILD"] === "1";
let contextId = undefined;
let global$1 = new Function('return this')();
const originSetTimeout = global$1.setTimeout;
@ -5498,15 +5503,34 @@ global$1.Entry = function () {
});
if (entryHooks.length <= 1) {
const source = path__default["default"].basename(jsFile);
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
if (inSSRBuild) {
console.log(`SSR build ${source} start`);
contextId = "SSR_CONTEXT";
const realContext = jsObtainContext(contextId);
global$1.context.id = contextId;
global$1.context = realContext;
entryHooks.forEach(e => e(contextId));
});
const panel = realContext === null || realContext === void 0 ? void 0 : realContext.entity;
panel.getRootView().apply({
layoutConfig: layoutConfig().most()
});
panel.onCreate();
panel.onShow();
panel.build(panel.getRootView());
fs__default["default"].writeFileSync(jsFile.replace(".js", ".ssr.json"), JSON.stringify(panel.getRootView().toModel()));
console.log(`SSR build ${source} end`);
}
else {
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
const realContext = jsObtainContext(contextId);
global$1.context.id = contextId;
global$1.context = realContext;
entryHooks.forEach(e => e(contextId));
});
}
return arguments[0];
}
}
@ -5535,24 +5559,41 @@ global$1.nativeLog = (type, msg) => {
}
};
global$1.nativeRequire = () => {
if (inSSRBuild) {
console.error("Do not support nativeRequire in ssr mode", new Error().stack);
return false;
}
console.error("nativeRequire", new Error().stack);
console.error("Do not call here in debugging");
return false;
};
global$1.nativeBridge = () => {
if (inSSRBuild) {
console.error("Do not support nativeBridge in ssr mode", new Error().stack);
return false;
}
console.error("nativeBridge", new Error().stack);
console.error("Do not call here in debugging");
return false;
};
global$1.Environment = new Proxy({}, {
get: (target, p, receiver) => {
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack);
return undefined;
}
console.error("Environment Getter", new Error().stack);
console.error("Do not call here in debugging");
return undefined;
},
set: (target, p, v, receiver) => {
console.error("Environment Setter", new Error().stack);
console.error("Do not call here in debugging");
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack);
}
else {
console.error("Environment Setter", new Error().stack);
console.error("Do not call here in debugging");
}
return Reflect.set(target, p, v, receiver);
}
});

View File

@ -17,6 +17,10 @@ import * as doric from './src/runtime/sandbox'
import WebSocket from "ws"
import path from 'path'
import { Panel } from './src/ui/panel';
import { layoutConfig } from "./src/util/layoutconfig";
import fs from "fs";
//Is in SSR Build Mode
const inSSRBuild = process.env["SSR_BUILD"] === "1";
type MSG = {
type: "D2C" | "C2D" | "C2S" | "D2S" | "S2C" | "S2D",
@ -164,15 +168,34 @@ global.Entry = function () {
})
if (entryHooks.length <= 1) {
const source = path.basename(jsFile)
console.log(`Debugging ${source}`)
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
if (inSSRBuild) {
console.log(`SSR build ${source} start`)
contextId = "SSR_CONTEXT";
const realContext = doric.jsObtainContext(contextId);
global.context.id = contextId;
global.context = realContext;
entryHooks.forEach(e => e(contextId))
});
entryHooks.forEach(e => e(contextId));
const panel = realContext?.entity as Panel;
panel.getRootView().apply({
layoutConfig: layoutConfig().most()
});
panel.onCreate();
panel.onShow();
panel.build(panel.getRootView());
fs.writeFileSync(jsFile.replace(".js", ".ssr.json"),
JSON.stringify(panel.getRootView().toModel()));
console.log(`SSR build ${source} end`);
} else {
console.log(`Debugging ${source}`)
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
const realContext = doric.jsObtainContext(contextId);
global.context.id = contextId;
global.context = realContext;
entryHooks.forEach(e => e(contextId));
});
}
return arguments[0];
}
}
@ -206,12 +229,20 @@ global.nativeLog = (type: string, msg: string) => {
}
global.nativeRequire = () => {
if (inSSRBuild) {
console.error("Do not support nativeRequire in ssr mode", new Error().stack)
return false;
}
console.error("nativeRequire", new Error().stack);
console.error("Do not call here in debugging");
return false;
}
global.nativeBridge = () => {
if (inSSRBuild) {
console.error("Do not support nativeBridge in ssr mode", new Error().stack)
return false;
}
console.error("nativeBridge", new Error().stack);
console.error("Do not call here in debugging");
return false;
@ -219,13 +250,21 @@ global.nativeBridge = () => {
global.Environment = new Proxy({}, {
get: (target, p, receiver) => {
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack)
return undefined;
}
console.error("Environment Getter", new Error().stack);
console.error("Do not call here in debugging");
return undefined
},
set: (target, p, v, receiver) => {
console.error("Environment Setter", new Error().stack)
console.error("Do not call here in debugging");
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack)
} else {
console.error("Environment Setter", new Error().stack)
console.error("Do not call here in debugging");
}
return Reflect.set(target, p, v, receiver);
}
})

View File

@ -26,6 +26,10 @@ import * as doric from './src/runtime/sandbox';
import WebSocket from "ws";
import path from 'path';
import { Panel } from './src/ui/panel';
import { layoutConfig } from "./src/util/layoutconfig";
import fs from "fs";
//Is in SSR Build Mode
const inSSRBuild = process.env["SSR_BUILD"] === "1";
let contextId = undefined;
let global = new Function('return this')();
const originSetTimeout = global.setTimeout;
@ -175,15 +179,34 @@ global.Entry = function () {
});
if (entryHooks.length <= 1) {
const source = path.basename(jsFile);
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
if (inSSRBuild) {
console.log(`SSR build ${source} start`);
contextId = "SSR_CONTEXT";
const realContext = doric.jsObtainContext(contextId);
global.context.id = contextId;
global.context = realContext;
entryHooks.forEach(e => e(contextId));
});
const panel = realContext === null || realContext === void 0 ? void 0 : realContext.entity;
panel.getRootView().apply({
layoutConfig: layoutConfig().most()
});
panel.onCreate();
panel.onShow();
panel.build(panel.getRootView());
fs.writeFileSync(jsFile.replace(".js", ".ssr.json"), JSON.stringify(panel.getRootView().toModel()));
console.log(`SSR build ${source} end`);
}
else {
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
const realContext = doric.jsObtainContext(contextId);
global.context.id = contextId;
global.context = realContext;
entryHooks.forEach(e => e(contextId));
});
}
return arguments[0];
}
}
@ -212,24 +235,41 @@ global.nativeLog = (type, msg) => {
}
};
global.nativeRequire = () => {
if (inSSRBuild) {
console.error("Do not support nativeRequire in ssr mode", new Error().stack);
return false;
}
console.error("nativeRequire", new Error().stack);
console.error("Do not call here in debugging");
return false;
};
global.nativeBridge = () => {
if (inSSRBuild) {
console.error("Do not support nativeBridge in ssr mode", new Error().stack);
return false;
}
console.error("nativeBridge", new Error().stack);
console.error("Do not call here in debugging");
return false;
};
global.Environment = new Proxy({}, {
get: (target, p, receiver) => {
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack);
return undefined;
}
console.error("Environment Getter", new Error().stack);
console.error("Do not call here in debugging");
return undefined;
},
set: (target, p, v, receiver) => {
console.error("Environment Setter", new Error().stack);
console.error("Do not call here in debugging");
if (inSSRBuild) {
console.error("Do not support Environment in ssr mode", new Error().stack);
}
else {
console.error("Environment Setter", new Error().stack);
console.error("Do not call here in debugging");
}
return Reflect.set(target, p, v, receiver);
}
});

View File

@ -276,9 +276,10 @@ export function jsObtainEntry(contextId) {
};
}
const global = Function('return this')();
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global.Environment
&& (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global, "console", {
warn: logw,
error: loge,

View File

@ -295,9 +295,10 @@ export function jsObtainEntry(contextId: string) {
}
const global = Function('return this')()
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global.Envrionemnt &&
(Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global, "console", {
warn: logw,
error: loge,

View File

@ -334,9 +334,10 @@ export function jsObtainEntry(contextId: string) {
}
const global = Function('return this')()
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global.Environment
&& (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global, "console", {
warn: logw,
error: loge,

View File

@ -1483,9 +1483,10 @@ var doric = (function (exports) {
};
}
const global$1 = Function('return this')();
if (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt') {
if (global$1.Environment
&& (Environment.platform === 'Android'
|| Environment.platform === 'iOS'
|| Environment.platform === 'Qt')) {
Reflect.set(global$1, "console", {
warn: logw,
error: loge,
@ -1952,6 +1953,7 @@ class View {
}
set ref(ref) {
ref.current = this;
this._ref = ref;
}
doAnimation(context, animation) {
return this.nativeChannel(context, "doAnimation")(animation.toModel()).then((args) => {

File diff suppressed because one or more lines are too long