You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@echarts.apache.org by sh...@apache.org on 2022/02/22 02:49:12 UTC

[echarts-bar-racing] branch master updated: refact: use async and await to optimize the code flow

This is an automated email from the ASF dual-hosted git repository.

shenyi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/echarts-bar-racing.git


The following commit(s) were added to refs/heads/master by this push:
     new aebdafd  refact: use async and await to optimize the code flow
aebdafd is described below

commit aebdafd0934e3ac5856686fb07c017f916e6ff6c
Author: pissang <bm...@gmail.com>
AuthorDate: Tue Feb 22 10:49:05 2022 +0800

    refact: use async and await to optimize the code flow
---
 src/components/BChart.vue | 189 +++++++++++++++++++++-------------------------
 src/helper/timeline.ts    |  16 ++--
 2 files changed, 93 insertions(+), 112 deletions(-)

diff --git a/src/components/BChart.vue b/src/components/BChart.vue
index a5c080c..ebc0907 100644
--- a/src/components/BChart.vue
+++ b/src/components/BChart.vue
@@ -33,6 +33,12 @@ const headerLength = 2;
 let chart: echarts.ECharts;
 let recorder;
 
+function wait(time: number) {
+    return new Promise((resolve) => {
+        setTimeout(resolve, time);
+    });
+}
+
 export default defineComponent({
     name: 'BChart',
     props: {
@@ -56,92 +62,71 @@ export default defineComponent({
     mounted() {
     },
     methods: {
-        run() {
+        async run() {
             this.doResetChart();
-            this.doRun();
-        },
-
-        clearTimeoutHandlers() {
-            for (let i = 0; i < this.timeoutHandlers.length; ++i) {
-                clearTimeout(this.timeoutHandlers[i]);
-            }
-            this.timeoutHandlers = [];
+            await this.doRun();
         },
 
-        removeTimeoutHandlers(handler: number) {
-            for (let i = 0; i < this.timeoutHandlers.length; ++i) {
-                if (this.timeoutHandlers[i] === handler) {
-                    this.timeoutHandlers.splice(i, 1);
-                }
-            }
-        },
-
-        captureVideo(width: number, height: number, fps: number): Promise<boolean> {
-            return new Promise(resolve => {
-                try {
-                    this.isExportingVideo = true;
-                    this.doResetChart(width, height, 1);
-                    const container = chart.getDom();
-                    const canvas = container.children[0].children[0] as HTMLCanvasElement;
-                    if (container.clientHeight) {
-                        if (container.clientWidth / container.clientHeight > width / height) {
-                            canvas.style.height = container.clientHeight + 'px';
-                            canvas.style.width = container.clientHeight / height * width + 'px';
-                        }
-                        else {
-                            canvas.style.width = container.clientWidth + 'px';
-                            canvas.style.height = container.clientWidth / width * height + 'px';
-                        }
+        async captureVideo(width: number, height: number, fps: number) {
+            try {
+                this.isExportingVideo = true;
+                this.doResetChart(width, height, 1);
+                const container = chart.getDom();
+                const canvas = container.children[0].children[0] as HTMLCanvasElement;
+                if (container.clientHeight) {
+                    if (container.clientWidth / container.clientHeight > width / height) {
+                        canvas.style.height = container.clientHeight + 'px';
+                        canvas.style.width = container.clientHeight / height * width + 'px';
                     }
+                    else {
+                        canvas.style.width = container.clientWidth + 'px';
+                        canvas.style.height = container.clientWidth / width * height + 'px';
+                    }
+                }
 
-                    recorder = new WebMWriter({
-                        frameRate: fps || 30,
-                        transparent: true
-                    });
-
-                    timeline.setFixedFrameRate(fps);
-                    timeline.onMockFaq(elapsed => {
-                        recorder.addFrame(canvas, elapsed);
-                    });
-                    timeline.startMock();
+                recorder = new WebMWriter({
+                    frameRate: fps || 30,
+                    transparent: true
+                });
 
-                    const title = this.title || this.$t('toolName') || 'bar-racing';
+                timeline.setFixedFrameRate(fps);
+                timeline.startMock(elapsed => {
+                    recorder.addFrame(canvas);
+                });
 
-                    this.doRun(() => {
-                        let hasError = false;
-                        try {
-                            recorder.complete()
-                                .then(function(webMBlob) {
-                                    const url = URL.createObjectURL(webMBlob);
-                                    const link = document.createElement('a');
-                                    link.download = title;
-                                    link.href = url;
-                                    const event = new MouseEvent('click');
-                                    link.dispatchEvent(event);
-                                    setTimeout(() => {
-                                        URL.revokeObjectURL(url);
-                                    }, 1);
-                                });
-                        }
-                        catch (e) {
-                            console.error(e);
-                            hasError = true;
-                        }
+                const title = this.title || this.$t('toolName') || 'bar-racing';
 
-                        timeline.stopMock();
-                        this.isExportingVideo = false;
-                        setTimeout(() => {
-                            this.run();
-                            resolve(!hasError);
-                        });
-                    });
+                let hasError = false;
+                try {
+                    await this.doRun();
+                    const webMBlob = await recorder.complete()
+                    const url = URL.createObjectURL(webMBlob);
+                    const link = document.createElement('a');
+                    link.download = title;
+                    link.href = url;
+                    const event = new MouseEvent('click');
+                    link.dispatchEvent(event);
+                    setTimeout(() => {
+                        URL.revokeObjectURL(url);
+                    }, 1);
                 }
                 catch (e) {
                     console.error(e);
-                    this.isExportingVideo = false;
-                    resolve(false);
+                    hasError = true;
                 }
-            });
+
+                timeline.stopMock();
+                this.isExportingVideo = false;
+
+                wait(50);
+                this.run();
+                return !hasError
+            }
+            catch (e) {
+                console.error(e);
+                this.isExportingVideo = false;
+                return false;
+            }
         },
 
         cancelDownload() {
@@ -159,7 +144,6 @@ export default defineComponent({
         },
 
         doResetChart(width?: number, height?: number, dpr?: number) {
-            this.clearTimeoutHandlers();
             if (chart) {
                 chart.dispose();
                 chart = null;
@@ -198,6 +182,7 @@ export default defineComponent({
                         data: (this.chartData[headerLength] as string[]).slice(1).map(str => parseInt(str, 10)),
                         seriesLayoutBy: 'row',
                         realtimeSort: true,
+                        silent: true,
                         label: {
                             show: true,
                             position: 'right'
@@ -233,39 +218,39 @@ export default defineComponent({
             catch (e) {}
         },
 
-        doRun(onCompleted?: Function) {
+        async doRun(onProgress?: (curr: number, total: number) => void) {
             if (!this.chartData || this.chartData.length < headerLength) {
                 return;
             }
             const dataCnt = this.chartData.length - headerLength - 1;
             const that = this;
+
+            function step(row) {
+                chart.setOption({
+                    series: [{
+                        type: 'bar',
+                        id: 'bar',
+                        data: row.slice(1).map(str => parseInt(str, 10)),
+                        label: {
+                            valueAnimation: true
+                        },
+                        silent: that.isExportingVideo
+                    }],
+                    title: [{
+                        text: row[0]
+                    }]
+                });
+
+                return new Promise((resolve) => {
+                    setTimeout(() => {
+                        resolve(undefined);
+                    }, that.animationDuration)
+                })
+            }
+
             for (let i = 0; i < dataCnt; ++i) {
-                (function (i: number) {
-                    let timeout: number;
-                    const timeoutCb = function () {
-                        const row = that.chartData[headerLength + i + 1] as string[];
-                        chart.setOption({
-                            series: [{
-                                type: 'bar',
-                                id: 'bar',
-                                data: row.slice(1).map(str => parseInt(str, 10)),
-                                label: {
-                                    valueAnimation: true
-                                },
-                                silent: this.isExportingVideo
-                            }],
-                            title: [{
-                                text: row[0]
-                            }]
-                        });
-                        that.removeTimeoutHandlers(timeout);
-                        if (i === dataCnt - 1 && typeof onCompleted === 'function') {
-                            setTimeout(onCompleted, that.animationDuration);
-                        }
-                    };
-                    timeout = window.setTimeout(timeoutCb, i * that.animationDuration);
-                    that.timeoutHandlers.push(timeout);
-                })(i);
+                const row = that.chartData[headerLength + i + 1] as string[];
+                await step(row);
             }
         }
     }
diff --git a/src/helper/timeline.ts b/src/helper/timeline.ts
index 557adec..0a9d508 100644
--- a/src/helper/timeline.ts
+++ b/src/helper/timeline.ts
@@ -191,19 +191,13 @@ function MockDate(...args) {
 MockDate.prototype = Object.create(NativeDate.prototype);
 Object.setPrototypeOf(MockDate, NativeDate);
 
-// TODO Do we need to mock performance? Or leave some API that can keep real.
-
-let mockFaqCb = null;
-
-export function onMockFaq(cb) {
-    mockFaqCb = cb;
-}
+let rafCb = null;
 
 window.requestAnimationFrame = function (cb) {
     if (isMocking) {
         mockedRaf(cb);
-        if (typeof mockFaqCb === 'function') {
-            mockFaqCb(fixedFrameTime);
+        if (typeof rafCb === 'function') {
+            rafCb(fixedFrameTime);
         }
     }
     else {
@@ -215,7 +209,7 @@ export function setFixedFrameRate(fps: number) {
     fixedFrameTime = fps > 0 ? 1000 / fps : 16;
 }
 
-export function startMock() {
+export function startMock(frameCb) {
     isMocking = true;
     window.setTimeout = mockedTimeout;
     window.setInterval = mockedInterval;
@@ -226,11 +220,13 @@ export function startMock() {
     rafCbs = [];
     frameIdx = 0;
     timelineTime = 0;
+    rafCb = frameCb;
     nativeRaf(timelineLoop);
 }
 
 export function stopMock() {
     isMocking = false;
+    rafCb = null;
     window.requestAnimationFrame = nativeRaf;
     window.setTimeout = nativeSetTimeout;
     window.setInterval = nativeSetInterval;

---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@echarts.apache.org
For additional commands, e-mail: commits-help@echarts.apache.org