2021SC@SDUSC amis-低代码前端框架代码分析五
代码分析
log.js 这段代码,用于显示日志的组件,比如显示命令行的输出结果
const react_1 = (0, tslib_1.__importDefault)(require("node_modules/react/index"));
const factory_1 = require("src/factory.tsx");
const ansi_to_react_1 = (0, tslib_1.__importDefault)(require("node_modules/ansi-to-react/lib/index"));
const api_1 = require("src/utils/api.ts");
class Log extends react_1.default.Component {
constructor(props) {
super(props);
this.isDone = false;
this.autoScroll = false;
this.state = {
lastLine: '',
logs: []
};
this.logRef = react_1.default.createRef();
this.autoScroll = props.autoScroll || false;
this.pauseOrResumeScrolling = this.pauseOrResumeScrolling.bind(this);
}
componentWillUnmount() {
if (this.logRef && this.logRef.current) {
this.logRef.current.removeEventListener('scroll', this.pauseOrResumeScrolling);
}
}
componentDidMount() {
if (this.autoScroll && this.logRef && this.logRef.current) {
this.logRef.current.addEventListener('scroll', this.pauseOrResumeScrolling);
}
if (this.props.source) {
this.loadLogs();
}
}
componentDidUpdate() {
if (this.autoScroll && this.logRef && this.logRef.current) {
this.logRef.current.scrollTop = this.logRef.current.scrollHeight;
}
}
如果向上滚动就停止自动滚动,除非滚到底部
pauseOrResumeScrolling() {
if (this.logRef && this.logRef.current) {
const { scrollHeight, scrollTop, offsetHeight } = this.logRef.current;
this.autoScroll = scrollHeight - (scrollTop + offsetHeight) < 50;
}
}
因为这里返回结果是流式的,和普通 api 请求不一样,如果直接用 fetcher 经过 responseAdaptor 可能会导致出错,所以就直接 fetch 了
async loadLogs() {
const { source, data, env, translate: __, encoding } = this.props;
const api = (0, api_1.buildApi)(source, data);
const res = await fetch(api.url);
if (res.status === 200) {
const body = res.body;
if (!body) {
return;
}
const reader = body.getReader();
let lastline = '';
let logs = [];
for (;;) {
let { done, value } = await reader.read();
if (value) {
let text = new TextDecoder(encoding).decode(value, { stream: true });
const lines = text.split('\n');
if (lines.length === 1) {
lastline += lines[0];
this.setState({
lastLine: lastline
});
}
else {
lines[0] = lastline + lines[0];
lastline = lines.pop() || '';
logs = logs.concat(lines);
this.setState({
logs: logs,
lastLine: lastline
});
}
}
if (done) {
this.isDone = true;
return;
}
}
}
else {
env.notify('error', __('fetchFailed'));
}
}
总结
日志可以方便记录信息,方便维护。要利用好this不要弄混了
|