Commit 74e497ed authored by lvtz's avatar lvtz

fix rich-text

parent 60221eab
......@@ -34,27 +34,11 @@ Page({
} catch (error) {
content = [];
}
// data.content = this.replaceDetail(content);
data.content =content;
data.content = content;
this.setData({
detail: data,
})
}
})
},
replaceDetail (details){
var texts='';//待拼接的内容
while(details.indexOf('<img')!=-1){//寻找img 循环
texts+=details.substring('0',details.indexOf('<img')+4);//截取到<img前面的内容
details = details.substring(details.indexOf('<img')+4);//<img 后面的内容
if(details.indexOf('style=')!=-1 && details.indexOf('style=')<details.indexOf('>')){
texts+=details.substring(0,details.indexOf('style="')+7)+"max-width:100%;width: 100%;margin:0 auto;";//从 <img 后面的内容 截取到style= 加上自己要加的内容
details=details.substring(details.indexOf('style="')+7); //style后面的内容拼接
}else{
texts+=' style="max-width:100%;width: 100%" ';
}
}
texts+=details;//最后拼接的内容
return texts
}
})
\ No newline at end of file
{
"navigationBarTitleText": "帮助详情",
"usingComponents": {
"expiredTip": "../../components/expiredTip"
"expiredTip": "../../components/expiredTip",
"parser":"../../../components/Parser/parser"
}
}
\ No newline at end of file
......@@ -4,11 +4,7 @@
{{detail.title}}
</view>
<view class="detailbox" wx:if="{{detail.content.length > 0}}">
<rich-text
class="rich-text-box"
nodes="{{detail.content}}"
space="nbsp"
/>
<parser html="{{detail.content}}"></parser>
</view>
</view>
<view class="footer-box">
......
......@@ -9,7 +9,7 @@ Page({
localImageRoot: "../../../images/",
sid: 0,
page: 1,
perPage: 10,
perPage: 20,
list: [],
tatol: "",
hasmore: true,
......
/* Parser富文本插件 https://github.com/jin-yufeng/Parser */
"use strict";function _classCallCheck(t,s){if(!(t instanceof s))throw new TypeError("Cannot call a class as a function")}function isBlankChar(t){return" "==t||"\t"==t||"\r"==t||"\n"==t||"\v"==t||"\f"==t}var _createClass=function(){function t(t,s){for(var i=0;i<s.length;i++){var e=s[i];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(t,e.key,e)}}return function(s,i,e){return i&&t(s.prototype,i),e&&t(s,e),s}}(),config=require("./config.js"),CssHandler=function(){function t(s){_classCallCheck(this,t),this.parseCss=function(t){return new CssParser(t,{},!0).parse()},this.styles=s}return _createClass(t,[{key:"getStyle",value:function(t){var s="";return t=t.replace(/<style[\s\S]*?>([\s\S]*?)<\/style[\s\S]*?>/g,function(){return s+=arguments[1],""}),this.styles=new CssParser(s,this.styles).parse(),t}},{key:"match",value:function(t,s){var i=(this.styles[t]||"")+";";if(s.class)for(var e=s.class.split(" "),a=0;a<e.length;a++)i+=(this.styles["."+e[a]]||"")+";";return s.id&&(i+=(this.styles["#"+s.id]||"")+";"),";"==i?"":i}}]),t}();module.exports=CssHandler;var CssParser=function(){function t(s){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=arguments[2];_classCallCheck(this,t),this.data=s,this.res=e?i:this.merge(i),this._floor=0,this._i=0,this._list=[],this._comma=!1,this._sectionStart=0,this._stateHandler=this.SpaceHandler}return _createClass(t,[{key:"merge",value:function(t){var s=JSON.parse(JSON.stringify(config.userAgentStyles));for(var i in t)s[i]=(s[i]||"")+t[i];return s}},{key:"parse",value:function(){for(;this._i<this.data.length;this._i++)this._stateHandler(this.data[this._i]);return this.res}},{key:"SpaceHandler",value:function(t){"."==t||"#"==t||t>="a"&&t<="z"||t>="A"&&t<="Z"?(this._sectionStart=this._i,this._stateHandler=this.StyleNameHandler):"/"==t&&"*"==this.data[this._i+1]?this.CommentHandler():isBlankChar(t)||";"==t||(this._stateHandler=this.IgnoreHandler)}},{key:"CommentHandler",value:function(){this._i=this.data.indexOf("*/",this._i),-1==this._i&&(this._i=this.data.length),this._i++,this._stateHandler=this.SpaceHandler}},{key:"IgnoreHandler",value:function(t){"{"==t?this._floor++:"}"==t&&--this._floor<=0&&(this._list=[],this._stateHandler=this.SpaceHandler)}},{key:"StyleNameHandler",value:function(t){isBlankChar(t)?(this._list.push(this.data.substring(this._sectionStart,this._i)),this._stateHandler=this.NameSpaceHandler):"{"==t?(this._list.push(this.data.substring(this._sectionStart,this._i)),this._floor=1,this._sectionStart=this._i+1,this.ContentHandler()):","==t?(this._list.push(this.data.substring(this._sectionStart,this._i)),this._sectionStart=this._i+1,this._comma=!0):t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"."==t||"#"==t||"-"==t||"_"==t||(this._stateHandler=this.IgnoreHandler)}},{key:"NameSpaceHandler",value:function(t){"{"==t?(this._floor=1,this._sectionStart=this._i+1,this.ContentHandler()):","==t?(this._comma=!0,this._sectionStart=this._i+1,this._stateHandler=this.StyleNameHandler):isBlankChar(t)||(this._comma?(this._stateHandler=this.StyleNameHandler,this._sectionStart=this._i,this._i--,this._comma=!1):this._stateHandler=this.IgnoreHandler)}},{key:"ContentHandler",value:function(){this._i=this.data.indexOf("}",this._i),-1==this._i&&(this._i=this.data.length);for(var t,s=!1,i=this.data.substring(this._sectionStart,this._i),e=0;e<i.length;e++)isBlankChar(i[e])?s||(t=e,s=!0):s&&(0==t?i=i.substring(e):e-t>1&&(i=i.substring(0,t)+" "+i.substring(e)),e=t,s=!1);s&&(i=i.substring(0,t));for(var e=0;e<this._list.length;e++)this.res[this._list[e]]=(this.res[this._list[e]]||"")+i;this._list=[],this._stateHandler=this.SpaceHandler}}]),t}();
\ No newline at end of file
/*
解析和匹配 Css 的选择器
github:https://github.com/jin-yufeng/Parser
docs:https://jin-yufeng.github.io/Parser
author:JinYufeng
update:2020/03/15
*/
var cfg = require('./config.js');
class CssHandler {
constructor(tagStyle) {
var styles = Object.assign({}, cfg.userAgentStyles);
for (var item in tagStyle)
styles[item] = (styles[item] ? styles[item] + ';' : '') + tagStyle[item];
this.styles = styles;
}
getStyle = data => this.styles = new CssParser(data, this.styles).parse();
match(name, attrs) {
var tmp, matched = (tmp = this.styles[name]) ? tmp + ';' : '';
if (attrs.class) {
var items = attrs.class.split(' ');
for (var i = 0, item; item = items[i]; i++)
if (tmp = this.styles['.' + item])
matched += tmp + ';';
}
if (tmp = this.styles['#' + attrs.id])
matched += tmp + ';';
return matched;
}
}
module.exports = CssHandler;
class CssParser {
constructor(data, init) {
this.data = data;
this.floor = 0;
this.i = 0;
this.list = [];
this.res = init;
this.state = this.Space;
}
parse() {
for (var c; c = this.data[this.i]; this.i++)
this.state(c);
return this.res;
}
section = () => this.data.substring(this.start, this.i);
isLetter = c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
// 状态机
Space(c) {
if (c == '.' || c == '#' || this.isLetter(c)) {
this.start = this.i;
this.state = this.Name;
} else if (c == '/' && this.data[this.i + 1] == '*')
this.Comment();
else if (!cfg.blankChar[c] && c != ';')
this.state = this.Ignore;
}
Comment() {
this.i = this.data.indexOf('*/', this.i) + 1;
if (!this.i) this.i = this.data.length;
this.state = this.Space;
}
Ignore(c) {
if (c == '{') this.floor++;
else if (c == '}' && !--this.floor) this.state = this.Space;
}
Name(c) {
if (cfg.blankChar[c]) {
this.list.push(this.section());
this.state = this.NameSpace;
} else if (c == '{') {
this.list.push(this.section());
this.Content();
} else if (c == ',') {
this.list.push(this.section());
this.Comma();
} else if (!this.isLetter(c) && (c < '0' || c > '9') && c != '-' && c != '_')
this.state = this.Ignore;
}
NameSpace(c) {
if (c == '{') this.Content();
else if (c == ',') this.Comma();
else if (!cfg.blankChar[c]) this.state = this.Ignore;
}
Comma() {
while (cfg.blankChar[this.data[++this.i]]);
if (this.data[this.i] == '{') this.Content();
else {
this.start = this.i--;
this.state = this.Name;
}
}
Content() {
this.start = ++this.i;
if ((this.i = this.data.indexOf('}', this.i)) == -1) this.i = this.data.length;
var content = this.section();
for (var i = 0, item; item = this.list[i++];)
if (this.res[item]) this.res[item] += ';' + content;
else this.res[item] = content;
this.list = [];
this.state = this.Space;
}
}
\ No newline at end of file
/* Parser富文本插件 https://github.com/jin-yufeng/Parser */
"use strict";function _classCallCheck(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}function isBlankChar(t){return void 0!=t&&(" "==t||"\t"==t||"\r"==t||"\n"==t||"\v"==t||"\f"==t)}var _createClass=function(){function t(t,i){for(var s=0;s<i.length;s++){var e=i[s];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(t,e.key,e)}}return function(i,s,e){return s&&t(i.prototype,s),e&&t(i,e),i}}(),CssHandler=require("./CssHandler.js"),config=require("./config.js"),emoji;try{emoji=require("./emoji.js")}catch(t){}var MpHtmlParser=function(){function t(i){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=arguments[2];_classCallCheck(this,t),this.cb=e,this.CssHandler=new CssHandler(s.tagStyle),this.data=i,this.DOM=[],this.imgList=[],this.title="",this._attrName="",this._attrValue="",this._attrs={},this._domain=s.domain,this._protocol=s.domain?s.domain.includes("://")?this._domain.split("://")[0]:"http":void 0,this._i=0,this._sectionStart=0,this._stateHandler=this.TextHandler,this._STACK=[],this._tagName="",this._audioNum=0,this._videoNum=0,this._useAnchor=s.useAnchor,this._whiteSpace=!1}return _createClass(t,[{key:"parse",value:function(){for(this.CssHandler&&(this.data=this.CssHandler.getStyle(this.data));this._i<this.data.length;this._i++)this._stateHandler(this.data[this._i]);for(this._stateHandler==this.TextHandler&&this.setText();this._STACK.length;)this.popNode(this._STACK.pop());var t={title:this.title,nodes:this.DOM,imgList:this.imgList};if(!this.cb)return t;this.cb(t)}},{key:"TextHandler",value:function(t){if("<"==t){var i=this.data[this._i+1];i>="a"&&i<="z"||i>="A"&&i<="Z"?(this.setText(),this._stateHandler=this.TagNameHandler):"/"==i?(this.setText(),this._i++,i=this.data[this._i+1],i>="a"&&i<="z"||i>="A"&&i<="Z"?(this._sectionStart=this._i+1,this._stateHandler=this.EndTagHandler):this._stateHandler=this.CommentHandler):"!"==i&&(this.setText(),this._stateHandler=this.CommentHandler)}}},{key:"CommentHandler",value:function(){if("--"==this.data.substring(this._i+1,this._i+3)||"[CDATA["==this.data.substring(this._i+1,this._i+7)){if(this._i=this.data.indexOf("--\x3e",this._i+1),-1==this._i)return this._i=this.data.length;this._i=this._i+2}else if(this._i=this.data.indexOf(">",this._i+1),-1==this._i)return this._i=this.data.length;this._sectionStart=this._i+1,this._stateHandler=this.TextHandler}},{key:"TagNameHandler",value:function(t){isBlankChar(t)?(this._tagName=this.getSelection(!0),this.checkClose()?this.setNode():this._stateHandler=this.AttrNameHandler):this.checkClose()&&(this._tagName=this.getSelection(),this.setNode())}},{key:"AttrNameHandler",value:function(t){if(isBlankChar(t))if(this._attrName=this.getSelection(!0),"="==this.data[this._i]){for(;isBlankChar(this.data[++this._i]););this._sectionStart=this._i,this._i--,this._stateHandler=this.AttrValueHandler}else this.setAttr();else if("="==t){for(this._attrName=this.getSelection();isBlankChar(this.data[++this._i]););this._sectionStart=this._i,this._i--,this._stateHandler=this.AttrValueHandler}else this.checkClose()&&(this._attrName=this.getSelection(),this.setAttr())}},{key:"AttrValueHandler",value:function(t){if('"'==t||"'"==t){if(this._sectionStart++,-1==(this._i=this.data.indexOf(t,this._i+1)))return this._i=this.data.length}else for(;!isBlankChar(this.data[this._i]&&"/"!=this.data[this._i]&&">"!=this.data[this._i]);this._i++);for(this._attrValue=this.getSelection();this._attrValue.includes("&quot;");)this._attrValue=this._attrValue.replace("&quot;","");this.setAttr()}},{key:"EndTagHandler",value:function(t){if(isBlankChar(t)||">"==t||"/"==t){for(var i=this.getSelection().toLowerCase(),s=!1,e=this._STACK.length-1;e>=0;e--)if(this._STACK[e].name==i){s=!0;break}if(s)for(var a;s;)a=this._STACK.pop(),a.name==i&&(s=!1),this.popNode(a);else if("p"==i||"br"==i){var h=this._STACK.length?this._STACK[this._STACK.length-1].children:this.DOM,a={name:i,attrs:{},children:[]};h.push(a)}this._i=this.data.indexOf(">",this._i),-1==this._i?this._i=this.data.length:this._stateHandler=this.TextHandler}}},{key:"checkClose",value:function(){return">"==this.data[this._i]||"/"==this.data[this._i]&&">"==this.data[this._i+1]}},{key:"getSelection",value:function(t){for(var i=this._sectionStart==this._i?"":this.data.substring(this._sectionStart,this._i);t&&isBlankChar(this.data[++this._i]););return t&&this._i--,this._sectionStart=this._i+1,i}},{key:"setAttr",value:function(){for(config.trustAttrs[this._attrName]&&(this._attrs[this._attrName]=this._attrValue||"true"),this._attrValue="";isBlankChar(this.data[this._i]);)this._i++;this.checkClose()?this.setNode():this._stateHandler=this.AttrNameHandler}},{key:"setText",value:function(){var t=this.getSelection();if(t){if(!this._whiteSpace){for(var i,s=!1,e=!1,a=0;a<t.length;a++)isBlankChar(t[a])?s||(i=a,s=!0):(e=!0,s&&(a-i>1&&(t=t.substring(0,i)+" "+t.substring(a)),a=i,s=!1));if(s&&(t=t.substring(0,i)+" "),!t||!e)return}for(emoji&&(t=emoji.parseEmoji(t));t.includes("&nbsp;");)t=t.replace("&nbsp;"," ");for(var h,r,a=t.indexOf("&");-1!=a&&a<t.length;){if((h=t.indexOf(";",a))-a>=2&&h-a<=6){var n=t.substring(a,h);if(!n.includes("sp")&&!n.includes("lt")&&!n.includes("gt")){r=!0;break}}a=t.indexOf("&",a+1)}var l=this._STACK.length?this._STACK[this._STACK.length-1].children:this.DOM;if(l.length&&"text"==l[l.length-1].type)l[l.length-1].text+=t,r&&(l[l.length-1].decode=!0);else{var d={type:"text",text:t,decode:r};r&&(d.decode=!0),l.push(d)}}}},{key:"bubbling",value:function(){for(var t=this._STACK.length-1;t>=0;t--){if(0===config.trustTags[this._STACK[t].name])return this._STACK[t].name;this._STACK[t].continue=!0}}},{key:"setNode",value:function(){var t=this._STACK.length?this._STACK[this._STACK.length-1].children:this.DOM,i={name:this._tagName.toLowerCase(),attrs:this._attrs,children:[]};if(config.LabelAttrsHandler(i,this),this._useAnchor&&i.attrs.id&&this.bubbling(),this._attrs={},!config.selfClosingTags[this._tagName]){if(config.ignoreTags[i.name]||"title"==i.name){for(var s=++this._i;this._i<this.data.length;){if(this._i=this.data.indexOf("</",this._i),-1==this._i)return this._i=this.data.length;for(this._i+=2,this._sectionStart=this._i;!isBlankChar(this.data[this._i])&&">"!=this.data[this._i]&&"/"!=this.data[this._i];)this._i++;if(this.data.substring(this._sectionStart,this._i).toLowerCase()==i.name){"title"==i.name&&(this.title=this.data.substring(s,this._sectionStart-2)),this._i=this.data.indexOf(">",this._i),-1==this._i?this._i=this.data.length:this._sectionStart=this._i+1,this._stateHandler=this.TextHandler;break}}return}this._STACK.push(i),"pre"==i.name&&(this._whiteSapce=!0,i.pre=!0,config.highlight&&(this._sectionStart=this._i+1,this._i=this.data.indexOf("</pre",this._sectionStart),this.data=this.data.substring(0,this._sectionStart)+config.highlight(this.data.substring(this._sectionStart,this._i),i.attrs)+this.data.substring(this._i),this._i=this._sectionStart-1))}if("/"==this.data[this._i]&&this._i++,this._sectionStart=this._i+1,this._stateHandler=this.TextHandler,!config.ignoreTags[i.name]){i.attrs.style=this.CssHandler.match(i.name,i.attrs,i)+(i.attrs.style||""),i.attrs.style||delete i.attrs.style;for(var e=i.attrs.style?i.attrs.style.toLowerCase().split(";"):[],a=0;a<e.length;a++)if(e[a].includes("white-space")&&e[a].includes("pre")){this._whiteSpace=!0,i.pre=!0;break}t.push(i)}}},{key:"popNode",value:function(t){if(config.blockTags[t.name]?t.name="div":config.trustTags.hasOwnProperty(t.name)||(t.name="span"),t.pre){this._whiteSpace=!1,delete t.pre;for(var i=0;i<this._STACK.length;i++)this._STACK[i].pre&&(this._whiteSpace=!0)}if("table"==t.name){if(t.attrs.style=t.attrs.style||"",t.attrs.border&&(t.attrs.style+=";border:"+t.attrs.border+"px solid gray;"),t.attrs.hasOwnProperty("cellspacing")&&(t.attrs.style+=";border-spacing:"+t.attrs.cellspacing+"px"),t.attrs.border||t.attrs.hasOwnProperty("cellpadding"))for(var i=0;i<t.children.length;i++)!function i(s){if("th"==s.name||"td"==s.name)return t.attrs.border&&(s.attrs.style=(s.attrs.style||"")+";border:"+t.attrs.border+"px solid gray;"),void(t.attrs.hasOwnProperty("cellpadding")&&(s.attrs.style=(s.attrs.style||"")+";padding:"+t.attrs.cellpadding+"px"));if("text"!=s.type)for(var e=0;e<s.children.length;e++)i(s.children[e])}(t.children[i])}if(1==t.children.length&&"div"==t.name&&"div"==t.children[0].name){var s=t.children[0];t.attrs.style=t.attrs.style||"",s.attrs.style=s.attrs.style||"",!(t.attrs.style.includes("padding")&&(t.attrs.style.includes("margin")||s.attrs.style.includes("margin"))&&t.attrs.style.includes("display")&&s.attrs.style.includes("display"))||t.attrs.id&&t.attrs.id||t.attrs.class&&s.attrs.class||(s.attrs.style.includes("padding")&&(s.attrs.style="box-sizing:border-box;"+s.attrs.style),t.attrs.style=t.attrs.style+";"+s.attrs.style,t.attrs.id=(s.attrs.id||"")+(t.attrs.id||""),t.attrs.class=(s.attrs.class||"")+(t.attrs.class||""),t.children=s.children)}this.CssHandler.pop&&this.CssHandler.pop(t)}}]),t}();module.exports={parseHtml:function(t,i){return new Promise(function(s){return new MpHtmlParser(t,i,s).parse()})},parseHtmlSync:function(t,i){return new MpHtmlParser(t,i).parse()}};
\ No newline at end of file
/*
将 html 解析为适用于小程序 rich-text 的 DOM 结构
github:https://github.com/jin-yufeng/Parser
docs:https://jin-yufeng.github.io/Parser
author:JinYufeng
update:2020/03/26
*/
var cfg = require('./config.js'),
blankChar = cfg.blankChar,
CssHandler = require('./CssHandler.js'),
screenWidth = wx.getSystemInfoSync().screenWidth;
try {
var emoji = require('./emoji.js');
} catch (e) {}
class MpHtmlParser {
constructor(data, options = {}) {
this.attrs = {};
this.compress = options.compress;
this.CssHandler = new CssHandler(options.tagStyle, screenWidth);
this.data = data;
this.domain = options.domain;
this.DOM = [];
this.i = this.start = this.audioNum = this.imgNum = this.videoNum = 0;
this.protocol = this.domain && this.domain.includes('://') ? this.domain.split('://')[0] : 'http';
this.state = this.Text;
this.STACK = [];
this.useAnchor = options.useAnchor;
this.xml = options.xml;
}
parse() {
if (emoji) this.data = emoji.parseEmoji(this.data);
for (var c; c = this.data[this.i]; this.i++)
this.state(c);
if (this.state == this.Text) this.setText();
while (this.STACK.length) this.popNode(this.STACK.pop());
if (this.DOM.length) {
this.DOM[0].PoweredBy = 'Parser';
if (this.title) this.DOM[0].title = this.title;
}
return this.DOM;
}
// 设置属性
setAttr() {
var name = this.getName(this.attrName);
if (cfg.trustAttrs[name]) {
if (!this.attrVal) {
if (cfg.boolAttrs[name]) this.attrs[name] = 'T';
} else if (name == 'src') this.attrs[name] = this.getUrl(this.attrVal.replace(/&amp;/g, '&'));
else this.attrs[name] = this.attrVal;
}
this.attrVal = '';
while (blankChar[this.data[this.i]]) this.i++;
if (this.isClose()) this.setNode();
else {
this.start = this.i;
this.state = this.AttrName;
}
}
// 设置文本节点
setText() {
var back, text = this.section();
if (!text) return;
text = (cfg.onText && cfg.onText(text, () => back = true)) || text;
if (back) {
this.data = this.data.substr(0, this.start) + text + this.data.substr(this.i);
let j = this.start + text.length;
for (this.i = this.start; this.i < j; this.i++) this.state(this.data[this.i]);
return;
}
if (!this.pre) {
// 合并空白符
var tmp = [];
for (let i = text.length, c; c = text[--i];)
if (!blankChar[c] || (!blankChar[tmp[0]] && (c = ' '))) tmp.unshift(c);
text = tmp.join('');
if (text == ' ') return;
}
// 处理实体
var i = -1,
j, en, siblings = this.siblings();
while (1) {
if ((i = text.indexOf('&', i + 1)) == -1) break;
if ((j = text.indexOf(';', i + 2)) == -1) break;
if (text[i + 1] == '#') {
en = parseInt((text[i + 2] == 'x' ? '0' : '') + text.substring(i + 2, j));
if (!isNaN(en)) text = text.substr(0, i) + String.fromCharCode(en) + text.substr(j + 1);
} else {
en = text.substring(i + 1, j);
if (en == 'nbsp')
text = text.substr(0, i) + '\xA0' + text.substr(j + 1); // 解决 &nbsp; 失效
else if (en != 'lt' && en != 'gt' && en != 'amp' && en != 'ensp' && en != 'emsp' && en != 'quot' && en != 'apos') {
i && siblings.push({
type: 'text',
text: text.substr(0, i)
})
siblings.push({
type: 'text',
text: `&${en};`,
en: 1
})
text = text.substr(j + 1);
i = -1;
}
}
}
text && siblings.push({
type: 'text',
text
});
}
// 设置元素节点
setNode() {
var node = {
name: this.getName(this.tagName),
attrs: this.attrs
},
close = cfg.selfClosingTags[node.name] || (this.xml && this.data[this.i] == '/');
this.attrs = {};
if (!cfg.ignoreTags[node.name]) {
this.matchAttr(node);
if (!close) {
node.children = [];
if (node.name == 'pre' && cfg.highlight) {
this.remove(node);
this.pre = node.pre = true;
}
this.siblings().push(node);
this.STACK.push(node);
} else if (!cfg.filter || cfg.filter(node, this) != false)
this.siblings().push(node);
} else {
if (!close) this.remove(node);
else if (node.name == 'source') {
var parent = this.parent(),
attrs = node.attrs;
if (parent && attrs.src)
if (parent.name == 'video' || parent.name == 'audio')
parent.attrs.source.push(attrs.src);
else {
var i, media = attrs.media;
if (parent.name == 'picture' && !parent.attrs.src && (!media || (media.includes('px') &&
(((i = media.indexOf('min-width')) != -1 && (i = media.indexOf(':', i + 8)) != -1 && screenWidth > parseInt(media.substr(i + 1))) ||
((i = media.indexOf('max-width')) != -1 && (i = media.indexOf(':', i + 8)) != -1 && screenWidth < parseInt(media.substr(i + 1)))))))
parent.attrs.src = attrs.src;
}
} else if (node.name == 'base' && !this.domain) this.domain = node.attrs.href;
}
if (this.data[this.i] == '/') this.i++;
this.start = this.i + 1;
this.state = this.Text;
}
// 移除标签
remove(node) {
var name = node.name,
j = this.i;
while (1) {
if ((this.i = this.data.indexOf('</', this.i + 1)) == -1) {
if (name == 'pre' || name == 'svg') this.i = j;
else this.i = this.data.length;
return;
}
this.start = (this.i += 2);
while (!blankChar[this.data[this.i]] && !this.isClose()) this.i++;
if (this.getName(this.section()) == name) {
// 代码块高亮
if (name == 'pre') {
this.data = this.data.substr(0, j + 1) + cfg.highlight(this.data.substring(j + 1, this.i - 5), node.attrs) + this.data.substr(this.i - 5);
return this.i = j;
} else if (name == 'style')
this.CssHandler.getStyle(this.data.substring(j + 1, this.i - 7));
else if (name == 'title')
this.title = this.data.substring(j + 1, this.i - 7);
if ((this.i = this.data.indexOf('>', this.i)) == -1) this.i = this.data.length;
// 处理 svg
if (name == 'svg') {
var src = this.data.substring(j, this.i + 1);
if (!node.attrs.xmlns) src = ' xmlns="http://www.w3.org/2000/svg"' + src;
var i = j;
while (this.data[j] != '<') j--;
src = this.data.substring(j, i) + src;
var parent = this.parent();
if (node.attrs.width == '100%' && parent && (parent.attrs.style || '').includes('inline'))
parent.attrs.style = 'width:300px;max-width:100%;' + parent.attrs.style;
this.siblings().push({
name: 'img',
attrs: {
src: 'data:image/svg+xml;utf8,' + src.replace(/#/g, '%23')
},
svg: 1
})
}
return;
}
}
}
// 处理属性
matchAttr(node) {
var attrs = node.attrs,
style = this.CssHandler.match(node.name, attrs, node) + (attrs.style || ''),
styleObj = {};
if (attrs.id) {
if (this.compress & 1) attrs.id = void 0;
else if (this.useAnchor) this.bubble();
}
if ((this.compress & 2) && attrs.class) attrs.class = void 0;
switch (node.name) {
case 'a':
case 'ad':
this.bubble();
break;
case 'font':
if (attrs.color) {
styleObj['color'] = attrs.color;
attrs.color = void 0;
}
if (attrs.face) {
styleObj['font-family'] = attrs.face;
attrs.face = void 0;
}
if (attrs.size) {
var size = parseInt(attrs.size);
if (size < 1) size = 1;
else if (size > 7) size = 7;
var map = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'];
styleObj['font-size'] = map[size - 1];
attrs.size = void 0;
}
break;
case 'video':
case 'audio':
if (!attrs.id) attrs.id = node.name + (++this[`${node.name}Num`]);
else this[`${node.name}Num`]++;
if (node.name == 'video' && this.videoNum > 3) node.lazyLoad = 1;
attrs.source = [];
if (attrs.src) attrs.source.push(attrs.src);
if (!attrs.controls && !attrs.autoplay)
console.warn(`存在没有 controls 属性的 ${node.name} 标签,可能导致无法播放`, node);
this.bubble();
break;
case 'td':
case 'th':
if (attrs.colspan || attrs.rowspan)
for (var k = this.STACK.length, item; item = this.STACK[--k];)
if (item.name == 'table') {
item.c = void 0;
break;
}
}
if (attrs.align) {
styleObj['text-align'] = attrs.align;
attrs.align = void 0;
}
if (attrs.width) {
styleObj.width = parseFloat(attrs.width) + (attrs.width.includes('%') ? '%' : 'px');
attrs.width = void 0;
}
if (attrs.height) {
styleObj.height = parseFloat(attrs.height) + (attrs.height.includes('%') ? '%' : 'px');
attrs.height = void 0;
}
// 压缩 style
var styles = style.replace(/&quot;/g, '"').replace(/&amp;/g, '&').split(';');
style = '';
for (var i = 0, len = styles.length; i < len; i++) {
var info = styles[i].split(':');
if (info.length < 2) continue;
let key = info[0].trim().toLowerCase(),
value = info.slice(1).join(':').trim();
if (value.includes('-webkit') || value.includes('-moz') || value.includes('-ms') || value.includes('-o') || value.includes('safe'))
style += `;${key}:${value}`;
else if (!styleObj[key] || value.includes('import') || !styleObj[key].includes('import'))
styleObj[key] = value;
}
if (node.name == 'img' || node.name == 'picture') {
if (attrs['data-src']) {
attrs.src = attrs.src || attrs['data-src'];
attrs['data-src'] = void 0;
}
if ((attrs.src || node.name == 'picture') && !attrs.ignore) {
if (this.bubble()) {
if ((attrs.src || '').includes('.webp')) node.webp = 1;
attrs.i = (this.imgNum++).toString();
} else attrs.ignore = 'T';
}
if (attrs.ignore) styleObj['max-width'] = '100%';
var check = item => styleObj[item] && !styleObj[item].includes('auto');
if (check('width')) {
var parent = this.parent();
if (styleObj.width.includes('%') && parent && (parent.attrs.style || '').includes('inline')) {
parent.attrs.style += ';max-width:100%'
node.auto = 1;
}
if (parseInt(styleObj.width) > screenWidth)
styleObj.height = 'auto';
if (check('height')) node.mode = 'scaleToFill';
} else if (check('height')) node.mode = 'heightFix';
else node.auto = 1;
}
for (var key in styleObj) {
var value = styleObj[key];
if (key.includes('flex') || key == 'order' || key == 'self-align') node.c = 1;
// 填充链接
if (value.includes('url')) {
var j = value.indexOf('(');
if (j++ != -1) {
while (value[j] == '"' || value[j] == "'" || blankChar[value[j]]) j++;
value = value.substr(0, j) + this.getUrl(value.substr(j));
}
}
// 转换 rpx
else if (value.includes('rpx'))
value = value.replace(/[0-9.\s]*rpx/g, $ => parseFloat($) * screenWidth / 750 + 'px');
else if (key == 'white-space' && value.includes('pre'))
this.pre = node.pre = true;
style += `;${key}:${value}`;
}
style = style.substr(1);
if (style) attrs.style = style;
}
// 节点出栈处理
popNode(node) {
// 空白符处理
if (node.pre) {
node.pre = this.pre = void 0;
for (let i = this.STACK.length; i--;)
if (this.STACK[i].pre)
this.pre = true;
}
if (node.name == 'head' || (cfg.filter && cfg.filter(node, this) == false))
return this.siblings().pop();
var attrs = node.attrs;
// 替换一些标签名
if (node.name == 'picture') {
node.name = 'img';
if (!attrs.src && (node.children[0] || '').name == 'img')
attrs.src = node.children[0].attrs.src;
return node.children = void 0;
}
if (cfg.blockTags[node.name]) node.name = 'div';
else if (!cfg.trustTags[node.name]) node.name = 'span';
// 处理列表
if (node.c) {
if (node.name == 'ul') {
var floor = 1;
for (let i = this.STACK.length; i--;)
if (this.STACK[i].name == 'ul') floor++;
if (floor != 1)
for (let i = node.children.length; i--;)
node.children[i].floor = floor;
} else if (node.name == 'ol') {
for (let i = 0, num = 1, child; child = node.children[i++];)
if (child.name == 'li') {
child.type = 'ol';
child.num = ((num, type) => {
if (type == 'a') return String.fromCharCode(97 + (num - 1) % 26);
if (type == 'A') return String.fromCharCode(65 + (num - 1) % 26);
if (type == 'i' || type == 'I') {
num = (num - 1) % 99 + 1;
var one = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
ten = ['X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
res = (ten[Math.floor(num / 10) - 1] || '') + (one[num % 10 - 1] || '');
if (type == 'i') return res.toLowerCase();
return res;
}
return num;
})(num++, attrs.type) + '.';
}
}
}
// 处理表格的边框
if (node.name == 'table') {
var padding = attrs.cellpadding,
spacing = attrs.cellspacing,
border = attrs.border;
if (node.c) {
this.bubble();
attrs.style = (attrs.style || '') + ';display:table';
if (!padding) padding = 2;
if (!spacing) spacing = 2;
}
if (border) attrs.style = `border:${border}px solid gray;${attrs.style || ''}`;
if (spacing) attrs.style = `border-spacing:${spacing}px;${attrs.style || ''}`;
if (border || padding || node.c)
(function f(ns) {
for (var i = 0, n; n = ns[i]; i++) {
var style = n.attrs.style || '';
if (node.c && n.name[0] == 't') {
n.c = 1;
style += ';display:table-' + (n.name == 'th' || n.name == 'td' ? 'cell' : (n.name == 'tr' ? 'row' : 'row-group'));
}
if (n.name == 'th' || n.name == 'td') {
if (border) style = `border:${border}px solid gray;${style}`;
if (padding) style = `padding:${padding}px;${style}`;
} else f(n.children || []);
if (style) n.attrs.style = style;
}
})(node.children)
}
this.CssHandler.pop && this.CssHandler.pop(node);
// 自动压缩
if (node.name == 'div' && !Object.keys(attrs).length) {
var siblings = this.siblings();
if (!(node.children || []).length) siblings.pop();
else if (node.children.length == 1 && node.children[0].name == 'div')
siblings[siblings.length - 1] = node.children[0];
}
}
// 工具函数
bubble() {
for (var i = this.STACK.length, item; item = this.STACK[--i];) {
if (cfg.richOnlyTags[item.name]) {
if (item.name == 'table' && !Object.hasOwnProperty.call(item, 'c')) item.c = 1;
return false;
}
item.c = 1;
}
return true;
}
getUrl(url) {
if (url[0] == '/') {
if (url[1] == '/') url = this.protocol + ':' + url;
else if (this.domain) url = this.domain + url;
} else if (this.domain && url.indexOf('data:') != 0 && !url.includes('://'))
url = this.domain + '/' + url;
return url;
}
getName = val => this.xml ? val : val.toLowerCase();
isClose = () => this.data[this.i] == '>' || (this.data[this.i] == '/' && this.data[this.i + 1] == '>');
section = () => this.data.substring(this.start, this.i);
parent = () => this.STACK[this.STACK.length - 1];
siblings = () => this.STACK.length ? this.parent().children : this.DOM;
// 状态机
Text(c) {
if (c == '<') {
var next = this.data[this.i + 1],
isLetter = c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
if (isLetter(next)) {
this.setText();
this.start = this.i + 1;
this.state = this.TagName;
} else if (next == '/') {
this.setText();
if (isLetter(this.data[++this.i + 1])) {
this.start = this.i + 1;
this.state = this.EndTag;
} else this.Comment();
} else if (next == '!') {
this.setText();
this.Comment();
}
}
}
Comment() {
var key;
if (this.data.substring(this.i + 2, this.i + 4) == '--') key = '-->';
else if (this.data.substring(this.i + 2, this.i + 9) == '[CDATA[') key = ']]>';
else key = '>';
if ((this.i = this.data.indexOf(key, this.i + 2)) == -1) this.i = this.data.length;
else this.i += key.length - 1;
this.start = this.i + 1;
this.state = this.Text;
}
TagName(c) {
if (blankChar[c]) {
this.tagName = this.section();
while (blankChar[this.data[this.i]]) this.i++;
if (this.isClose()) this.setNode();
else {
this.start = this.i;
this.state = this.AttrName;
}
} else if (this.isClose()) {
this.tagName = this.section();
this.setNode();
}
}
AttrName(c) {
var blank = blankChar[c];
if (blank) {
this.attrName = this.section();
c = this.data[this.i];
}
if (c == '=') {
if (!blank) this.attrName = this.section();
while (blankChar[this.data[++this.i]]);
this.start = this.i--;
this.state = this.AttrValue;
} else if (blank) this.setAttr();
else if (this.isClose()) {
this.attrName = this.section();
this.setAttr();
}
}
AttrValue(c) {
if (c == '"' || c == "'") {
this.start++;
if ((this.i = this.data.indexOf(c, this.i + 1)) == -1) return this.i = this.data.length;
this.attrVal = this.section();
this.i++;
} else {
for (; !blankChar[this.data[this.i]] && !this.isClose(); this.i++);
this.attrVal = this.section();
}
this.setAttr();
}
EndTag(c) {
if (blankChar[c] || c == '>' || c == '/') {
var name = this.getName(this.section());
for (var i = this.STACK.length; i--;)
if (this.STACK[i].name == name) break;
if (i != -1) {
var node;
while ((node = this.STACK.pop()).name != name);
this.popNode(node);
} else if (name == 'p' || name == 'br')
this.siblings().push({
name,
attrs: {}
});
this.i = this.data.indexOf('>', this.i);
this.start = this.i + 1;
if (this.i == -1) this.i = this.data.length;
else this.state = this.Text;
}
}
}
module.exports = MpHtmlParser;
\ No newline at end of file
"use strict";var trustTags={a:0,abbr:1,ad:0,audio:0,b:1,blockquote:1,br:0,code:1,col:0,colgroup:0,dd:1,del:1,dl:1,dt:1,div:1,em:1,fieldset:0,font:1,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,hr:0,i:1,img:1,ins:1,label:1,legend:0,li:0,ol:0,p:1,q:1,source:0,span:1,strong:1,sub:0,sup:0,table:0,tbody:0,td:0,tfoot:0,th:0,thead:0,tr:0,u:1,ul:0,video:1},blockTags={address:!0,article:!0,aside:!0,body:!0,center:!0,cite:!0,footer:!0,header:!0,html:!0,nav:!0,pre:!0,section:!0},ignoreTags={area:!0,base:!0,basefont:!0,canvas:!0,circle:!0,command:!0,ellipse:!0,embed:!0,frame:!0,head:!0,iframe:!0,input:!0,isindex:!0,keygen:!0,line:!0,link:!0,map:!0,meta:!0,param:!0,path:!0,polygon:!0,polyline:!0,rect:!0,script:!0,source:!0,textarea:!0,title:!0,track:!0,use:!0,wbr:!0},userAgentStyles={a:"display:inline;color:#366092;word-break:break-all;",address:"font-style:italic;",blockquote:"background-color:#f6f6f6;border-left:3px solid #dbdbdb;color:#6c6c6c;padding:5px 0 5px 10px;",center:"text-align:center;",cite:"font-style:italic;",code:"padding:0 1px 0 1px;margin-left:2px;margin-right:2px;background-color:#f8f8f8;border-radius:3px;",dd:"margin-left:40px;",img:"max-width:100%;",mark:"display:inline;background-color:yellow;",pre:"font-family:monospace;white-space:pre;overflow:scroll;",s:"display:inline;text-decoration:line-through;",u:"display:inline;text-decoration:underline;"},SDKVersion=wx.getSystemInfoSync().SDKVersion,versionHigherThan=function(){for(var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=SDKVersion.split("."),s=t.split("."),r=Math.max(e.length,s.length);e.length<r;)e.push("0");for(;s.length<r;)s.push("0");for(var a=0;a<r;a++){var i=parseInt(e[a]),l=parseInt(s[a]);if(i>l)return!0;if(i<l)return!1}return!0};versionHigherThan("2.7.1")?(trustTags.bdi=0,trustTags.bdo=0,trustTags.caption=0,trustTags.rt=0,trustTags.ruby=0,ignoreTags.rp=!0,trustTags.big=1,trustTags.small=1,trustTags.pre=0,delete blockTags.pre):(blockTags.caption=!0,userAgentStyles.big="display:inline;font-size:1.2em;",userAgentStyles.small="display:inline;font-size:0.8em;"),module.exports={highlight:null,LabelAttrsHandler:function(t,e){switch(t.name){case"div":case"p":t.attrs.align&&(t.attrs.style="text-align:"+t.attrs.align+";"+(t.attrs.style||""),delete t.attrs.align);break;case"img":t.attrs["data-src"]&&(t.attrs.src=t.attrs.src||t.attrs["data-src"],delete t.attrs["data-src"]),!t.attrs.ignore&&t.attrs.src&&(e.imgList.includes(t.attrs.src)&&t.attrs.src.includes("http")&&(t.attrs.src=t.attrs.src+(t.attrs.src.includes("?")?"&":"?")+"parserid="+e.imgList.length),e.imgList.push(t.attrs.src),"a"==e.bubbling()&&(t.attrs.ignore="true")),e._domain&&"/"==t.attrs.src[0]&&("/"==t.attrs.src[1]?t.attrs.src=e._protocol+":"+t.attrs.src:t.attrs.src=e._domain+t.attrs.src);break;case"a":case"ad":e.bubbling();break;case"font":if(name="span",t.attrs.style=t.attrs.style||"",t.attrs.color&&(t.attrs.style="color:"+t.attrs.color+";"+t.attrs.style,delete t.attrs.color),t.attrs.face&&(t.attrs.style="font-family:"+t.attrs.face+";"+t.attrs.style,delete t.attrs.face),t.attrs.size){var s=parseInt(attrs.size);s<1?s=1:s>7&&(s=7);var r=[10,13,16,18,24,32,48];t.attrs.style="font-size:"+r[s-1]+"px;"+t.attrs.style,delete t.attrs.size}break;case"video":case"audio":t.attrs.id?e["_"+t.name+"Num"]++:t.attrs.id=t.name+ ++e["_"+t.name+"Num"],"video"==t.name&&(t.attrs.style=t.attrs.style||"",t.attrs.width&&(t.attrs.style="width:"+parseFloat(t.attrs.width)+(t.attrs.width.includes("%")?"%":"px")+";"+t.attrs.style,delete t.attrs.width),t.attrs.height&&(t.attrs.style="height:"+parseFloat(t.attrs.height)+(t.attrs.height.includes("%")?"%":"px")+";"+t.attrs.style,delete t.attrs.height),e._videoNum>3&&(t.lazyLoad=!0)),t.attrs.source=[],t.attrs.src&&t.attrs.source.push(t.attrs.src),t.attrs.controls||t.attrs.autoplay||console.warn("存在没有controls属性的"+t.name+"标签,可能导致无法播放",t),e.bubbling();break;case"source":var a=e._STACK[e._STACK.length-1];!a||"video"!=a.name&&"audio"!=a.name||(a.attrs.source.push(t.attrs.src),a.attrs.src||(a.attrs.src=t.attrs.src))}},trustAttrs:{align:!0,alt:!0,author:!0,autoplay:!0,border:!0,cellpadding:!0,cellspacing:!0,class:!0,color:!0,colspan:!0,controls:!0,"data-src":!0,dir:!0,face:!0,height:!0,href:!0,id:!0,ignore:!0,loop:!0,muted:!0,name:!0,poster:!0,rowspan:!0,size:!0,span:!0,src:!0,start:!0,style:!0,type:!0,"unit-id":!0,width:!0},selfClosingTags:{area:!0,base:!0,basefont:!0,br:!0,col:!0,circle:!0,ellipse:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,line:!0,link:!0,meta:!0,param:!0,path:!0,polygon:!0,polyline:!0,rect:!0,source:!0,track:!0,use:!0,wbr:!0},trustTags:trustTags,blockTags:blockTags,ignoreTags:ignoreTags,userAgentStyles:userAgentStyles,versionHigherThan:versionHigherThan};
\ No newline at end of file
/* 配置文件 */
const canIUse = wx.canIUse('editor'); // 高基础库标识,用于兼容
module.exports = {
// 过滤器函数
filter: null,
// 代码高亮函数
highlight: null,
// 文本处理函数
onText: null,
blankChar: makeMap(' ,\xA0,\t,\r,\n,\f'),
// 块级标签,将被转为 div
blockTags: makeMap('address,article,aside,body,caption,center,cite,footer,header,html,nav,section' + (canIUse ? '' : ',pre')),
// 将被移除的标签
ignoreTags: makeMap('area,base,basefont,canvas,command,embed,frame,iframe,input,isindex,keygen,link,map,meta,param,script,source,style,svg,textarea,title,track,use,wbr' + (canIUse ? ',rp' : '')),
// 只能被 rich-text 显示的标签
richOnlyTags: makeMap('a,colgroup,fieldset,legend,picture,table' + (canIUse ? ',bdi,bdo,rt,ruby' : '')),
// 自闭合的标签
selfClosingTags: makeMap('area,base,basefont,br,col,circle,ellipse,embed,frame,hr,img,input,isindex,keygen,line,link,meta,param,path,polygon,rect,source,track,use,wbr'),
// 信任的属性
trustAttrs: makeMap('align,alt,app-id,author,autoplay,border,cellpadding,cellspacing,class,color,colspan,controls,data-src,dir,face,height,href,id,ignore,loop,media,muted,name,path,poster,rowspan,size,span,src,start,style,type,unit-id,width,xmlns'),
// bool 型的属性
boolAttrs: makeMap('autoplay,controls,ignore,loop,muted'),
// 信任的标签
trustTags: makeMap('a,abbr,ad,audio,b,blockquote,br,code,col,colgroup,dd,del,dl,dt,div,em,fieldset,h1,h2,h3,h4,h5,h6,hr,i,img,ins,label,legend,li,ol,p,q,source,span,strong,sub,sup,table,tbody,td,tfoot,th,thead,tr,title,ul,video' + (canIUse ? ',bdi,bdo,caption,pre,rt,ruby' : '')),
// 默认的标签样式
userAgentStyles: {
address: 'font-style:italic',
big: 'display:inline;font-size:1.2em',
blockquote: 'background-color:#f6f6f6;border-left:3px solid #dbdbdb;color:#6c6c6c;padding:5px 0 5px 10px',
caption: 'display:table-caption;text-align:center',
center: 'text-align:center',
cite: 'font-style:italic',
dd: 'margin-left:40px',
mark: 'background-color:yellow',
pre: 'font-family:monospace;white-space:pre;overflow:scroll',
s: 'text-decoration:line-through',
small: 'display:inline;font-size:0.8em',
u: 'text-decoration:underline'
}
}
function makeMap(str) {
var map = {},
list = str.split(',');
for (var i = list.length; i--;)
map[list[i]] = true;
return map;
}
\ No newline at end of file
/*
parser 主组件
github:https://github.com/jin-yufeng/Parser
docs:https://jin-yufeng.github.io/Parser
author:JinYufeng
update:2020/03/26
*/
var cache = {},
Parser = require('./libs/MpHtmlParser.js'),
fs = wx.getFileSystemManager && wx.getFileSystemManager();
try {
var dom = require('./libs/document.js');
} catch (e) {}
// 计算 cache 的 key
function hash(str) {
for (var i = str.length, val = 5381; i--;)
val += (val << 5) + str.charCodeAt(i);
return val;
}
Component({
options: {
pureDataPattern: /^[acdgtux]|W/
},
properties: {
'html': {
type: null,
observer(html) {
if (this._refresh) this._refresh = false;
else this.setContent(html, false, true);
}
},
'autosetTitle': {
type: Boolean,
value: true
},
'autopause': {
type: Boolean,
value: true
},
'compress': Number,
'domain': String,
'gestureZoom': Boolean,
'lazyLoad': Boolean,
'selectable': Boolean,
'tagStyle': Object,
'showWithAnimation': Boolean,
'useAnchor': Boolean,
'useCache': Boolean,
'xml': Boolean
},
relations: {
'../parser-group/parser-group': {
type: 'ancestor'
}
},
created() {
// 图片数组
this.imgList = [];
this.imgList.setItem = function(i, src) {
if (!i || !src) return;
// 去重
if (src.indexOf('http') == 0 && this.includes(src)) {
var newSrc = '';
for (var j = 0, c; c = src[j]; j++) {
if (c == '/' && src[j - 1] != '/' && src[j + 1] != '/') break;
newSrc += Math.random() > 0.5 ? c.toUpperCase() : c;
}
newSrc += src.substr(j);
return this[i] = newSrc;
}
this[i] = src;
// 暂存 data src
if (src.includes('data:image')) {
var info = src.match(/data:image\/(\S+?);(\S+?),(.+)/);
if (!info) return;
var filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${info[1]}`;
fs && fs.writeFile({
filePath,
data: info[3],
encoding: info[2],
success: () => this[i] = filePath
})
}
}
this.imgList.each = function(f) {
for (var i = 0, len = this.length; i < len; i++)
this.setItem(i, f(this[i], i, this));
}
},
detached() {
// 删除暂存
this.imgList.each(src => {
if (src && src.includes(wx.env.USER_DATA_PATH) && fs)
fs.unlink({
filePath: src
})
})
clearInterval(this._timer);
},
methods: {
// 锚点跳转
navigateTo(obj) {
if (!this.data.useAnchor)
return obj.fail && obj.fail({
errMsg: 'Anchor is disabled'
})
this.createSelectorQuery()
.select('.top' + (obj.id ? '>>>#' + obj.id : '')).boundingClientRect()
.selectViewport().scrollOffset().exec(res => {
if (!res[0])
return this.group ? this.group.navigateTo(this.i, obj) :
obj.fail && obj.fail({
errMsg: 'Label not found'
});
obj.scrollTop = res[1].scrollTop + res[0].top;
wx.pageScrollTo(obj);
})
},
// 获取文本
getText(ns = this.data.html) {
var txt = '';
for (var i = 0, n; n = ns[i++];) {
if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
else if (n.type == 'br') txt += '\n';
else {
// 块级标签前后加换行
var br = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] > '0' && n.name[1] < '7');
if (br && txt && txt[txt.length - 1] != '\n') txt += '\n';
if (n.children) txt += this.getText(n.children);
if (br && txt[txt.length - 1] != '\n') txt += '\n';
else if (n.name == 'td' || n.name == 'th') txt += '\t';
}
}
return txt;
},
// 获取视频 context
getVideoContext(id) {
if (!id) return this.videoContexts;
for (var i = this.videoContexts.length; i--;)
if (this.videoContexts[i].id == id) return this.videoContexts[i];
},
// 渲染富文本
setContent(html, append, _watch) {
var data = {};
if (!html) {
if (_watch || append) return;
data.html = '';
} else if (typeof html == 'string') {
let parser = new Parser(html, this.data);
// 缓存读取
if (this.data.useCache) {
var hashVal = hash(html);
if (cache[hashVal]) data.html = cache[hashVal];
else {
data.html = parser.parse();
cache[hashVal] = data.html;
}
} else data.html = parser.parse();
this._refresh = true;
this.triggerEvent('parse', data.html);
} else if (html.constructor == Array) {
// 转换不符合格式的 array
if (html.length && html[0].PoweredBy != 'Parser') {
let parser = new Parser('', this.data);
(function f(ns) {
for (var i = 0, n; n = ns[i]; i++) {
if (n.type == 'text') continue;
n.attrs = n.attrs || {};
for (var key in n.attrs)
if (typeof n.attrs[key] != 'string') n.attrs[key] = n.attrs[key].toString();
parser.matchAttr(n);
if (n.children) {
parser.STACK.push(n);
f(n.children);
parser.popNode(parser.STACK.pop());
}
}
})(html);
data.html = html;
}
if (!_watch) data.html = html;
} else if (typeof html == 'object' && html.nodes) {
data.html = html.nodes;
console.warn('错误的 html 类型:object 类型已废弃');
} else
return console.warn('错误的 html 类型:' + typeof html);
if (append) {
this._refresh = true;
data.html = (this.data.html || []).concat(data.html);
} else if (this.data.showWithAnimation) data.showAm = 'animation: show .5s';
if (data.html || data.showAm) this.setData(data);
// 设置标题
if (this.data.html.length && this.data.html[0].title && this.data.autosetTitle)
wx.setNavigationBarTitle({
title: this.data.html[0].title
})
this.imgList.length = 0;
this.videoContexts = [];
if (dom) this.document = new dom(this.data.html, 'html', this);
var ns = this.selectAllComponents('.top,.top>>>._node');
for (let i = 0, n; n = ns[i++];) {
n.top = this;
for (var j = 0, item; item = n.data.nodes[j++];) {
if (item.c) continue;
// 获取图片列表
if (item.name == 'img')
this.imgList.setItem(item.attrs.i, item.attrs.src);
// 音视频控制
else if (item.name == 'video' || item.name == 'audio') {
var ctx;
if (item.name == 'video') ctx = wx.createVideoContext(item.attrs.id, n);
else ctx = n.selectComponent('#' + item.attrs.id);
if (ctx) {
ctx.id = item.attrs.id;
this.videoContexts.push(ctx);
}
}
}
}
(wx.nextTick || setTimeout)(() => this.triggerEvent('load'), 50);
var height;
clearInterval(this._timer);
this._timer = setInterval(() => {
this.createSelectorQuery().select('.top').boundingClientRect(res => {
this.rect = res;
if (res.height == height) {
this.triggerEvent('ready', res)
clearInterval(this._timer);
}
height = res.height;
}).exec();
}, 350)
},
// 预加载
preLoad(html, num) {
if (typeof html == 'string') {
var id = hash(html);
html = new Parser(html, this.data).parse();
cache[id] = html;
}
var imgs, wait = [];
(function f(ns) {
for (var i = 0, n; n = ns[i++];) {
if (n.name == 'img' && n.attrs.src && !wait.includes(n.attrs.src))
wait.push(n.attrs.src);
f(n.children || []);
}
})(html);
if (num) wait = wait.slice(0, num);
this._wait = (this._wait || []).concat(wait);
if (!this.data.imgs) imgs = this._wait.splice(0, 15);
else if (this.data.imgs.length < 15)
imgs = this.data.imgs.concat(this._wait.splice(0, 15 - this.data.imgs.length));
imgs && this.setData({
imgs
});
},
_load(e) {
if (this._wait.length)
this.setData({
[`imgs[${e.target.id}]`]: this._wait.shift()
})
},
// 事件处理
_tap(e) {
if (this.data.gestureZoom && e.timeStamp - this._lastT < 300) {
var initY = e.detail.y - e.currentTarget.offsetTop;
if (this._zoom) {
this._scaleAm.translateX(0).scale(1).step();
wx.pageScrollTo({
scrollTop: (initY + this._initY) / 2 - e.touches[0].clientY,
duration: 400
})
} else {
var initX = e.detail.x - e.currentTarget.offsetLeft;
this._initY = initY;
this._scaleAm = wx.createAnimation({
transformOrigin: `${initX}px ${this._initY}px 0`,
timingFunction: 'ease-in-out'
});
this._scaleAm.scale(2).step();
this._tMax = initX / 2;
this._tMin = (initX - this.rect.width) / 2;
this._tX = 0;
}
this._zoom = !this._zoom;
this.setData({
scaleAm: this._scaleAm.export()
})
}
this._lastT = e.timeStamp;
},
_touchstart(e) {
if (e.touches.length == 1)
this._initX = this._lastX = e.touches[0].pageX;
},
_touchmove(e) {
var diff = e.touches[0].pageX - this._lastX;
if (this._zoom && e.touches.length == 1 && Math.abs(diff) > 20) {
this._lastX = e.touches[0].pageX;
if ((this._tX <= this._tMin && diff < 0) || (this._tX >= this._tMax && diff > 0)) return;
this._tX += diff * Math.abs(this._lastX - this._initX) * 0.05;
if (this._tX < this._tMin) this._tX = this._tMin;
if (this._tX > this._tMax) this._tX = this._tMax;
this._scaleAm.translateX(this._tX).step();
this.setData({
scaleAm: this._scaleAm.export()
})
}
}
}
})
\ No newline at end of file
{
"component": true,
"usingComponents": {
"trees": "./trees/trees"
}
}
\ No newline at end of file
<!--parser 主组件-->
<slot wx:if="{{!html[0].name&&!html[0].type}}" />
<trees class="top" style="{{selectable?'user-select:text;-webkit-user-select:text;':''}}{{showAm}}" animation="{{scaleAm}}" lazy-load="{{lazyLoad}}" nodes="{{html[0].name||html[0].type?html:[]}}" bindtap="_tap" bindtouchstart="_touchstart" bindtouchmove="_touchmove" />
<image wx:for="{{imgs}}" wx:key="index" id="{{index}}" src="{{item}}" hidden bindload="_load" />
\ No newline at end of file
:host {
display: block;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
.top {
display: inherit;
}
@keyframes show {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
\ No newline at end of file
"use strict";var inlineTags={abbr:!0,b:!0,big:!0,code:!0,del:!0,em:!0,font:!0,i:!0,ins:!0,label:!0,mark:!0,q:!0,s:!0,small:!0,span:!0,strong:!0,u:!0};module.exports={getStyle:function(t,e){res="";var s=getRegExp("float[^;]+(?![sS]*?float)","i");return s.test(t)&&(res+=s.exec(t)[0]),s=getRegExp("margin[^;]+","gi"),s.test(t)&&(res+=";"+t.match(s).join(";")),s=getRegExp("displays*:s*([^;]*)(?![sS]*?display)","i"),s.test(t)&&"flex"!=s.exec(t)[1]?res+=";"+s.exec(t)[0]:res+=";display:"+e,s=getRegExp("flex[^;]*:[^;]+","ig"),s.test(t)&&(res+=";"+t.match(s).join(";")),s=getRegExp("[^;s]*width[^;]+","ig"),s.test(t)&&(res+=";"+t.match(s).join(";")),res},setImgStyle:function(t,e,s){return"widthFix"==e&&(t.attrs.style+=";height:auto !important"),t.attrs.style&&(t.attrs.style=t.attrs.style.replace(getRegExp("width[^;]*?%","gi"),"width:100%").replace(getRegExp("margin[^;]+","gi"),"")),s||(delete t.attrs.src,t.attrs.style+=";width:5px !important;height:5px !important"),[t]},setStyle:function(t){return t.attrs.style&&(t.attrs.style=t.attrs.style.replace(getRegExp("width[^;]*?%","gi"),"width:100%").replace(getRegExp("margin[^;]+","gi"),"")),[t]},notContinue:function(t){return"a"==t.name||"li"==t.name||"ol"==t.name||"ul"==t.name||!(t["continue"]||inlineTags[t.name])}};
\ No newline at end of file
var inlineTags = {
abbr: 1,
b: 1,
big: 1,
code: 1,
del: 1,
em: 1,
i: 1,
ins: 1,
label: 1,
q: 1,
small: 1,
span: 1,
strong: 1
}
module.exports = {
// 获取图片大小
load: function (e) {
if (e.target.dataset.auto)
e.instance.setStyle({
width: e.detail.width + 'px'
})
},
// 链接点击态
visited: function (e, owner) {
if (!e.instance.hasClass('_visited'))
e.instance.addClass('_visited')
owner.callMethod('linkpress', e);
},
// 是否通过 rich-text 显示
useRichText: function (item) {
return !item.c && !inlineTags[item.name] && (item.attrs.style || '').indexOf('display:inline') == -1
}
}
\ No newline at end of file
/* Parser富文本插件 https://github.com/jin-yufeng/Parser */
"use strict";Component({data:{imgLoad:!1},created:function(){var t=this;this.triggerError=function(r,e,o,a,i){t._top&&t._top.triggerEvent("error",{source:r,target:e,errMsg:o,errCode:a,context:i})},this.loadSource=function(r){return!t.data.controls[r.id]&&r.source.length>1?(t.data.controls[r.id]={play:!1,index:1},t.setData({controls:t.data.controls}),!0):!!(t.data.controls[r.id]&&r.source.length>t.data.controls[r.id].index+1)&&(t.data.controls[r.id].index++,t.setData({controls:t.data.controls}),!0)}},detached:function(){this._observer&&this._observer.disconnect()},properties:{nodes:{type:Array,value:[]},controls:{type:Object,value:{}}},methods:{playEvent:function(t){if(this._top&&this._top.videoContexts.length>1&&this._top.data.autopause){var r=!0,e=!1,o=void 0;try{for(var a,i=this._top.videoContexts[Symbol.iterator]();!(r=(a=i.next()).done);r=!0){var n=a.value;n.id!=t.currentTarget.dataset.id&&n.pause()}}catch(t){e=!0,o=t}finally{try{!r&&i.return&&i.return()}finally{if(e)throw o}}}},previewEvent:function(t){if(this._top&&!t.target.dataset.hasOwnProperty("ignore")){var r=!0,e=t.currentTarget.dataset.src;this._top.triggerEvent("imgtap",{id:t.currentTarget.id,src:e,ignore:function(){return r=!1}}),r&&this._top.data.autopreview&&wx.previewImage({current:e,urls:this._top.imgList.length?this._top.imgList:[e]})}},tapEvent:function(t){if(this._top){var r=!0,e=t.currentTarget.dataset.href;this._top.triggerEvent("linkpress",{href:e,ignore:function(){return r=!1}}),r&&e&&("#"==e[0]?this._top.data.useAnchor&&this._top.navigateTo({id:e.substring(1)}):/^http/.test(e)?this._top.data.autocopy&&wx.setClipboardData({data:e,success:function(){wx.showToast({title:"链接已复制"})}}):wx.navigateTo({url:e}))}},adError:function(t){this.triggerError("ad",t.currentTarget,t.detail.errMsg,t.detail.errCode)},videoError:function(t){!this.loadSource(t.currentTarget.dataset)&&this._top&&this.triggerError("video",t.currentTarget,t.detail.errMsg,void 0,this._top.getVideoContext(t.currentTarget.id))},audioError:function(t){this.loadSource(t.currentTarget.dataset)||this.triggerError("audio",t.currentTarget,t.detail.errMsg)},loadVideo:function(t){this.data.controls[t.currentTarget.dataset.id]={play:!0,index:0},this.setData({controls:this.data.controls})}}});
\ No newline at end of file
/*
trees 递归子组件
github:https://github.com/jin-yufeng/Parser
docs:https://jin-yufeng.github.io/Parser
author:JinYufeng
update:2020/03/23
*/
Component({
data: {
canIUse: !!wx.chooseMessageFile
},
properties: {
nodes: Array,
lazyLoad: Boolean
},
methods: {
// 视频播放事件
play(e) {
this.top.group && this.top.group.pause(this.top.i);
if (this.top.videoContexts.length > 1 && this.top.data.autopause)
for (var i = this.top.videoContexts.length; i--;)
if (this.top.videoContexts[i].id != e.currentTarget.id)
this.top.videoContexts[i].pause();
},
// 图片点击事件
imgtap(e) {
var attrs = e.target.dataset.attrs;
if (!attrs.ignore) {
var preview = true;
this.top.triggerEvent('imgtap', {
id: e.target.id,
src: attrs.src,
ignore: () => preview = false
})
if (preview) {
if (this.top.group) return this.top.group.preview(this.top.i, attrs.i);
var urls = this.top.imgList,
current = urls[attrs.i] ? urls[attrs.i] : (urls = [attrs.src], attrs.src);
wx.previewImage({
current,
urls
})
}
}
},
// 链接点击事件
linkpress(e) {
var jump = true,
attrs = e.currentTarget.dataset.attrs;
attrs.ignore = () => jump = false;
this.top.triggerEvent('linkpress', attrs);
if (jump) {
if (attrs['app-id'])
wx.navigateToMiniProgram({
appId: attrs['app-id'],
path: attrs.path
})
else if (attrs.href) {
if (attrs.href[0] == '#')
this.top.navigateTo({
id: attrs.href.substring(1)
})
else if (attrs.href.indexOf('http') == 0 || attrs.href.indexOf('//') == 0)
wx.setClipboardData({
data: attrs.href,
success: () =>
wx.showToast({
title: '链接已复制'
})
})
else
wx.navigateTo({
url: attrs.href,
})
}
}
},
// 错误事件
error(e) {
var context, src = '',
source = e.target.dataset.source,
i = e.target.dataset.i,
node = this.data.nodes[i];
if (source == 'video' || source == 'audio') {
// 加载其他 source
var index = (node.i || 0) + 1;
if (index < node.attrs.source.length)
return this.setData({
[`nodes[${i}].i`]: index
})
if (this.top) context = this.top.getVideoContext(e.target.id);
} else if (source == 'img')
context = {
setSrc: (newSrc) => src = newSrc
}
this.top && this.top.triggerEvent('error', {
source,
target: e.target,
context,
...e.detail
})
if (source == 'img') {
var data = {
[`nodes[${i}].attrs.src`]: src
}
if (!src) data[`nodes[${i}].err`] = 1;
this.setData(data);
}
},
// 加载视频
loadVideo(e) {
var i = e.target.dataset.i;
this.setData({
[`nodes[${i}].lazyLoad`]: false,
[`nodes[${i}].attrs.autoplay`]: true
})
},
// 加载图片
loadImg(e) {
var data = e.target.dataset;
if (data.auto)
this.setData({
[`nodes[${data.i}].attrs.style`]: `${this.data.nodes[data.i].attrs.style};width:${e.detail.width}px`
})
}
}
})
\ No newline at end of file
{"component":true,"usingComponents":{"trees":"./trees"}}
\ No newline at end of file
{
"component": true,
"usingComponents": {
"trees": "./trees"
}
}
\ No newline at end of file
<wxs module="Handler" src="./handler.wxs" /><block wx:for='{{nodes}}' wx:key="index"><block wx:if="{{Handler.notContinue(item)}}"><rich-text wx:if="{{item.name=='img'}}" id="{{item.attrs.id}}" class="img" style="text-indent:0;{{Handler.getStyle(item.attrs.style,'inline-block')}}" nodes='{{Handler.setImgStyle(item,controls.imgMode,imgLoad)}}' data-ignore='{{item.attrs.ignore}}' data-src='{{item.attrs.src}}' bindtap='previewEvent' /><block wx:elif="{{item.type=='text'}}"><text wx:if="{{!item.decode}}" decode>{{item.text}}</text><rich-text wx:else style="display:inline-block" nodes="{{[item]}}"></rich-text></block><text wx:elif="{{item.name=='br'}}">\n</text><block wx:elif="{{item.name=='video'}}"><view wx:if="{{item.lazyLoad&&!controls[item.attrs.id].play}}" class="pvideo {{item.attrs.class||''}}" style="{{item.attrs.style}}" data-id="{{item.attrs.id}}" bindtap="loadVideo"><view class="video-triangle" /></view><video wx:else src='{{controls[item.attrs.id]?item.attrs.source[controls[item.attrs.id].index]:item.attrs.src}}' id="{{item.attrs.id}}" loop='{{item.attrs.loop}}' controls='{{item.attrs.controls}}' autoplay="{{item.attrs.autoplay||controls[item.attrs.id].play}}" unit-id="{{item.attrs['unit-id']}}" class="v {{item.attrs.class||''}}" muted="{{item.attrs.muted}}" style="{{item.attrs.style}}" data-id="{{item.attrs.id}}" data-source="{{item.attrs.source}}" bindplay='playEvent' binderror="videoError" /></block><audio wx:elif="{{item.name=='audio'}}" id="{{item.attrs.id}}" class="{{item.attrs.class}}" src='{{controls[item.attrs.id]?item.attrs.source[controls[item.attrs.id].index]:item.attrs.src}}' loop='{{item.attrs.loop}}' controls='{{item.attrs.controls}}' poster='{{item.attrs.poster}}' name='{{item.attrs.name}}' author='{{item.attrs.author}}' style="{{item.attrs.style}}" data-id="{{item.attrs.id}}" data-source="{{item.attrs.source}}" binderror="audioError" /><view wx:elif="{{item.name=='a'}}" url="{{item.attrs.href}}" class="a {{item.attrs.class||''}}" style="{{item.attrs.style}}" data-href='{{item.attrs.href}}' hover-class="navigator-hover" hover-start-time="25" hover-stay-time="300" bindtap="tapEvent"><trees class="node" nodes="{{item.children}}" controls="{{controls}}" /></view><ad wx:elif="{{item.name=='ad'}}" unit-id="{{item.attrs['unit-id']}}" class="{{item.attrs.class}}" style="{{item.attrs.style}}" binderror="adError"></ad><rich-text wx:else id="{{item.attrs.id}}" class="{{item.name}}" style="{{Handler.getStyle(item.attrs.style,'block')}}" nodes="{{Handler.setStyle(item)}}" /></block><trees wx:else id="{{item.attrs.id}}" class="node {{item.name+' '+(item.attrs.class||'')}}" style="{{item.attrs.style}}" nodes="{{item.children}}" controls="{{controls}}" /></block>
\ No newline at end of file
<!--trees 递归子组件-->
<wxs module="handler" src="./handler.wxs" />
<block wx:for="{{nodes}}" wx:key="index" wx:for-item="n">
<rich-text wx:if="{{n.en||n.svg||n.err}}" class="_svg" nodes="{{[n]}}" />
<!--图片-->
<image wx:elif="{{n.name=='img'}}" class="_img" style="{{n.attrs.style}}" src="{{n.attrs.src}}" lazy-load="{{lazyLoad}}" mode="{{n.mode||'widthFix'}}" show-menu-by-longpress="{{!n.attrs.ignore}}" webp="{{n.webp}}" data-attrs="{{n.attrs}}" data-i="{{index}}" data-auto="{{n.auto}}" data-source="img" bindtap="imgtap" bindload="{{canIUse?handler.load:'loadImg'}}" binderror="error" />
<!--文本-->
<text wx:elif="{{n.type=='text'}}" decode>{{n.text}}</text>
<text wx:elif="{{n.name=='br'}}">\n</text>
<!--链接-->
<view wx:elif="{{n.name=='a'}}" class="_a {{n.attrs.class}}" hover-class="_hover" style="{{n.attrs.style}}" data-attrs="{{n.attrs}}" bindtap="{{canIUse?handler.visited:'linkpress'}}">
<trees nodes="{{n.children}}" />
</view>
<!--视频-->
<block wx:elif="{{n.name=='video'}}">
<view wx:if="{{n.lazyLoad}}" id="{{n.attrs.id}}" class="_video {{n.attrs.class}}" style="{{n.attrs.style}}" data-i="{{index}}" bindtap="loadVideo" />
<video wx:else id="{{n.attrs.id}}" class="{{n.attrs.class}}" style="{{n.attrs.style}}" autoplay="{{n.attrs.autoplay}}" controls="{{n.attrs.controls}}" loop="{{n.attrs.loop}}" muted="{{n.attrs.muted}}" poster="{{n.attrs.poster}}" src="{{n.attrs.source[n.i||0]}}" unit-id="{{n.attrs['unit-id']}}" data-i="{{index}}" data-source="video" binderror="error" bindplay="play" />
</block>
<!--音频-->
<audio wx:elif="{{n.name=='audio'}}" id="{{n.attrs.id}}" class="{{n.attrs.class}}" style="{{n.attrs.style}}" author="{{n.attrs.author}}" autoplay="{{n.attrs.autoplay}}" controls="{{n.attrs.controls}}" loop="{{n.attrs.loop}}" name="{{n.attrs.name}}" poster="{{n.attrs.poster}}" src="{{n.attrs.source[n.i||0]}}" data-i="{{index}}" data-source="audio" binderror="error" bindplay="play" />
<!--广告-->
<ad wx:elif="{{n.name=='ad'}}" class="{{n.attrs.class}}" style="{{n.attrs.style}}" unit-id="{{n.attrs['unit-id']}}" data-source="ad" binderror="error" />
<!--列表-->
<view wx:elif="{{n.name=='li'}}" class="{{n.attrs.class}}" style="{{n.attrs.style}};display:flex">
<view wx:if="{{n.type=='ol'}}" class="_ol-bef">{{n.num}}</view>
<view wx:else class="_ul-bef">
<view wx:if="{{n.floor%3==0}}" class="_ul-p1">█</view>
<view wx:elif="{{n.floor%3==2}}" class="_ul-p2" />
<view wx:else class="_ul-p1" style="border-radius:50%">█</view>
</view>
<trees class="_node _li" lazy-load="{{lazyLoad}}" nodes="{{n.children}}" />
</view>
<!--富文本-->
<rich-text wx:elif="{{handler.useRichText(n)}}" id="{{n.attrs.id}}" class="_p __{{n.name}}" nodes="{{[n]}}" />
<!--继续递归-->
<trees wx:else id="{{n.attrs.id}}" class="_node _{{n.name}} {{n.attrs.class}}" style="{{n.attrs.style}}" lazy-load="{{lazyLoad}}" nodes="{{n.children}}" />
</block>
\ No newline at end of file
.navigator-hover{opacity:.7;text-decoration:underline}:host{display:inherit;float:inherit}.a{display:inline;color:#366092}.sub,.sup,.bdo,.bdi,.ruby,.rt{display:inline-block!important}.div,.blockquote,.p{display:block}.b,.strong{display:inline;font-weight:bold}.em,.i{display:inline;font-style:italic}.del{display:inline;text-decoration:line-through}.ins{display:inline;text-decoration:underline}.code{display:inline;font-family:monospace}.big{font-size:1.2em;display:inline}.small{font-size:.8em;display:inline}.q,.span,.label,.abbr{display:inline}.q::before{content:'"'}.q::after{content:'"'}.pvideo{background-color:black;width:300px;height:225px;display:inline-block;position:relative}.video-triangle{border-width:15px 0 15px 30px;border-style:solid;border-color:transparent transparent transparent white;position:absolute;left:50%;top:50%;margin:-15px 0 0 -15px}
\ No newline at end of file
/* 在这里引入自定义样式 */
/* 链接和图片效果 */
._a {
color: #366092;
display: inline;
padding: 1.5px 0 1.5px 0;
word-break: break-all;
}
._hover {
opacity: 0.7;
text-decoration: underline;
}
._visited {
color: #551a8b;
}
._img {
height: 50px;
max-width: 100%;
}
/* 内部样式 */
:host {
display: inline;
}
._blockquote, ._div, ._p, ._ul, ._ol, ._li {
display: block;
}
._b, ._strong {
font-weight: bold;
}
._code {
font-family: monospace;
}
._del {
text-decoration: line-through;
}
._em, ._i {
font-style: italic;
}
._h1 {
font-size: 2em;
}
._h2 {
font-size: 1.5em;
}
._h3 {
font-size: 1.17em;
}
._h5 {
font-size: 0.83em;
}
._h6 {
font-size: 0.67em;
}
._h1, ._h2, ._h3, ._h4, ._h5, ._h6 {
display: block;
font-weight: bold;
}
._ins {
text-decoration: underline;
}
._li {
flex: 1;
width: 0;
}
._ol-bef {
margin-right: 5px;
text-align: right;
width: 36px;
}
._ul-bef {
line-height: normal;
margin: 0 12px 0 23px;
}
._ol-bef, ._ul_bef {
flex: none;
user-select: none;
}
._ul-p1 {
display: inline-block;
height: 0.3em;
line-height: 0.3em;
overflow: hidden;
width: 0.3em;
}
._ul-p2 {
border: 0.05em solid black;
border-radius: 50%;
display: inline-block;
height: 0.23em;
width: 0.23em;
}
._q::before {
content: '"';
}
._q::after {
content: '"';
}
._sub {
font-size: smaller;
vertical-align: sub;
}
._sup {
font-size: smaller;
vertical-align: super;
}
.__bdi, .__bdo, .__ruby, .__rt, ._svg {
display: inline-block;
}
._video {
background-color: black;
display: inline-block;
height: 225px;
position: relative;
width: 300px;
}
._video::after {
border-left-color: white;
border-style: solid;
border-width: 15px 0 15px 30px;
content: '';
left: 50%;
margin: -15px 0 0 -15px;
position: absolute;
top: 50%;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment