Skip to content

Commit

Permalink
feat: support Date type data
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Oct 18, 2019
1 parent 12057a4 commit 87536d4
Show file tree
Hide file tree
Showing 12 changed files with 132 additions and 17 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
node_modules/
npm-debug.log
/test/e2e.spec.js
/test/karma-context.html
coverage
vendor/
dist/
Expand Down
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ THIS SECTION IS FOR MAINTAINERS ONLY

THIS SECTION IS FOR MAINTAINERS ONLY

作为对照和参考,本仓库也维护了 JS 版本的 SSR。它和 PHP SSR 一同演化,可以跑通所有 san 代码库提供的 SSR 集成测试和 e2e 测试(例外:有两项测试使用了是平台相关的 Date API,已经移除)
作为对照和参考,本仓库也维护了 JS 版本的 SSR。它和 PHP SSR 一同演化,可以跑通所有 san 代码库提供的 SSR 集成测试和 e2e 测试。

JS SSR 目前存在以下问题:

Expand All @@ -113,4 +113,25 @@ JS SSR 目前存在以下问题:
* ES6 Property 必须中 constructor 中赋值,也会找不到。
* 只能编译 Component 文件,不支持引用纯工具文件。例如:`const someFilter = require('./somfilter'); export default class Component { static filters = { someFilter }}`

## Contribute

Development Prerequisites:

* Node.js>=8
* PHP 7
* [composer](https://getcomposer.org)

Install dependencies:

```bash
npm install
composer install
```

Run tests

```bash
npm test
```

[san]: https://github.com/baidu/san
7 changes: 7 additions & 0 deletions bin/build-e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ function buildFile (caseDir) {
specTpl = fs.readFileSync(abFilePath, 'UTF-8')
break

case 'data.js':
componentDataLiteral = fs.readFileSync(abFilePath, 'UTF-8')
componentDataLiteral = componentDataLiteral
.slice(componentDataLiteral.indexOf('{'))
.replace(/;\s*$/, '')
break

case 'data.json':
componentDataLiteral = fs.readFileSync(abFilePath, 'UTF-8')
break
Expand Down
14 changes: 11 additions & 3 deletions bin/render.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
#!/usr/bin/env node

const { readFileSync } = require('fs')
const { existsSync, readFileSync } = require('fs')
const { resolve, join } = require('path')

const caseName = process.argv[2]
const caseRoot = resolve(__dirname, '../test/cases')
const caseDir = resolve(caseRoot, caseName)
const jsSSRPath = join(caseDir, 'ssr.js')
const dataPath = join(caseDir, 'data.json')

const data = JSON.parse(readFileSync(dataPath, 'utf8'))
const data = getData(caseDir)
const noDataOutput = /-ndo$/.test(caseDir)
const jsRendered = require(jsSSRPath)(data, noDataOutput)
process.stdout.write(jsRendered)

function getData (caseDir) {
const dataJSPath = join(caseDir, 'data.js')
if (existsSync(dataJSPath)) {
return require(dataJSPath)
}
const dataPath = join(caseDir, 'data.json')
return JSON.parse(readFileSync(dataPath, 'utf8'))
}
13 changes: 11 additions & 2 deletions bin/render.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
$caseDir = "test/cases/" . $caseName;
include($caseDir . '/ssr.php');

$dataStr = file_get_contents($caseDir . "/data.json");
$data = json_decode($dataStr);
$data = getData($caseDir);

$noDataOutput = preg_match('/-ndo$/', $caseName);
$renderFunc = '\\san\\renderer\\' . dashesToCamelCase($caseName) . '\\render';
Expand All @@ -19,3 +18,13 @@ function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
}
return $str;
}

function getData($caseDir) {
$dataFile = $caseDir . '/data.php';
if (file_exists($dataFile)) {
require_once($dataFile);
return data();
}
$dataStr = file_get_contents($caseDir . "/data.json");
return json_decode($dataStr);
}
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
"progress": "^2.0.3",
"snake-case": "^2.1.0",
"ts-morph": "^4.0.1",
"ts2php": "^0.12.3",
"ts2php": "^0.12.5",
"typescript": "^3.4.5",
"yargs": "^14.2.0"
}
Expand Down
61 changes: 58 additions & 3 deletions runtime/Ts2Php_Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ static public function str_slice($origin, $start, $end = null) {
* @param $postion {number}
* @return {boolean}
*/
static public function startsWith($origin, $substr, $postion = 0){
return strncmp($substr, $origin, strlen($substr)) === $postion;
static public function startsWith($origin, $substr, $position = 0){
if ($position !== 0) {
$origin = substr($origin, $position);
}
return strncmp($substr, $origin, strlen($substr)) === 0;
}

/**
Expand Down Expand Up @@ -89,6 +92,51 @@ static public function includes($haystack, $needle, $postion = 0){
return $pos !== false && $pos >= $postion;
}

/**
* string.prototype.match
* @param $patten {string}
* @param $subject {string}
* @param $isStr {boolean}
*/
static public function match($patten, $subject, $isStr = false, $isAll = false) {
$matches = array();

if ($isStr) {
$patten = '/' . preg_quote($patten, '/') . '/';
}
else if ($isAll) {
preg_match_all($patten, $subject, $matches);
if (empty($matches[0])) {
return null;
}
return $matches[0];
}


$res = preg_match($patten, $subject, $matches);
if ($res === 0) {
return null;
}

// support group
$group = array();
foreach($matches as $x=>$x_val) {
if (!is_numeric($x)) {
$group[$x] = $x_val;
unset($matches[$x]);
}
}
if (!empty($group)) {
$matches['group'] = $group;
}

// index, input
$matches['index'] = strpos($subject, $matches[0]);
$matches['input'] = $subject;

return $matches;
}

/**
* string.prototype.indexOf
* @param $haystack {string}
Expand Down Expand Up @@ -246,14 +294,17 @@ static public function random() {
*
* @class Ts2Php_Date
*/
class Ts2Php_Date {
class Ts2Php_Date implements \JsonSerializable {
private $value = 0;
function __construct($v = -1) {
if ($v == -1) {
$v = time() * 1000;
}
$this->value = intval($v / 1000);
}
public function jsonSerialize () {
return $this->toISOString();
}
// Returns the day of the month (from 1-31)
public function getDate() {
$result = 0 + date('d', $this->value);
Expand Down Expand Up @@ -396,6 +447,10 @@ public function toLocaleTimeString() {
public function toLocaleString() {
return date('Y-m-d H:i:s',$this->value);
}
// Converts a Date object to ISO 8601 Extended Format
public function toISOString () {
return date('Y-m-d\TH:i:s.000\Z',$this->value);
}

private function padTime($time) {
if (!is_numeric($time)) {
Expand Down
14 changes: 14 additions & 0 deletions runtime/underscore.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ public static function data($ctx, $seq = []) {
return $data;
}

public static function setDefaultData($ctx) {
$data = $ctx->data;
$inst = $ctx->instance;

if (!method_exists($inst, 'initData')) return;

$initData = $inst->initData();
foreach ($initData as $key => $val) {
if (isset($data->$key)) continue;
$data->$key = $val;
}
return $data;
}

public static function sortedStringify($obj) {
if (!is_object($obj)) {
return json_encode($obj, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
Expand Down
2 changes: 1 addition & 1 deletion src/bin/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function test (got) {
function deepEqual (lhs, rhs) {
if (typeof lhs === 'object') {
for (const key of Object.keys(lhs)) {
if (!deepEqual(rhs[key], rhs[key])) return false
if (!deepEqual(lhs[key], rhs[key])) return false
}
return true
}
Expand Down
4 changes: 2 additions & 2 deletions src/compilers/php-render-compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ const stringifier = {
},

date: function (source) {
return 'new Date(' + source.getTime() + ')'
return 'new \\san\\runtime\\Ts2Php_Date(' + source.getTime() + ')'
},

any: function (source) {
Expand Down Expand Up @@ -1177,7 +1177,7 @@ function genComponentContextCode (component, emitter) {

emitter.writeLine(`"sanssrCid" => ${component.constructor.sanssrCid || 0},`)
emitter.writeLine('"sourceSlots" => $sourceSlots,')
emitter.writeLine('"data" => $data ? $data : ' + stringifier.any(component.data.get()) + ',')
emitter.writeLine('"data" => $data ? $data : (object)[],')
emitter.writeLine('"owner" => $parentCtx,')
emitter.writeLine('"slotRenderers" => []')

Expand Down
2 changes: 1 addition & 1 deletion src/emitters/generate-php-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function generatePHPCode (sourceFile: SanSourceFile, modules: ModuleInfo[
emitHeader: false,
plugins: [],
modules: keyBy(modules, 'name'),
helperClass: '\\san\\runtime\\Ts2Php_Helper',
helperNamespace: '\\san\\runtime\\',
compilerOptions
}
const { errors, phpCode } = compile(sourceFile.getFilePath(), options)
Expand Down

0 comments on commit 87536d4

Please sign in to comment.