Repository: ssssssss-team/spider-flow Branch: master Commit: c799cca99c7d Files: 213 Total size: 4.0 MB Directory structure: gitextract_2yt2vx0u/ ├── .gitattributes ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── db/ │ └── spiderflow.sql ├── pom.xml ├── spider-flow-api/ │ ├── pom.xml │ └── src/ │ └── main/ │ └── java/ │ └── org/ │ └── spiderflow/ │ ├── ExpressionEngine.java │ ├── Grammerable.java │ ├── annotation/ │ │ ├── Comment.java │ │ ├── Example.java │ │ └── Return.java │ ├── common/ │ │ └── CURDController.java │ ├── concurrent/ │ │ ├── ChildPriorThreadSubmitStrategy.java │ │ ├── LinkedThreadSubmitStrategy.java │ │ ├── ParentPriorThreadSubmitStrategy.java │ │ ├── RandomThreadSubmitStrategy.java │ │ ├── SpiderFlowThreadPoolExecutor.java │ │ ├── SpiderFutureTask.java │ │ └── ThreadSubmitStrategy.java │ ├── context/ │ │ ├── CookieContext.java │ │ ├── SpiderContext.java │ │ └── SpiderContextHolder.java │ ├── enums/ │ │ ├── FlowNoticeType.java │ │ └── FlowNoticeWay.java │ ├── executor/ │ │ ├── FunctionExecutor.java │ │ ├── FunctionExtension.java │ │ ├── PluginConfig.java │ │ └── ShapeExecutor.java │ ├── expression/ │ │ └── DynamicMethod.java │ ├── io/ │ │ ├── Line.java │ │ ├── RandomAccessFileReader.java │ │ └── SpiderResponse.java │ ├── listener/ │ │ └── SpiderListener.java │ ├── model/ │ │ ├── Grammer.java │ │ ├── JsonBean.java │ │ ├── Plugin.java │ │ ├── Shape.java │ │ ├── SpiderLog.java │ │ ├── SpiderNode.java │ │ └── SpiderOutput.java │ └── utils/ │ └── Maps.java ├── spider-flow-core/ │ ├── pom.xml │ └── src/ │ └── main/ │ └── java/ │ └── org/ │ └── spiderflow/ │ └── core/ │ ├── Spider.java │ ├── executor/ │ │ ├── function/ │ │ │ ├── Base64FunctionExecutor.java │ │ │ ├── DateFunctionExecutor.java │ │ │ ├── ExtractFunctionExecutor.java │ │ │ ├── FileFunctionExecutor.java │ │ │ ├── JsonFunctionExecutor.java │ │ │ ├── ListFunctionExecutor.java │ │ │ ├── MD5FunctionExecutor.java │ │ │ ├── RandomFunctionExecutor.java │ │ │ ├── StringFunctionExecutor.java │ │ │ ├── ThreadFunctionExecutor.java │ │ │ ├── UrlFunctionExecutor.java │ │ │ └── extension/ │ │ │ ├── ArrayFunctionExtension.java │ │ │ ├── DateFunctionExtension.java │ │ │ ├── ElementFunctionExtension.java │ │ │ ├── ElementsFunctionExtension.java │ │ │ ├── ListFunctionExtension.java │ │ │ ├── MapFunctionExtension.java │ │ │ ├── ObjectFunctionExtension.java │ │ │ ├── ResponseFunctionExtension.java │ │ │ ├── SqlRowSetExtension.java │ │ │ └── StringFunctionExtension.java │ │ └── shape/ │ │ ├── CommentExecutor.java │ │ ├── ExecuteSQLExecutor.java │ │ ├── ForkJoinExecutor.java │ │ ├── FunctionExecutor.java │ │ ├── LoopExecutor.java │ │ ├── OutputExecutor.java │ │ ├── ProcessExecutor.java │ │ ├── RequestExecutor.java │ │ ├── StartExecutor.java │ │ └── VariableExecutor.java │ ├── expression/ │ │ ├── DefaultExpressionEngine.java │ │ ├── ExpressionError.java │ │ ├── ExpressionGlobalVariables.java │ │ ├── ExpressionTemplate.java │ │ ├── ExpressionTemplateContext.java │ │ ├── interpreter/ │ │ │ ├── AstInterpreter.java │ │ │ ├── JavaReflection.java │ │ │ └── Reflection.java │ │ └── parsing/ │ │ ├── Ast.java │ │ ├── CharacterStream.java │ │ ├── Parser.java │ │ ├── Span.java │ │ ├── Token.java │ │ ├── TokenStream.java │ │ ├── TokenType.java │ │ └── Tokenizer.java │ ├── io/ │ │ ├── HttpRequest.java │ │ └── HttpResponse.java │ ├── job/ │ │ ├── SpiderJob.java │ │ ├── SpiderJobContext.java │ │ └── SpiderJobManager.java │ ├── mapper/ │ │ ├── DataSourceMapper.java │ │ ├── FlowNoticeMapper.java │ │ ├── FunctionMapper.java │ │ ├── SpiderFlowMapper.java │ │ ├── TaskMapper.java │ │ └── VariableMapper.java │ ├── model/ │ │ ├── DataSource.java │ │ ├── FlowNotice.java │ │ ├── Function.java │ │ ├── SpiderFlow.java │ │ ├── Task.java │ │ └── Variable.java │ ├── script/ │ │ └── ScriptManager.java │ ├── serializer/ │ │ └── FastJsonSerializer.java │ ├── service/ │ │ ├── DataSourceService.java │ │ ├── FlowNoticeService.java │ │ ├── FunctionService.java │ │ ├── SpiderFlowService.java │ │ ├── TaskService.java │ │ └── VariableService.java │ └── utils/ │ ├── DataSourceUtils.java │ ├── EmailUtils.java │ ├── ExecutorsUtils.java │ ├── ExpressionUtils.java │ ├── ExtractUtils.java │ ├── FileUtils.java │ └── SpiderFlowUtils.java └── spider-flow-web/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── org/ │ └── spiderflow/ │ ├── SpiderApplication.java │ ├── configuration/ │ │ ├── ResourcesConfiguration.java │ │ └── WebSocketConfiguration.java │ ├── controller/ │ │ ├── DataSourceController.java │ │ ├── FlowNoticeController.java │ │ ├── FunctionController.java │ │ ├── SpiderFlowController.java │ │ ├── SpiderRestController.java │ │ ├── TaskController.java │ │ └── VariableController.java │ ├── logback/ │ │ ├── SpiderFlowFileAppender.java │ │ └── SpiderFlowWebSocketAppender.java │ ├── model/ │ │ ├── SpiderWebSocketContext.java │ │ └── WebSocketEvent.java │ └── websocket/ │ └── WebSocketEditorServer.java └── resources/ ├── application.properties ├── logback-spring.xml └── static/ ├── css/ │ ├── easyui.css │ ├── editor.css │ ├── index.css │ ├── layui-black-gray.css │ └── layui-blue.css ├── datasource-edit.html ├── datasources.html ├── editCron.html ├── editor.html ├── function-edit.html ├── functions.html ├── index.html ├── js/ │ ├── canvas-viewer.js │ ├── codemirror/ │ │ ├── codemirror.css │ │ ├── codemirror.js │ │ ├── dracula.css │ │ ├── idea.css │ │ ├── javascript.js │ │ ├── placeholder.js │ │ ├── show-hint.css │ │ ├── show-hint.js │ │ ├── spiderflow-hint.js │ │ ├── spiderflow.js │ │ └── sql.js │ ├── common.js │ ├── cron/ │ │ └── cron.js │ ├── editor.js │ ├── index.js │ ├── jsontree/ │ │ ├── jsontree.css │ │ └── jsontree.js │ ├── layui/ │ │ ├── css/ │ │ │ ├── layui.css │ │ │ ├── layui.mobile.css │ │ │ └── modules/ │ │ │ ├── code.css │ │ │ ├── laydate/ │ │ │ │ └── default/ │ │ │ │ └── laydate.css │ │ │ └── layer/ │ │ │ └── default/ │ │ │ └── layer.css │ │ ├── ext/ │ │ │ ├── eleTree/ │ │ │ │ ├── eleTree.css │ │ │ │ └── eleTree.js │ │ │ └── treeselect/ │ │ │ └── treeselect.js │ │ ├── extends/ │ │ │ ├── formSelects-v4.css │ │ │ ├── formSelects-v4.js │ │ │ └── treeGrid.js │ │ └── layui.all.js │ ├── log-viewer.js │ ├── mxgraph/ │ │ ├── css/ │ │ │ ├── common.css │ │ │ └── explorer.css │ │ ├── mxgraph.js │ │ └── resources/ │ │ ├── editor.txt │ │ ├── editor_de.txt │ │ ├── editor_zh.txt │ │ ├── graph.txt │ │ ├── graph_de.txt │ │ └── graph_zh.txt │ └── spider-editor.js ├── log.html ├── resources/ │ └── templates/ │ ├── comment.html │ ├── edge.html │ ├── executeSql.html │ ├── forkJoin.html │ ├── function.html │ ├── loop.html │ ├── output.html │ ├── process.html │ ├── request.html │ ├── root.html │ ├── start.html │ └── variable.html ├── spiderList-notice.html ├── spiderList.html ├── task.html ├── variable-edit.html └── variables.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ *.js linguist-language=java *.css linguist-language=java *.html linguist-language=java ================================================ FILE: .gitignore ================================================ target *.iml out/ .idea .classpath .project .settings bin/ .myeclipse ================================================ FILE: Dockerfile ================================================ FROM java:8 MAINTAINER octopus RUN mkdir -p /spider-flow WORKDIR /spider-flow EXPOSE 8088 ADD ./spider-flow-web/target/spider-flow.jar ./ CMD sleep 30;java -Djava.security.egd=file:/dev/./urandom -jar spider-flow.jar ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 小东 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

[介绍](#介绍) | [特性](#特性) | [插件](#插件) | DEMO站点 | 文档 | 更新日志 | [截图](#项目部分截图) | [其它开源](#其它开源项目) | [免责声明](#免责声明) ## 介绍 平台以流程图的方式定义爬虫,是一个高度灵活可配置的爬虫平台 ## 特性 - [x] 支持Xpath/JsonPath/css选择器/正则提取/混搭提取 - [x] 支持JSON/XML/二进制格式 - [x] 支持多数据源、SQL select/selectInt/selectOne/insert/update/delete - [x] 支持爬取JS动态渲染(或ajax)的页面 - [x] 支持代理 - [x] 支持自动保存至数据库/文件 - [x] 常用字符串、日期、文件、加解密等函数 - [x] 支持插件扩展(自定义执行器,自定义方法) - [x] 任务监控,任务日志 - [x] 支持HTTP接口 - [x] 支持Cookie自动管理 - [x] 支持自定义函数 ## 插件 - [x] [Selenium插件](https://gitee.com/ssssssss-team/spider-flow-selenium) - [x] [Redis插件](https://gitee.com/ssssssss-team/spider-flow-redis) - [x] [OSS插件](https://gitee.com/ssssssss-team/spider-flow-oss) - [x] [Mongodb插件](https://gitee.com/ssssssss-team/spider-flow-mongodb) - [x] [IP代理池插件](https://gitee.com/ssssssss-team/spider-flow-proxypool) - [x] [OCR识别插件](https://gitee.com/ssssssss-team/spider-flow-ocr) - [x] [电子邮箱插件](https://gitee.com/ssssssss-team/spider-flow-mailbox) ## 项目部分截图 ### 爬虫列表 ![爬虫列表](https://images.gitee.com/uploads/images/2020/0412/104521_e1eb3fbb_297689.png "list.png") ### 爬虫测试 ![爬虫测试](https://images.gitee.com/uploads/images/2020/0412/104659_b06dfbf0_297689.gif "test.gif") ### Debug ![Debug](https://images.gitee.com/uploads/images/2020/0412/104741_f9e1190e_297689.png "debug.png") ### 日志 ![日志](https://images.gitee.com/uploads/images/2020/0412/104800_a757f569_297689.png "logo.png") ## 其它开源项目 - [spider-flow-vue,spider-flow的前端](https://gitee.com/ssssssss-team/spider-flow-vue) - [magic-api,一个以XML为基础自动映射为HTTP接口的框架](https://gitee.com/ssssssss-team/magic-api) - [magic-api-spring-boot-starter](https://gitee.com/ssssssss-team/magic-api-spring-boot-starter) ## 免责声明 请勿将`spider-flow`应用到任何可能会违反法律规定和道德约束的工作中,请友善使用`spider-flow`,遵守蜘蛛协议,不要将`spider-flow`用于任何非法用途。如您选择使用`spider-flow`即代表您遵守此协议,作者不承担任何由于您违反此协议带来任何的法律风险和损失,一切后果由您承担。 ================================================ FILE: db/spiderflow.sql ================================================ SET FOREIGN_KEY_CHECKS=0; CREATE DATABASE spiderflow; USE spiderflow; DROP TABLE IF EXISTS `sp_flow`; CREATE TABLE `sp_flow` ( `id` varchar(32) NOT NULL, `name` varchar(64) DEFAULT NULL COMMENT '任务名字', `xml` longtext DEFAULT NULL COMMENT 'xml表达式', `cron` varchar(255) DEFAULT NULL COMMENT 'corn表达式', `enabled` char(1) DEFAULT '0' COMMENT '任务是否启动,默认未启动', `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `last_execute_time` datetime DEFAULT NULL COMMENT '上一次执行时间', `next_execute_time` datetime DEFAULT NULL COMMENT '下一次执行时间', `execute_count` int(8) DEFAULT NULL COMMENT '定时执行的已执行次数', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '爬虫任务表'; INSERT INTO `sp_flow` VALUES ('b45fb98d2a564c23ba623a377d5e12e9', '爬取码云GVP', '\n \n \n \n {"spiderName":"爬取码云GVP","threadCount":""}\n \n \n \n \n \n \n {"shape":"start"}\n \n \n \n \n \n {"value":"抓取首页","loopVariableName":"","sleep":"","timeout":"","response-charset":"","method":"GET","body-type":"none","body-content-type":"text/plain","loopCount":"","url":"https://gitee.com/gvp/all","proxy":"","request-body":[""],"follow-redirect":"1","shape":"request"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"提取项目名、地址","loopVariableName":"","variable-name":["projectUrls","projectNames"],"loopCount":"","variable-value":["${extract.selectors(resp.html,'.categorical-project-card a','attr','href')}","${extract.selectors(resp.html,'.project-name')}"],"shape":"variable"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"抓取详情页","loopVariableName":"projectIndex","sleep":"","timeout":"","response-charset":"","method":"GET","body-type":"none","body-content-type":"text/plain","loopCount":"10","url":"https://gitee.com/${projectUrls[projectIndex]}","proxy":"","request-body":[""],"follow-redirect":"1","shape":"request"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"提取项目描述","loopVariableName":"","variable-name":["projectDesc"],"loopCount":"","variable-value":["${extract.selector(resp.html,'.git-project-desc-text')}"],"shape":"variable"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"输出","output-name":["项目名","项目地址","项目描述"],"output-value":["${projectNames[projectIndex]}","https://gitee.com${projectUrls[projectIndex]}","${projectDesc}"],"shape":"output"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n\n', null, '0', '2019-08-22 13:46:54', null, null, null); INSERT INTO `sp_flow` VALUES ('f0a67f17ee1a498a9b2f4ca30556f3c3', '抓取每日菜价', '\n \n \n \n {"spiderName":"抓取每日菜价","threadCount":""}\n \n \n \n \n \n \n {"shape":"start"}\n \n \n \n \n \n {"value":"开始抓取","loopVariableName":"","sleep":"","timeout":"","response-charset":"","method":"GET","body-type":"none","body-content-type":"text/plain","loopCount":"","url":"http://www.beijingprice.cn:8086/price/priceToday/PageLoad/LoadPrice?jsoncallback=1","proxy":"","request-body":[""],"follow-redirect":"1","shape":"request"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"解析JSON","loopVariableName":"","variable-name":["jsonstr","jsondata","data"],"loopCount":"","variable-value":["${string.substring(resp.html,2,resp.html.length()-1)}","${json.parse(jsonstr)}","${extract.jsonpath(jsondata[0],'data')}"],"shape":"variable"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"输出","loopVariableName":"i","output-name":["菜名","菜价","单位"],"loopCount":"${list.length(data)}","output-value":["${data[i].ItemName}","${data[i].Price04}","${data[i].ItemUnit}"],"shape":"output"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n\n', null, '0', '2019-08-22 13:48:22', null, null, null); INSERT INTO `sp_flow` VALUES ('b4430885ba8349588d1220d37eac831d', '爬取开源中国动弹', '\n \n \n \n {"spiderName":"爬取开源中国动弹","threadCount":""}\n \n \n \n \n \n \n {"shape":"start"}\n \n \n \n \n \n {"value":"爬取动弹","loopVariableName":"","sleep":"","timeout":"","response-charset":"","method":"GET","parameter-name":["type","lastLogId"],"body-type":"none","body-content-type":"text/plain","loopCount":"","url":"https://www.oschina.net/tweets/widgets/_tweet_index_list ","proxy":"","parameter-value":["ajax","${lastLogId}"],"request-body":"","follow-redirect":"1","tls-validate":"1","shape":"request"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"提取lastLogId以及tweets","loopVariableName":"","variable-name":["lastLogId","tweets","fetchCount"],"loopCount":"","variable-value":["${resp.selector('.tweet-item:last-child').attr('data-tweet-id')}","${resp.selectors('.tweet-item[data-tweet-id]')}","${fetchCount == null ? 0 : fetchCount + 1}"],"shape":"variable"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"循环","loopVariableName":"index","loopCount":"${list.length(tweets)}","shape":"loop"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"提取详细信息","loopVariableName":"","variable-name":["content","author","like","reply","publishTime"],"loopCount":"","variable-value":["${tweets[index].selector('.text').text()}","${tweets[index].selector('.user').text()}","${tweets[index].selector('.like span').text()}","${tweets[index].selector('.reply span').text()}","${tweets[index].selector('.date').regx('(.*?)&nbsp')}"],"shape":"variable"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"输出","loopVariableName":"","output-name":["作者","内容","点赞数","评论数","发布时间"],"loopCount":"","output-value":["${author}","${content}","${like}","${reply}","${publishTime}"],"shape":"output"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n \n \n \n \n \n \n {"value":"爬取5页","condition":"${fetchCount < 3}"}\n \n \n \n\n', '', '0', '2019-11-03 17:02:49', '2019-11-04 10:11:31', '2019-11-03 17:30:56', '3'); INSERT INTO `sp_flow` VALUES ('663aaa5e36a84c9594ef3cfd6738e9a7', '百度热点', '\n \n \n \n {"spiderName":"百度热点","threadCount":""}\n \n \n \n \n \n \n {"shape":"start"}\n \n \n \n \n \n {"value":"开始抓取","loopVariableName":"","sleep":"","timeout":"","response-charset":"gbk","method":"GET","body-type":"none","body-content-type":"text/plain","loopCount":"","url":"https://top.baidu.com/buzz?b=1&fr=topindex","proxy":"","request-body":"","follow-redirect":"1","tls-validate":"1","shape":"request"}\n \n \n \n \n \n {"value":"定义变量","loopVariableName":"","variable-name":["elementbd"],"loopCount":"","variable-value":["${resp.xpaths('//*[@id=\\"main\\"]/div[2]/div/table/tbody/tr')}"],"shape":"variable"}\n \n \n \n \n \n {"value":"输出","loopVariableName":"i","output-name":["名称","地址","百度指数","2"],"loopCount":"${elementbd.size()-1}","output-value":["${elementbd[i+1].xpath('//td[2]/a[1]/text()')}","${elementbd[i+1].xpath('//td[2]/a[1]/@href')}","${elementbd[i+1].xpath('//td[4]/span/text()')}","${elementbd[i+1].xpath('//td[3]/a[2]/text()')}"],"shape":"output"}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n \n \n {"value":"","condition":""}\n \n \n \n\n', '0 0/30 * * * ? *', '1', '2019-10-20 17:24:21', '2019-11-04 08:52:05', '2019-10-30 14:52:39', '45'); DROP TABLE IF EXISTS `sp_datasource`; CREATE TABLE `sp_datasource` ( `id` varchar(32) NOT NULL, `name` varchar(255) DEFAULT NULL, `driver_class_name` varchar(255) DEFAULT NULL, `jdbc_url` varchar(255) DEFAULT NULL, `username` varchar(64) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; DROP TABLE IF EXISTS `sp_variable`; CREATE TABLE `sp_variable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL COMMENT '变量名', `value` varchar(512) DEFAULT NULL COMMENT '变量值', `description` varchar(255) DEFAULT NULL COMMENT '变量描述', `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4; /* v0.3.0 新增 */ DROP TABLE IF EXISTS `sp_task`; CREATE TABLE `sp_task` ( `id` int(11) NOT NULL AUTO_INCREMENT, `flow_id` varchar(32) NOT NULL, `begin_time` datetime DEFAULT NULL, `end_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4; /* v0.4.0 新增 */ DROP TABLE IF EXISTS `sp_function`; CREATE TABLE `sp_function` ( `id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '函数名', `parameter` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '参数', `script` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'js脚本', `create_date` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; /* v0.5.0 新增 */ DROP TABLE IF EXISTS `sp_flow_notice`; CREATE TABLE `sp_flow_notice` ( `id` varchar(32) NOT NULL, `recipients` varchar(200) DEFAULT NULL COMMENT '收件人', `notice_way` char(10) DEFAULT NULL COMMENT '通知方式', `start_notice` char(1) DEFAULT '0' COMMENT '流程开始通知:1:开启通知,0:关闭通知', `exception_notice` char(1) DEFAULT '0' COMMENT '流程异常通知:1:开启通知,0:关闭通知', `end_notice` char(1) DEFAULT '0' COMMENT '流程结束通知:1:开启通知,0:关闭通知', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '爬虫任务通知表'; ================================================ FILE: pom.xml ================================================ 4.0.0 org.spiderflow spider-flow 0.5.0 pom spider-flow https://gitee.com/jmxd/spider-flow org.springframework.boot spring-boot-starter-parent 2.0.7.RELEASE UTF-8 ${project.version} 1.2.83 1.1.16 2.11.5 3.1.0 1.6 1.8 2.7 28.2-jre 1.11.3 0.3.1 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-quartz org.springframework.boot spring-boot-starter-mail org.springframework spring-jdbc org.springframework.boot spring-boot-starter-websocket com.baomidou mybatis-plus-boot-starter ${mybatis.plus.version} mysql mysql-connector-java com.alibaba fastjson ${alibaba.fastjson.version} com.alibaba druid-spring-boot-starter ${alibaba.druid.version} com.alibaba transmittable-thread-local ${alibaba.transmittable.version} org.apache.commons commons-text ${apache.commons.text.verion} org.apache.commons commons-csv ${apache.commons.csv.verion} commons-io commons-io ${commons.io.version} commons-codec commons-codec com.google.guava guava ${guava.version} org.jsoup jsoup ${jsoup.version} us.codecraft xsoup ${xsoup.version} org.spiderflow spider-flow-api ${spider-flow.version} org.spiderflow spider-flow-core ${spider-flow.version} org.spiderflow spider-flow-selenium ${spider-flow.version} org.spiderflow spider-flow-proxypool ${spider-flow.version} org.spiderflow spider-flow-mongodb ${spider-flow.version} org.spiderflow spider-flow-redis ${spider-flow.version} org.spiderflow spider-flow-ocr ${spider-flow.version} org.spiderflow spider-flow-oss ${spider-flow.version} org.spiderflow spider-flow-mailbox ${spider-flow.version} spider-flow-api spider-flow-core spider-flow-web ================================================ FILE: spider-flow-api/pom.xml ================================================ 4.0.0 org.spiderflow spider-flow 0.5.0 spider-flow-api spider-flow-api https://gitee.com/jmxd/spider-flow/tree/master/spider-flow-api UTF-8 ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/ExpressionEngine.java ================================================ package org.spiderflow; import java.util.Map; /** * 表达式引擎 */ public interface ExpressionEngine { /** * 执行表达式 * @param expression 表达式 * @param variables 变量 * @return */ Object execute(String expression, Map variables); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/Grammerable.java ================================================ package org.spiderflow; import java.util.List; import org.spiderflow.model.Grammer; public interface Grammerable { List grammers(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/annotation/Comment.java ================================================ package org.spiderflow.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 该注解用来标注自定义的方法注释,用来页面代码提示 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.TYPE}) public @interface Comment { String value(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/annotation/Example.java ================================================ package org.spiderflow.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 该注解用来标注自定义的方法注释,用来页面代码案例 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Example { String value(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/annotation/Return.java ================================================ package org.spiderflow.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 该注解用来标注自定义的方法注释,用来页面提示返回值类型 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Return { Class[] value(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/common/CURDController.java ================================================ package org.spiderflow.common; import org.spiderflow.model.JsonBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; public abstract class CURDController,M extends BaseMapper, T> { @Autowired private S service; @RequestMapping("/list") public IPage list(@RequestParam(name = "page",defaultValue = "1")Integer page, @RequestParam(name = "limit",defaultValue = "1")Integer size){ return service.page(new Page(page, size), new QueryWrapper().orderByDesc("create_date")); } @RequestMapping("get") public JsonBean get(String id) { return new JsonBean(service.getById(id)); } @RequestMapping("delete") public JsonBean delete(String id){ return new JsonBean(service.removeById(id)); } @RequestMapping("save") public JsonBean save(T t){ return new JsonBean(service.saveOrUpdate(t)); } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/ChildPriorThreadSubmitStrategy.java ================================================ package org.spiderflow.concurrent; import org.spiderflow.model.SpiderNode; import java.util.Comparator; import java.util.PriorityQueue; public class ChildPriorThreadSubmitStrategy implements ThreadSubmitStrategy{ private Object mutex = this; private Comparator comparator = (o1, o2) -> { if(o1.hasLeftNode(o2.getNodeId())){ return -1; } return 1; }; private PriorityQueue> priorityQueue = new PriorityQueue<>((o1, o2) -> comparator.compare(o1.getNode(),o2.getNode())); @Override public Comparator comparator() { return comparator; } @Override public void add(SpiderFutureTask task) { synchronized (mutex){ priorityQueue.add(task); } } @Override public boolean isEmpty() { synchronized (mutex){ return priorityQueue.isEmpty(); } } @Override public SpiderFutureTask get() { synchronized (mutex){ return priorityQueue.poll(); } } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/LinkedThreadSubmitStrategy.java ================================================ package org.spiderflow.concurrent; import org.spiderflow.model.SpiderNode; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class LinkedThreadSubmitStrategy implements ThreadSubmitStrategy{ private List> taskList = new CopyOnWriteArrayList<>(); @Override public Comparator comparator() { return (o1, o2) -> -1; } @Override public void add(SpiderFutureTask task) { taskList.add(task); } @Override public boolean isEmpty() { return taskList.isEmpty(); } @Override public SpiderFutureTask get() { return taskList.remove(0); } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/ParentPriorThreadSubmitStrategy.java ================================================ package org.spiderflow.concurrent; import org.spiderflow.model.SpiderNode; import java.util.Comparator; import java.util.PriorityQueue; public class ParentPriorThreadSubmitStrategy implements ThreadSubmitStrategy { private Object mutex = this; private Comparator comparator = (o1, o2) -> { if (o1.hasLeftNode(o2.getNodeId())) { return 1; } return -1; }; private PriorityQueue> priorityQueue = new PriorityQueue<>((o1, o2) -> comparator.compare(o1.getNode(), o2.getNode())); @Override public Comparator comparator() { return comparator; } @Override public void add(SpiderFutureTask task) { synchronized (mutex) { priorityQueue.add(task); } } @Override public boolean isEmpty() { synchronized (mutex) { return priorityQueue.isEmpty(); } } @Override public SpiderFutureTask get() { synchronized (mutex) { return priorityQueue.poll(); } } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/RandomThreadSubmitStrategy.java ================================================ package org.spiderflow.concurrent; import org.apache.commons.lang3.RandomUtils; import org.spiderflow.model.SpiderNode; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class RandomThreadSubmitStrategy implements ThreadSubmitStrategy{ private List> taskList = new CopyOnWriteArrayList<>(); @Override public Comparator comparator() { return (o1, o2) -> RandomUtils.nextInt(0,3) - 1; } @Override public void add(SpiderFutureTask task) { taskList.add(task); } @Override public boolean isEmpty() { return taskList.isEmpty(); } @Override public SpiderFutureTask get() { return taskList.remove(RandomUtils.nextInt(0, taskList.size())); } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/SpiderFlowThreadPoolExecutor.java ================================================ package org.spiderflow.concurrent; import org.spiderflow.model.SpiderNode; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class SpiderFlowThreadPoolExecutor { /** * 最大线程数 */ private int maxThreads; /** * 真正线程池 */ private ThreadPoolExecutor executor; /** * 线程number计数器 */ private final AtomicInteger poolNumber = new AtomicInteger(1); /** * ThreadGroup */ private static final ThreadGroup SPIDER_FLOW_THREAD_GROUP = new ThreadGroup("spider-flow-group"); /** * 线程名称前缀 */ private static final String THREAD_POOL_NAME_PREFIX = "spider-flow-"; public SpiderFlowThreadPoolExecutor(int maxThreads) { super(); this.maxThreads = maxThreads; //创建线程池实例 this.executor = new ThreadPoolExecutor(maxThreads, maxThreads, 10, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), runnable -> { //重写线程名称 return new Thread(SPIDER_FLOW_THREAD_GROUP, runnable, THREAD_POOL_NAME_PREFIX + poolNumber.getAndIncrement()); }); } public Future submit(Runnable runnable){ return this.executor.submit(runnable); } /** * 创建子线程池 * @param threads 线程池大小 * @return */ public SubThreadPoolExecutor createSubThreadPoolExecutor(int threads,ThreadSubmitStrategy submitStrategy){ return new SubThreadPoolExecutor(Math.min(maxThreads, threads),submitStrategy); } /** * 子线程池 */ public class SubThreadPoolExecutor{ /** * 线程池大小 */ private int threads; /** * 正在执行中的任务 */ private Future[] futures; /** * 执行中的数量 */ private AtomicInteger executing = new AtomicInteger(0); /** * 是否运行中 */ private volatile boolean running = true; /** * 是否提交任务中 */ private volatile boolean submitting = false; private ThreadSubmitStrategy submitStrategy; public SubThreadPoolExecutor(int threads,ThreadSubmitStrategy submitStrategy) { super(); this.threads = threads; this.futures = new Future[threads]; this.submitStrategy = submitStrategy; } /** * 等待所有线程执行完毕 */ public void awaitTermination(){ while(executing.get() > 0){ removeDoneFuture(); } running = false; //当停止时,唤醒提交任务线程使其结束 synchronized (submitStrategy){ submitStrategy.notifyAll(); } } private int index(){ for (int i = 0; i < threads; i++) { if(futures[i] == null || futures[i].isDone()){ return i; } } return -1; } /** * 清除已完成的任务 */ private void removeDoneFuture(){ for (int i = 0; i < threads; i++) { try { if(futures[i] != null && futures[i].get(10,TimeUnit.MILLISECONDS) == null){ futures[i] = null; } } catch (Throwable t) { //忽略异常 } } } /** * 等待有空闲线程 */ private void await(){ while(index() == -1){ removeDoneFuture(); } } /** * 异步提交任务 */ public Future submitAsync(Runnable runnable, T value, SpiderNode node){ SpiderFutureTask future = new SpiderFutureTask<>(()-> { try { //执行任务 runnable.run(); } finally { //正在执行的线程数-1 executing.decrementAndGet(); } }, value,node,this); submitStrategy.add(future); //如果是第一次调用submitSync方法,则启动提交任务线程 if(!submitting){ submitting = true; CompletableFuture.runAsync(this::submit); } synchronized (submitStrategy){ //通知继续从集合中取任务提交到线程池中 submitStrategy.notifyAll(); } return future; } private void submit(){ while(running){ try { synchronized (submitStrategy){ //如果集合是空的,则等待提交 if(submitStrategy.isEmpty()){ submitStrategy.wait(); //等待唤醒 } } //当该线程被唤醒时,把集合中所有任务都提交到线程池中 while(!submitStrategy.isEmpty()){ //从提交策略中获取任务提交到线程池中 SpiderFutureTask futureTask = submitStrategy.get(); //如果没有空闲线程且在线程池中提交,则直接运行 if(index() == -1 && Thread.currentThread().getThreadGroup() == SPIDER_FLOW_THREAD_GROUP){ futureTask.run(); }else{ //等待有空闲线程时在提交 await(); //提交任务至线程池中 futures[index()] = executor.submit(futureTask); } } } catch (InterruptedException ignored) { } } } } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/SpiderFutureTask.java ================================================ package org.spiderflow.concurrent; import java.util.concurrent.FutureTask; import org.spiderflow.concurrent.SpiderFlowThreadPoolExecutor.SubThreadPoolExecutor; import org.spiderflow.model.SpiderNode; public class SpiderFutureTask extends FutureTask { private SubThreadPoolExecutor executor; private SpiderNode node; public SpiderFutureTask(Runnable runnable, V result, SpiderNode node,SubThreadPoolExecutor executor) { super(runnable,result); this.executor = executor; this.node = node; } public SubThreadPoolExecutor getExecutor() { return executor; } public SpiderNode getNode() { return node; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/concurrent/ThreadSubmitStrategy.java ================================================ package org.spiderflow.concurrent; import org.spiderflow.model.SpiderNode; import java.util.Comparator; public interface ThreadSubmitStrategy { Comparator comparator(); void add(SpiderFutureTask task); boolean isEmpty(); SpiderFutureTask get(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/context/CookieContext.java ================================================ package org.spiderflow.context; import java.util.HashMap; /** * Cookie上下文 */ public class CookieContext extends HashMap { } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/context/SpiderContext.java ================================================ package org.spiderflow.context; import org.spiderflow.concurrent.SpiderFlowThreadPoolExecutor.SubThreadPoolExecutor; import org.spiderflow.model.SpiderNode; import org.spiderflow.model.SpiderOutput; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.ReentrantLock; /** * 爬虫上下文 * @author jmxd * */ public class SpiderContext extends HashMap{ private String id = UUID.randomUUID().toString().replace("-", ""); /** * 流程ID */ private String flowId; private static final long serialVersionUID = 8379177178417619790L; /** * 流程执行线程 */ private SubThreadPoolExecutor threadPool; /** * 根节点 */ private SpiderNode rootNode; /** * 爬虫是否运行中 */ private volatile boolean running = true; /** * Future队列 */ private LinkedBlockingQueue> futureQueue = new LinkedBlockingQueue<>(); /** * Cookie上下文 */ private CookieContext cookieContext = new CookieContext(); public List getOutputs() { return Collections.emptyList(); } public T get(String key){ return (T) super.get(key); } public T get(String key,T defaultValue){ T value = this.get(key); return value == null ? defaultValue : value; } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public LinkedBlockingQueue> getFutureQueue() { return futureQueue; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } public void addOutput(SpiderOutput output){ } public SubThreadPoolExecutor getThreadPool() { return threadPool; } public void setThreadPool(SubThreadPoolExecutor threadPool) { this.threadPool = threadPool; } public SpiderNode getRootNode() { return rootNode; } public void setRootNode(SpiderNode rootNode) { this.rootNode = rootNode; } public String getId() { return id; } public CookieContext getCookieContext() { return cookieContext; } public void pause(String nodeId,String event,String key,Object value){} public void resume(){} public void stop(){} } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/context/SpiderContextHolder.java ================================================ package org.spiderflow.context; import com.alibaba.ttl.TransmittableThreadLocal; public class SpiderContextHolder { private static final ThreadLocal THREAD_LOCAL = new TransmittableThreadLocal<>(); public static SpiderContext get() { return THREAD_LOCAL.get(); } public static void set(SpiderContext context) { THREAD_LOCAL.set(context); } public static void remove() { THREAD_LOCAL.remove(); } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/enums/FlowNoticeType.java ================================================ package org.spiderflow.enums; /** * 流程通知类型 * * @author BillDowney * @date 2020年4月4日 上午1:32:53 */ public enum FlowNoticeType { /** * 流程开始通知 */ startNotice, /** * 流程异常通知 */ exceptionNotice, /** * 流程结束通知 */ endNotice } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/enums/FlowNoticeWay.java ================================================ package org.spiderflow.enums; import java.util.LinkedHashMap; import java.util.Map; /** * 流程通知方式 * * @author BillDowney * @date 2020年4月3日 下午3:26:18 */ public enum FlowNoticeWay { email("邮件通知"); private FlowNoticeWay(String title) { this.title = title; } private String title; @Override public String toString() { return this.name() + ":" + this.title; } public static Map getMap() { Map map = new LinkedHashMap(); for (FlowNoticeWay type : FlowNoticeWay.values()) { map.put(type.name(), type.toString()); } return map; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/executor/FunctionExecutor.java ================================================ package org.spiderflow.executor; public interface FunctionExecutor { String getFunctionPrefix(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/executor/FunctionExtension.java ================================================ package org.spiderflow.executor; public interface FunctionExtension { Class support(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/executor/PluginConfig.java ================================================ package org.spiderflow.executor; import org.spiderflow.model.Plugin; public interface PluginConfig { Plugin plugin(); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/executor/ShapeExecutor.java ================================================ package org.spiderflow.executor; import java.util.Map; import org.spiderflow.context.SpiderContext; import org.spiderflow.model.Shape; import org.spiderflow.model.SpiderNode; /** * 执行器接口 * @author jmxd * */ public interface ShapeExecutor { String LOOP_VARIABLE_NAME = "loopVariableName"; String LOOP_COUNT = "loopCount"; String THREAD_COUNT = "threadCount"; default Shape shape(){ return null; } /** * 节点形状 * @return 节点形状名称 */ String supportShape(); /** * 执行器具体的功能实现 * @param node 当前要执行的爬虫节点 * @param context 爬虫上下文 * @param variables 节点流程的全部变量的集合 */ void execute(SpiderNode node, SpiderContext context, Map variables); default boolean allowExecuteNext(SpiderNode node, SpiderContext context, Map variables){ return true; } default boolean isThread(){ return true; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/expression/DynamicMethod.java ================================================ package org.spiderflow.expression; import java.util.List; public interface DynamicMethod { Object execute(String methodName, List parameters); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/io/Line.java ================================================ package org.spiderflow.io; public class Line { private long from; private String text; private long to; public Line(long from, String text, long to) { this.from = from; this.text = text; this.to = to; } public long getFrom() { return from; } public void setFrom(long from) { this.from = from; } public String getText() { return text; } public void setText(String text) { this.text = text; } public long getTo() { return to; } public void setTo(long to) { this.to = to; } @Override public String toString() { return "Line{" + "from=" + from + ", text='" + text + '\'' + ", to=" + to + '}'; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/io/RandomAccessFileReader.java ================================================ package org.spiderflow.io; import java.io.Closeable; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class RandomAccessFileReader implements Closeable { private RandomAccessFile raf; /** * 从index位置开始读取 */ private long index; /** * 读取顺序,默认倒叙 */ private boolean reversed; /** * 缓冲区大小 */ private int bufSize; public RandomAccessFileReader(RandomAccessFile raf, long index, boolean reversed) throws IOException { this(raf, index, 1024, reversed); } public RandomAccessFileReader(RandomAccessFile raf, long index, int bufSize, boolean reversed) throws IOException { if (raf == null) { throw new NullPointerException("file is null"); } this.raf = raf; this.reversed = reversed; this.bufSize = bufSize; this.index = index; this.init(); } private void init() throws IOException { if (reversed) { this.index = this.index == -1 ? this.raf.length() : Math.min(this.index, this.raf.length()); } else { this.index = Math.min(Math.max(this.index, 0), this.raf.length()); } if (this.index > 0) { this.raf.seek(this.index); } } /** * 读取n行 * * @param n 要读取的行数 * @param keywords 搜索的关键词 * @param matchcase 是否区分大小写 * @param regx 是否是正则搜索 * @return 返回Line对象,包含行的起始位置与终止位置 */ public List readLine(int n, String keywords, boolean matchcase, boolean regx) throws IOException { List lines = new ArrayList<>(n); long lastCRLFIndex = reversed ? this.index : (this.index > 0 ? this.index + 1 : -1); boolean find = keywords == null || keywords.isEmpty(); Pattern pattern = regx && !find ? Pattern.compile(keywords) : null; while (n > 0) { byte[] buf = reversed ? new byte[(int) Math.min(this.bufSize, this.index)] : new byte[this.bufSize]; if (this.reversed) { if (this.index == 0) { break; } this.raf.seek(this.index -= buf.length); } int len = this.raf.read(buf, 0, buf.length); if (len == -1) { //已读完 break; } for (int i = 0; i < len && n > 0; i++) { int readIndex = reversed ? len - i - 1 : i; if (isCRLF(buf[readIndex])) { //如果读取到\r或\n if (Math.abs(this.index + readIndex - lastCRLFIndex) > 1) { //两行之间的间距,当=1时则代表有\r\n,\n\r,\r\r,\n\n四种情况之一 long fromIndex = reversed ? this.index + readIndex : lastCRLFIndex; //计算起止位置 long endIndex = reversed ? lastCRLFIndex : this.index + readIndex; //计算终止位置 Line line = readLine(fromIndex + 1, endIndex); //取出文本 if (find || (find = (pattern == null ? find(line.getText(), keywords, matchcase) : find(line.getText(), pattern)))) { //定位查找,使被查找的行始终在第一行 if (reversed) { lines.add(0, line); //反向查找时,插入到List头部 } else { lines.add(line); } n--; } } lastCRLFIndex = this.index + readIndex; //记录上次读取到的\r或\n位置 } } if (!reversed) { this.index += buf.length; } } if (reversed && n > 0 && lastCRLFIndex > 1 && (find || lines.size() > 0)) { lines.add(0, readLine(0, lastCRLFIndex)); } return lines; } private boolean find(String text, String keywords, boolean matchcase) { return matchcase ? text.contains(keywords) : text.toLowerCase().contains(keywords.toLowerCase()); } private boolean find(String text, Pattern pattern) { return pattern.matcher(text).find(); } /** * 从指定位置读取一行 * * @param fromIndex 开始位置 * @param endIndex 结束位置 * @return 返回Line对象 * @throws IOException */ private Line readLine(long fromIndex, long endIndex) throws IOException { long index = this.raf.getFilePointer(); this.raf.seek(fromIndex); byte[] buf = new byte[(int) (endIndex - fromIndex)]; this.raf.read(buf, 0, buf.length); Line line = new Line(fromIndex, new String(buf), endIndex); this.raf.seek(index); return line; } private boolean isCRLF(byte b) { return b == 13 || b == 10; } @Override public void close() throws IOException { if (this.raf != null) { this.raf.close(); } } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/io/SpiderResponse.java ================================================ package org.spiderflow.io; import java.io.InputStream; import java.util.Map; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import com.alibaba.fastjson.JSON; public interface SpiderResponse { @Comment("获取返回状态码") @Example("${resp.statusCode}") int getStatusCode(); @Comment("获取网页标题") @Example("${resp.title}") String getTitle(); @Comment("获取网页html") @Example("${resp.html}") String getHtml(); @Comment("获取json") @Example("${resp.json}") default Object getJson(){ return JSON.parse(getHtml()); } @Comment("获取cookies") @Example("${resp.cookies}") Map getCookies(); @Comment("获取headers") @Example("${resp.headers}") Map getHeaders(); @Comment("获取byte[]") @Example("${resp.bytes}") byte[] getBytes(); @Comment("获取ContentType") @Example("${resp.contentType}") String getContentType(); @Comment("获取当前url") @Example("${resp.url}") String getUrl(); @Example("${resp.setCharset('UTF-8')}") default void setCharset(String charset){ } @Example("${resp.stream}") default InputStream getStream(){ return null; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/listener/SpiderListener.java ================================================ package org.spiderflow.listener; import org.spiderflow.context.SpiderContext; public interface SpiderListener { /** * 开始执行之前 */ void beforeStart(SpiderContext context); /** * 执行完毕之后 */ void afterEnd(SpiderContext context); } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/Grammer.java ================================================ package org.spiderflow.model; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.annotation.Return; public class Grammer { private String owner; private String method; private String comment; private String example; private String function; private List returns; public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getFunction() { return function; } public void setFunction(String function) { this.function = function; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getExample() { return example; } public void setExample(String example) { this.example = example; } public List getReturns() { return returns; } public void setReturns(List returns) { this.returns = returns; } public static List findGrammers(Class clazz,String function,String owner,boolean mustStatic){ Method[] methods = clazz.getDeclaredMethods(); List grammers = new ArrayList<>(); for (Method method : methods) { if(Modifier.isPublic(method.getModifiers()) && (Modifier.isStatic(method.getModifiers())||!mustStatic)){ Grammer grammer = new Grammer(); grammer.setMethod(method.getName()); Comment comment = method.getAnnotation(Comment.class); if(comment != null){ grammer.setComment(comment.value()); } Example example = method.getAnnotation(Example.class); if(example != null){ grammer.setExample(example.value()); } Return returns = method.getAnnotation(Return.class); if(returns != null){ Class[] clazzs = returns.value(); List returnTypes = new ArrayList<>(); for (int i = 0; i < clazzs.length; i++) { returnTypes.add(clazzs[i].getSimpleName()); } grammer.setReturns(returnTypes); }else{ grammer.setReturns(Collections.singletonList(method.getReturnType().getSimpleName())); } grammer.setFunction(function); grammer.setOwner(owner); grammers.add(grammer); } } return grammers; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/JsonBean.java ================================================ package org.spiderflow.model; public class JsonBean { private Integer code = 1; private String message = "执行成功"; private T data; public JsonBean(Integer code, String message, T data) { this.code = code; this.message = message; this.data = data; } public JsonBean(Integer code, String message) { this.code = code; this.message = message; } public JsonBean(T data) { this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/Plugin.java ================================================ package org.spiderflow.model; public class Plugin { private String name; private String url; public Plugin(String name, String url) { this.name = name; this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/Shape.java ================================================ package org.spiderflow.model; public class Shape { private String name; private String label; private String title; private String image; private String desc; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/SpiderLog.java ================================================ package org.spiderflow.model; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.exception.ExceptionUtils; public class SpiderLog { private String level; private String message; private List variables; public SpiderLog(String level,String message, List variables) { if(variables != null && variables.size() > 0){ List nVariables = new ArrayList<>(variables.size()); for (Object object : variables) { if(object instanceof Throwable){ nVariables.add(ExceptionUtils.getStackTrace((Throwable) object)); }else{ nVariables.add(object); } } this.variables = nVariables; } this.level = level; this.message = message; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List getVariables() { return variables; } public void setVariables(List variables) { this.variables = variables; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/SpiderNode.java ================================================ package org.spiderflow.model; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import com.alibaba.fastjson.JSONArray; /** * 爬虫节点 * @author jmxd * */ public class SpiderNode { /** * 节点的Json属性 */ private Map jsonProperty = new HashMap<>(); /** * 节点列表中的下一个节点 */ private List nextNodes = new ArrayList<>(); /** * 节点列表中的上一个节点 */ private List prevNodes = new ArrayList<>(); /** * 父级节点ID */ private Set parentNodes; /** * 节点流转条件 */ private Map condition = new HashMap<>(); /** * 异常流转 */ private Map exception = new HashMap<>(); /** * 传递变量 */ private Map transmitVariable = new HashMap<>(); /** * 节点名称 */ private String nodeName; /** * 节点ID */ private String nodeId; /** * 计数器,用来计算当前节点执行中的个数 */ private AtomicInteger counter = new AtomicInteger(); public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String getStringJsonValue(String key){ String value = (String) this.jsonProperty.get(key); if(value != null){ value = StringEscapeUtils.unescapeHtml4(value); } return value; } public String getStringJsonValue(String key,String defaultValue){ String value = getStringJsonValue(key); return StringUtils.isNotBlank(value) ? value : defaultValue; } public List> getListJsonValue(String ... keys){ List arrays = new ArrayList<>(); int size = -1; List> result = new ArrayList<>(); for (int i = 0; i < keys.length; i++) { JSONArray jsonArray = (JSONArray) this.jsonProperty.get(keys[i]); if(jsonArray != null){ if(size == -1){ size = jsonArray.size(); }else if(size != jsonArray.size()){ throw new ArrayIndexOutOfBoundsException(); } arrays.add(jsonArray); } } for (int i = 0;i < size;i++) { Map item = new HashMap<>(); for (int j = 0; j < keys.length; j++) { String val = arrays.get(j).getString(i); if(val != null){ val = StringEscapeUtils.unescapeHtml4(val); } item.put(keys[j],val); } result.add(item); } return result; } public void setJsonProperty(Map jsonProperty) { this.jsonProperty = jsonProperty; } public void addNextNode(SpiderNode nextNode){ nextNode.prevNodes.add(this); this.nextNodes.add(nextNode); } public String getExceptionFlow(String fromNodeId) { return exception.get(fromNodeId); } public boolean isTransmitVariable(String fromNodeId) { String value = transmitVariable.get(fromNodeId); return value == null || "1".equalsIgnoreCase(value); } public void setTransmitVariable(String fromNodeId,String value){ this.transmitVariable.put(fromNodeId,value); } public void setExceptionFlow(String fromNodeId,String value){ this.exception.put(fromNodeId,value); } public List getNextNodes() { return nextNodes; } public String getCondition(String fromNodeId) { return condition.get(fromNodeId); } public void setCondition(String fromNodeId,String condition) { this.condition.put(fromNodeId, condition); } public void increment(){ counter.incrementAndGet(); } public void decrement(){ counter.decrementAndGet(); } public boolean hasLeftNode(String nodeId){ if(parentNodes == null){ Set parents = new HashSet<>(); generateParents(parents); this.parentNodes = parents; } return this.parentNodes.contains(nodeId); } private void generateParents(Set parents){ for (SpiderNode prevNode : prevNodes) { if(parents.add(prevNode.nodeId)){ prevNode.generateParents(parents); } } } public boolean isDone(){ return isDone(new HashSet<>()); } public boolean isDone(Set visited){ if(this.counter.get() == 0){ for (SpiderNode prevNode : prevNodes) { if(visited.add(nodeId)&&!prevNode.isDone(visited)){ return false; } } return true; } return false; } @Override public String toString() { return "SpiderNode [jsonProperty=" + jsonProperty + ", nextNodes=" + nextNodes + ", condition=" + condition + ", nodeName=" + nodeName + ", nodeId=" + nodeId + "]"; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/model/SpiderOutput.java ================================================ package org.spiderflow.model; import java.util.ArrayList; import java.util.List; public class SpiderOutput { /** * 节点名称 */ private String nodeName; /** * 节点Id */ private String nodeId; /** * 输出项的名 */ private List outputNames = new ArrayList<>(); /** * 输出项的值 */ private List values = new ArrayList<>(); public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public List getOutputNames() { return outputNames; } public void setOutputNames(List outputNames) { this.outputNames = outputNames; } public List getValues() { return values; } public void setValues(List values) { this.values = values; } public void addOutput(String name,Object value){ this.outputNames.add(name); this.values.add(value); } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } @Override public String toString() { return "SpiderOutput [nodeName=" + nodeName + ", nodeId=" + nodeId + ", outputNames=" + outputNames + ", values=" + values + "]"; } } ================================================ FILE: spider-flow-api/src/main/java/org/spiderflow/utils/Maps.java ================================================ package org.spiderflow.utils; import java.util.HashMap; import java.util.List; import java.util.Map; public class Maps { public static Map add(Map srcMap,K k,V v){ HashMap destMap = new HashMap<>(srcMap); destMap.put(k, v); return destMap; } public static Map newMap(K key,V value){ HashMap map = new HashMap<>(); map.put(key, value); return map; } public static Map add(Map srcMap,List ks,List vs){ HashMap destMap = new HashMap<>(srcMap); if(ks != null && vs != null && ks.size() == vs.size()){ int size = ks.size(); for (int i = 0; i < size; i++) { destMap.put(ks.get(0), vs.get(0)); } } return destMap; } } ================================================ FILE: spider-flow-core/pom.xml ================================================ 4.0.0 org.spiderflow spider-flow 0.5.0 spider-flow-core spider-flow-core https://gitee.com/jmxd/spider-flow/tree/master/spider-flow-core UTF-8 org.spiderflow spider-flow-api ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/Spider.java ================================================ package org.spiderflow.core; import com.alibaba.ttl.TtlRunnable; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.concurrent.*; import org.spiderflow.concurrent.SpiderFlowThreadPoolExecutor.SubThreadPoolExecutor; import org.spiderflow.context.SpiderContext; import org.spiderflow.context.SpiderContextHolder; import org.spiderflow.core.executor.shape.LoopExecutor; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.service.FlowNoticeService; import org.spiderflow.core.utils.ExecutorsUtils; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.core.utils.SpiderFlowUtils; import org.spiderflow.enums.FlowNoticeType; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.listener.SpiderListener; import org.spiderflow.model.SpiderNode; import org.spiderflow.model.SpiderOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * 爬虫的核心类 * * @author jmxd */ @Component public class Spider { @Autowired(required = false) private List listeners; @Value("${spider.thread.max:64}") private Integer totalThreads; @Value("${spider.thread.default:8}") private Integer defaultThreads; @Value("${spider.detect.dead-cycle:5000}") private Integer deadCycle; @Autowired private FlowNoticeService flowNoticeService; public static SpiderFlowThreadPoolExecutor executorInstance; private static final String ATOMIC_DEAD_CYCLE = "__atomic_dead_cycle"; private static Logger logger = LoggerFactory.getLogger(Spider.class); @PostConstruct private void init() { executorInstance = new SpiderFlowThreadPoolExecutor(totalThreads); } public List run(SpiderFlow spiderFlow, SpiderContext context, Map variables) { if (variables == null) { variables = new HashMap<>(); } SpiderNode root = SpiderFlowUtils.loadXMLFromString(spiderFlow.getXml()); // 流程开始通知 flowNoticeService.sendFlowNotice(spiderFlow, FlowNoticeType.startNotice); executeRoot(root, context, variables); // 流程结束通知 flowNoticeService.sendFlowNotice(spiderFlow, FlowNoticeType.endNotice); return context.getOutputs(); } public List run(SpiderFlow spiderFlow, SpiderContext context) { return run(spiderFlow, context, new HashMap<>()); } public void runWithTest(SpiderNode root, SpiderContext context) { //将上下文存到ThreadLocal里,以便后续使用 SpiderContextHolder.set(context); //死循环检测的计数器(死循环检测只在测试时有效) AtomicInteger executeCount = new AtomicInteger(0); //存入到上下文中,以供后续检测 context.put(ATOMIC_DEAD_CYCLE, executeCount); //执行根节点 executeRoot(root, context, new HashMap<>()); //当爬虫任务执行完毕时,判断是否超过预期 if (executeCount.get() > deadCycle) { logger.error("检测到可能出现死循环,测试终止"); } else { logger.info("测试完毕!"); } //将上下文从ThreadLocal移除,防止内存泄漏 SpiderContextHolder.remove(); } /** * 执行根节点 */ private void executeRoot(SpiderNode root, SpiderContext context, Map variables) { //获取当前流程执行线程数 int nThreads = NumberUtils.toInt(root.getStringJsonValue(ShapeExecutor.THREAD_COUNT), defaultThreads); String strategy = root.getStringJsonValue("submit-strategy"); ThreadSubmitStrategy submitStrategy; //选择提交策略,这里一定要使用new,不能与其他实例共享 if("linked".equalsIgnoreCase(strategy)){ submitStrategy = new LinkedThreadSubmitStrategy(); }else if("child".equalsIgnoreCase(strategy)){ submitStrategy = new ChildPriorThreadSubmitStrategy(); }else if("parent".equalsIgnoreCase(strategy)){ submitStrategy = new ParentPriorThreadSubmitStrategy(); }else{ submitStrategy = new RandomThreadSubmitStrategy(); } //创建子线程池,采用一父多子的线程池,子线程数不能超过总线程数(超过时进入队列等待),+1是因为会占用一个线程用来调度执行下一级 SubThreadPoolExecutor pool = executorInstance.createSubThreadPoolExecutor(Math.max(nThreads,1) + 1,submitStrategy); context.setRootNode(root); context.setThreadPool(pool); //触发监听器 if (listeners != null) { listeners.forEach(listener -> listener.beforeStart(context)); } Comparator comparator = submitStrategy.comparator(); //启动一个线程开始执行任务,并监听其结束并执行下一级 Future f = pool.submitAsync(TtlRunnable.get(() -> { try { //执行具体节点 Spider.this.executeNode(null, root, context, variables); Queue> queue = context.getFutureQueue(); //循环从队列中获取Future,直到队列为空结束,当任务完成时,则执行下一级 while (!queue.isEmpty()) { try { //TODO 这里应该是取出最先执行完毕的任务 Optional> max = queue.stream().filter(Future::isDone).max((o1, o2) -> { try { return comparator.compare(((SpiderTask) o1.get()).node, ((SpiderTask) o2.get()).node); } catch (InterruptedException | ExecutionException e) { } return 0; }); if (max.isPresent()) { //判断任务是否完成 queue.remove(max.get()); if (context.isRunning()) { //检测是否运行中(当在页面中点击"停止"时,此值为false,其余为true) SpiderTask task = (SpiderTask) max.get().get(); task.node.decrement(); //任务执行完毕,计数器减一(该计数器是给Join节点使用) if (task.executor.allowExecuteNext(task.node, context, task.variables)) { //判断是否允许执行下一级 logger.debug("执行节点[{}:{}]完毕", task.node.getNodeName(), task.node.getNodeId()); //执行下一级 Spider.this.executeNextNodes(task.node, context, task.variables); } else { logger.debug("执行节点[{}:{}]完毕,忽略执行下一节点", task.node.getNodeName(), task.node.getNodeId()); } } } //睡眠1ms,让出cpu Thread.sleep(1); } catch (InterruptedException ignored) { } catch (Throwable t){ logger.error("程序发生异常",t); } } //等待线程池结束 pool.awaitTermination(); } finally { //触发监听器 if (listeners != null) { listeners.forEach(listener -> listener.afterEnd(context)); } } }), null, root); try { f.get(); //阻塞等待所有任务执行完毕 } catch (InterruptedException | ExecutionException ignored) {} } /** * 执行下一级节点 */ private void executeNextNodes(SpiderNode node, SpiderContext context, Map variables) { List nextNodes = node.getNextNodes(); if (nextNodes != null) { for (SpiderNode nextNode : nextNodes) { executeNode(node, nextNode, context, variables); } } } /** * 执行节点 */ public void executeNode(SpiderNode fromNode, SpiderNode node, SpiderContext context, Map variables) { String shape = node.getStringJsonValue("shape"); if (StringUtils.isBlank(shape)) { executeNextNodes(node, context, variables); return; } //判断箭头上的条件,如果不成立则不执行 if (!executeCondition(fromNode, node, variables, context)) { return; } logger.debug("执行节点[{}:{}]", node.getNodeName(), node.getNodeId()); //找到对应的执行器 ShapeExecutor executor = ExecutorsUtils.get(shape); if (executor == null) { logger.error("执行失败,找不到对应的执行器:{}", shape); context.setRunning(false); } int loopCount = 1; //循环次数默认为1,如果节点有循环属性且填了循环次数/集合,则取出循环次数 int loopStart = 0; //循环起始位置 int loopEnd = 1; //循环结束位置 String loopCountStr = node.getStringJsonValue(ShapeExecutor.LOOP_COUNT); Object loopArray = null; boolean isLoop = false; if (isLoop = StringUtils.isNotBlank(loopCountStr)) { try { loopArray = ExpressionUtils.execute(loopCountStr, variables); if(loopArray == null){ loopCount = 0; }else if(loopArray instanceof Collection){ loopCount = ((Collection)loopArray).size(); loopArray = ((Collection)loopArray).toArray(); }else if(loopArray.getClass().isArray()){ loopCount = Array.getLength(loopArray); }else{ loopCount = NumberUtils.toInt(loopArray.toString(),0); loopArray = null; } loopEnd = loopCount; if(loopCount > 0){ loopStart = Math.max(NumberUtils.toInt(node.getStringJsonValue(LoopExecutor.LOOP_START), 0),0); int end = NumberUtils.toInt(node.getStringJsonValue(LoopExecutor.LOOP_END), -1); if(end >=0){ loopEnd = Math.min(end,loopEnd); }else{ loopEnd = Math.max(loopEnd + end + 1,0); } } logger.info("获取循环次数{}={}", loopCountStr, loopCount); } catch (Throwable t) { loopCount = 0; logger.error("获取循环次数失败,异常信息:{}", t); } } if (loopCount > 0) { //获取循环下标的变量名称 String loopVariableName = node.getStringJsonValue(ShapeExecutor.LOOP_VARIABLE_NAME); String loopItem = node.getStringJsonValue(LoopExecutor.LOOP_ITEM,"item"); List tasks = new ArrayList<>(); for (int i = loopStart; i < loopEnd; i++) { node.increment(); //节点执行次数+1(后续Join节点使用) if (context.isRunning()) { Map nVariables = new HashMap<>(); // 判断是否需要传递变量 if(fromNode == null || node.isTransmitVariable(fromNode.getNodeId())){ nVariables.putAll(variables); } if(isLoop){ // 存入下标变量 if (!StringUtils.isBlank(loopVariableName)) { nVariables.put(loopVariableName, i); } // 存入item nVariables.put(loopItem,loopArray == null ? i : Array.get(loopArray, i)); } tasks.add(new SpiderTask(TtlRunnable.get(() -> { if (context.isRunning()) { try { //死循环检测,当执行节点次数大于阈值时,结束本次测试 AtomicInteger executeCount = context.get(ATOMIC_DEAD_CYCLE); if (executeCount != null && executeCount.incrementAndGet() > deadCycle) { context.setRunning(false); return; } //执行节点具体逻辑 executor.execute(node, context, nVariables); //当未发生异常时,移除ex变量 nVariables.remove("ex"); } catch (Throwable t) { nVariables.put("ex", t); logger.error("执行节点[{}:{}]出错,异常信息:{}", node.getNodeName(), node.getNodeId(), t); } } }), node, nVariables, executor)); } } LinkedBlockingQueue> futureQueue = context.getFutureQueue(); for (SpiderTask task : tasks) { if(executor.isThread()){ //判断节点是否是异步运行 //提交任务至线程池中,并将Future添加到队列末尾 futureQueue.add(context.getThreadPool().submitAsync(task.runnable, task, node)); }else{ FutureTask futureTask = new FutureTask<>(task.runnable, task); futureTask.run(); futureQueue.add(futureTask); } } } } /** * 判断箭头上的表达式是否成立 */ private boolean executeCondition(SpiderNode fromNode, SpiderNode node, Map variables, SpiderContext context) { if (fromNode != null) { boolean hasException = variables.get("ex") != null; String exceptionFlow = node.getExceptionFlow(fromNode.getNodeId()); //当出现异常流转 : 1 //未出现异常流转 : 2 if(("1".equalsIgnoreCase(exceptionFlow) && !hasException) || ("2".equalsIgnoreCase(exceptionFlow) && hasException)){ return false; } String condition = node.getCondition(fromNode.getNodeId()); if (StringUtils.isNotBlank(condition)) { // 判断是否有条件 Object result = null; try { result = ExpressionUtils.execute(condition, variables); } catch (Exception e) { logger.error("判断{}出错,异常信息:{}", condition, e); } if (result != null) { boolean isContinue = "true".equals(result) || Objects.equals(result, true); logger.debug("判断{}={}", condition, isContinue); return isContinue; } return false; } } return true; } class SpiderTask{ Runnable runnable; SpiderNode node; Map variables; ShapeExecutor executor; public SpiderTask(Runnable runnable, SpiderNode node, Map variables,ShapeExecutor executor) { this.runnable = runnable; this.node = node; this.variables = variables; this.executor = executor; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/Base64FunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import org.apache.commons.codec.binary.Base64; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * 字符串内容和Base64互相转换 工具类 防止NPE * @author Administrator * */ @Component @Comment("base64常用方法") public class Base64FunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "base64"; } @Comment("根据byte[]进行base64加密") @Example("${base64.encode(resp.bytes)}") public static String encode(byte[] bytes){ return bytes != null ? Base64.encodeBase64String(bytes) : null; } @Comment("根据String进行base64加密") @Example("${base64.encode(resp.bytes,'UTF-8')}") public static String encode(String content,String charset){ return encode(StringFunctionExecutor.bytes(content,charset)); } @Comment("根据String进行base64加密") @Example("${base64.encode(resp.html)}") public static String encode(String content){ return encode(StringFunctionExecutor.bytes(content)); } @Comment("根据byte[]进行base64加密") @Example("${base64.encodeBytes(resp.bytes)}") public static byte[] encodeBytes(byte[] bytes){ return bytes != null ? Base64.encodeBase64(bytes) : null; } @Comment("根据String进行base64加密") @Example("${base64.encodeBytes(resp.html,'UTF-8')}") public static byte[] encodeBytes(String content,String charset){ return encodeBytes(StringFunctionExecutor.bytes(content,charset)); } @Comment("根据String进行base64加密") @Example("${base64.encodeBytes(resp.html)}") public static byte[] encodeBytes(String content){ return encodeBytes(StringFunctionExecutor.bytes(content)); } @Comment("根据String进行base64解密") @Example("${base64.decode(resp.html)}") public static byte[] decode(String base64){ return base64 != null ? Base64.decodeBase64(base64) :null; } @Comment("根据byte[]进行base64解密") @Example("${base64.decode(resp.bytes)}") public static byte[] decode(byte[] base64){ return base64 != null ? Base64.decodeBase64(base64) :null; } @Comment("根据String进行base64解密") @Example("${base64.decodeString(resp.html)}") public static String decodeString(String base64){ return base64 != null ? new String(Base64.decodeBase64(base64)) :null; } @Comment("根据byte[]进行base64解密") @Example("${base64.decodeString(resp.bytes)}") public static String decodeString(byte[] base64){ return base64 != null ? new String(Base64.decodeBase64(base64)) :null; } @Comment("根据byte[]进行base64解密") @Example("${base64.decodeString(resp.bytes,'UTF-8')}") public static String decodeString(byte[] base64,String charset){ return base64 != null ? StringFunctionExecutor.newString(Base64.decodeBase64(base64),charset) :null; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/DateFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.text.ParseException; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * 时间获取/格式化 工具类 防止NPE 默认格式(yyyy-MM-dd HH:mm:ss) * @author Administrator * */ @Component @Comment("日期常用方法") public class DateFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "date"; } private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; @Comment("格式化日期") @Example("${date.format(date.now())}") public static String format(Date date) { return format(date, DEFAULT_PATTERN); } @Comment("格式化日期") @Example("${date.format(1569059534000l)}") public static String format(Long millis) { return format(millis, DEFAULT_PATTERN); } @Comment("格式化日期") @Example("${date.format(date.now(),'yyyy-MM-dd')}") public static String format(Date date, String pattern) { return date != null ? DateFormatUtils.format(date, pattern) : null; } @Comment("格式化日期") @Example("${date.format(1569059534000l,'yyyy-MM-dd')}") public static String format(Long millis, String pattern) { return millis != null ? DateFormatUtils.format(millis, pattern) : null; } @Comment("字符串转为日期类型") @Example("${date.parse('2019-01-01 00:00:00')}") public static Date parse(String date) throws ParseException{ return date != null ? DateUtils.parseDate(date, DEFAULT_PATTERN) : null; } @Comment("字符串转为日期类型") @Example("${date.parse('2019-01-01','yyyy-MM-dd')}") public static Date parse(String date,String pattern) throws ParseException{ return date != null ? DateUtils.parseDate(date, pattern) : null; } @Comment("数字为日期类型") @Example("${date.parse(1569059534000l)}") public static Date parse(Long millis){ return new Date(millis); } @Comment("获取当前时间") @Example("${date.now()}") public static Date now(){ return new Date(); } @Comment("获取指定日期n年后的日期") @Example("${date.addYears(date.now(),2)}") public static Date addYears(Date date,int amount){ return DateUtils.addYears(date, amount); } @Comment("获取指定日期n月后的日期") @Example("${date.addMonths(date.now(),2)}") public static Date addMonths(Date date,int amount){ return DateUtils.addMonths(date, amount); } @Comment("获取指定日期n天后的日期") @Example("${date.addDays(date.now(),2)}") public static Date addDays(Date date,int amount){ return DateUtils.addDays(date, amount); } @Comment("获取指定日期n小时后的日期") @Example("${date.addHours(date.now(),2)}") public static Date addHours(Date date,int amount){ return DateUtils.addHours(date, amount); } @Comment("获取指定日期n分钟后的日期") @Example("${date.addMinutes(date.now(),2)}") public static Date addMinutes(Date date,int amount){ return DateUtils.addMinutes(date, amount); } @Comment("获取指定日期n秒后的日期") @Example("${date.addSeconds(date.now(),2)}") public static Date addSeconds(Date date,int amount){ return DateUtils.addSeconds(date, amount); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/ExtractFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; @Component @Comment("数据抽取常用方法") public class ExtractFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "extract"; } @Comment("根据jsonpath提取内容") @Example("${extract.jsonpath(resp.json,'$.code')}") public static Object jsonpath(Object root,String jsonpath){ return ExtractUtils.getValueByJsonPath(root, jsonpath); } @Comment("根据正则表达式提取内容") @Example("${extract.regx(resp.html,'(.*?)')}") public static String regx(String content,String pattern){ return ExtractUtils.getFirstMatcher(content, pattern, true); } @Comment("根据正则表达式提取内容") @Example("${extract.regx(resp.html,'(.*?)',1)}") public static String regx(String content,String pattern,int groupIndex){ return ExtractUtils.getFirstMatcher(content, pattern, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${extract.regx(resp.html,'(.*?)',[1,2])}") public static List regx(String content,String pattern,List groups){ return ExtractUtils.getFirstMatcher(content, pattern, groups); } @Comment("根据正则表达式提取内容") @Example("${extract.regxs(resp.html,'

(.*?)

')}") public static List regxs(String content,String pattern){ return ExtractUtils.getMatchers(content, pattern, true); } @Comment("根据正则表达式提取内容") @Example("${extract.regxs(resp.html,'

(.*?)

',1)}") public static List regxs(String content,String pattern,int groupIndex){ return ExtractUtils.getMatchers(content, pattern, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${extract.regxs(resp.html,'(.*?)',[1,2])}") public static List> regxs(String content,String pattern,List groups){ return ExtractUtils.getMatchers(content, pattern, groups); } @Comment("根据xpath提取内容") @Example("${extract.xpath(resp.element(),'//title/text()')}") public static String xpath(Element element,String xpath){ return ExtractUtils.getValueByXPath(element, xpath); } @Comment("根据xpath提取内容") @Example("${extract.xpath(resp.html,'//title/text()')}") public static String xpath(String content,String xpath){ return xpath(Jsoup.parse(content),xpath); } @Comment("根据xpaths提取内容") @Example("${extract.xpaths(resp.element(),'//h2/text()')}") public static List xpaths(Element element,String xpath){ return ExtractUtils.getValuesByXPath(element, xpath); } @Comment("根据xpaths提取内容") @Example("${extract.xpaths(resp.html,'//h2/text()')}") public static List xpaths(String content,String xpath){ return xpaths(Jsoup.parse(content),xpath); } @Comment("根据css选择器提取内容") @Example("${extract.selectors(resp.html,'div > a')}") public static List selectors(Object object,String selector){ return ExtractUtils.getHTMLBySelector(getElement(object), selector); } @Comment("根据css选择器提取内容") @Example("${extract.selector(resp.html,'div > a','text')}") public static Object selector(Object object,String selector,String type){ if("element".equals(type)){ return ExtractUtils.getFirstElement(getElement(object), selector); }else if("text".equals(type)){ return ExtractUtils.getFirstTextBySelector(getElement(object), selector); }else if("outerhtml".equals(type)){ return ExtractUtils.getFirstOuterHTMLBySelector(getElement(object), selector); } return null; } @Comment("根据css选择器提取内容") @Example("${extract.selector(resp.html,'div > a','attr','href')}") public static String selector(Object object,String selector,String type,String attrValue){ if("attr".equals(type)){ return ExtractUtils.getFirstAttrBySelector(getElement(object), selector,attrValue); } return null; } @Comment("根据css选择器提取内容") @Example("${extract.selector(resp.html,'div > a')}") public static String selector(Object object,String selector){ return ExtractUtils.getFirstHTMLBySelector(getElement(object), selector); } @Comment("根据css选择器提取内容") @Example("${extract.selectors(resp.html,'div > a','element')}") public static Object selectors(Object object,String selector,String type){ if("element".equals(type)){ return ExtractUtils.getElements(getElement(object), selector); }else if("text".equals(type)){ return ExtractUtils.getTextBySelector(getElement(object), selector); }else if("outerhtml".equals(type)){ return ExtractUtils.getOuterHTMLBySelector(getElement(object), selector); } return null; } @Comment("根据css选择器提取内容") @Example("${extract.selectors(resp.html,'div > a','attr','href')}") public static Object selectors(Object object,String selector,String type,String attrValue){ if("attr".equals(type)){ return ExtractUtils.getAttrBySelector(getElement(object), selector,attrValue); } return null; } private static Element getElement(Object object){ if(object != null){ return object instanceof Element ? (Element)object:Jsoup.parse((String) object); } return null; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/FileFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.io.*; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.io.IOUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.core.utils.FileUtils; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; /** * 文件读写 工具类 防止NPE * @author Administrator * */ @Component @Comment("file常用方法") public class FileFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "file"; } /** * * @param path 文件路径/名 * @param createDirectory 是否需要创建 * @return File 文件 */ private static File getFile(String path,boolean createDirectory){ File f = new File(path); if(createDirectory&&!f.getParentFile().exists()){ f.getParentFile().mkdirs(); } return f; } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.html,false)}") public static void write(String path,String content,boolean append) throws IOException{ write(path,content,Charset.defaultCharset().name(),append); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.html,'UTF-8',false)}") public static void write(String path,String content,String charset,boolean append) throws IOException{ write(path,StringFunctionExecutor.bytes(content, charset),append); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.bytes,false)}") public static void write(String path,byte[] bytes,boolean append) throws IOException{ write(path, new ByteArrayInputStream(bytes),append); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.stream,false)}") public static void write(String path, InputStream stream, boolean append) throws IOException { try(FileOutputStream fos = new FileOutputStream(getFile(path,true),append)){ IOUtils.copyLarge(stream, fos); } } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.bytes,false)}") public static void write(String path, InputStream stream) throws IOException { write(path, stream,false); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.html)}") public static void write(String path,String content) throws IOException{ write(path,content,false); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.html,'UTF-8')}") public static void write(String path,String content,String charset) throws IOException{ write(path,content,charset,false); } @Comment("写出文件") @Example("${file.write('e:/result.html',resp.bytes)}") public static void write(String path,byte[] bytes) throws IOException{ write(path,bytes,false); } @Comment("下载Url资源") @Example("${file.download('e:/downloadPath',urls)}") public static void download(String path, List urls) throws IOException{ if(!CollectionUtils.isEmpty(urls)) { for (String url : urls) { FileUtils.downloadFile(path, url, true); } } } @Comment("下载Url资源") @Example("${file.download('e:/downloadPath',urls)}") public static void download(String path, String url) throws IOException { if (url != null) { FileUtils.downloadFile(path, url, true); } } @Comment("读取文件") @Example("${file.bytes('e:/result.html')}") public static byte[] bytes(String path) throws IOException{ try(FileInputStream fis = new FileInputStream(getFile(path, false))){ return IOUtils.toByteArray(fis); } } @Comment("读取文件") @Example("${file.string('e:/result.html','UTF-8')}") public static String string(String path,String charset) throws IOException{ return StringFunctionExecutor.newString(bytes(path), charset); } @Comment("读取文件") @Example("${file.string('e:/result.html')}") public static String string(String path) throws IOException{ return StringFunctionExecutor.newString(bytes(path), Charset.defaultCharset().name()); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/JsonFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; /** * Json和String互相转换 工具类 防止NPE * @author Administrator * */ @Component @Comment("json常用方法") public class JsonFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "json"; } @Comment("将字符串转为json对象") @Example("${json.parse('{code : 1}')}") public static Object parse(String jsonString){ return jsonString != null ? JSON.parse(jsonString) : null; } @Comment("将对象转为json字符串") @Example("${json.stringify(objVar)}") public static String stringify(Object object){ return object != null ? JSON.toJSONString(object) : null; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/ListFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * List 工具类 防止NPE 添加了类似python的split()方法 * @author Administrator * */ @Component @Comment("list常用方法") public class ListFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "list"; } @Comment("获取list的长度") @Example("${list.length(listVar)}") public static int length(List list){ return list != null ? list.size() : 0; } /** * * @param list 原List * @param len 按多长进行分割 * @return List> 分割后的数组 */ @Comment("分割List") @Example("${list.split(listVar,10)}") public static List> split(List list,int len){ List> result = new ArrayList<>(); if (list == null || list.size() == 0 || len < 1) { return result; } int size = list.size(); int count = (size + len - 1) / len; for (int i = 0; i < count; i++) { List subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1))); result.add(subList); } return result; } @Comment("截取List") @Example("${list.sublist(listVar,fromIndex,toIndex)}") public static List sublist(List list,int fromIndex,int toIndex){ return list!= null ? list.subList(fromIndex, toIndex) : new ArrayList<>(); } @Comment("过滤字符串list元素") @Example("${listVar.filterStr(pattern)}") public static List filterStr(List list, String pattern) { if (list == null || list.isEmpty()) { return null; } List result = new ArrayList<>(list.size()); for (String item : list) { if (Pattern.matches(pattern, item)) { result.add(item); } } return result; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/MD5FunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import org.apache.commons.codec.digest.DigestUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; @Component @Comment("MD5常用方法") public class MD5FunctionExecutor implements FunctionExecutor { @Override public String getFunctionPrefix() { return "md5"; } @Comment("md5加密") @Example("${md5.string(resp.html)}") public static String string(String str){ return DigestUtils.md5Hex(str); } @Comment("md5加密") @Example("${md5.string(resp.bytes)}") public static String string(byte[] bytes){ return DigestUtils.md5Hex(bytes); } @Comment("md5加密") @Example("${md5.string(resp.stream)}") public static String string(InputStream stream) throws IOException { return DigestUtils.md5Hex(stream); } @Comment("md5加密") @Example("${md5.bytes(resp.html)}") public static byte[] bytes(String str){ return DigestUtils.md5(str); } @Comment("md5加密") @Example("${md5.bytes(resp.bytes)}") public static byte[] bytes(byte[] bytes){ return DigestUtils.md5(bytes); } @Comment("md5加密") @Example("${md5.bytes(resp.stream)}") public static byte[] bytes(InputStream stream) throws IOException { return DigestUtils.md5(stream); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/RandomFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import org.apache.commons.lang3.RandomUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * 随机数/字符串 生成方法 * @author Administrator * */ @Component public class RandomFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "random"; } @Comment("随机获取int") @Example("${random.randomInt(1,10)}") public static int randomInt(int min,int max){ return RandomUtils.nextInt(min, max); } @Comment("随机获取double") @Example("${random.randomDouble(1,10)}") public static double randomDouble(double min,double max){ return RandomUtils.nextDouble(min, max); } @Comment("随机获取long") @Example("${random.randomLong(1,10)}") public static long randomLong(long min,long max){ return RandomUtils.nextLong(min, max); } /** * * @param chars 字符个数 * @param length 字符范围 * @return String 随机字符串 */ @Comment("随机获取字符串") @Example("${random.string('abcde',10)}") public static String string(String chars,int length){ if (chars != null) { char[] newChars = new char[length]; int len = chars.length(); for (int i = 0; i < length; i++) { newChars[i] = chars.charAt(randomInt(0,len)); } return new String(newChars); } return null; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/StringFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * String 工具类 防止NPE * @author Administrator * */ @Component @Comment("string常用方法") public class StringFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "string"; } @Comment("截取字符串方法") @Example("${string.substring(str,5)}") public static String substring(String content, int beginIndex) { return content != null ? content.substring(beginIndex) : null; } @Comment("截取字符串方法") @Example("${string.substring(str,0,str.length() - 1)}") public static String substring(String content, int beginIndex, int endIndex) { return content != null ? content.substring(beginIndex, endIndex) : null; } @Comment("将字符串转为小写") @Example("${string.lower(str)}") public static String lower(String content) { return content != null ? content.toLowerCase() : null; } @Comment("将字符串转为大写") @Example("${string.upper(str)}") public static String upper(String content) { return content != null ? content.toUpperCase() : null; } @Comment("查找指定字符在字符串在中的位置") @Example("${string.indexOf(content,str)}") public static int indexOf(String content, String str) { return content != null ? content.indexOf(str) : -1; } @Comment("查找指定字符在字符串中最后出现的位置") @Example("${string.lastIndexOf(content,str)}") public static int lastIndexOf(String content, String str) { return content != null ? content.lastIndexOf(str) : -1; } @Comment("查找指定字符在字符串在中的位置") @Example("${string.indexOf(content,str,fromIndex)}") public static int indexOf(String content, String str, int fromIndex) { return content != null ? content.indexOf(str, fromIndex) : -1; } @Comment("将字符串转为int") @Example("${string.toInt(value)}") public static int toInt(String value){ return Integer.parseInt(value); } @Comment("将字符串转为Integer") @Example("${string.toInt(value,defaultValue)}") public static Integer toInt(String value,Integer defaultValue){ try { return Integer.parseInt(value); } catch (Exception e) { return defaultValue; } } @Comment("字符串替换") @Example("${string.replace(content,source,target)}") public static String replace(String content,String source,String target){ return content != null ? content.replace(source, target): null; } @Comment("正则替换字符串") @Example("${string.replaceAll(content,regx,target)}") public static String replaceAll(String content,String regx,String target){ return content != null ? content.replaceAll(regx, target): null; } @Comment("正则替换字符串") @Example("${string.replaceFirst(content,regx,target)}") public static String replaceFirst(String content,String regx,String target){ return content != null ? content.replaceFirst(regx, target): null; } @Comment("正则替换字符串") @Example("${string.length(content)}") public static int length(String content){ return content != null ? content.length() : -1; } @Comment("去除字符串两边的空格") @Example("${string.trim(content)}") public static String trim(String content){ return content != null ? content.trim() : null; } @Comment("分割字符串") @Example("${string.split(content,regx)}") public static List split(String content,String regx){ return content != null ? Arrays.asList(content.split(regx)) : new ArrayList<>(0); } @Comment("获取字符串的byte[]") @Example("${string.bytes(content)}") public static byte[] bytes(String content){ return content != null ? content.getBytes() : null; } @Comment("获取字符串的byte[]") @Example("${string.bytes(content,charset)}") public static byte[] bytes(String content,String charset){ try { return content != null ? content.getBytes(charset) : null; } catch (UnsupportedEncodingException e) { return null; } } @Comment("byte[]转String") @Example("${string.newString(bytes)}") public static String newString(byte[] bytes){ return bytes != null ? new String(bytes) : null; } @Comment("byte[]转String") @Example("${string.newString(bytes,charset)}") public static String newString(byte[] bytes,String charset){ try { return bytes != null ? new String(bytes,charset) : null; } catch (UnsupportedEncodingException e) { return null; } } @Comment("判断两个字符串是否相同") @Example("${string.newString(bytes,charset)}") public static boolean equals(String str1,String str2){ return str1 == null ? str2 == null : str1.equals(str2); } @Comment("生成UUID") @Example("${string.uuid()}") public static String uuid() { return UUID.randomUUID().toString().replace("-", ""); } @Comment("生成多个UUID") @Example("${string.uuid(size)}") public static List uuids(Integer size) { List ids = new ArrayList(); for (int i = 0; i < size; i++) { ids.add(UUID.randomUUID().toString().replace("-", "")); } return ids; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/ThreadFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * Created on 2019-12-06 * * @author Octopus */ @Component @Comment("thread常用方法") public class ThreadFunctionExecutor implements FunctionExecutor { @Override public String getFunctionPrefix() { return "thread"; } @Comment("线程休眠") @Example("${thread.sleep(1000L)}") public static void sleep(Long sleepTime){ try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/UrlFunctionExecutor.java ================================================ package org.spiderflow.core.executor.function; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExecutor; import org.springframework.stereotype.Component; /** * url 按指定字符集进行编码/解码 默认字符集(UTF-8) 工具类 防止NPE */ @Component public class UrlFunctionExecutor implements FunctionExecutor{ @Override public String getFunctionPrefix() { return "url"; } @Comment("获取url参数") @Example("${url.parameter('http://www.baidu.com/s?wd=spider-flow','wd')}") public static String parameter(String url,String key){ return parameterMap(url).get(key); } @Comment("获取url全部参数") @Example("${url.parameterMap('http://www.baidu.com/s?wd=spider-flow&abbr=sf')}") public static Map parameterMap(String url){ Map map = new HashMap(); int index = url.indexOf("?"); if(index != -1) { String param = url.substring(index+1); if(StringUtils.isNotBlank(param)) { String[] params = param.split("&"); for (String item : params) { String[] kv = item.split("="); if(kv.length > 0) { if(StringUtils.isNotBlank(kv[0])) { String value = ""; if(StringUtils.isNotBlank(kv[1])) { int kv1Index = kv[1].indexOf("#"); if(kv1Index != -1) { value = kv[1].substring(0,kv1Index); }else { value = kv[1]; } } map.put(kv[0],value); } } } } } return map; } @Comment("url编码") @Example("${url.encode('http://www.baidu.com/s?wd=spider-flow')}") public static String encode(String url){ return encode(url,Charset.defaultCharset().name()); } @Comment("url编码") @Example("${url.encode('http://www.baidu.com/s?wd=spider-flow','UTF-8')}") public static String encode(String url,String charset){ try { return url != null ? URLEncoder.encode(url,charset) : null; } catch (UnsupportedEncodingException e) { return null; } } @Comment("url解码") @Example("${url.decode(strVar)}") public static String decode(String url){ return decode(url,Charset.defaultCharset().name()); } @Comment("url解码") @Example("${url.decode(strVar,'UTF-8')}") public static String decode(String url,String charset){ try { return url != null ? URLDecoder.decode(url, charset) : null; } catch (UnsupportedEncodingException e) { return null; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ArrayFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; @Component public class ArrayFunctionExtension implements FunctionExtension{ @Override public Class support() { return Object[].class; } @Comment("获取数组的长度") @Example("${arrayVar.size()}") public static int size(Object[] objs){ return objs.length; } @Comment("将数组拼接起来") @Example("${arrayVar.join()}") public static String join(Object[] objs,String separator){ return StringUtils.join(objs,separator); } @Comment("将数组用separator拼接起来") @Example("${arrayVar.join('-')}") public static String join(Object[] objs){ return StringUtils.join(objs); } @Comment("将数组转为List") @Example("${arrayVar.toList()}") public static List toList(Object[] objs){ return Arrays.asList(objs); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/DateFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; @Component public class DateFunctionExtension implements FunctionExtension{ @Override public Class support() { return Date.class; } @Comment("格式化日期") @Example("${dateVar.format()}") public static String format(Date date){ return format(date, "yyyy-MM-dd HH:mm:ss"); } @Comment("格式化日期") @Example("${dateVar.format('yyyy-MM-dd HH:mm:ss')}") public static String format(Date date,String pattern){ return DateFormatUtils.format(date,pattern); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ElementFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import java.util.List; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.annotation.Return; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; @Component public class ElementFunctionExtension implements FunctionExtension{ @Override public Class support() { return Element.class; } @Comment("根据xpath提取内容") @Example("${elementVar.xpath('//title/text()')}") @Return({Element.class,String.class}) public static String xpath(Element element,String xpath){ return ExtractUtils.getValueByXPath(element, xpath); } @Comment("根据xpath提取内容") @Example("${elementVar.xpaths('//h2/text()')}") @Return({Element.class,String.class}) public static List xpaths(Element element,String xpath){ return ExtractUtils.getValuesByXPath(element, xpath); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regx('(.*?)')}") public static String regx(Element element,String regx){ return ExtractUtils.getFirstMatcher(element.html(), regx, true); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regx('(.*?)',1)}") public static String regx(Element element,String regx,int groupIndex){ return ExtractUtils.getFirstMatcher(element.html(), regx, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regx('(.*?)',[1,2])}") public static List regx(Element element,String regx,List groups){ return ExtractUtils.getFirstMatcher(element.html(), regx, groups); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regxs('

(.*?)

')}") public static List regxs(Element element,String regx){ return ExtractUtils.getMatchers(element.html(), regx, true); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regxs('

(.*?)

',1)}") public static List regxs(Element element,String regx,int groupIndex){ return ExtractUtils.getMatchers(element.html(), regx, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${elementVar.regxs('(.*?)',[1,2])}") public static List> regxs(Element element,String regx,List groups){ return ExtractUtils.getMatchers(element.html(), regx, groups); } @Comment("根据css选择器提取内容") @Example("${elementVar.selector('div > a')}") public static Element selector(Element element,String cssQuery){ return element.selectFirst(cssQuery); } @Comment("根据css选择器提取内容") @Example("${elementVar.selectors('div > a')}") public static Elements selectors(Element element,String cssQuery){ return element.select(cssQuery); } @Comment("获取同级节点") @Example("${elementVar.subling()}") public static Elements subling(Element element){ return element.siblingElements(); } @Comment("获取上级节点") @Example("${elementVar.parent()}") public static Element parent(Element element){ return element.parent(); } @Comment("获取上级节点") @Example("${elementVar.parents()}") public static Elements parents(Element element){ return element.parents(); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ElementsFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class ElementsFunctionExtension implements FunctionExtension{ @Override public Class support() { return Elements.class; } @Comment("根据xpath提取内容") @Example("${elementsVar.xpath('//title/text()')}") public static String xpath(Elements elements,String xpath){ return ExtractUtils.getValueByXPath(elements, xpath); } @Comment("根据xpath提取内容") @Example("${elementsVar.xpaths('//h2/text()')}") public static List xpaths(Elements elements,String xpath){ return ExtractUtils.getValuesByXPath(elements, xpath); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regx('(.*?)')}") public static String regx(Elements elements,String regx){ return ExtractUtils.getFirstMatcher(elements.html(), regx, true); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regx('(.*?)',1)}") public static String regx(Elements elements,String regx,int groupIndex){ return ExtractUtils.getFirstMatcher(elements.html(), regx, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regx('(.*?)',[1,2])}") public static List regx(Elements elements,String regx,List groups){ return ExtractUtils.getFirstMatcher(elements.html(), regx, groups); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regxs('

(.*?)

')}") public static List regxs(Elements elements,String regx){ return ExtractUtils.getMatchers(elements.html(), regx, true); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regxs('

(.*?)

',1)}") public static List regxs(Elements elements,String regx,int groupIndex){ return ExtractUtils.getMatchers(elements.html(), regx, groupIndex); } @Comment("根据正则表达式提取内容") @Example("${elementsVar.regxs('(.*?)',[1,2])}") public static List> regxs(Elements elements,String regx,List groups){ return ExtractUtils.getMatchers(elements.html(), regx, groups); } @Comment("根据css选择器提取内容") @Example("${elementsVar.selector('div > a')}") public static Element selector(Elements elements,String selector){ Elements foundElements = elements.select(selector); if(foundElements.size() > 0){ return foundElements.get(0); } return null; } @Comment("返回所有attr") @Example("${elementsVar.attrs('href')}") public static List attrs(Elements elements,String key){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.attr(key)); } return list; } @Comment("返回所有value") @Example("${elementsVar.vals()}") public static List vals(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.val()); } return list; } @Comment("返回所有text") @Example("${elementsVar.texts()}") public static List texts(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.text()); } return list; } @Comment("返回所有html") @Example("${elementsVar.htmls()}") public static List htmls(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.html()); } return list; } @Comment("返回所有outerHtml") @Example("${elementsVar.outerHtmls()}") public static List outerHtmls(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.outerHtml()); } return list; } @Comment("返回所有ownTexts") @Example("${elementsVar.ownTexts()}") public static List ownTexts(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.ownText()); } return list; } @Comment("返回所有wholeText") @Example("${elementsVar.wholeTexts()}") public static List wholeTexts(Elements elements){ List list = new ArrayList<>(elements.size()); for (Element element : elements) { list.add(element.wholeText()); } return list; } @Comment("根据css选择器提取内容") @Example("${elementsVar.selectors('div > a')}") public static Elements selectors(Elements elements,String selector){ return elements.select(selector); } @Comment("获取上级节点") @Example("${elementsVar.parents()}") public static Elements parents(Elements elements){ return elements.parents(); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ListFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import org.apache.commons.lang3.StringUtils; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.List; @Component public class ListFunctionExtension implements FunctionExtension{ @Override public Class support() { return List.class; } @Comment("获取list的长度") @Example("${listVar.length()}") public static int length(List list){ return list.size(); } @Comment("将list拼接起来") @Example("${listVar.join()}") public static String join(List list){ return StringUtils.join(list.toArray()); } @Comment("将list用separator拼接起来") @Example("${listVar.join('-')}") public static String join(List list,String separator){ if(list.size() == 1){ return list.get(0).toString(); }else{ return StringUtils.join(list.toArray(),separator); } } @Comment("将list排序") @Example("${listVar.sort()}") public static List sort(List list){ Collections.sort(list); return list; } @Comment("将list打乱顺序") @Example("${listVar.shuffle()}") public static List shuffle(List list){ Collections.shuffle(list); return list; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/MapFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Component public class MapFunctionExtension implements FunctionExtension { @Override public Class support() { return Map.class; } @Comment("将map转换为List") @Example("${mapmVar.toList('=')}") public static List toList(Map map,String separator){ return map.entrySet().stream().map(entry-> entry.getKey() + separator + entry.getValue()).collect(Collectors.toList()); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ObjectFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import java.util.Objects; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; @Component public class ObjectFunctionExtension implements FunctionExtension{ @Override public Class support() { return Object.class; } @Comment("将对象转为string类型") @Example("${objVar.string()}") public static String string(Object obj){ if (obj instanceof String) { return (String) obj; } return Objects.toString(obj); } @Comment("根据jsonpath提取内容") @Example("${objVar.jsonpath('$.code')}") public static Object jsonpath(Object obj,String path){ if(obj instanceof String){ return ExtractUtils.getValueByJsonPath(JSON.parse((String)obj), path); } return ExtractUtils.getValueByJsonPath(obj, path); } @Comment("睡眠等待一段时间") @Example("${objVar.sleep(1000)}") public static Object sleep(Object obj, int millis) { try { Thread.sleep(millis); } catch (InterruptedException ignored) { } return obj; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/ResponseFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.annotation.Return; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExtension; import org.spiderflow.io.SpiderResponse; import org.springframework.stereotype.Component; @Component public class ResponseFunctionExtension implements FunctionExtension { @Override public Class support() { return SpiderResponse.class; } @Comment("将请求结果转为Element对象") @Example("${resp.element()}") public static Element element(SpiderResponse response) { return Jsoup.parse(response.getHtml(),response.getUrl()); } @Comment("根据xpath在请求结果中查找") @Example("${resp.xpath('//title/text()')}") @Return({Element.class, String.class}) public static String xpath(SpiderResponse response, String xpath) { return ExtractUtils.getValueByXPath(element(response), xpath); } @Comment("根据xpath在请求结果中查找") @Example("${resp.xpaths('//a/@href')}") public static List xpaths(SpiderResponse response, String xpath) { return ExtractUtils.getValuesByXPath(element(response), xpath); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regx('(.*?)')}") public static String regx(SpiderResponse response, String pattern) { return ExtractUtils.getFirstMatcher(response.getHtml(), pattern, true); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regx('(.*?)',1)}") public static String regx(SpiderResponse response, String pattern, int groupIndex) { return ExtractUtils.getFirstMatcher(response.getHtml(), pattern, groupIndex); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regx('(.*?)',[1,2])}") public static List regx(SpiderResponse response, String pattern, List groups) { return ExtractUtils.getFirstMatcher(response.getHtml(), pattern, groups); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regxs('

(.*?)

')}") public static List regxs(SpiderResponse response, String pattern) { return ExtractUtils.getMatchers(response.getHtml(), pattern, true); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regxs('

(.*?)

',1)}") public static List regxs(SpiderResponse response, String pattern, int groupIndex) { return ExtractUtils.getMatchers(response.getHtml(), pattern, groupIndex); } @Comment("根据正则表达式提取请求结果中的内容") @Example("${resp.regxs('(.*?)',[1,2])}") public static List> regxs(SpiderResponse response, String pattern, List groups) { return ExtractUtils.getMatchers(response.getHtml(), pattern, groups); } @Comment("根据css选择器提取请求结果") @Example("${resp.selector('div > a')}") public static Element selector(SpiderResponse response, String selector) { return ElementFunctionExtension.selector(element(response), selector); } @Comment("根据css选择器提取请求结果") @Example("${resp.selectors('div > a')}") public static Elements selectors(SpiderResponse response, String selector) { return ElementFunctionExtension.selectors(element(response), selector); } @Comment("根据jsonpath提取请求结果") @Example("${resp.jsonpath('$.code')}") public static Object jsonpath(SpiderResponse response, String path) { return ExtractUtils.getValueByJsonPath(response.getJson(), path); } @Comment("获取页面上的链接") @Example("${resp.links()}") public static List links(SpiderResponse response) { return ExtractUtils.getAttrBySelector(element(response), "a", "abs:href") .stream() .filter(link -> StringUtils.isNotBlank(link)) .collect(Collectors.toList()); } @Comment("获取页面上的链接") @Example("${resp.links('https://www\\.xxx\\.com/xxxx/(.*?)')}") public static List links(SpiderResponse response, String regx) { Pattern pattern = Pattern.compile(regx); return links(response) .stream() .filter(link -> pattern.matcher(link).matches()) .collect(Collectors.toList()); } @Comment("获取当前页面所有图片链接") @Example("${resp.images()}") public static List images(SpiderResponse response) { return ExtractUtils.getAttrBySelector(element(response), "img", "src") .stream() .filter(link -> StringUtils.isNotBlank(link)) .collect(Collectors.toList()); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/SqlRowSetExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import org.apache.commons.lang3.exception.ExceptionUtils; import org.spiderflow.annotation.Example; import org.spiderflow.executor.FunctionExtension; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class SqlRowSetExtension implements FunctionExtension { public static Map tableMetaMap = new HashMap<>(); @Override public Class support() { return SqlRowSet.class; } @Example("${rs.nextToMap()}") public static Map nextToMap(SqlRowSet sqlRowSet) { try { if (!sqlRowSet.next()) { return null; } String[] columnNames = sqlRowSet.getMetaData().getColumnNames(); Map result = new HashMap<>(); for (String columnName : columnNames) { result.put(columnName, sqlRowSet.getObject(columnName)); } return result; } catch (Exception e) { ExceptionUtils.wrapAndThrow(e); } return null; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/function/extension/StringFunctionExtension.java ================================================ package org.spiderflow.core.executor.function.extension; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.text.StringEscapeUtils; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.select.Elements; import org.spiderflow.annotation.Comment; import org.spiderflow.annotation.Example; import org.spiderflow.annotation.Return; import org.spiderflow.core.executor.function.DateFunctionExecutor; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.FunctionExtension; import org.springframework.stereotype.Component; import java.text.ParseException; import java.util.Date; import java.util.List; @Component public class StringFunctionExtension implements FunctionExtension{ @Override public Class support() { return String.class; } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regx('(.*?)')}") public static String regx(String source,String pattern){ return ExtractUtils.getFirstMatcher(source, pattern, true); } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regx('(.*?)',1)}") public static String regx(String source,String pattern,int groupIndex){ return ExtractUtils.getFirstMatcher(source, pattern, groupIndex); } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regx('(.*?)',[1,2])}") public static List regx(String source,String pattern,List groups){ return ExtractUtils.getFirstMatcher(source, pattern, groups); } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regxs('

(.*?)

')}") public static List regxs(String source,String pattern){ return ExtractUtils.getMatchers(source, pattern, true); } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regxs('

(.*?)

',1)}") public static List regxs(String source,String pattern,int groupIndex){ return ExtractUtils.getMatchers(source, pattern, groupIndex); } @Comment("根据正则表达式提取String中的内容") @Example("${strVar.regxs('(.*?)',[1,2])}") public static List> regxs(String source,String pattern,List groups){ return ExtractUtils.getMatchers(source, pattern, groups); } @Comment("根据xpath在String变量中查找") @Example("${strVar.xpath('//title/text()')}") @Return({Element.class,String.class}) public static String xpath(String source,String xpath){ return ExtractUtils.getValueByXPath(element(source), xpath); } @Comment("根据xpath在String变量中查找") @Example("${strVar.xpaths('//a/@href')}") public static List xpaths(String source,String xpath){ return ExtractUtils.getValuesByXPath(element(source), xpath); } @Comment("将String变量转为Element对象") @Example("${strVar.element()}") public static Element element(String source){ return Parser.xmlParser().parseInput(source,""); } @Comment("根据css选择器提取") @Example("${strVar.selector('div > a')}") public static Element selector(String source,String cssQuery){ return element(source).selectFirst(cssQuery); } @Comment("根据css选择器提取") @Example("${strVar.selector('div > a')}") public static Elements selectors(String source,String cssQuery){ return element(source).select(cssQuery); } @Comment("将string转为json对象") @Example("${strVar.json()}") public static Object json(String source){ return JSON.parse(source); } @Comment("根据jsonpath提取内容") @Example("${strVar.jsonpath('$.code')}") public static Object jsonpath(String source,String jsonPath){ return ExtractUtils.getValueByJsonPath(json(source), jsonPath); } @Comment("将字符串转为int类型") @Example("${strVar.toInt(0)}") public static Integer toInt(String source,int defaultValue){ return NumberUtils.toInt(source, defaultValue); } @Comment("将字符串转为int类型") @Example("${strVar.toInt()}") public static Integer toInt(String source){ return NumberUtils.toInt(source); } @Comment("将字符串转为double类型") @Example("${strVar.toDouble()}") public static Double toDouble(String source){ return NumberUtils.toDouble(source); } @Comment("将字符串转为long类型") @Example("${strVar.toLong()}") public static Long toLong(String source){ return NumberUtils.toLong(source); } @Comment("将字符串转为date类型") @Example("${strVar.toDate('yyyy-MM-dd HH:mm:ss')}") public static Date toDate(String source,String pattern) throws ParseException{ return DateFunctionExecutor.parse(source, pattern); } @Comment("反转义字符串") @Example("${strVar.unescape()}") public static String unescape(String source){ return StringEscapeUtils.unescapeJava(source); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/CommentExecutor.java ================================================ package org.spiderflow.core.executor.shape; import org.spiderflow.context.SpiderContext; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; import java.util.Map; @Component public class CommentExecutor implements ShapeExecutor{ @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { } @Override public String supportShape() { return "comment"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/ExecuteSQLExecutor.java ================================================ package org.spiderflow.core.executor.shape; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.Grammerable; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.utils.DataSourceUtils; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.core.utils.ExtractUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.Grammer; import org.spiderflow.model.SpiderNode; import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Component; import java.lang.reflect.Array; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.*; /** * SQL执行器 * * @author jmxd */ @Component public class ExecuteSQLExecutor implements ShapeExecutor, Grammerable { public static final String DATASOURCE_ID = "datasourceId"; public static final String SQL = "sql"; public static final String STATEMENT_TYPE = "statementType"; public static final String STATEMENT_SELECT = "select"; public static final String STATEMENT_SELECT_ONE = "selectOne"; public static final String STATEMENT_SELECT_INT = "selectInt"; public static final String STATEMENT_INSERT = "insert"; public static final String STATEMENT_UPDATE = "update"; public static final String STATEMENT_DELETE = "delete"; public static final String SELECT_RESULT_STREAM = "isStream"; public static final String STATEMENT_INSERT_PK = "insertofPk"; private static final Logger logger = LoggerFactory.getLogger(ExecuteSQLExecutor.class); @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { String dsId = node.getStringJsonValue(DATASOURCE_ID); String sql = node.getStringJsonValue(SQL); if (StringUtils.isBlank(dsId)) { logger.warn("数据源ID为空!"); } else if (StringUtils.isBlank(sql)) { logger.warn("sql为空!"); } else { JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource(dsId)); //把变量替换成占位符 List parameters = ExtractUtils.getMatchers(sql, "#(.*?)#", true); sql = sql.replaceAll("#(.*?)#", "?"); try { Object sqlObject = ExpressionUtils.execute(sql, variables); if(sqlObject == null){ logger.warn("获取的sql为空!"); return; } sql = sqlObject.toString(); context.pause(node.getNodeId(),"common",SQL,sql); } catch (Exception e) { logger.error("获取sql出错,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } int size = parameters.size(); Object[] params = new Object[size]; boolean hasList = false; int parameterSize = 0; //当参数中存在List或者数组时,认为是批量操作 for (int i = 0; i < size; i++) { Object parameter = ExpressionUtils.execute(parameters.get(i), variables); if (parameter != null) { if (parameter instanceof List) { hasList = true; parameterSize = Math.max(parameterSize, ((List) parameter).size()); } else if (parameter.getClass().isArray()) { hasList = true; parameterSize = Math.max(parameterSize, Array.getLength(parameter)); } } params[i] = parameter; } String statementType = node.getStringJsonValue(STATEMENT_TYPE); logger.debug("执行sql:{}", sql); if (STATEMENT_SELECT.equals(statementType)) { boolean isStream = "1".equals(node.getStringJsonValue(SELECT_RESULT_STREAM)); try { if (isStream) { variables.put("rs", template.queryForRowSet(sql, params)); } else { variables.put("rs", template.queryForList(sql, params)); } } catch (Exception e) { variables.put("rs", null); logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } else if (STATEMENT_SELECT_ONE.equals(statementType)) { Map rs; try { rs = template.queryForMap(sql, params); variables.put("rs", rs); } catch (Exception e) { variables.put("rs", null); logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } else if (STATEMENT_SELECT_INT.equals(statementType)) { Integer rs; try { rs = template.queryForObject(sql, params, Integer.class); rs = rs == null ? 0 : rs; variables.put("rs", rs); } catch (Exception e) { variables.put("rs", 0); logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } else if (STATEMENT_UPDATE.equals(statementType) || STATEMENT_INSERT.equals(statementType) || STATEMENT_DELETE.equals(statementType)) { try { int updateCount = 0; if (hasList) { /* 批量操作时,将参数Object[]转化为List 当参数不为数组或List时,自动转为Object[] 当数组或List长度不足时,自动取最后一项补齐 */ int[] rs = template.batchUpdate(sql, convertParameters(params, parameterSize)); if (rs.length > 0) { updateCount = Arrays.stream(rs).sum(); } } else { updateCount = template.update(sql, params); } variables.put("rs", updateCount); } catch (Exception e) { logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); variables.put("rs", -1); ExceptionUtils.wrapAndThrow(e); } } else if(STATEMENT_INSERT_PK.equals(statementType)) { try { KeyHolder keyHolder = new GeneratedKeyHolder(); final String insertSQL = sql; template.update(con -> { PreparedStatement ps = con.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS); new ArgumentPreparedStatementSetter(params).setValues(ps); return ps; }, keyHolder); variables.put("rs", keyHolder.getKey().intValue()); } catch (Exception e) { logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); variables.put("rs", -1); ExceptionUtils.wrapAndThrow(e); } } } } private List convertParameters(Object[] params, int length) { List result = new ArrayList<>(length); int size = params.length; for (int i = 0; i < length; i++) { Object[] parameters = new Object[size]; for (int j = 0; j < size; j++) { parameters[j] = getValue(params[j], i); } result.add(parameters); } return result; } private Object getValue(Object object, int index) { if (object == null) { return null; } else if (object instanceof List) { List list = (List) object; int size = list.size(); if (size > 0) { return list.get(Math.min(list.size() - 1, index)); } } else if (object.getClass().isArray()) { int size = Array.getLength(object); if (size > 0) { Array.get(object, Math.min(-1, index)); } } else { return object; } return null; } @Override public String supportShape() { return "executeSql"; } @Override public List grammers() { Grammer grammer = new Grammer(); grammer.setComment("执行SQL结果"); grammer.setFunction("rs"); grammer.setReturns(Arrays.asList("List>", "int")); return Collections.singletonList(grammer); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/ForkJoinExecutor.java ================================================ package org.spiderflow.core.executor.shape; import org.spiderflow.context.SpiderContext; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * 等待执行结束执行器 * */ @Component public class ForkJoinExecutor implements ShapeExecutor { /** * 缓存已完成节点的变量 */ private Map> cachedVariables = new HashMap<>(); @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { } @Override public String supportShape() { return "forkJoin"; } @Override public boolean allowExecuteNext(SpiderNode node, SpiderContext context, Map variables) { String key = context.getId() + "-" + node.getNodeId(); synchronized (node){ boolean isDone = node.isDone(); Map cached = cachedVariables.get(key); if(!isDone){ if(cached == null){ cached = new HashMap<>(); cachedVariables.put(key, cached); } cached.putAll(variables); }else if(cached != null){ //将缓存的变量存入到当前变量中,传递给下一级 variables.putAll(cached); cachedVariables.remove(key); } return isDone; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/FunctionExecutor.java ================================================ package org.spiderflow.core.executor.shape; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; /** * 函数执行器 * @author Administrator * */ @Component public class FunctionExecutor implements ShapeExecutor{ public static final String FUNCTION = "function"; private static final Logger logger = LoggerFactory.getLogger(FunctionExecutor.class); @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { List> functions = node.getListJsonValue(FUNCTION); for (Map item : functions) { String function = item.get(FUNCTION); if(StringUtils.isNotBlank(function)){ try { logger.debug("执行函数{}",function); ExpressionUtils.execute(function, variables); } catch (Exception e) { logger.error("执行函数{}失败,异常信息:{}",function,e); ExceptionUtils.wrapAndThrow(e); } } } } @Override public String supportShape() { return "function"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/LoopExecutor.java ================================================ package org.spiderflow.core.executor.shape; import java.util.Map; import org.spiderflow.context.SpiderContext; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; /** * 循环执行器 * @author Administrator * */ @Component public class LoopExecutor implements ShapeExecutor{ public static final String LOOP_ITEM = "loopItem"; public static final String LOOP_START = "loopStart"; public static final String LOOP_END = "loopEnd"; @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { } @Override public String supportShape() { return "loop"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/OutputExecutor.java ================================================ package org.spiderflow.core.executor.shape; import com.alibaba.fastjson.JSON; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.ibatis.jdbc.SQL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.serializer.FastJsonSerializer; import org.spiderflow.core.utils.DataSourceUtils; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.io.SpiderResponse; import org.spiderflow.listener.SpiderListener; import org.spiderflow.model.SpiderNode; import org.spiderflow.model.SpiderOutput; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.io.*; import java.util.*; /** * 输出执行器 * @author Administrator * */ @Component public class OutputExecutor implements ShapeExecutor, SpiderListener { public static final String OUTPUT_ALL = "output-all"; public static final String OUTPUT_NAME = "output-name"; public static final String OUTPUT_VALUE = "output-value"; public static final String DATASOURCE_ID = "datasourceId"; public static final String OUTPUT_DATABASE = "output-database"; public static final String OUTPUT_CSV = "output-csv"; public static final String TABLE_NAME = "tableName"; public static final String CSV_NAME = "csvName"; public static final String CSV_ENCODING = "csvEncoding"; private static Logger logger = LoggerFactory.getLogger(OutputExecutor.class); /** * 输出CSVPrinter节点变量 */ private Map cachePrinter = new HashMap<>(); @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { SpiderOutput output = new SpiderOutput(); output.setNodeName(node.getNodeName()); output.setNodeId(node.getNodeId()); boolean outputAll = "1".equals(node.getStringJsonValue(OUTPUT_ALL)); boolean databaseFlag = "1".equals(node.getStringJsonValue(OUTPUT_DATABASE)); boolean csvFlag = "1".equals(node.getStringJsonValue(OUTPUT_CSV)); if (outputAll) { outputAll(output, variables); } List> outputs = node.getListJsonValue(OUTPUT_NAME, OUTPUT_VALUE); Map outputData = null; if (databaseFlag || csvFlag) { outputData = new HashMap<>(outputs.size()); } for (Map item : outputs) { Object value = null; String outputValue = item.get(OUTPUT_VALUE); String outputName = item.get(OUTPUT_NAME); try { value = ExpressionUtils.execute(outputValue, variables); context.pause(node.getNodeId(),"common",outputName,value); logger.debug("输出{}={}", outputName,value); } catch (Exception e) { logger.error("输出{}出错,异常信息:{}", outputName,e); } output.addOutput(outputName, value); if ((databaseFlag || csvFlag) && value != null) { outputData.put(outputName, value.toString()); } } if(databaseFlag){ String dsId = node.getStringJsonValue(DATASOURCE_ID); String tableName = node.getStringJsonValue(TABLE_NAME); if (StringUtils.isBlank(dsId)) { logger.warn("数据源ID为空!"); } else if (StringUtils.isBlank(tableName)) { logger.warn("表名为空!"); } else { outputDB(dsId, tableName, outputData); } } if (csvFlag) { String csvName = node.getStringJsonValue(CSV_NAME); outputCSV(node, context, csvName, outputData); } context.addOutput(output); } /** * 输出所有参数 * @param output * @param variables */ private void outputAll(SpiderOutput output,Map variables){ for (Map.Entry item : variables.entrySet()) { Object value = item.getValue(); if (value instanceof SpiderResponse) { SpiderResponse resp = (SpiderResponse) value; output.addOutput(item.getKey() + ".html", resp.getHtml()); continue; } //去除不输出的信息 if ("ex".equals(item.getKey())) { continue; } //去除不能序列化的参数 try { JSON.toJSONString(value, FastJsonSerializer.serializeConfig); } catch (Exception e) { e.printStackTrace(); continue; } //输出信息 output.addOutput(item.getKey(), item.getValue()); } } private void outputDB(String databaseId, String tableName, Map data) { if (data == null || data.isEmpty()) { return; } JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource(databaseId)); Set keySet = data.keySet(); Object[] params = new Object[data.size()]; SQL sql = new SQL(); //设置表名 sql.INSERT_INTO(tableName); int index = 0; //设置字段名 for (String key : keySet) { sql.VALUES(key, "?"); params[index] = data.get(key); index++; } try { //执行sql template.update(sql.toString(), params); } catch (Exception e) { logger.error("执行sql出错,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } private void outputCSV(SpiderNode node, SpiderContext context, String csvName, Map data) { if (data == null || data.isEmpty()) { return; } String key = context.getId() + "-" + node.getNodeId(); CSVPrinter printer = cachePrinter.get(key); List records = new ArrayList<>(data.size()); String[] headers = data.keySet().toArray(new String[data.size()]); try { if (printer == null) { synchronized (cachePrinter) { printer = cachePrinter.get(key); if (printer == null) { CSVFormat format = CSVFormat.DEFAULT.withHeader(headers); FileOutputStream os = new FileOutputStream(csvName); String csvEncoding = node.getStringJsonValue(CSV_ENCODING); if ("UTF-8BOM".equals(csvEncoding)) { csvEncoding = csvEncoding.substring(0, 5); byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; os.write(bom); os.flush(); } OutputStreamWriter osw = new OutputStreamWriter(os, csvEncoding); printer = new CSVPrinter(osw, format); cachePrinter.put(key, printer); } } } for (int i = 0; i < headers.length; i++) { records.add(data.get(headers[i]).toString()); } synchronized (cachePrinter) { printer.printRecord(records); } } catch (IOException e) { logger.error("文件输出错误,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } @Override public String supportShape() { return "output"; } @Override public void beforeStart(SpiderContext context) { } @Override public void afterEnd(SpiderContext context) { this.releasePrinters(); } private void releasePrinters() { for (Iterator> iterator = this.cachePrinter.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = iterator.next(); CSVPrinter printer = entry.getValue(); if (printer != null) { try { printer.flush(); printer.close(); this.cachePrinter.remove(entry.getKey()); } catch (IOException e) { logger.error("文件输出错误,异常信息:{}", e.getMessage(), e); ExceptionUtils.wrapAndThrow(e); } } } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/ProcessExecutor.java ================================================ package org.spiderflow.core.executor.shape; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.Spider; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.service.SpiderFlowService; import org.spiderflow.core.utils.SpiderFlowUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 子流程执行器 * @author Administrator * */ @Component public class ProcessExecutor implements ShapeExecutor{ public static final String FLOW_ID = "flowId"; private static Logger logger = LoggerFactory.getLogger(ProcessExecutor.class); @Autowired private SpiderFlowService spiderFlowService; @Autowired private Spider spider; @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { String flowId = node.getStringJsonValue("flowId"); SpiderFlow spiderFlow = spiderFlowService.getById(flowId); if(spiderFlow != null){ logger.info("执行子流程:{}", spiderFlow.getName()); SpiderNode root = SpiderFlowUtils.loadXMLFromString(spiderFlow.getXml()); spider.executeNode(null,root,context,variables); }else{ logger.info("执行子流程:{}失败,找不到该子流程", flowId); } } @Override public String supportShape() { return "process"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/RequestExecutor.java ================================================ package org.spiderflow.core.executor.shape; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnel; import com.google.common.hash.Funnels; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.Grammerable; import org.spiderflow.context.CookieContext; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.executor.function.MD5FunctionExecutor; import org.spiderflow.core.io.HttpRequest; import org.spiderflow.core.io.HttpResponse; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.io.SpiderResponse; import org.spiderflow.listener.SpiderListener; import org.spiderflow.model.Grammer; import org.spiderflow.model.SpiderNode; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.*; import java.nio.charset.Charset; import java.util.*; /** * 请求执行器 * @author Administrator * */ @Component public class RequestExecutor implements ShapeExecutor,Grammerable, SpiderListener { public static final String SLEEP = "sleep"; public static final String URL = "url"; public static final String PROXY = "proxy"; public static final String REQUEST_METHOD = "method"; public static final String PARAMETER_NAME = "parameter-name"; public static final String PARAMETER_VALUE = "parameter-value"; public static final String COOKIE_NAME = "cookie-name"; public static final String COOKIE_VALUE = "cookie-value"; public static final String PARAMETER_FORM_NAME = "parameter-form-name"; public static final String PARAMETER_FORM_VALUE = "parameter-form-value"; public static final String PARAMETER_FORM_FILENAME = "parameter-form-filename"; public static final String PARAMETER_FORM_TYPE = "parameter-form-type"; public static final String BODY_TYPE = "body-type"; public static final String BODY_CONTENT_TYPE = "body-content-type"; public static final String REQUEST_BODY = "request-body"; public static final String HEADER_NAME = "header-name"; public static final String HEADER_VALUE = "header-value"; public static final String TIMEOUT = "timeout"; public static final String RETRY_COUNT = "retryCount"; public static final String RETRY_INTERVAL = "retryInterval"; public static final String RESPONSE_CHARSET = "response-charset"; public static final String FOLLOW_REDIRECT = "follow-redirect"; public static final String TLS_VALIDATE = "tls-validate"; public static final String LAST_EXECUTE_TIME = "__last_execute_time_"; public static final String COOKIE_AUTO_SET = "cookie-auto-set"; public static final String REPEAT_ENABLE = "repeat-enable"; public static final String BLOOM_FILTER_KEY = "_bloomfilter"; @Value("${spider.workspace}") private String workspcace; @Value("${spider.bloomfilter.capacity:5000000}") private Integer capacity; @Value("${spider.bloomfilter.error-rate:0.00001}") private Double errorRate; private static final Logger logger = LoggerFactory.getLogger(RequestExecutor.class); @Override public String supportShape() { return "request"; } @PostConstruct void init(){ //允许设置被限制的请求头 System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { CookieContext cookieContext = context.getCookieContext(); String sleepCondition = node.getStringJsonValue(SLEEP); if(StringUtils.isNotBlank(sleepCondition)){ try { Object value = ExpressionUtils.execute(sleepCondition, variables); if(value != null){ long sleepTime = NumberUtils.toLong(value.toString(), 0L); synchronized (node.getNodeId().intern()) { //实际等待时间 = 上次执行时间 + 睡眠时间 - 当前时间 Long lastExecuteTime = context.get(LAST_EXECUTE_TIME + node.getNodeId(), 0L); if (lastExecuteTime != 0) { sleepTime = lastExecuteTime + sleepTime - System.currentTimeMillis(); } if (sleepTime > 0) { context.pause(node.getNodeId(),"common",SLEEP,sleepTime); logger.debug("设置延迟时间:{}ms", sleepTime); Thread.sleep(sleepTime); } context.put(LAST_EXECUTE_TIME + node.getNodeId(), System.currentTimeMillis()); } } } catch (Throwable t) { logger.error("设置延迟时间失败", t); } } BloomFilter bloomFilter = null; //重试次数 int retryCount = NumberUtils.toInt(node.getStringJsonValue(RETRY_COUNT), 0) + 1; //重试间隔时间,单位毫秒 int retryInterval = NumberUtils.toInt(node.getStringJsonValue(RETRY_INTERVAL), 0); boolean successed = false; for (int i = 0; i < retryCount && !successed; i++) { HttpRequest request = HttpRequest.create(); //设置请求url String url = null; try { url = ExpressionUtils.execute(node.getStringJsonValue(URL), variables).toString(); } catch (Exception e) { logger.error("设置请求url出错,异常信息", e); ExceptionUtils.wrapAndThrow(e); } if("1".equalsIgnoreCase(node.getStringJsonValue(REPEAT_ENABLE,"0"))){ bloomFilter = createBloomFilter(context); synchronized (bloomFilter){ if(bloomFilter.mightContain(MD5FunctionExecutor.string(url))){ logger.info("过滤重复URL:{}",url); return; } } } context.pause(node.getNodeId(),"common",URL,url); logger.info("设置请求url:{}", url); request.url(url); //设置请求超时时间 int timeout = NumberUtils.toInt(node.getStringJsonValue(TIMEOUT), 60000); logger.debug("设置请求超时时间:{}", timeout); request.timeout(timeout); String method = Objects.toString(node.getStringJsonValue(REQUEST_METHOD), "GET"); //设置请求方法 request.method(method); logger.debug("设置请求方法:{}", method); //是否跟随重定向 boolean followRedirects = !"0".equals(node.getStringJsonValue(FOLLOW_REDIRECT)); request.followRedirect(followRedirects); logger.debug("设置跟随重定向:{}", followRedirects); //是否验证TLS证书,默认是验证 if("0".equals(node.getStringJsonValue(TLS_VALIDATE))){ request.validateTLSCertificates(false); logger.debug("设置TLS证书验证:{}", false); } SpiderNode root = context.getRootNode(); //设置请求header setRequestHeader(root, request, root.getListJsonValue(HEADER_NAME,HEADER_VALUE), context, variables); setRequestHeader(node, request, node.getListJsonValue(HEADER_NAME,HEADER_VALUE), context, variables); //设置全局Cookie Map cookies = getRequestCookie(root, root.getListJsonValue(COOKIE_NAME, COOKIE_VALUE), context, variables); if(!cookies.isEmpty()){ logger.info("设置全局Cookie:{}", cookies); request.cookies(cookies); } //设置自动管理的Cookie boolean cookieAutoSet = !"0".equals(node.getStringJsonValue(COOKIE_AUTO_SET)); if(cookieAutoSet && !cookieContext.isEmpty()){ context.pause(node.getNodeId(),COOKIE_AUTO_SET,COOKIE_AUTO_SET,cookieContext); request.cookies(cookieContext); logger.info("自动设置Cookie:{}", cookieContext); } //设置本节点Cookie cookies = getRequestCookie(node, node.getListJsonValue(COOKIE_NAME, COOKIE_VALUE), context, variables); if(!cookies.isEmpty()){ request.cookies(cookies); logger.debug("设置Cookie:{}", cookies); } if(cookieAutoSet){ cookieContext.putAll(cookies); } String bodyType = node.getStringJsonValue(BODY_TYPE); List streams = null; if("raw".equals(bodyType)){ String contentType = node.getStringJsonValue(BODY_CONTENT_TYPE); request.contentType(contentType); try { Object requestBody = ExpressionUtils.execute(node.getStringJsonValue(REQUEST_BODY), variables); context.pause(node.getNodeId(),"request-body",REQUEST_BODY,requestBody); request.data(requestBody); logger.info("设置请求Body:{}", requestBody); } catch (Exception e) { logger.debug("设置请求Body出错", e); } }else if("form-data".equals(bodyType)){ List> formParameters = node.getListJsonValue(PARAMETER_FORM_NAME,PARAMETER_FORM_VALUE,PARAMETER_FORM_TYPE,PARAMETER_FORM_FILENAME); streams = setRequestFormParameter(node,request,formParameters,context,variables); }else{ //设置请求参数 setRequestParameter(root, request, root.getListJsonValue(PARAMETER_NAME,PARAMETER_VALUE), context, variables); setRequestParameter(node, request, node.getListJsonValue(PARAMETER_NAME,PARAMETER_VALUE), context, variables); } //设置代理 String proxy = node.getStringJsonValue(PROXY); if(StringUtils.isNotBlank(proxy)){ try { Object value = ExpressionUtils.execute(proxy, variables); context.pause(node.getNodeId(),"common",PROXY,value); if(value != null){ String[] proxyArr = value.toString().split(":"); if(proxyArr.length == 2){ request.proxy(proxyArr[0], Integer.parseInt(proxyArr[1])); logger.info("设置代理:{}",proxy); } } } catch (Exception e) { logger.error("设置代理出错,异常信息:{}",e); } } Throwable exception = null; try { HttpResponse response = request.execute(); successed = response.getStatusCode() == 200; if(successed){ if(bloomFilter != null){ synchronized (bloomFilter){ bloomFilter.put(MD5FunctionExecutor.string(url)); } } String charset = node.getStringJsonValue(RESPONSE_CHARSET); if(StringUtils.isNotBlank(charset)){ response.setCharset(charset); logger.debug("设置response charset:{}",charset); } //cookie存入cookieContext cookieContext.putAll(response.getCookies()); //结果存入变量 variables.put("resp", response); } } catch (IOException e) { successed = false; exception = e; } finally{ if(streams != null){ for (InputStream is : streams) { try { is.close(); } catch (Exception e) { } } } if(!successed){ if(i + 1 < retryCount){ if(retryInterval > 0){ try { Thread.sleep(retryInterval); } catch (InterruptedException ignored) { } } logger.info("第{}次重试:{}",i + 1,url); }else{ //记录访问失败的日志 if(context.getFlowId() != null){ //测试环境 //TODO 需增加记录请求参数 File file = new File(workspcace, context.getFlowId() + File.separator + "logs" + File.separator + "access_error.log"); try { File directory = file.getParentFile(); if(!directory.exists()){ directory.mkdirs(); } FileUtils.write(file,url + "\r\n","UTF-8",true); } catch (IOException ignored) { } } logger.error("请求{}出错,异常信息:{}",url,exception); } } } } } private List setRequestFormParameter(SpiderNode node, HttpRequest request,List> parameters,SpiderContext context,Map variables){ List streams = new ArrayList<>(); if(parameters != null){ for (Map nameValue : parameters) { Object value; String parameterName = nameValue.get(PARAMETER_FORM_NAME); if(StringUtils.isNotBlank(parameterName)){ String parameterValue = nameValue.get(PARAMETER_FORM_VALUE); String parameterType = nameValue.get(PARAMETER_FORM_TYPE); String parameterFilename = nameValue.get(PARAMETER_FORM_FILENAME); boolean hasFile = "file".equals(parameterType); try { value = ExpressionUtils.execute(parameterValue, variables); if(hasFile){ InputStream stream = null; if(value instanceof byte[]){ stream = new ByteArrayInputStream((byte[]) value); }else if(value instanceof String){ stream = new ByteArrayInputStream(((String)value).getBytes()); }else if(value instanceof InputStream){ stream = (InputStream) value; } if(stream != null){ streams.add(stream); request.data(parameterName, parameterFilename, stream); context.pause(node.getNodeId(),"request-body",parameterName,parameterFilename); logger.info("设置请求参数:{}={}",parameterName,parameterFilename); }else{ logger.warn("设置请求参数:{}失败,无二进制内容",parameterName); } }else{ request.data(parameterName, value); context.pause(node.getNodeId(),"request-body",parameterName,value); logger.info("设置请求参数:{}={}",parameterName,value); } } catch (Exception e) { logger.error("设置请求参数:{}出错,异常信息:{}",parameterName,e); } } } } return streams; } private Map getRequestCookie(SpiderNode node, List> cookies, SpiderContext context, Map variables) { Map cookieMap = new HashMap<>(); if (cookies != null) { for (Map nameValue : cookies) { Object value; String cookieName = nameValue.get(COOKIE_NAME); if (StringUtils.isNotBlank(cookieName)) { String cookieValue = nameValue.get(COOKIE_VALUE); try { value = ExpressionUtils.execute(cookieValue, variables); if (value != null) { cookieMap.put(cookieName, value.toString()); context.pause(node.getNodeId(),"request-cookie",cookieName,value.toString()); logger.info("设置请求Cookie:{}={}", cookieName, value); } } catch (Exception e) { logger.error("设置请求Cookie:{}出错,异常信息:{}", cookieName, e); } } } } return cookieMap; } private void setRequestParameter(SpiderNode node, HttpRequest request, List> parameters, SpiderContext context, Map variables) { if (parameters != null) { for (Map nameValue : parameters) { Object value = null; String parameterName = nameValue.get(PARAMETER_NAME); if (StringUtils.isNotBlank(parameterName)) { String parameterValue = nameValue.get(PARAMETER_VALUE); try { value = ExpressionUtils.execute(parameterValue, variables); context.pause(node.getNodeId(),"request-parameter",parameterName,value); logger.info("设置请求参数:{}={}", parameterName, value); } catch (Exception e) { logger.error("设置请求参数:{}出错,异常信息:{}", parameterName, e); } request.data(parameterName, value); } } } } private void setRequestHeader(SpiderNode node,HttpRequest request, List> headers, SpiderContext context, Map variables) { if (headers != null) { for (Map nameValue : headers) { Object value = null; String headerName = nameValue.get(HEADER_NAME); if (StringUtils.isNotBlank(headerName)) { String headerValue = nameValue.get(HEADER_VALUE); try { value = ExpressionUtils.execute(headerValue, variables); context.pause(node.getNodeId(),"request-header",headerName,value); logger.info("设置请求Header:{}={}", headerName, value); } catch (Exception e) { logger.error("设置请求Header:{}出错,异常信息:{}", headerName, e); } request.header(headerName, value); } } } } @Override public List grammers() { List grammers = Grammer.findGrammers(SpiderResponse.class,"resp" , "SpiderResponse", false); Grammer grammer = new Grammer(); grammer.setFunction("resp"); grammer.setComment("抓取结果"); grammer.setOwner("SpiderResponse"); grammers.add(grammer); return grammers; } @Override public void beforeStart(SpiderContext context) { } private BloomFilter createBloomFilter(SpiderContext context){ BloomFilter filter = context.get(BLOOM_FILTER_KEY); if(filter == null){ Funnel funnel = Funnels.stringFunnel(Charset.forName("UTF-8")); String fileName = context.getFlowId() + File.separator + "url.bf"; File file = new File(workspcace,fileName); if(file.exists()){ try(FileInputStream fis = new FileInputStream(file)){ filter = BloomFilter.readFrom(fis,funnel); } catch (IOException e) { logger.error("读取布隆过滤器出错",e); } }else{ filter = BloomFilter.create(funnel,capacity,errorRate); } context.put(BLOOM_FILTER_KEY,filter); } return filter; } @Override public void afterEnd(SpiderContext context) { BloomFilter filter = context.get(BLOOM_FILTER_KEY); if(filter != null){ File file = new File(workspcace,context.getFlowId() + File.separator + "url.bf"); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } try(FileOutputStream fos = new FileOutputStream(file)){ filter.writeTo(fos); fos.flush(); }catch(IOException e){ logger.error("保存布隆过滤器出错",e); } } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/StartExecutor.java ================================================ package org.spiderflow.core.executor.shape; import java.util.Map; import org.spiderflow.context.SpiderContext; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; /** * 开始执行器 * @author Administrator * */ @Component public class StartExecutor implements ShapeExecutor{ @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { } @Override public String supportShape() { return "start"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/executor/shape/VariableExecutor.java ================================================ package org.spiderflow.core.executor.shape; import java.util.List; import java.util.Map; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.SpiderNode; import org.springframework.stereotype.Component; /** * 定义变量执行器 * @author Administrator * */ @Component public class VariableExecutor implements ShapeExecutor{ private static final String VARIABLE_NAME = "variable-name"; private static final String VARIABLE_VALUE = "variable-value"; private static final Logger logger = LoggerFactory.getLogger(VariableExecutor.class); @Override public void execute(SpiderNode node, SpiderContext context, Map variables) { List> variableList = node.getListJsonValue(VARIABLE_NAME,VARIABLE_VALUE); for (Map nameValue : variableList) { Object value = null; String variableName = nameValue.get(VARIABLE_NAME); String variableValue = nameValue.get(VARIABLE_VALUE); try { value = ExpressionUtils.execute(variableValue, variables); logger.debug("设置变量{}={}",variableName,value); context.pause(node.getNodeId(),"common",variableName,value); } catch (Exception e) { logger.error("设置变量{}出错,异常信息:{}",variableName,e); ExceptionUtils.wrapAndThrow(e); } variables.put(variableName, value); } } @Override public String supportShape() { return "variable"; } @Override public boolean isThread() { return false; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/DefaultExpressionEngine.java ================================================ package org.spiderflow.core.expression; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.spiderflow.ExpressionEngine; import org.spiderflow.core.expression.interpreter.Reflection; import org.spiderflow.executor.FunctionExecutor; import org.spiderflow.executor.FunctionExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class DefaultExpressionEngine implements ExpressionEngine{ @Autowired private List functionExecutors; @Autowired private List functionExtensions; @PostConstruct private void init(){ for (FunctionExtension extension : functionExtensions) { Reflection.getInstance().registerExtensionClass(extension.support(), extension.getClass()); } } @Override public Object execute(String expression, Map variables) { if(StringUtils.isBlank(expression)){ return expression; } ExpressionTemplateContext context = new ExpressionTemplateContext(variables); for (FunctionExecutor executor : functionExecutors) { context.set(executor.getFunctionPrefix(), executor); } ExpressionGlobalVariables.getVariables().entrySet().forEach(entry->{ context.set(entry.getKey(),ExpressionTemplate.create(entry.getValue()).render(context)); }); try { ExpressionTemplateContext.set(context); return ExpressionTemplate.create(expression).render(context); } finally { ExpressionTemplateContext.remove(); } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/ExpressionError.java ================================================ package org.spiderflow.core.expression; import org.spiderflow.core.expression.parsing.Span; import org.spiderflow.core.expression.parsing.Span.Line; import org.spiderflow.core.expression.parsing.TokenStream; /** All errors reported by the library go through the static functions of this class. */ public class ExpressionError { /** *

* Create an error message based on the provided message and stream, highlighting the line on which the error happened. If the * stream has more tokens, the next token will be highlighted. Otherwise the end of the source of the stream will be * highlighted. *

* *

* Throws a {@link RuntimeException} *

*/ public static void error (String message, TokenStream stream) { if (stream.hasMore()) error(message, stream.consume().getSpan()); else { String source = stream.getSource(); if (source == null) error(message, new Span(" ", 0, 1)); else error(message, new Span(source, source.length() - 1, source.length())); } } /** Create an error message based on the provided message and location, highlighting the location in the line on which the * error happened. Throws a {@link TemplateException} **/ public static void error (String message, Span location, Throwable cause) { Line line = location.getLine(); message = "Error (" + line.getLineNumber() + "): " + message + "\n\n"; message += line.getText(); message += "\n"; int errorStart = location.getStart() - line.getStart(); int errorEnd = errorStart + location.getText().length() - 1; for (int i = 0, n = line.getText().length(); i < n; i++) { boolean useTab = line.getText().charAt(i) == '\t'; message += i >= errorStart && i <= errorEnd ? "^" : useTab ? "\t" : " "; } if (cause == null) throw new TemplateException(message, location); else throw new TemplateException(message, location, cause); } /** Create an error message based on the provided message and location, highlighting the location in the line on which the * error happened. Throws a {@link TemplateException} **/ public static void error (String message, Span location) { error(message, location, null); } /** Exception thrown by all basis-template code via {@link ExpressionError#error(String, Span)}. In case an error happens deep inside a * list of included templates, the {@link #getMessage()} method will return a condensed error message. **/ public static class TemplateException extends RuntimeException { private static final long serialVersionUID = 1L; private final Span location; private final String errorMessage; private TemplateException (String message, Span location) { super(message); this.errorMessage = message; this.location = location; } public TemplateException (String message, Span location, Throwable cause) { super(message, cause); this.errorMessage = message; this.location = location; } /** Returns the location in the template at which the error happened. **/ public Span getLocation () { return location; } @Override public String getMessage () { StringBuilder builder = new StringBuilder(); if (getCause() == null || getCause() == this) { return super.getMessage(); } builder.append(errorMessage.substring(0, errorMessage.indexOf('\n'))); builder.append("\n"); Throwable cause = getCause(); while (cause != null && cause != this) { if (cause instanceof TemplateException) { TemplateException ex = (TemplateException)cause; if (ex.getCause() == null || ex.getCause() == ex) builder.append(ex.errorMessage); else builder.append(ex.errorMessage.substring(0, ex.errorMessage.indexOf('\n'))); builder.append("\n"); } cause = cause.getCause(); } return builder.toString(); } } public static class StringLiteralException extends RuntimeException { private static final long serialVersionUID = 1L; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/ExpressionGlobalVariables.java ================================================ package org.spiderflow.core.expression; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ExpressionGlobalVariables { private static Map variables = new HashMap<>(); private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public static void reset(Map map){ Lock lock = readWriteLock.writeLock(); lock.lock(); try { variables.clear(); variables.putAll(map); } finally { lock.unlock(); } } public static Map getVariables(){ Lock lock = readWriteLock.readLock(); lock.lock(); try { return variables; } finally { lock.unlock(); } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/ExpressionTemplate.java ================================================ package org.spiderflow.core.expression; import java.io.OutputStream; import java.util.List; import org.spiderflow.core.expression.interpreter.AstInterpreter; import org.spiderflow.core.expression.parsing.Ast; import org.spiderflow.core.expression.parsing.Ast.Node; import org.spiderflow.core.expression.parsing.Parser; /** A template is loaded by a {@link TemplateLoader} from a file marked up with the basis-template language. The template can be * rendered to a {@link String} or {@link OutputStream} by calling one of the render() methods. The * {@link ExpressionTemplateContext} passed to the render() methods is used to look up variable values referenced in the * template. */ public class ExpressionTemplate { private final List nodes; /** Internal. Created by {@link Parser}. **/ private ExpressionTemplate (List nodes) { this.nodes = nodes; } public static ExpressionTemplate create(String source){ return new ExpressionTemplate(Parser.parse(source)); } /** Internal. The AST nodes representing this template after parsing. See {@link Ast}. Used by {@link AstInterpreter}. **/ public List getNodes () { return nodes; } /** Renders the template using the TemplateContext to resolve variable values referenced in the template. **/ public Object render (ExpressionTemplateContext context) { return AstInterpreter.interpret(this, context); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/ExpressionTemplateContext.java ================================================ package org.spiderflow.core.expression; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.spiderflow.core.expression.interpreter.AstInterpreter; /** *

* A template context stores mappings from variable names to user provided variable values. A {@link ExpressionTemplate} is given a context * for rendering to resolve variable values it references in template expressions. *

* *

* Internally, a template context is a stack of these mappings, similar to scopes in a programming language, and used as such by * the {@link AstInterpreter}. *

*/ public class ExpressionTemplateContext { private final List> scopes = new ArrayList>(); /** Keeps track of previously allocated, unused scopes. New scopes are first tried to be retrieved from this pool to avoid * generating garbage. **/ private final List> freeScopes = new ArrayList>(); private final static ThreadLocal CONTEXT_THREAD_LOCAL = new ThreadLocal<>(); public static ExpressionTemplateContext get(){ return CONTEXT_THREAD_LOCAL.get(); } public static void remove(){ CONTEXT_THREAD_LOCAL.remove(); } public static void set(ExpressionTemplateContext context){ CONTEXT_THREAD_LOCAL.set(context); } public ExpressionTemplateContext () { push(); } public ExpressionTemplateContext(Map variables) { this(); if(variables != null){ variables.forEach(this::set); } } /** Sets the value of the variable with the given name. If the variable already exists in one of the scopes, that variable is * set. Otherwise the variable is set on the last pushed scope. */ public ExpressionTemplateContext set (String name, Object value) { for (int i = scopes.size() - 1; i >= 0; i--) { Map ctx = scopes.get(i); if (ctx.isEmpty()) continue; if (ctx.containsKey(name)) { ctx.put(name, value); return this; } } scopes.get(scopes.size() - 1).put(name, value); return this; } /** Sets the value of the variable with the given name on the last pushed scope **/ public ExpressionTemplateContext setOnCurrentScope (String name, Object value) { scopes.get(scopes.size() - 1).put(name, value); return this; } /** Internal. Returns the value of the variable with the given name, walking the scope stack from top to bottom, similar to how * scopes in programming languages are searched for variables. */ public Object get (String name) { for (int i = scopes.size() - 1; i >= 0; i--) { Map ctx = scopes.get(i); if (ctx.isEmpty()) continue; Object value = ctx.get(name); if (value != null) return value; } return null; } /** Internal. Returns all variables currently defined in this context. */ public Set getVariables () { Set variables = new HashSet(); for (int i = 0, n = scopes.size(); i < n; i++) { variables.addAll(scopes.get(i).keySet()); } return variables; } /** Internal. Pushes a new "scope" onto the stack. **/ public void push () { Map newScope = freeScopes.size() > 0 ? freeScopes.remove(freeScopes.size() - 1) : new HashMap(); scopes.add(newScope); } /** Internal. Pops the top of the "scope" stack. **/ public void pop () { Map oldScope = scopes.remove(scopes.size() - 1); oldScope.clear(); freeScopes.add(oldScope); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/interpreter/AstInterpreter.java ================================================ package org.spiderflow.core.expression.interpreter; import java.io.IOException; import java.util.List; import org.spiderflow.core.expression.ExpressionError; import org.spiderflow.core.expression.ExpressionError.TemplateException; import org.spiderflow.core.expression.ExpressionTemplate; import org.spiderflow.core.expression.ExpressionTemplateContext; import org.spiderflow.core.expression.parsing.Ast; import org.spiderflow.core.expression.parsing.Ast.Node; import org.spiderflow.core.expression.parsing.Ast.Text; /** *

* Interprets a Template given a TemplateContext to lookup variable values in and writes the evaluation results to an output * stream. Uses the global {@link Reflection} instance as returned by {@link Reflection#getInstance()} to access members and call * methods. *

* *

* The interpeter traverses the AST as stored in {@link ExpressionTemplate#getNodes()}. the interpeter has a method for each AST node type * (see {@link Ast} that evaluates that node. A node may return a value, to be used in the interpretation of a parent node or to * be written to the output stream. *

**/ public class AstInterpreter { public static Object interpret (ExpressionTemplate template, ExpressionTemplateContext context) { try { return interpretNodeList(template.getNodes(), template, context); } catch (Throwable t) { if (t instanceof TemplateException) throw (TemplateException)t; else { ExpressionError.error("执行表达式出错 " + t.getMessage(), template.getNodes().get(0).getSpan(),t); return null; // never reached } } } public static Object interpretNodeList (List nodes, ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { String result = ""; for (int i = 0, n = nodes.size(); i < n; i++) { Node node = nodes.get(i); Object value = node.evaluate(template, context); if(node instanceof Text){ result += node.getSpan().getText(); }else if(value == null){ if(i == 0 && i + 1 == n){ return null; } result += "null"; }else if(value instanceof String || value instanceof Number || value instanceof Boolean){ if(i ==0 && i + 1 ==n){ return value; } result += value; }else if(i + 1 < n){ ExpressionError.error("表达式执行错误", node.getSpan()); }else{ return value; } } return result; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/interpreter/JavaReflection.java ================================================ package org.spiderflow.core.expression.interpreter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class JavaReflection extends Reflection { private final Map, Map> fieldCache = new ConcurrentHashMap, Map>(); private final Map, Map> methodCache = new ConcurrentHashMap, Map>(); private final Map, Map>> extensionmethodCache = new ConcurrentHashMap<>(); @SuppressWarnings("rawtypes") @Override public Object getField (Object obj, String name) { Class cls = obj instanceof Class ? (Class)obj : obj.getClass(); Map fields = fieldCache.get(cls); if (fields == null) { fields = new ConcurrentHashMap(); fieldCache.put(cls, fields); } Field field = fields.get(name); if (field == null) { try { field = cls.getDeclaredField(name); field.setAccessible(true); fields.put(name, field); } catch (Throwable t) { // fall through, try super classes } if (field == null) { Class parentClass = cls.getSuperclass(); while (parentClass != Object.class && parentClass != null) { try { field = parentClass.getDeclaredField(name); field.setAccessible(true); fields.put(name, field); } catch (NoSuchFieldException e) { // fall through } parentClass = parentClass.getSuperclass(); } } } return field; } @Override public Object getFieldValue (Object obj, Object field) { Field javaField = (Field)field; try { return javaField.get(obj); } catch (Throwable e) { throw new RuntimeException("Couldn't get value of field '" + javaField.getName() + "' from object of type '" + obj.getClass().getSimpleName() + "'"); } } @Override public void registerExtensionClass(Class target,Class clazz){ Method[] methods = clazz.getDeclaredMethods(); if(methods != null){ Map> cachedMethodMap = extensionmethodCache.get(target); if(cachedMethodMap == null){ cachedMethodMap = new HashMap<>(); extensionmethodCache.put(target,cachedMethodMap); } for (Method method : methods) { if(Modifier.isStatic(method.getModifiers()) && method.getParameterCount() > 0){ List cachedList = cachedMethodMap.get(method.getName()); if(cachedList == null){ cachedList = new ArrayList<>(); cachedMethodMap.put(method.getName(), cachedList); } cachedList.add(method); } } } } @Override public Object getExtensionMethod(Object obj, String name, Object... arguments) { Class cls = obj instanceof Class ? (Class)obj : obj.getClass(); if(cls.isArray()){ cls = Object[].class; } return getExtensionMethod(cls,name,arguments); } private Object getExtensionMethod(Class cls, String name, Object... arguments) { if(cls == null){ cls = Object.class; } Map> methodMap = extensionmethodCache.get(cls); if(methodMap != null){ List methodList = methodMap.get(name); if(methodList != null){ Class[] parameterTypes = new Class[arguments.length + 1]; parameterTypes[0] = cls; for (int i = 0; i < arguments.length; i++) { parameterTypes[i + 1] = arguments[i] == null ? null : arguments[i].getClass(); } return findMethod(methodList, parameterTypes); } } if(cls != Object.class){ Class[] interfaces = cls.getInterfaces(); if(interfaces != null){ for (Class clazz : interfaces) { Object method = getExtensionMethod(clazz,name,arguments); if(method != null){ return method; } } } return getExtensionMethod(cls.getSuperclass(),name,arguments); } return null; } @Override public Object getMethod (Object obj, String name, Object... arguments) { Class cls = obj instanceof Class ? (Class)obj : obj.getClass(); Map methods = methodCache.get(cls); if (methods == null) { methods = new ConcurrentHashMap(); methodCache.put(cls, methods); } Class[] parameterTypes = new Class[arguments.length]; for (int i = 0; i < arguments.length; i++) { parameterTypes[i] = arguments[i] == null ? null : arguments[i].getClass(); } JavaReflection.MethodSignature signature = new MethodSignature(name, parameterTypes); Method method = methods.get(signature); if (method == null) { try { if (name == null) { method = findApply(cls); } else { method = findMethod(cls, name, parameterTypes); if(method == null && parameterTypes != null){ method = findMethod(cls, name, new Class[]{Object[].class}); } } method.setAccessible(true); methods.put(signature, method); } catch (Throwable e) { // fall through } if (method == null) { Class parentClass = cls.getSuperclass(); while (parentClass != Object.class && parentClass != null) { try { if (name == null) method = findApply(parentClass); else { method = findMethod(parentClass, name, parameterTypes); } method.setAccessible(true); methods.put(signature, method); } catch (Throwable e) { // fall through } parentClass = parentClass.getSuperclass(); } } } return method; } /** Returns the apply() method of a functional interface. **/ private static Method findApply (Class cls) { for (Method method : cls.getDeclaredMethods()) { if (method.getName().equals("apply")) return method; } return null; } private static Method findMethod (List methods, Class[] parameterTypes) { Method foundMethod = null; int foundScore = 0; for (Method method : methods) { // Check if the types match. Class[] otherTypes = method.getParameterTypes(); if(parameterTypes.length != otherTypes.length){ continue; } boolean match = true; int score = 0; for (int ii = 0, nn = parameterTypes.length; ii < nn; ii++) { Class type = parameterTypes[ii]; Class otherType = otherTypes[ii]; if (!otherType.isAssignableFrom(type)) { score++; if (!isPrimitiveAssignableFrom(type, otherType)) { score++; if (!isCoercible(type, otherType)) { match = false; break; } else { score++; } } }else if(type == null && otherType.isPrimitive()){ match = false; break; } } if (match) { if (foundMethod == null) { foundMethod = method; foundScore = score; } else { if (score < foundScore) { foundScore = score; foundMethod = method; } } } } return foundMethod; } /** Returns the method best matching the given signature, including type coercion, or null. **/ private static Method findMethod (Class cls, String name, Class[] parameterTypes) { Method[] methods = cls.getDeclaredMethods(); List methodList = new ArrayList<>(); for (int i = 0, n = methods.length; i < n; i++) { Method method = methods[i]; // if neither name or parameter list size match, bail on this method if (!method.getName().equals(name)) continue; if (method.getParameterTypes().length != parameterTypes.length) continue; methodList.add(method); } return findMethod(methodList,parameterTypes); } /** Returns whether the from type can be assigned to the to type, assuming either type is a (boxed) primitive type. We can * relax the type constraint a little, as we'll invoke a method via reflection. That means the from type will always be boxed, * as the {@link Method#invoke(Object, Object...)} method takes objects. **/ private static boolean isPrimitiveAssignableFrom (Class from, Class to) { if ((from == Boolean.class || from == boolean.class) && (to == boolean.class || to == Boolean.class)) return true; if ((from == Integer.class || from == int.class) && (to == int.class || to == Integer.class)) return true; if ((from == Float.class || from == float.class) && (to == float.class || to == Float.class)) return true; if ((from == Double.class || from == double.class) && (to == double.class || to == Double.class)) return true; if ((from == Byte.class || from == byte.class) && (to == byte.class || to == Byte.class)) return true; if ((from == Short.class || from == short.class) && (to == short.class || to == Short.class)) return true; if ((from == Long.class || from == long.class) && (to == long.class || to == Long.class)) return true; if ((from == Character.class || from == char.class) && (to == char.class || to == Character.class)) return true; return false; } public static String[] getStringTypes(Object[] objects){ String[] parameterTypes = new String[objects == null ? 0: objects.length]; if(objects != null){ for(int i=0,len = objects.length;i from, Class to) { if (from == Integer.class || from == int.class) { return to == float.class || to == Float.class || to == double.class || to == Double.class || to == long.class || to == Long.class; } if (from == Float.class || from == float.class) { return to == double.class || to == Double.class; } if (from == Double.class || from == double.class) { return false; } if (from == Character.class || from == char.class) { return to == int.class || to == Integer.class || to == float.class || to == Float.class || to == double.class || to == Double.class || to == long.class || to == Long.class; } if (from == Byte.class || from == byte.class) { return to == int.class || to == Integer.class || to == float.class || to == Float.class || to == double.class || to == Double.class || to == long.class || to == Long.class || to == short.class || to == Short.class; } if (from == Short.class || from == short.class) { return to == int.class || to == Integer.class || to == float.class || to == Float.class || to == double.class || to == Double.class || to == long.class || to == Long.class; } if (from == Long.class || from == long.class) { return to == float.class || to == Float.class || to == double.class || to == Double.class; } if(from == int[].class || from == Integer[].class){ return to == Object[].class || to == float[].class || to == Float[].class || to == double[].class || to == Double[].class || to == long[].class || to == Long[].class; } return false; } @Override public Object callMethod (Object obj, Object method, Object... arguments) { Method javaMethod = (Method)method; try { return javaMethod.invoke(obj, arguments); } catch (Throwable t) { throw new RuntimeException("Couldn't call method '" + javaMethod.getName() + "' with arguments '" + Arrays.toString(arguments) + "' on object of type '" + obj.getClass().getSimpleName() + "'.", t); } } private static class MethodSignature { private final String name; @SuppressWarnings("rawtypes") private final Class[] parameters; private final int hashCode; @SuppressWarnings("rawtypes") public MethodSignature (String name, Class[] parameters) { this.name = name; this.parameters = parameters; final int prime = 31; int hash = 1; hash = prime * hash + ((name == null) ? 0 : name.hashCode()); hash = prime * hash + Arrays.hashCode(parameters); hashCode = hash; } @Override public int hashCode () { return hashCode; } @Override public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JavaReflection.MethodSignature other = (JavaReflection.MethodSignature)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (!Arrays.equals(parameters, other.parameters)) return false; return true; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/interpreter/Reflection.java ================================================ package org.spiderflow.core.expression.interpreter; /** Used by {@link AstInterpreter} to access fields and methods of objects. This is a singleton class used by all * {@link AstInterpreter} instances. Replace the default implementation via {@link #setInstance(Reflection)}. The implementation * must be thread-safe. */ public abstract class Reflection { private static Reflection instance = new JavaReflection(); /** Sets the Reflection instance to be used by all Template interpreters **/ public synchronized static void setInstance (Reflection reflection) { instance = reflection; } /** Returns the Reflection instance used to fetch field and call methods **/ public synchronized static Reflection getInstance () { return instance; } /** Returns an opaque handle to a field with the given name or null if the field could not be found **/ public abstract Object getField (Object obj, String name); /** Returns an opaque handle to the method with the given name best matching the signature implied by the given arguments, or * null if the method could not be found. If obj is an instance of Class, the matching static method is returned. If the name * is null and the object is a {@link FunctionalInterface}, the first declared method on the object is returned. **/ public abstract Object getMethod (Object obj, String name, Object... arguments); public abstract Object getExtensionMethod (Object obj, String name,Object ... arguments); public abstract void registerExtensionClass(Class target,Class clazz); /** Returns the value of the field from the object. The field must have been previously retrieved via * {@link #getField(Object, String)}. **/ public abstract Object getFieldValue (Object obj, Object field); /** Calls the method on the object with the given arguments. The method must have been previously retrieved via * {@link #getMethod(Object, String, Object...)}. **/ public abstract Object callMethod (Object obj, Object method, Object... arguments); } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/Ast.java ================================================ package org.spiderflow.core.expression.parsing; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.spiderflow.core.expression.ExpressionError; import org.spiderflow.core.expression.ExpressionError.TemplateException; import org.spiderflow.core.expression.ExpressionTemplate; import org.spiderflow.core.expression.ExpressionTemplateContext; import org.spiderflow.core.expression.interpreter.AstInterpreter; import org.spiderflow.core.expression.interpreter.JavaReflection; import org.spiderflow.core.expression.interpreter.Reflection; import org.spiderflow.core.script.ScriptManager; import org.spiderflow.expression.DynamicMethod; import javax.xml.transform.Source; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.*; /** Templates are parsed into an abstract syntax tree (AST) nodes by a Parser. This class contains all AST node types. */ public abstract class Ast { /** Base class for all AST nodes. A node minimally stores the {@link Span} that references its location in the * {@link Source}. **/ public abstract static class Node { private final Span span; public Node (Span span) { this.span = span; } /** Returns the {@link Span} referencing this node's location in the {@link Source}. **/ public Span getSpan () { return span; } @Override public String toString () { return span.getText(); } public abstract Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException; } /** A text node represents an "un-templated" span in the source that should be emitted verbatim. **/ public static class Text extends Node { private final String content; public Text (Span text) { super(text); String unescapedValue = text.getText(); StringBuilder builder = new StringBuilder(); CharacterStream stream = new CharacterStream(unescapedValue); while (stream.hasMore()) { if (stream.match("\\{", true)) { builder.append('{'); } else if (stream.match("\\}", true)) { builder.append('}'); } else { builder.append(stream.consume()); } } content = builder.toString(); } /** Returns the UTF-8 representation of this text node. **/ public String getContent () { return content; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return null; } } /** All expressions are subclasses of this node type. Expressions are separated into unary operations (!, -), binary operations * (+, -, *, /, etc.) and ternary operations (?:). */ public abstract static class Expression extends Node { public Expression (Span span) { super(span); } } /** An unary operation node represents a logical or numerical negation. **/ public static class UnaryOperation extends Expression { public static enum UnaryOperator { Not, Negate, Positive; public static UnaryOperator getOperator (Token op) { if (op.getType() == TokenType.Not) { return UnaryOperator.Not; } if (op.getType() == TokenType.Plus) { return UnaryOperator.Positive; } if (op.getType() == TokenType.Minus) { return UnaryOperator.Negate; } ExpressionError.error("Unknown unary operator " + op + ".", op.getSpan()); return null; // not reached } } private final UnaryOperator operator; private final Expression operand; public UnaryOperation (Token operator, Expression operand) { super(operator.getSpan()); this.operator = UnaryOperator.getOperator(operator); this.operand = operand; } public UnaryOperator getOperator () { return operator; } public Expression getOperand () { return operand; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Object operand = getOperand().evaluate(template, context); if (getOperator() == UnaryOperator.Negate) { if (operand instanceof Integer) { return -(Integer)operand; } else if (operand instanceof Float) { return -(Float)operand; } else if (operand instanceof Double) { return -(Double)operand; } else if (operand instanceof Byte) { return -(Byte)operand; } else if (operand instanceof Short) { return -(Short)operand; } else if (operand instanceof Long) { return -(Long)operand; } else { ExpressionError.error("Operand of operator '" + getOperator().name() + "' must be a number, got " + operand, getSpan()); return null; // never reached } } else if (getOperator() == UnaryOperator.Not) { if (!(operand instanceof Boolean)) { ExpressionError.error("Operand of operator '" + getOperator().name() + "' must be a boolean", getSpan()); } return !(Boolean)operand; } else { return operand; } } } /** A binary operation represents arithmetic operators, like addition or division, comparison operators, like less than or * equals, logical operators, like and, or an assignment. **/ public static class BinaryOperation extends Expression { public static enum BinaryOperator { Addition, Subtraction, Multiplication, Division, Modulo, Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual, And, Or, Xor, Assignment; public static BinaryOperator getOperator (Token op) { if (op.getType() == TokenType.Plus) { return BinaryOperator.Addition; } if (op.getType() == TokenType.Minus) { return BinaryOperator.Subtraction; } if (op.getType() == TokenType.Asterisk) { return BinaryOperator.Multiplication; } if (op.getType() == TokenType.ForwardSlash) { return BinaryOperator.Division; } if (op.getType() == TokenType.Percentage) { return BinaryOperator.Modulo; } if (op.getType() == TokenType.Equal) { return BinaryOperator.Equal; } if (op.getType() == TokenType.NotEqual) { return BinaryOperator.NotEqual; } if (op.getType() == TokenType.Less) { return BinaryOperator.Less; } if (op.getType() == TokenType.LessEqual) { return BinaryOperator.LessEqual; } if (op.getType() == TokenType.Greater) { return BinaryOperator.Greater; } if (op.getType() == TokenType.GreaterEqual) { return BinaryOperator.GreaterEqual; } if (op.getType() == TokenType.And) { return BinaryOperator.And; } if (op.getType() == TokenType.Or) { return BinaryOperator.Or; } if (op.getType() == TokenType.Xor) { return BinaryOperator.Xor; } if (op.getType() == TokenType.Assignment) { return BinaryOperator.Assignment; } ExpressionError.error("Unknown binary operator " + op + ".", op.getSpan()); return null; // not reached } } private final Expression leftOperand; private final BinaryOperator operator; private final Expression rightOperand; public BinaryOperation (Expression leftOperand, Token operator, Expression rightOperand) { super(operator.getSpan()); this.leftOperand = leftOperand; this.operator = BinaryOperator.getOperator(operator); this.rightOperand = rightOperand; } public Expression getLeftOperand () { return leftOperand; } public BinaryOperator getOperator () { return operator; } public Expression getRightOperand () { return rightOperand; } private Object evaluateAddition (Object left, Object right) { if (left instanceof String || right instanceof String) { return left.toString() + right.toString(); } if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() + ((Number)right).doubleValue(); } if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() + ((Number)right).floatValue(); } if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() + ((Number)right).longValue(); } if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() + ((Number)right).intValue(); } if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() + ((Number)right).shortValue(); } if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() + ((Number)right).byteValue(); } ExpressionError.error("Operands for addition operator must be numbers or strings, got " + left + ", " + right + ".", getSpan()); return null; // never reached } private Object evaluateSubtraction (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() - ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() - ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() - ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() - ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() - ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() - ((Number)right).byteValue(); } else { ExpressionError.error("Operands for subtraction operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateMultiplication (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() * ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() * ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() * ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() * ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() * ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() * ((Number)right).byteValue(); } else { ExpressionError.error("Operands for multiplication operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateDivision (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() / ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() / ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() / ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() / ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() / ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() / ((Number)right).byteValue(); } else { ExpressionError.error("Operands for division operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateModulo (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() % ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() % ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() % ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() % ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() % ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() % ((Number)right).byteValue(); } else { ExpressionError.error("Operands for modulo operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private boolean evaluateLess (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() < ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() < ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() < ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() < ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() < ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() < ((Number)right).byteValue(); } else { ExpressionError.error("Operands for less operator must be numbers" + left + ", " + right + ".", getSpan()); return false; // never reached } } private Object evaluateLessEqual (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() <= ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() <= ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() <= ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() <= ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() <= ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() <= ((Number)right).byteValue(); } else { ExpressionError.error("Operands for less/equal operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateGreater (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() > ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() > ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() > ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() > ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() > ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() > ((Number)right).byteValue(); } else { ExpressionError.error("Operands for greater operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateGreaterEqual (Object left, Object right) { if (left instanceof Double || right instanceof Double) { return ((Number)left).doubleValue() >= ((Number)right).doubleValue(); } else if (left instanceof Float || right instanceof Float) { return ((Number)left).floatValue() >= ((Number)right).floatValue(); } else if (left instanceof Long || right instanceof Long) { return ((Number)left).longValue() >= ((Number)right).longValue(); } else if (left instanceof Integer || right instanceof Integer) { return ((Number)left).intValue() >= ((Number)right).intValue(); } else if (left instanceof Short || right instanceof Short) { return ((Number)left).shortValue() >= ((Number)right).shortValue(); } else if (left instanceof Byte || right instanceof Byte) { return ((Number)left).byteValue() >= ((Number)right).byteValue(); } else { ExpressionError.error("Operands for greater/equal operator must be numbers" + left + ", " + right + ".", getSpan()); return null; // never reached } } private Object evaluateAnd (Object left, ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { if (!(left instanceof Boolean)) { ExpressionError.error("Left operand must be a boolean, got " + left + ".", getLeftOperand().getSpan()); } if (!(Boolean)left) { return false; } Object right = getRightOperand().evaluate(template, context); if (!(right instanceof Boolean)) { ExpressionError.error("Right operand must be a boolean, got " + right + ".", getRightOperand().getSpan()); } return (Boolean)left && (Boolean)right; } private Object evaluateOr (Object left, ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { if (!(left instanceof Boolean)) { ExpressionError.error("Left operand must be a boolean, got " + left + ".", getLeftOperand().getSpan()); } if ((Boolean)left) { return true; } Object right = getRightOperand().evaluate(template, context); if (!(right instanceof Boolean)) { ExpressionError.error("Right operand must be a boolean, got " + right + ".", getRightOperand().getSpan()); } return (Boolean)left || (Boolean)right; } private Object evaluateXor (Object left, Object right) { if (!(left instanceof Boolean)) { ExpressionError.error("Left operand must be a boolean, got " + left + ".", getLeftOperand().getSpan()); } if (!(right instanceof Boolean)) { ExpressionError.error("Right operand must be a boolean, got " + right + ".", getRightOperand().getSpan()); } return (Boolean)left ^ (Boolean)right; } private Object evaluateEqual (Object left, Object right) { if (left != null) { return left.equals(right); } if (right != null) { return right.equals(left); } return true; } private Object evaluateNotEqual (Object left, Object right) { return !(Boolean)evaluateEqual(left, right); } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { if (getOperator() == BinaryOperator.Assignment) { if (!(getLeftOperand() instanceof VariableAccess)) { ExpressionError.error("Can only assign to top-level variables in context.", getLeftOperand().getSpan()); } Object value = getRightOperand().evaluate(template, context); context.set(((VariableAccess)getLeftOperand()).getVariableName().getText(), value); return null; } Object left = getLeftOperand().evaluate(template, context); Object right = getOperator() == BinaryOperator.And || getOperator() == BinaryOperator.Or ? null : getRightOperand().evaluate(template, context); switch (getOperator()) { case Addition: return evaluateAddition(left, right); case Subtraction: return evaluateSubtraction(left, right); case Multiplication: return evaluateMultiplication(left, right); case Division: return evaluateDivision(left, right); case Modulo: return evaluateModulo(left, right); case Less: return evaluateLess(left, right); case LessEqual: return evaluateLessEqual(left, right); case Greater: return evaluateGreater(left, right); case GreaterEqual: return evaluateGreaterEqual(left, right); case Equal: return evaluateEqual(left, right); case NotEqual: return evaluateNotEqual(left, right); case And: return evaluateAnd(left, template, context); case Or: return evaluateOr(left, template, context); case Xor: return evaluateXor(left, right); default: ExpressionError.error("Binary operator " + getOperator().name() + " not implemented", getSpan()); return null; } } } /** A ternary operation is an abbreviated if/then/else operation, and equivalent to the the ternary operator in Java. **/ public static class TernaryOperation extends Expression { private final Expression condition; private final Expression trueExpression; private final Expression falseExpression; public TernaryOperation (Expression condition, Expression trueExpression, Expression falseExpression) { super(new Span(condition.getSpan(), falseExpression.getSpan())); this.condition = condition; this.trueExpression = trueExpression; this.falseExpression = falseExpression; } public Expression getCondition () { return condition; } public Expression getTrueExpression () { return trueExpression; } public Expression getFalseExpression () { return falseExpression; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Object condition = getCondition().evaluate(template, context); if (!(condition instanceof Boolean)) { ExpressionError.error("Condition of ternary operator must be a boolean, got " + condition + ".", getSpan()); } return ((Boolean)condition) ? getTrueExpression().evaluate(template, context) : getFalseExpression().evaluate(template, context); } } /** A null literal, with the single value null **/ public static class NullLiteral extends Expression { public NullLiteral (Span span) { super(span); } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return null; } } /** A boolean literal, with the values true and false **/ public static class BooleanLiteral extends Expression { private final Boolean value; public BooleanLiteral (Span literal) { super(literal); this.value = Boolean.parseBoolean(literal.getText()); } public Boolean getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A double precision floating point literal. Must be marked with the d suffix, e.g. "1.0d". **/ public static class DoubleLiteral extends Expression { private final Double value; public DoubleLiteral (Span literal) { super(literal); this.value = Double.parseDouble(literal.getText().substring(0, literal.getText().length() - 1)); } public Double getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A single precision floating point literla. May be optionally marked with the f suffix, e.g. "1.0f". **/ public static class FloatLiteral extends Expression { private final Float value; public FloatLiteral (Span literal) { super(literal); String text = literal.getText(); if (text.charAt(text.length() - 1) == 'f') { text = text.substring(0, text.length() - 1); } this.value = Float.parseFloat(text); } public Float getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A byte literal. Must be marked with the b suffix, e.g. "123b". **/ public static class ByteLiteral extends Expression { private final Byte value; public ByteLiteral (Span literal) { super(literal); this.value = Byte.parseByte(literal.getText().substring(0, literal.getText().length() - 1)); } public Byte getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A short literal. Must be marked with the s suffix, e.g. "123s". **/ public static class ShortLiteral extends Expression { private final Short value; public ShortLiteral (Span literal) { super(literal); this.value = Short.parseShort(literal.getText().substring(0, literal.getText().length() - 1)); } public Short getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** An integer literal. **/ public static class IntegerLiteral extends Expression { private final Integer value; public IntegerLiteral (Span literal) { super(literal); this.value = Integer.parseInt(literal.getText()); } public Integer getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A long integer literal. Must be marked with the l suffix, e.g. "123l". **/ public static class LongLiteral extends Expression { private final Long value; public LongLiteral (Span literal) { super(literal); this.value = Long.parseLong(literal.getText().substring(0, literal.getText().length() - 1)); } public Long getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A character literal, enclosed in single quotes. Supports escape sequences \n, \r,\t, \' and \\. **/ public static class CharacterLiteral extends Expression { private final Character value; public CharacterLiteral (Span literal) { super(literal); String text = literal.getText(); if (text.length() > 3) { if (text.charAt(2) == 'n') { value = '\n'; } else if (text.charAt(2) == 'r') { value = '\r'; } else if (text.charAt(2) == 't') { value = '\t'; } else if (text.charAt(2) == '\\') { value = '\\'; } else if (text.charAt(2) == '\'') { value = '\''; } else { ExpressionError.error("Unknown escape sequence '" + literal.getText() + "'.", literal); value = 0; // never reached } } else { this.value = literal.getText().charAt(1); } } public Character getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** A string literal, enclosed in double quotes. Supports escape sequences \n, \r, \t, \" and \\. **/ public static class StringLiteral extends Expression { private final String value; public StringLiteral (Span literal) { super(literal); String text = getSpan().getText(); String unescapedValue = text.substring(1, text.length() - 1); StringBuilder builder = new StringBuilder(); CharacterStream stream = new CharacterStream(unescapedValue); while (stream.hasMore()) { if (stream.match("\\\\", true)) { builder.append('\\'); } else if (stream.match("\\n", true)) { builder.append('\n'); } else if (stream.match("\\r", true)) { builder.append('\r'); } else if (stream.match("\\t", true)) { builder.append('\t'); } else if (stream.match("\\\"", true)) { builder.append('"'); } else { builder.append(stream.consume()); } } value = builder.toString(); } /** Returns the literal without quotes **/ public String getValue () { return value; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { return value; } } /** Represents a top-level variable access by name. E.g. in the expression "a + 1", a would be encoded as a * VariableAccess node. Variables can be both read (in expressions) and written to (in assignments). Variable values are looked * up and written to a {@link ExpressionTemplateContext}. **/ public static class VariableAccess extends Expression { public VariableAccess (Span name) { super(name); } public Span getVariableName () { return getSpan(); } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Object value = context.get(getSpan().getText()); //if (value == null) ExpressionError.error("找不到变量'" + getSpan().getText() + "'或变量值为null", getSpan()); return value; } } /** Represents a map or array element access of the form mapOrArray[keyOrIndex]. Maps and arrays may only be read * from. **/ public static class MapOrArrayAccess extends Expression { private final Expression mapOrArray; private final Expression keyOrIndex; public MapOrArrayAccess (Span span, Expression mapOrArray, Expression keyOrIndex) { super(span); this.mapOrArray = mapOrArray; this.keyOrIndex = keyOrIndex; } /** Returns an expression that must evaluate to a map or array. **/ public Expression getMapOrArray () { return mapOrArray; } /** Returns an expression that is used as the key or index to fetch a map or array element. **/ public Expression getKeyOrIndex () { return keyOrIndex; } @SuppressWarnings("rawtypes") @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Object mapOrArray = getMapOrArray().evaluate(template, context); if (mapOrArray == null) { return null; } Object keyOrIndex = getKeyOrIndex().evaluate(template, context); if (keyOrIndex == null) { return null; } if (mapOrArray instanceof Map) { return ((Map)mapOrArray).get(keyOrIndex); } else if (mapOrArray instanceof List) { if (!(keyOrIndex instanceof Number)) { ExpressionError.error("List index must be an integer, but was " + keyOrIndex.getClass().getSimpleName(), getKeyOrIndex().getSpan()); } int index = ((Number)keyOrIndex).intValue(); return ((List)mapOrArray).get(index); } else { if (!(keyOrIndex instanceof Number)) { ExpressionError.error("Array index must be an integer, but was " + keyOrIndex.getClass().getSimpleName(), getKeyOrIndex().getSpan()); } int index = ((Number)keyOrIndex).intValue(); if (mapOrArray instanceof int[]) { return ((int[])mapOrArray)[index]; } else if (mapOrArray instanceof float[]) { return ((float[])mapOrArray)[index]; } else if (mapOrArray instanceof double[]) { return ((double[])mapOrArray)[index]; } else if (mapOrArray instanceof boolean[]) { return ((boolean[])mapOrArray)[index]; } else if (mapOrArray instanceof char[]) { return ((char[])mapOrArray)[index]; } else if (mapOrArray instanceof short[]) { return ((short[])mapOrArray)[index]; } else if (mapOrArray instanceof long[]) { return ((long[])mapOrArray)[index]; } else if (mapOrArray instanceof byte[]) { return ((byte[])mapOrArray)[index]; } else if (mapOrArray instanceof String) { return Character.toString(((String)mapOrArray).charAt(index)); } else { return ((Object[])mapOrArray)[index]; } } } } /** Represents an access of a member (field or method or entry in a map) of the form object.member. Members may * only be read from. **/ public static class MemberAccess extends Expression { private final Expression object; private final Span name; private Object cachedMember; public MemberAccess (Expression object, Span name) { super(name); this.object = object; this.name = name; } /** Returns the object on which to access the member. **/ public Expression getObject () { return object; } /** The name of the member. **/ public Span getName () { return name; } /** Returns the cached member descriptor as returned by {@link Reflection#getField(Object, String)} or * {@link Reflection#getMethod(Object, String, Object...)}. See {@link #setCachedMember(Object)}. **/ public Object getCachedMember () { return cachedMember; } /** Sets the member descriptor as returned by {@link Reflection#getField(Object, String)} or * {@link Reflection#getMethod(Object, String, Object...)} for faster member lookups. Called by {@link AstInterpreter} the * first time this node is evaluated. Subsequent evaluations can use the cached descriptor, avoiding a costly reflective * lookup. **/ public void setCachedMember (Object cachedMember) { this.cachedMember = cachedMember; } @SuppressWarnings("rawtypes") @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Object object = getObject().evaluate(template, context); if (object == null) { return null; } // special case for array.length if (object.getClass().isArray() && getName().getText().equals("length")) { return Array.getLength(object); } // special case for map, allows to do map.key instead of map[key] if (object instanceof Map) { Map map = (Map)object; return map.get(getName().getText()); } Object field = getCachedMember(); if (field != null) { try { return Reflection.getInstance().getFieldValue(object, field); } catch (Throwable t) { // fall through } } String text = getName().getText(); field = Reflection.getInstance().getField(object, text); if (field == null) { String methodName = null; if(text.length() > 1){ methodName = text.substring(0,1).toUpperCase() + text.substring(1); }else{ methodName = text.toUpperCase(); } MemberAccess access = new MemberAccess(this.object, new Span("get" + methodName)); MethodCall methodCall = new MethodCall(getName(),access, Collections.emptyList()); try { return methodCall.evaluate(template, context); } catch (TemplateException e) { if(ExceptionUtils.indexOfThrowable(e, InvocationTargetException.class) > -1){ ExpressionError.error(String.format("在%s中调用方法get%s发生异常" ,object.getClass() ,methodName), getSpan(),e); return null; } access = new MemberAccess(this.object, new Span("is" + methodName)); methodCall = new MethodCall(getName(),access, Collections.emptyList()); try { return methodCall.evaluate(template, context); } catch (TemplateException e1) { if(ExceptionUtils.indexOfThrowable(e1, InvocationTargetException.class) > -1){ ExpressionError.error(String.format("在%s中调用方法is%s发生异常" ,object.getClass() ,methodName), getSpan(),e); return null; } ExpressionError.error(String.format("在%s中找不到属性%s或者方法get%s、方法is%s" ,object.getClass() ,getName().getText() ,methodName ,methodName), getSpan()); } } } setCachedMember(field); return Reflection.getInstance().getFieldValue(object, field); } } /** Represents a call to a top-level function. A function may either be a {@link FunctionalInterface} stored in a * {@link ExpressionTemplateContext}, or a {@link Macro} defined in a template. */ public static class FunctionCall extends Expression { private final Expression function; private final List arguments; private Object cachedFunction; private final ThreadLocal cachedArguments; public FunctionCall (Span span, Expression function, List arguments) { super(span); this.function = function; this.arguments = arguments; this.cachedArguments = new ThreadLocal(); } /** Return the expression that must evaluate to a {@link FunctionalInterface} or a {@link Macro}. **/ public Expression getFunction () { return function; } /** Returns the list of expressions to be passed to the function as arguments. **/ public List getArguments () { return arguments; } /** Returns the cached "function" descriptor as returned by {@link Reflection#getMethod(Object, String, Object...)} or the * {@link Macro}. See {@link #setCachedFunction(Object)}. **/ public Object getCachedFunction () { return cachedFunction; } /** Sets the "function" descriptor as returned by {@link Reflection#getMethod(Object, String, Object...)} for faster * lookups, or the {@link Macro} to be called. Called by {@link AstInterpreter} the first time this node is evaluated. * Subsequent evaluations can use the cached descriptor, avoiding a costly reflective lookup. **/ public void setCachedFunction (Object cachedFunction) { this.cachedFunction = cachedFunction; } /** Returns a scratch buffer to store arguments in when calling the function in {@link AstInterpreter}. Avoids generating * garbage. **/ public Object[] getCachedArguments () { Object[] args = cachedArguments.get(); if (args == null) { args = new Object[arguments.size()]; cachedArguments.set(args); } return args; } /** Must be invoked when this node is done evaluating so we don't leak memory **/ public void clearCachedArguments () { Object[] args = getCachedArguments(); for (int i = 0; i < args.length; i++) { args[i] = null; } } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { try { Object[] argumentValues = getCachedArguments(); List arguments = getArguments(); for (int i = 0, n = argumentValues.length; i < n; i++) { Expression expr = arguments.get(i); argumentValues[i] = expr.evaluate(template, context); } // This is a special case to handle template level macros. If a call to a macro is // made, evaluating the function expression will result in an exception, as the // function name can't be found in the context. Instead we need to manually check // if the function expression is a VariableAccess and if so, if it can be found // in the context. Object function = null; if (getFunction() instanceof VariableAccess) { VariableAccess varAccess = (VariableAccess)getFunction(); function = context.get(varAccess.getVariableName().getText()); } else { function = getFunction().evaluate(template, context); } if (function != null) { Object method = getCachedFunction(); if (method != null) { try { return Reflection.getInstance().callMethod(function, method, argumentValues); } catch (Throwable t) { // fall through } } method = Reflection.getInstance().getMethod(function, null, argumentValues); if (method == null) { ExpressionError.error("Couldn't find function.", getSpan()); } setCachedFunction(method); try { return Reflection.getInstance().callMethod(function, method, argumentValues); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); return null; // never reached } } else if(ScriptManager.containsFunction(getFunction().getSpan().getText())){ try { return ScriptManager.eval(context,getFunction().getSpan().getText(),argumentValues); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); return null; // never reached } } else { ExpressionError.error("Couldn't find function " + getFunction(), getSpan()); return null; // never reached } } finally { clearCachedArguments(); } } } /** Represents a call to a method of the form object.method(a, b, c). **/ public static class MethodCall extends Expression { private final MemberAccess method; private final List arguments; private Object cachedMethod; private final ThreadLocal cachedArguments; public MethodCall (Span span, MemberAccess method, List arguments) { super(span); this.method = method; this.arguments = arguments; this.cachedArguments = new ThreadLocal(); } /** Returns the object on which to call the method. **/ public Expression getObject () { return method.getObject(); } /** Returns the method to call. **/ public MemberAccess getMethod () { return method; } /** Returns the list of expressions to be passed to the function as arguments. **/ public List getArguments () { return arguments; } /** Returns the cached member descriptor as returned by {@link Reflection#getMethod(Object, String, Object...)}. See * {@link #setCachedMember(Object)}. **/ public Object getCachedMethod () { return cachedMethod; } /** Sets the method descriptor as returned by {@link Reflection#getMethod(Object, String, Object...)} for faster lookups. * Called by {@link AstInterpreter} the first time this node is evaluated. Subsequent evaluations can use the cached * descriptor, avoiding a costly reflective lookup. **/ public void setCachedMethod (Object cachedMethod) { this.cachedMethod = cachedMethod; } /** Returns a scratch buffer to store arguments in when calling the function in {@link AstInterpreter}. Avoids generating * garbage. **/ public Object[] getCachedArguments () { Object[] args = cachedArguments.get(); if (args == null) { args = new Object[arguments.size()]; cachedArguments.set(args); } return args; } /** Must be invoked when this node is done evaluating so we don't leak memory **/ public void clearCachedArguments () { Object[] args = getCachedArguments(); for (int i = 0; i < args.length; i++) { args[i] = null; } } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { try { Object object = getObject().evaluate(template, context); if (object == null) { return null; } Object[] argumentValues = getCachedArguments(); List arguments = getArguments(); for (int i = 0, n = argumentValues.length; i < n; i++) { Expression expr = arguments.get(i); argumentValues[i] = expr.evaluate(template, context); } if(object instanceof DynamicMethod){ try { Object method = DynamicMethod.class.getDeclaredMethod("execute", String.class,List.class); Object[] newArgumentValues = new Object[]{getMethod().getName().getText(),Arrays.asList(argumentValues)}; return Reflection.getInstance().callMethod(object, method, newArgumentValues); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); return null; // never reached } } // Otherwise try to find a corresponding method or field pointing to a lambda. Object method = getCachedMethod(); if (method != null) { try { return Reflection.getInstance().callMethod(object, method, argumentValues); } catch (Throwable t) { // fall through } } method = Reflection.getInstance().getMethod(object, getMethod().getName().getText(), argumentValues); if (method != null) { // found the method on the object, call it setCachedMethod(method); try { return Reflection.getInstance().callMethod(object, method, argumentValues); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); return null; // never reached } } method = Reflection.getInstance().getExtensionMethod(object, getMethod().getName().getText(), argumentValues); if(method != null){ try { int argumentLength = argumentValues == null ? 0 : argumentValues.length; Object[] parameters = new Object[argumentLength + 1]; if(argumentLength > 0){ for (int i = 0; i < argumentLength; i++) { parameters[i + 1] = argumentValues[i]; } } parameters[0] = object; if(object.getClass().isArray()){ Object[] objs = new Object[Array.getLength(object)]; for (int i = 0,len = objs.length; i < len; i++) { Array.set(objs, i, Array.get(object, i)); } parameters[0] = objs; } return Reflection.getInstance().callMethod(object, method, parameters); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); // fall through return null; } }else { // didn't find the method on the object, try to find a field pointing to a lambda Object field = Reflection.getInstance().getField(object, getMethod().getName().getText()); if (field == null){ ExpressionError.error("在'" + object.getClass() + "'中找不到方法 " + getMethod().getName().getText() + "(" + StringUtils.join(JavaReflection.getStringTypes(argumentValues),",") + ")", getSpan()); } Object function = Reflection.getInstance().getFieldValue(object, field); method = Reflection.getInstance().getMethod(function, null, argumentValues); if (method == null){ ExpressionError.error("在'" + object.getClass() + "'中找不到方法 " + getMethod().getName().getText() + "("+ StringUtils.join(JavaReflection.getStringTypes(argumentValues),",") +")", getSpan()); } try { return Reflection.getInstance().callMethod(function, method, argumentValues); } catch (Throwable t) { ExpressionError.error(t.getMessage(), getSpan(), t); return null; // never reached } } } finally { clearCachedArguments(); } } } /** Represents a map literal of the form { key: value, key2: value, ... } which can be nested. */ public static class MapLiteral extends Expression { private final List keys; private final List values; public MapLiteral (Span span, List keys, List values) { super(span); this.keys = keys; this.values = values; } public List getKeys () { return keys; } public List getValues () { return values; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { Map map = new HashMap<>(); for (int i = 0, n = keys.size(); i < n; i++) { Object value = values.get(i).evaluate(template, context); Token tokenKey = keys.get(i); String key = tokenKey.getSpan().getText(); if(tokenKey.getType() == TokenType.StringLiteral){ key = (String) new StringLiteral(tokenKey.getSpan()).evaluate(template, context); }else if(key != null && key.startsWith("$")){ Object objKey = context.get(key.substring(1)); if(objKey != null){ key = objKey.toString(); }else{ key = null; } } map.put(key, value); } return map; } } /** Represents a list literal of the form [ value, value2, value3, ...] which can be nested. */ public static class ListLiteral extends Expression { public final List values; public ListLiteral (Span span, List values) { super(span); this.values = values; } public List getValues () { return values; } @Override public Object evaluate (ExpressionTemplate template, ExpressionTemplateContext context) throws IOException { List list = new ArrayList<>(); for (int i = 0, n = values.size(); i < n; i++) { list.add(values.get(i).evaluate(template, context)); } return list; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/CharacterStream.java ================================================ package org.spiderflow.core.expression.parsing; import javax.xml.transform.Source; /** Wraps a the content of a {@link Source} and handles traversing the contained characters. Manages a current {@link Span} via * the {@link #startSpan()} and {@link #endSpan()} methods. */ public class CharacterStream { private final String source; private int index = 0; private final int end; private int spanStart = 0; public CharacterStream (String source) { this(source, 0, source.length()); } public CharacterStream (String source, int start, int end) { if (start > end) throw new IllegalArgumentException("Start must be <= end."); if (start < 0) throw new IndexOutOfBoundsException("Start must be >= 0."); if (start > Math.max(0, source.length() - 1)) throw new IndexOutOfBoundsException("Start outside of string."); if (end > source.length()) throw new IndexOutOfBoundsException("End outside of string."); this.source = source; this.index = start; this.end = end; } /** Returns whether there are more characters in the stream **/ public boolean hasMore () { return index < end; } /** Returns the next character without advancing the stream **/ public char peek () { if (!hasMore()) throw new RuntimeException("No more characters in stream."); return source.charAt(index++); } /** Returns the next character and advance the stream **/ public char consume () { if (!hasMore()) throw new RuntimeException("No more characters in stream."); return source.charAt(index++); } /** Matches the given needle with the next characters. Returns true if the needle is matched, false otherwise. If there's a * match and consume is true, the stream is advanced by the needle's length. */ public boolean match (String needle, boolean consume) { int needleLength = needle.length(); if(needleLength + index >end){ return false; } for (int i = 0, j = index; i < needleLength; i++, j++) { if (index >= end) return false; if (needle.charAt(i) != source.charAt(j)) return false; } if (consume) index += needleLength; return true; } /** Returns whether the next character is a digit and optionally consumes it. **/ public boolean matchDigit (boolean consume) { if (index >= end) return false; char c = source.charAt(index); if (Character.isDigit(c)) { if (consume) index++; return true; } return false; } /** Returns whether the next character is the start of an identifier and optionally consumes it. Adheres to * {@link Character#isJavaIdentifierStart(char)}. **/ public boolean matchIdentifierStart (boolean consume) { if (index >= end) return false; char c = source.charAt(index); if (Character.isJavaIdentifierStart(c) || c == '@') { if (consume) index++; return true; } return false; } /** Returns whether the next character is the start of an identifier and optionally consumes it. Adheres to * {@link Character#isJavaIdentifierPart(char)}. **/ public boolean matchIdentifierPart (boolean consume) { if (index >= end) return false; char c = source.charAt(index); if (Character.isJavaIdentifierPart(c)) { if (consume) index++; return true; } return false; } /** Skips any number of successive whitespace characters. **/ public void skipWhiteSpace () { while (true) { if (index >= end) return; char c = source.charAt(index); if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { index++; continue; } else { break; } } } /** Start a new Span at the current stream position. Call {@link #endSpan()} to complete the span. **/ public void startSpan () { spanStart = index; } /** Completes the span started with {@link #startSpan()} at the current stream position. **/ public Span endSpan () { return new Span(source, spanStart, index); } public boolean isSpanEmpty () { return spanStart == this.index; } /** Returns the current character position in the stream. **/ public int getPosition () { return index; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/Parser.java ================================================ package org.spiderflow.core.expression.parsing; import java.util.ArrayList; import java.util.List; import javax.xml.transform.Source; import org.spiderflow.core.expression.ExpressionError; import org.spiderflow.core.expression.ExpressionTemplate; import org.spiderflow.core.expression.parsing.Ast.BinaryOperation; import org.spiderflow.core.expression.parsing.Ast.BooleanLiteral; import org.spiderflow.core.expression.parsing.Ast.ByteLiteral; import org.spiderflow.core.expression.parsing.Ast.CharacterLiteral; import org.spiderflow.core.expression.parsing.Ast.DoubleLiteral; import org.spiderflow.core.expression.parsing.Ast.Expression; import org.spiderflow.core.expression.parsing.Ast.FloatLiteral; import org.spiderflow.core.expression.parsing.Ast.FunctionCall; import org.spiderflow.core.expression.parsing.Ast.IntegerLiteral; import org.spiderflow.core.expression.parsing.Ast.ListLiteral; import org.spiderflow.core.expression.parsing.Ast.LongLiteral; import org.spiderflow.core.expression.parsing.Ast.MapLiteral; import org.spiderflow.core.expression.parsing.Ast.MapOrArrayAccess; import org.spiderflow.core.expression.parsing.Ast.MemberAccess; import org.spiderflow.core.expression.parsing.Ast.MethodCall; import org.spiderflow.core.expression.parsing.Ast.Node; import org.spiderflow.core.expression.parsing.Ast.NullLiteral; import org.spiderflow.core.expression.parsing.Ast.ShortLiteral; import org.spiderflow.core.expression.parsing.Ast.StringLiteral; import org.spiderflow.core.expression.parsing.Ast.TernaryOperation; import org.spiderflow.core.expression.parsing.Ast.Text; import org.spiderflow.core.expression.parsing.Ast.UnaryOperation; import org.spiderflow.core.expression.parsing.Ast.VariableAccess; /** Parses a {@link Source} into a {@link ExpressionTemplate}. The implementation is a simple recursive descent parser with a lookahead of * 1. **/ public class Parser { /** Parses a {@link Source} into a {@link ExpressionTemplate}. **/ public static List parse (String source) { List nodes = new ArrayList(); TokenStream stream = new TokenStream(new Tokenizer().tokenize(source)); while (stream.hasMore()) { nodes.add(parseStatement(stream)); } return nodes; } /** Parse a statement, which may either be a text block, if statement, for statement, while statement, macro definition, * include statement or an expression. **/ private static Node parseStatement (TokenStream tokens) { Node result = null; if (tokens.match(TokenType.TextBlock, false)) result = new Text(tokens.consume().getSpan()); else result = parseExpression(tokens); // consume semi-colons as statement delimiters while (tokens.match(";", true)) ; return result; } private static Expression parseExpression (TokenStream stream) { return parseTernaryOperator(stream); } private static Expression parseTernaryOperator (TokenStream stream) { Expression condition = parseBinaryOperator(stream, 0); if (stream.match(TokenType.Questionmark, true)) { Expression trueExpression = parseTernaryOperator(stream); stream.expect(TokenType.Colon); Expression falseExpression = parseTernaryOperator(stream); return new TernaryOperation(condition, trueExpression, falseExpression); } else { return condition; } } private static final TokenType[][] binaryOperatorPrecedence = new TokenType[][] {new TokenType[] {TokenType.Assignment}, new TokenType[] {TokenType.Or, TokenType.And, TokenType.Xor}, new TokenType[] {TokenType.Equal, TokenType.NotEqual}, new TokenType[] {TokenType.Less, TokenType.LessEqual, TokenType.Greater, TokenType.GreaterEqual}, new TokenType[] {TokenType.Plus, TokenType.Minus}, new TokenType[] {TokenType.ForwardSlash, TokenType.Asterisk, TokenType.Percentage}}; private static Expression parseBinaryOperator (TokenStream stream, int level) { int nextLevel = level + 1; Expression left = nextLevel == binaryOperatorPrecedence.length ? parseUnaryOperator(stream) : parseBinaryOperator(stream, nextLevel); TokenType[] operators = binaryOperatorPrecedence[level]; while (stream.hasMore() && stream.match(false, operators)) { Token operator = stream.consume(); Expression right = nextLevel == binaryOperatorPrecedence.length ? parseUnaryOperator(stream) : parseBinaryOperator(stream, nextLevel); left = new BinaryOperation(left, operator, right); } return left; } private static final TokenType[] unaryOperators = new TokenType[] {TokenType.Not, TokenType.Plus, TokenType.Minus}; private static Expression parseUnaryOperator (TokenStream stream) { if (stream.match(false, unaryOperators)) { return new UnaryOperation(stream.consume(), parseUnaryOperator(stream)); } else { if (stream.match(TokenType.LeftParantheses, true)) { Expression expression = parseExpression(stream); stream.expect(TokenType.RightParantheses); return expression; } else { return parseAccessOrCallOrLiteral(stream); } } } private static Expression parseAccessOrCallOrLiteral (TokenStream stream) { if (stream.match(TokenType.Identifier, false)) { return parseAccessOrCall(stream,TokenType.Identifier); } else if (stream.match(TokenType.LeftCurly, false)) { return parseMapLiteral(stream); } else if (stream.match(TokenType.LeftBracket, false)) { return parseListLiteral(stream); } else if (stream.match(TokenType.StringLiteral, false)) { if(stream.hasNext()){ if(stream.next().getType() == TokenType.Period){ stream.prev(); return parseAccessOrCall(stream,TokenType.StringLiteral); } stream.prev(); } return new StringLiteral(stream.expect(TokenType.StringLiteral).getSpan()); } else if (stream.match(TokenType.BooleanLiteral, false)) { return new BooleanLiteral(stream.expect(TokenType.BooleanLiteral).getSpan()); } else if (stream.match(TokenType.DoubleLiteral, false)) { return new DoubleLiteral(stream.expect(TokenType.DoubleLiteral).getSpan()); } else if (stream.match(TokenType.FloatLiteral, false)) { return new FloatLiteral(stream.expect(TokenType.FloatLiteral).getSpan()); } else if (stream.match(TokenType.ByteLiteral, false)) { return new ByteLiteral(stream.expect(TokenType.ByteLiteral).getSpan()); } else if (stream.match(TokenType.ShortLiteral, false)) { return new ShortLiteral(stream.expect(TokenType.ShortLiteral).getSpan()); } else if (stream.match(TokenType.IntegerLiteral, false)) { return new IntegerLiteral(stream.expect(TokenType.IntegerLiteral).getSpan()); } else if (stream.match(TokenType.LongLiteral, false)) { return new LongLiteral(stream.expect(TokenType.LongLiteral).getSpan()); } else if (stream.match(TokenType.CharacterLiteral, false)) { return new CharacterLiteral(stream.expect(TokenType.CharacterLiteral).getSpan()); } else if (stream.match(TokenType.NullLiteral, false)) { return new NullLiteral(stream.expect(TokenType.NullLiteral).getSpan()); } else { ExpressionError.error("Expected a variable, field, map, array, function or method call, or literal.", stream); return null; // not reached } } private static Expression parseMapLiteral (TokenStream stream) { Span openCurly = stream.expect(TokenType.LeftCurly).getSpan(); List keys = new ArrayList<>(); List values = new ArrayList<>(); while (stream.hasMore() && !stream.match("}", false)) { if(stream.match(TokenType.StringLiteral, false)){ keys.add(stream.expect(TokenType.StringLiteral)); }else{ keys.add(stream.expect(TokenType.Identifier)); } stream.expect(":"); values.add(parseExpression(stream)); if (!stream.match("}", false)) stream.expect(TokenType.Comma); } Span closeCurly = stream.expect("}").getSpan(); return new MapLiteral(new Span(openCurly, closeCurly), keys, values); } private static Expression parseListLiteral (TokenStream stream) { Span openBracket = stream.expect(TokenType.LeftBracket).getSpan(); List values = new ArrayList<>(); while (stream.hasMore() && !stream.match(TokenType.RightBracket, false)) { values.add(parseExpression(stream)); if (!stream.match(TokenType.RightBracket, false)) stream.expect(TokenType.Comma); } Span closeBracket = stream.expect(TokenType.RightBracket).getSpan(); return new ListLiteral(new Span(openBracket, closeBracket), values); } private static Expression parseAccessOrCall (TokenStream stream,TokenType tokenType) { //Span identifier = stream.expect(TokenType.Identifier); //Expression result = new VariableAccess(identifier); Span identifier = stream.expect(tokenType).getSpan(); Expression result = tokenType == TokenType.StringLiteral ? new StringLiteral(identifier) :new VariableAccess(identifier); while (stream.hasMore() && stream.match(false, TokenType.LeftParantheses, TokenType.LeftBracket, TokenType.Period)) { // function or method call if (stream.match(TokenType.LeftParantheses, false)) { List arguments = parseArguments(stream); Span closingSpan = stream.expect(TokenType.RightParantheses).getSpan(); if (result instanceof VariableAccess || result instanceof MapOrArrayAccess) result = new FunctionCall(new Span(result.getSpan(), closingSpan), result, arguments); else if (result instanceof MemberAccess) { result = new MethodCall(new Span(result.getSpan(), closingSpan), (MemberAccess)result, arguments); } else { ExpressionError.error("Expected a variable, field or method.", stream); } } // map or array access else if (stream.match(TokenType.LeftBracket, true)) { Expression keyOrIndex = parseExpression(stream); Span closingSpan = stream.expect(TokenType.RightBracket).getSpan(); result = new MapOrArrayAccess(new Span(result.getSpan(), closingSpan), result, keyOrIndex); } // field or method access else if (stream.match(TokenType.Period, true)) { identifier = stream.expect(TokenType.Identifier).getSpan(); result = new MemberAccess(result, identifier); } } return result; } /** Does not consume the closing parentheses. **/ private static List parseArguments (TokenStream stream) { stream.expect(TokenType.LeftParantheses); List arguments = new ArrayList(); while (stream.hasMore() && !stream.match(TokenType.RightParantheses, false)) { arguments.add(parseExpression(stream)); if (!stream.match(TokenType.RightParantheses, false)) stream.expect(TokenType.Comma); } return arguments; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/Span.java ================================================ package org.spiderflow.core.expression.parsing; /** A span within a source string denoted by start and end index, with the latter being exclusive. */ public class Span { /** the source string this span refers to **/ private final String source; /** start index in source string, starting at 0 **/ private int start; /** end index in source string, exclusive, starting at 0 **/ private int end; /** Cached String instance to reduce pressure on GC **/ private final String cachedText; public Span (String source) { this(source, 0, source.length()); } public Span (String source, int start, int end) { if (start > end) throw new IllegalArgumentException("Start must be <= end."); if (start < 0) throw new IndexOutOfBoundsException("Start must be >= 0."); if (start > source.length() - 1) throw new IndexOutOfBoundsException("Start outside of string."); if (end >source.length()) throw new IndexOutOfBoundsException("End outside of string."); this.source = source; this.start = start; this.end = end; this.cachedText = source.substring(start, end); } public Span (Span start, Span end) { if (!start.source.equals(end.source)) throw new IllegalArgumentException("The two spans do not reference the same source."); if (start.start > end.end) throw new IllegalArgumentException("Start must be <= end."); if (start.start < 0) throw new IndexOutOfBoundsException("Start must be >= 0."); if (start.start > start.source.length() - 1) throw new IndexOutOfBoundsException("Start outside of string."); if (end.end > start.source.length()) throw new IndexOutOfBoundsException("End outside of string."); this.source = start.source; this.start = start.start; this.end = end.end; this.cachedText = source.substring(this.start, this.end); } /** Returns the text referenced by this span **/ public String getText () { return cachedText; } /** Returns the index of the first character of this span. **/ public int getStart () { return start; } /** Returns the index of the last character of this span plus 1. **/ public int getEnd () { return end; } /** Returns the source string this span references. **/ public String getSource () { return source; } @Override public String toString () { return "Span [text=" + getText() + ", start=" + start + ", end=" + end + "]"; } /** Returns the line this span is on. Does not return a correct result for spans across multiple lines. **/ public Line getLine () { int lineStart = start; while (true) { if (lineStart < 0) break; char c = source.charAt(lineStart); if (c == '\n') { lineStart = lineStart + 1; break; } lineStart--; } if (lineStart < 0) lineStart = 0; int lineEnd = end; while (true) { if (lineEnd > source.length() - 1) break; char c = source.charAt(lineEnd); if (c == '\n') { break; } lineEnd++; } int lineNumber = 0; int idx = lineStart; while (idx > 0) { char c = source.charAt(idx); if (c == '\n') { lineNumber++; } idx--; } lineNumber++; return new Line(source, lineStart, lineEnd, lineNumber); } /** A line within a Source **/ public static class Line { private final String source; private final int start; private final int end; private final int lineNumber; public Line (String source, int start, int end, int lineNumber) { this.source = source; this.start = start; this.end = end; this.lineNumber = lineNumber; } public String getSource () { return source; } public int getStart () { return start; } public int getEnd () { return end; } public int getLineNumber () { return lineNumber; } public String getText () { return source.substring(start, end); } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/Token.java ================================================ package org.spiderflow.core.expression.parsing; /** A token produced by the {@link Tokenizer}. */ public class Token { private final TokenType type; private final Span span; public Token (TokenType type, Span span) { this.type = type; this.span = span; } public TokenType getType () { return type; } public Span getSpan () { return span; } public String getText () { return span.getText(); } @Override public String toString () { return "Token [type=" + type + ", span=" + span + "]"; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/TokenStream.java ================================================ package org.spiderflow.core.expression.parsing; import java.util.List; import javax.xml.transform.Source; import org.spiderflow.core.expression.ExpressionError; /** Iterates over a list of {@link Token} instances, provides methods to match expected tokens and throw errors in case of a * mismatch. */ public class TokenStream { private final List tokens; private int index; private final int end; public TokenStream (List tokens) { this.tokens = tokens; this.index = 0; this.end = tokens.size(); } /** Returns whether there are more tokens in the stream. **/ public boolean hasMore () { return index < end; } public boolean hasNext(){ return index + 1 < end; } public boolean hasPrev(){ return index > 0; } /** Consumes the next token and returns it. **/ public Token consume () { if (!hasMore()) throw new RuntimeException("Reached the end of the source."); return tokens.get(index++); } public Token next(){ if (!hasMore()) throw new RuntimeException("Reached the end of the source."); return tokens.get(++index); } public Token prev(){ if(index == 0){ throw new RuntimeException("Reached the end of the source."); } return tokens.get(--index); } /** Checks if the next token has the give type and optionally consumes, or throws an error if the next token did not match the * type. */ public Token expect (TokenType type) { boolean result = match(type, true); if (!result) { Token token = index < tokens.size() ? tokens.get(index) : null; Span span = token != null ? token.getSpan() : null; if (span == null) ExpressionError.error("Expected '" + type.getError() + "', but reached the end of the source.", this); else ExpressionError.error("Expected '" + type.getError() + "', but got '" + token.getText() + "'", span); return null; // never reached } else { return tokens.get(index - 1); } } /** Checks if the next token matches the given text and optionally consumes, or throws an error if the next token did not match * the text. */ public Token expect (String text) { boolean result = match(text, true); if (!result) { Token token = index < tokens.size() ? tokens.get(index) : null; Span span = token != null ? token.getSpan() : null; if (span == null) ExpressionError.error("Expected '" + text + "', but reached the end of the source.", this); else ExpressionError.error("Expected '" + text + "', but got '" + token.getText() + "'", span); return null; // never reached } else { return tokens.get(index - 1); } } /** Matches and optionally consumes the next token in case of a match. Returns whether the token matched. */ public boolean match (TokenType type, boolean consume) { if (index >= end) return false; if (tokens.get(index).getType() == type) { if (consume) index++; return true; } return false; } /** Matches and optionally consumes the next token in case of a match. Returns whether the token matched. */ public boolean match (String text, boolean consume) { if (index >= end) return false; if (tokens.get(index).getText().equals(text)) { if (consume) index++; return true; } return false; } /** Matches any of the token types and optionally consumes the next token in case of a match. Returns whether the token * matched. */ public boolean match (boolean consume, TokenType... types) { for (TokenType type : types) { if (match(type, consume)) return true; } return false; } /** Matches any of the token texts and optionally consumes the next token in case of a match. Returns whether the token * matched. */ public boolean match (boolean consume, String... tokenTexts) { for (String text : tokenTexts) { if (match(text, consume)) return true; } return false; } /** Returns the {@link Source} this stream wraps. */ public String getSource () { if (tokens.size() == 0) return null; return tokens.get(0).getSpan().getSource(); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/TokenType.java ================================================ package org.spiderflow.core.expression.parsing; import java.util.Arrays; import java.util.Comparator; /** Enumeration of token types. A token type consists of a representation for error messages, and may optionally specify a literal * to be used by the {@link CharacterStream} to recognize the token. Token types are sorted by their literal length to easy * matching of token types with common prefixes, e.g. "<" and "<=". Token types with longer literals are matched first. */ public enum TokenType { // @off TextBlock("a text block"), Period(".", "."), Comma(",", ","), Semicolon(";", ";"), Colon(":", ":"), Plus("+", "+"), Minus("-", "-"), Asterisk("*", "*"), ForwardSlash("/", "/"), PostSlash("\\", "\\"), Percentage("%", "%"), LeftParantheses("(", ")"), RightParantheses(")", ")"), LeftBracket("[", "["), RightBracket("]", "]"), LeftCurly("{", "{"), RightCurly("}"), // special treatment! Less("<", "<"), Greater(">", ">"), LessEqual("<=", "<="), GreaterEqual(">=", ">="), Equal("==", "=="), NotEqual("!=", "!="), Assignment("=", "="), And("&&", "&&"), Or("||", "||"), Xor("^", "^"), Not("!", "!"), Questionmark("?", "?"), DoubleQuote("\"", "\""), SingleQuote("'", "'"), BooleanLiteral("true or false"), DoubleLiteral("a double floating point number"), FloatLiteral("a floating point number"), LongLiteral("a long integer number"), IntegerLiteral("an integer number"), ShortLiteral("a short integer number"), ByteLiteral("a byte integer number"), CharacterLiteral("a character"), StringLiteral("a string"), NullLiteral("null"), Identifier("an identifier"); // @on private static TokenType[] values; static { // Sort the token types by their literal length. The character stream uses this // this order to match tokens with the longest length first. values = TokenType.values(); Arrays.sort(values, new Comparator() { @Override public int compare (TokenType o1, TokenType o2) { if (o1.literal == null && o2.literal == null) return 0; if (o1.literal == null && o2.literal != null) return 1; if (o1.literal != null && o2.literal == null) return -1; return o2.literal.length() - o1.literal.length(); } }); } private final String literal; private final String error; TokenType (String error) { this.literal = null; this.error = error; } TokenType (String literal, String error) { this.literal = literal; this.error = error; } /** The literal to match, may be null. **/ public String getLiteral () { return literal; } /** The error string to use when reporting this token type in an error message. **/ public String getError () { return error; } /** Returns an array of token types, sorted in descending order based on their literal length. This is used by the * {@link CharacterStream} to match token types with the longest literal first. E.g. "<=" will be matched before "<". **/ public static TokenType[] getSortedValues () { return values; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/expression/parsing/Tokenizer.java ================================================ package org.spiderflow.core.expression.parsing; import java.util.ArrayList; import java.util.List; import org.spiderflow.core.expression.ExpressionError; import org.spiderflow.core.expression.ExpressionError.StringLiteralException; import org.spiderflow.core.expression.ExpressionError.TemplateException; public class Tokenizer { /** Tokenizes the source into tokens with a {@link TokenType}. Text blocks not enclosed in {{ }} are returned as a single token * of type {@link TokenType.TextBlock}. {{ and }} are not returned as individual tokens. See {@link TokenType} for the list of * tokens this tokenizer understands. */ public List tokenize (String source) { List tokens = new ArrayList(); if (source.length() == 0) return tokens; CharacterStream stream = new CharacterStream(source); stream.startSpan(); RuntimeException re = null; while (stream.hasMore()) { if (stream.match("${", false)) { if (!stream.isSpanEmpty()) tokens.add(new Token(TokenType.TextBlock, stream.endSpan())); stream.startSpan(); boolean isContinue = false; do{ while (!stream.match("}", true)) { if (!stream.hasMore()) ExpressionError.error("Did not find closing }.", stream.endSpan()); stream.consume(); } try{ tokens.addAll(tokenizeCodeSpan(stream.endSpan())); isContinue = false; re = null; }catch(TemplateException e){ re = e; if(e.getCause() != null || stream.hasMore()){ isContinue = true; } } }while(isContinue); if(re != null){ throw re; } stream.startSpan(); } else { stream.consume(); } } if (!stream.isSpanEmpty()) tokens.add(new Token(TokenType.TextBlock, stream.endSpan())); return tokens; } private static List tokenizeCodeSpan (Span span) { String source = span.getSource(); CharacterStream stream = new CharacterStream(source, span.getStart(), span.getEnd()); List tokens = new ArrayList(); // match opening tag and throw it away if (!stream.match("${", true)) ExpressionError.error("Expected ${", new Span(source, stream.getPosition(), stream.getPosition() + 1)); int leftCount = 0; int rightCount = 0; outer: while (stream.hasMore()) { // skip whitespace stream.skipWhiteSpace(); // Number literal, both integers and floats. Number literals may be suffixed by a type identifier. if (stream.matchDigit(false)) { TokenType type = TokenType.IntegerLiteral; stream.startSpan(); while (stream.matchDigit(true)) ; if (stream.match(TokenType.Period.getLiteral(), true)) { type = TokenType.FloatLiteral; while (stream.matchDigit(true)) ; } if (stream.match("b", true) || stream.match("B", true)) { if (type == TokenType.FloatLiteral) ExpressionError.error("Byte literal can not have a decimal point.", stream.endSpan()); type = TokenType.ByteLiteral; } else if (stream.match("s", true) || stream.match("S", true)) { if (type == TokenType.FloatLiteral) ExpressionError.error("Short literal can not have a decimal point.", stream.endSpan()); type = TokenType.ShortLiteral; } else if (stream.match("l", true) || stream.match("L", true)) { if (type == TokenType.FloatLiteral) ExpressionError.error("Long literal can not have a decimal point.", stream.endSpan()); type = TokenType.LongLiteral; } else if (stream.match("f", true) || stream.match("F", true)) { type = TokenType.FloatLiteral; } else if (stream.match("d", true) || stream.match("D", true)) { type = TokenType.DoubleLiteral; } Span numberSpan = stream.endSpan(); tokens.add(new Token(type, numberSpan)); continue; } // String literal if (stream.match(TokenType.SingleQuote.getLiteral(), true)) { stream.startSpan(); boolean matchedEndQuote = false; while (stream.hasMore()) { // Note: escape sequences like \n are parsed in StringLiteral if (stream.match("\\", true)) { stream.consume(); } if (stream.match(TokenType.SingleQuote.getLiteral(), true)) { matchedEndQuote = true; break; } stream.consume(); } if (!matchedEndQuote) ExpressionError.error("字符串没有结束符\'", stream.endSpan(),new StringLiteralException()); Span stringSpan = stream.endSpan(); stringSpan = new Span(stringSpan.getSource(), stringSpan.getStart() - 1, stringSpan.getEnd()); tokens.add(new Token(TokenType.StringLiteral, stringSpan)); continue; } // String literal if (stream.match(TokenType.DoubleQuote.getLiteral(), true)) { stream.startSpan(); boolean matchedEndQuote = false; while (stream.hasMore()) { // Note: escape sequences like \n are parsed in StringLiteral if (stream.match("\\", true)) { stream.consume(); } if (stream.match(TokenType.DoubleQuote.getLiteral(), true)) { matchedEndQuote = true; break; } stream.consume(); } if (!matchedEndQuote) ExpressionError.error("字符串没有结束符\"", stream.endSpan(),new StringLiteralException()); Span stringSpan = stream.endSpan(); stringSpan = new Span(stringSpan.getSource(), stringSpan.getStart() - 1, stringSpan.getEnd()); tokens.add(new Token(TokenType.StringLiteral, stringSpan)); continue; } // Identifier, keyword, boolean literal, or null literal if (stream.matchIdentifierStart(true)) { stream.startSpan(); while (stream.matchIdentifierPart(true)) ; Span identifierSpan = stream.endSpan(); identifierSpan = new Span(identifierSpan.getSource(), identifierSpan.getStart() - 1, identifierSpan.getEnd()); if (identifierSpan.getText().equals("true") || identifierSpan.getText().equals("false")) { tokens.add(new Token(TokenType.BooleanLiteral, identifierSpan)); } else if (identifierSpan.getText().equals("null")) { tokens.add(new Token(TokenType.NullLiteral, identifierSpan)); } else { tokens.add(new Token(TokenType.Identifier, identifierSpan)); } continue; } // Simple tokens for (TokenType t : TokenType.getSortedValues()) { if (t.getLiteral() != null) { if (stream.match(t.getLiteral(), true)) { if(t == TokenType.LeftCurly){ leftCount ++; } tokens.add(new Token(t, new Span(source, stream.getPosition() - t.getLiteral().length(), stream.getPosition()))); continue outer; } } } if(leftCount!=rightCount&&stream.match("}", true)){ rightCount++; tokens.add(new Token(TokenType.RightCurly, new Span(source, stream.getPosition() - 1, stream.getPosition()))); continue outer; } // match closing tag if (stream.match("}", false)) break; ExpressionError.error("Unknown token", new Span(source, stream.getPosition(), stream.getPosition() + 1)); } // code spans must end with } if (!stream.match("}", true)) ExpressionError.error("Expected }", new Span(source, stream.getPosition(), stream.getPosition() + 1)); return tokens; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/io/HttpRequest.java ================================================ package org.spiderflow.core.io; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.jsoup.Connection; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; /** * 请求对象包装类 * @author Administrator * */ public class HttpRequest { private Connection connection = null; public static HttpRequest create(){ return new HttpRequest(); } public HttpRequest url(String url){ this.connection = Jsoup.connect(url); this.connection.method(Method.GET); this.connection.timeout(60000); return this; } public HttpRequest headers(Map headers){ this.connection.headers(headers); return this; } public HttpRequest header(String key,String value){ this.connection.header(key, value); return this; } public HttpRequest header(String key,Object value){ if(value != null){ this.connection.header(key,value.toString()); } return this; } public HttpRequest cookies(Map cookies){ this.connection.cookies(cookies); return this; } public HttpRequest cookie(String name, String value) { if (value != null) { this.connection.cookie(name, value); } return this; } public HttpRequest contentType(String contentType){ this.connection.header("Content-Type", contentType); return this; } public HttpRequest data(String key,String value){ this.connection.data(key, value); return this; } public HttpRequest data(String key,Object value){ if(value != null){ this.connection.data(key, value.toString()); } return this; } public HttpRequest data(String key,String filename,InputStream is){ this.connection.data(key, filename, is); return this; } public HttpRequest data(Object body){ if(body != null){ this.connection.requestBody(body.toString()); } return this; } public HttpRequest data(Map data){ this.connection.data(data); return this; } public HttpRequest method(String method){ this.connection.method(Method.valueOf(method)); return this; } public HttpRequest followRedirect(boolean followRedirects){ this.connection.followRedirects(followRedirects); return this; } public HttpRequest timeout(int timeout){ this.connection.timeout(timeout); return this; } public HttpRequest proxy(String host,int port){ this.connection.proxy(host, port); return this; } @SuppressWarnings("deprecation") public HttpRequest validateTLSCertificates(boolean value){ this.connection.validateTLSCertificates(value); return this; } public HttpResponse execute() throws IOException{ this.connection.ignoreContentType(true); this.connection.ignoreHttpErrors(true); this.connection.maxBodySize(0); Response response = connection.execute(); return new HttpResponse(response); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/io/HttpResponse.java ================================================ package org.spiderflow.core.io; import com.alibaba.fastjson.JSON; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.spiderflow.io.SpiderResponse; import java.io.InputStream; import java.util.Map; /** * 响应对象包装类 * @author Administrator * */ public class HttpResponse implements SpiderResponse{ private Response response; private int statusCode; private String urlLink; private String htmlValue; private String titleName; private Object jsonValue; public HttpResponse(Response response){ super(); this.response = response; this.statusCode = response.statusCode(); this.urlLink = response.url().toExternalForm(); } @Override public int getStatusCode(){ return statusCode; } @Override public String getTitle() { if (titleName == null) { synchronized (this){ titleName = Jsoup.parse(getHtml()).title(); } } return titleName; } @Override public String getHtml(){ if(htmlValue == null){ synchronized (this){ htmlValue = response.body(); } } return htmlValue; } @Override public Object getJson(){ if(jsonValue == null){ jsonValue = JSON.parse(getHtml()); } return jsonValue; } @Override public Map getCookies(){ return response.cookies(); } @Override public Map getHeaders(){ return response.headers(); } @Override public byte[] getBytes(){ return response.bodyAsBytes(); } @Override public String getContentType(){ return response.contentType(); } @Override public void setCharset(String charset) { this.response.charset(charset); } @Override public String getUrl() { return urlLink; } @Override public InputStream getStream() { return response.bodyStream(); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/job/SpiderJob.java ================================================ package org.spiderflow.core.job; import org.apache.commons.lang3.time.DateFormatUtils; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.context.SpiderContextHolder; import org.spiderflow.core.Spider; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.model.Task; import org.spiderflow.core.service.SpiderFlowService; import org.spiderflow.core.service.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 爬虫定时执行 * * @author Administrator */ @Component public class SpiderJob extends QuartzJobBean { @Autowired private Spider spider; @Autowired private SpiderFlowService spiderFlowService; @Autowired private TaskService taskService; private static Map contextMap = new HashMap<>(); @Value("${spider.job.enable:true}") private boolean spiderJobEnable; @Value("${spider.workspace}") private String workspace; private static Logger logger = LoggerFactory.getLogger(SpiderJob.class); @Override protected void executeInternal(JobExecutionContext context) { if (!spiderJobEnable) { return; } JobDataMap dataMap = context.getMergedJobDataMap(); SpiderFlow spiderFlow = (SpiderFlow) dataMap.get(SpiderJobManager.JOB_PARAM_NAME); if("1".equalsIgnoreCase(spiderFlow.getEnabled())){ run(spiderFlow, context.getNextFireTime()); } } public void run(String id) { run(spiderFlowService.getById(id), null); } public void run(SpiderFlow spiderFlow, Date nextExecuteTime) { Task task = new Task(); task.setFlowId(spiderFlow.getId()); task.setBeginTime(new Date()); taskService.save(task); run(spiderFlow,task,nextExecuteTime); } public void run(SpiderFlow spiderFlow, Task task,Date nextExecuteTime) { SpiderJobContext context = null; Date now = new Date(); try { context = SpiderJobContext.create(this.workspace, spiderFlow.getId(),task.getId(),false); SpiderContextHolder.set(context); contextMap.put(task.getId(), context); logger.info("开始执行任务{}", spiderFlow.getName()); spider.run(spiderFlow, context); logger.info("执行任务{}完毕,下次执行时间:{}", spiderFlow.getName(), nextExecuteTime == null ? null : DateFormatUtils.format(nextExecuteTime, "yyyy-MM-dd HH:mm:ss")); } catch (Exception e) { logger.error("执行任务{}出错", spiderFlow.getName(), e); } finally { if (context != null) { context.close(); } task.setEndTime(new Date()); taskService.saveOrUpdate(task); contextMap.remove(task.getId()); SpiderContextHolder.remove(); } spiderFlowService.executeCountIncrement(spiderFlow.getId(), now, nextExecuteTime); } public static SpiderContext getSpiderContext(Integer taskId) { return contextMap.get(taskId); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/job/SpiderJobContext.java ================================================ package org.spiderflow.core.job; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.model.SpiderOutput; public class SpiderJobContext extends SpiderContext{ private static final long serialVersionUID = 9099787449108938453L; private static Logger logger = LoggerFactory.getLogger(SpiderJobContext.class); private OutputStream outputstream; private List outputs = new ArrayList<>(); private boolean output; public SpiderJobContext(OutputStream outputstream,boolean output) { super(); this.outputstream = outputstream; this.output = output; } public void close(){ try { this.outputstream.close(); } catch (Exception e) { } } @Override public void addOutput(SpiderOutput output) { if(this.output){ synchronized (this.outputs){ this.outputs.add(output); } } } @Override public List getOutputs() { return outputs; } public OutputStream getOutputstream(){ return this.outputstream; } public static SpiderJobContext create(String directory,String id,Integer taskId,boolean output){ OutputStream os = null; try { File file = new File(new File(directory),id + File.separator + "logs" + File.separator + taskId + ".log"); File dirFile = file.getParentFile(); if(!dirFile.exists()){ dirFile.mkdirs(); } os = new FileOutputStream(file, true); } catch (Exception e) { logger.error("创建日志文件出错",e); } SpiderJobContext context = new SpiderJobContext(os, output); context.setFlowId(id); return context; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/job/SpiderJobManager.java ================================================ package org.spiderflow.core.job; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.Spider; import org.spiderflow.core.model.SpiderFlow; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; /** * 爬虫定时执行管理 * @author Administrator * */ @Component public class SpiderJobManager { private static Logger logger = LoggerFactory.getLogger(SpiderJobManager.class); private final static String JOB_NAME = "SPIDER_TASK_"; public final static String JOB_PARAM_NAME = "SPIDER_FLOW"; @Autowired private SpiderJob spiderJob; /** * 调度器 */ @Autowired private Scheduler scheduler; private JobKey getJobKey(String id){ return JobKey.jobKey(JOB_NAME + id); } private TriggerKey getTriggerKey(String id){ return TriggerKey.triggerKey(JOB_NAME + id); } /** * 新建定时任务 * @param spiderFlow 爬虫流程图 * @return boolean true/false */ public Date addJob(SpiderFlow spiderFlow){ try { JobDetail job = JobBuilder.newJob(SpiderJob.class).withIdentity(getJobKey(spiderFlow.getId())).build(); job.getJobDataMap().put(JOB_PARAM_NAME, spiderFlow); CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(spiderFlow.getCron()).withMisfireHandlingInstructionDoNothing(); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(spiderFlow.getId())).withSchedule(cronScheduleBuilder).build(); return scheduler.scheduleJob(job,trigger); } catch (SchedulerException e) { logger.error("创建定时任务出错",e); return null; } } public void run(String id){ Spider.executorInstance.submit(()->{ spiderJob.run(id); }); } public boolean remove(String id){ try { scheduler.deleteJob(getJobKey(id)); return true; } catch (SchedulerException e) { logger.error("删除定时任务失败",e); return false; } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/DataSourceMapper.java ================================================ package org.spiderflow.core.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import org.spiderflow.core.model.DataSource; import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface DataSourceMapper extends BaseMapper{ @Select("select id,name from sp_datasource") List selectAll(); } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/FlowNoticeMapper.java ================================================ package org.spiderflow.core.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.spiderflow.core.model.FlowNotice; @Mapper public interface FlowNoticeMapper extends BaseMapper { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/FunctionMapper.java ================================================ package org.spiderflow.core.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.spiderflow.core.model.Function; @Mapper public interface FunctionMapper extends BaseMapper { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/SpiderFlowMapper.java ================================================ package org.spiderflow.core.mapper; import java.util.Date; import java.util.List; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.spiderflow.core.model.SpiderFlow; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * 爬虫资源库 实现爬虫的入库 * @author Administrator * */ public interface SpiderFlowMapper extends BaseMapper{ @Select({ "" }) IPage selectSpiderPage(Page page,@Param("name") String name); @Insert("insert into sp_flow(id,name,xml,enabled) values(#{id},#{name},#{xml},'0')") int insertSpiderFlow(@Param("id") String id, @Param("name") String name, @Param("xml") String xml); @Update("update sp_flow set name = #{name},xml = #{xml} where id = #{id}") int updateSpiderFlow(@Param("id") String id, @Param("name") String name, @Param("xml") String xml); @Update("update sp_flow set execute_count = 0 where id = #{id}") int resetExecuteCount(@Param("id") String id); @Update("update sp_flow set execute_count = ifnull(execute_count,0) + 1,last_execute_time = #{lastExecuteTime},next_execute_time = #{nextExecuteTime} where id = #{id}") int executeCountIncrementAndExecuteTime(@Param("id") String id, @Param("lastExecuteTime") Date lastExecuteTime, @Param("nextExecuteTime") Date nextExecuteTime); @Update("update sp_flow set execute_count = ifnull(execute_count,0) + 1,last_execute_time = #{lastExecuteTime} where id = #{id}") int executeCountIncrement(@Param("id") String id, @Param("lastExecuteTime") Date lastExecuteTime); @Update("update sp_flow set cron = #{cron},next_execute_time = #{nextExecuteTime} where id = #{id}") int resetCornExpression(@Param("id") String id, @Param("cron") String cron, @Param("nextExecuteTime") Date nextExecuteTime); @Update("update sp_flow set enabled = #{enabled} where id = #{id}") int resetSpiderStatus(@Param("id") String id, @Param("enabled") String enabled); @Update("update sp_flow set next_execute_time = null where id = #{id}") int resetNextExecuteTime(@Param("id") String id); @Update("update sp_flow set next_execute_time = null") int resetNextExecuteTime(); @Select("select id,name from sp_flow") List selectFlows(); @Select("select id,name from sp_flow where id != #{id}") List selectOtherFlows(@Param("id") String id); @Select("select max(a.id) from `sp_task` a left join sp_flow b on a.flow_id = b.id where b.id = #{id}") Integer getFlowMaxTaskId(@Param("id")String id); @Select("select COUNT(id) from sp_flow where id = #{id}") Integer getCountById(@Param("id")String id); } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/TaskMapper.java ================================================ package org.spiderflow.core.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.spiderflow.core.model.Task; @Mapper public interface TaskMapper extends BaseMapper { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/mapper/VariableMapper.java ================================================ package org.spiderflow.core.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.spiderflow.core.model.Variable; public interface VariableMapper extends BaseMapper { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/DataSource.java ================================================ package org.spiderflow.core.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; @TableName("sp_datasource") public class DataSource { @TableId(type = IdType.UUID) private String id; private String name; private String driverClassName; private String jdbcUrl; private String username; private String password; private Date createDate; public DataSource() { } public DataSource(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/FlowNotice.java ================================================ package org.spiderflow.core.model; import org.spiderflow.enums.FlowNoticeWay; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; /** * 爬虫任务通知实体 * * @author BillDowney * @date 2020年4月3日 下午2:57:46 */ @TableName("sp_flow_notice") public class FlowNotice { @TableField(exist = false) private final String START_FLAG = "1"; /** * 主键,对应{@link SpiderFlow}中的流程id */ @TableId(type = IdType.UUID) private String id; /** * 收件人,多个收件人用","隔开,每个收件人可添加单独通知标记,如不添加通知标记则使用默认配置通知方式 * 例:sms:13012345678,email:12345678@qq.com,13012345670 */ private String recipients; /** * 通知方式{@link FlowNoticeWay} */ private String noticeWay; /** * 流程开始通知:1:开启通知,0:关闭通知 */ private String startNotice; /** * 流程异常通知:1:开启通知,0:关闭通知 */ private String exceptionNotice; /** * 流程结束通知:1:开启通知,0:关闭通知 */ private String endNotice; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRecipients() { return recipients; } public void setRecipients(String recipients) { this.recipients = recipients; } public String getNoticeWay() { return noticeWay; } public void setNoticeWay(String noticeWay) { this.noticeWay = noticeWay; } public String getStartNotice() { return startNotice; } public void setStartNotice(String startNotice) { this.startNotice = startNotice; } public String getExceptionNotice() { return exceptionNotice; } public void setExceptionNotice(String exceptionNotice) { this.exceptionNotice = exceptionNotice; } public String getEndNotice() { return endNotice; } public void setEndNotice(String endNotice) { this.endNotice = endNotice; } public boolean judgeStartNotice() { if (START_FLAG.equals(this.startNotice)) { return true; } return false; } public boolean judgeExceptionNotice() { if (START_FLAG.equals(this.exceptionNotice)) { return true; } return false; } public boolean judgeEndNotice() { if (START_FLAG.equals(this.endNotice)) { return true; } return false; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/Function.java ================================================ package org.spiderflow.core.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; @TableName("sp_function") public class Function { @TableId(type = IdType.UUID) private String id; private String name; private String parameter; private String script; private Date createDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/SpiderFlow.java ================================================ package org.spiderflow.core.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; /** * 爬虫持久化实体类 */ @TableName("sp_flow") public class SpiderFlow { @TableId(type = IdType.UUID) private String id; /** * 定时任务表达式 */ private String cron; private String name; /** * xml流程图 */ private String xml; private String enabled; private Date createDate; private Date lastExecuteTime; private Date nextExecuteTime; /** * 定时执行的执行次数 */ private Integer executeCount; @TableField(exist = false) private Integer running; public SpiderFlow() { } public SpiderFlow(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getXml() { return xml; } public void setXml(String xml) { this.xml = xml; } public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } public String getEnabled() { return enabled; } public void setEnabled(String enabled) { this.enabled = enabled; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getLastExecuteTime() { return lastExecuteTime; } public void setLastExecuteTime(Date lastExecuteTime) { this.lastExecuteTime = lastExecuteTime; } public Date getNextExecuteTime() { return nextExecuteTime; } public void setNextExecuteTime(Date nextExecuteTime) { this.nextExecuteTime = nextExecuteTime; } public Integer getExecuteCount() { return executeCount; } public void setExecuteCount(Integer executeCount) { this.executeCount = executeCount; } public Integer getRunning() { return running; } public void setRunning(Integer running) { this.running = running; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/Task.java ================================================ package org.spiderflow.core.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; @TableName("sp_task") public class Task { @TableId(type = IdType.AUTO) private Integer id; private String flowId; private Date beginTime; private Date endTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/model/Variable.java ================================================ package org.spiderflow.core.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; @TableName("sp_variable") public class Variable { @TableId(type = IdType.AUTO) private Integer id; private String name; private String value; private String description; private Date createDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/script/ScriptManager.java ================================================ package org.spiderflow.core.script; import jdk.nashorn.api.scripting.ScriptObjectMirror; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.expression.ExpressionTemplate; import org.spiderflow.core.expression.ExpressionTemplateContext; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ScriptManager { private static Logger logger = LoggerFactory.getLogger(ScriptManager.class); private static ScriptEngine scriptEngine; private static Set functions = new HashSet<>(); private static ReadWriteLock lock = new ReentrantReadWriteLock(); public static void setScriptEngine(ScriptEngine engine){ scriptEngine = engine; StringBuffer script = new StringBuffer(); script.append("var ExpressionTemplate = Java.type('") .append(ExpressionTemplate.class.getName()) .append("');") .append("var ExpressionTemplateContext = Java.type('") .append(ExpressionTemplateContext.class.getName()) .append("');") .append("function _eval(expression) {") .append("return ExpressionTemplate.create(expression).render(ExpressionTemplateContext.get());") .append("}"); try { scriptEngine.eval(script.toString()); } catch (ScriptException e) { logger.error("注册_eval函数失败",e); } } public static void clearFunctions(){ functions.clear(); } public static ScriptEngine createEngine(){ return new ScriptEngineManager().getEngineByName("nashorn"); } public static void lock(){ lock.writeLock().lock(); } public static void unlock(){ lock.writeLock().unlock(); } public static void registerFunction(ScriptEngine engine,String functionName,String parameters,String script){ try { engine.eval(concatScript(functionName,parameters,script)); functions.add(functionName); logger.info("注册自定义函数{}成功",functionName); } catch (ScriptException e) { logger.warn("注册自定义函数{}失败",functionName,e); } } private static String concatScript(String functionName,String parameters,String script){ StringBuffer scriptBuffer = new StringBuffer(); scriptBuffer.append("function ") .append(functionName) .append("(") .append(parameters == null ? "" : parameters) .append("){") .append(script) .append("}"); return scriptBuffer.toString(); } public static boolean containsFunction(String functionName){ try { lock.readLock().lock(); return functions.contains(functionName); } finally { lock.readLock().unlock(); } } public static void validScript(String functionName,String parameters,String script) throws Exception { new ScriptEngineManager().getEngineByName("nashorn").eval(concatScript(functionName,parameters,script)); } public static Object eval(ExpressionTemplateContext context, String functionName, Object ... args) throws ScriptException, NoSuchMethodException { if("_eval".equals(functionName)){ if(args == null || args.length != 1){ throw new ScriptException("_eval必须要有一个参数"); }else{ return ExpressionTemplate.create(args[0].toString()).render(context); } } if(scriptEngine == null){ throw new NoSuchMethodException(functionName); } try{ lock.readLock().lock(); return convertObject(((Invocable) scriptEngine).invokeFunction(functionName, args)); } finally{ lock.readLock().unlock(); } } private static Object convertObject(Object object){ if(object instanceof ScriptObjectMirror){ ScriptObjectMirror mirror = (ScriptObjectMirror) object; if(mirror.isArray()){ int size = mirror.size(); Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = convertObject(mirror.getSlot(i)); } return array; }else{ String className = mirror.getClassName(); if("Date".equalsIgnoreCase(className)){ return new Date(mirror.to(Long.class)); } //其它类型待处理 } } return object; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/serializer/FastJsonSerializer.java ================================================ package org.spiderflow.core.serializer; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import java.io.IOException; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; /** * Created on 2019-12-23 */ public class FastJsonSerializer implements ObjectSerializer { public static SerializeConfig serializeConfig; static { serializeConfig = new SerializeConfig(); FastJsonSerializer serializer = new FastJsonSerializer(); serializeConfig.put(Long.TYPE, serializer); serializeConfig.put(Long.class, serializer); serializeConfig.put(BigDecimal.class, serializer); serializeConfig.put(BigInteger.class, serializer); } @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if(object == null){ if(serializer.isEnabled(SerializerFeature.WriteNullNumberAsZero)){ serializer.out.write("0"); }else{ serializer.out.writeNull(); } return; } serializer.out.writeString(object.toString()); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/DataSourceService.java ================================================ package org.spiderflow.core.service; import org.spiderflow.core.mapper.DataSourceMapper; import org.spiderflow.core.model.DataSource; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @Service public class DataSourceService extends ServiceImpl { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/FlowNoticeService.java ================================================ package org.spiderflow.core.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.expression.ExpressionTemplate; import org.spiderflow.core.expression.ExpressionTemplateContext; import org.spiderflow.core.mapper.FlowNoticeMapper; import org.spiderflow.core.mapper.SpiderFlowMapper; import org.spiderflow.core.model.FlowNotice; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.utils.EmailUtils; import org.spiderflow.core.utils.ExpressionUtils; import org.spiderflow.enums.FlowNoticeType; import org.spiderflow.enums.FlowNoticeWay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cglib.beans.BeanMap; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service public class FlowNoticeService extends ServiceImpl { private static final Logger logger = LoggerFactory.getLogger(FlowNoticeService.class); @Autowired private SpiderFlowMapper spiderFlowMapper; @Autowired private EmailUtils emailUtils; @Value("${spider.notice.subject:spider-flow流程通知}") private String subject; @Value("${spider.notice.content.start}") private String startContext; @Value("${spider.notice.content.end}") private String endContext; @Value("${spider.notice.content.exception}") private String exceptionContext; @Override public boolean saveOrUpdate(FlowNotice entity) { if (spiderFlowMapper.getCountById(entity.getId()) == 0) { throw new RuntimeException("没有找到对应的流程"); } return super.saveOrUpdate(entity); } /** * 发送对应的流程通知 * * @param spiderFlow 流程信息 * @param type 通知类型 * @author BillDowney * @date 2020年4月4日 上午1:37:50 */ public void sendFlowNotice(SpiderFlow spiderFlow, FlowNoticeType type) { FlowNotice notice = baseMapper.selectById(spiderFlow.getId()); if (notice != null && !StringUtils.isEmpty(notice.getRecipients()) && !StringUtils.isEmpty(notice.getNoticeWay())) { String content = null; String sendSubject = this.subject; switch (type) { case startNotice: if (notice.judgeStartNotice()) { content = startContext; sendSubject += " - 流程开始执行"; } break; case endNotice: if (notice.judgeEndNotice()) { content = endContext; sendSubject += " - 流程执行完毕"; } break; case exceptionNotice: if (notice.judgeExceptionNotice()) { content = exceptionContext; sendSubject += " - 流程发生异常"; } break; } if (StringUtils.isEmpty(content)) { return; } // 定义一个上下文变量 Map variables = new HashMap(); // 放入流程信息 BeanMap beanMap = BeanMap.create(spiderFlow); for (Object key : beanMap.keySet()) { variables.put(key + "", beanMap.get(key)); } // 放入当前时间 variables.put("currentDate", this.getCurrentDate()); content = ExpressionUtils.execute(content.replaceAll("[{]", "\\${"), variables) + ""; // 整理收件人 String recipients = notice.getRecipients(); for (String recipient : recipients.split(",")) { String noticeWay = notice.getNoticeWay(); String people = recipient; // 如果含有":"证明单独配置了发送方式 if (recipient.contains(":")) { String[] strs = recipient.split(":"); noticeWay = strs[0]; people = strs[1]; } FlowNoticeWay way = FlowNoticeWay.email; try { way = FlowNoticeWay.valueOf(noticeWay); } catch (Exception e) { logger.error(e.getMessage(), e); } switch (way) { case email: emailUtils.sendSimpleMail(sendSubject, content, people); break; } } } } private String getCurrentDate() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); return sdf.format(new Date()); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/FunctionService.java ================================================ package org.spiderflow.core.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.mapper.FunctionMapper; import org.spiderflow.core.model.Function; import org.spiderflow.core.script.ScriptManager; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.script.ScriptEngine; import java.io.Serializable; @Service public class FunctionService extends ServiceImpl { private static Logger logger = LoggerFactory.getLogger(FunctionService.class); /** * 初始化/重置自定义函数 */ @PostConstruct private void init(){ try { ScriptManager.lock(); ScriptManager.clearFunctions(); ScriptEngine engine = ScriptManager.createEngine(); super.list().forEach(function -> { ScriptManager.registerFunction(engine,function.getName(),function.getParameter(),function.getScript()); }); ScriptManager.setScriptEngine(engine); } finally { ScriptManager.unlock(); } } public String saveFunction(Function entity) { try { ScriptManager.validScript(entity.getName(),entity.getParameter(),entity.getScript()); super.saveOrUpdate(entity); init(); return null; } catch (Exception e) { logger.error("保存自定义函数出错",e); return ExceptionUtils.getStackTrace(e); } } @Override public boolean removeById(Serializable id) { boolean ret = super.removeById(id); init(); return ret; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/SpiderFlowService.java ================================================ package org.spiderflow.core.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.TriggerBuilder; import org.quartz.TriggerUtils; import org.quartz.spi.OperableTrigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.job.SpiderJobManager; import org.spiderflow.core.mapper.FlowNoticeMapper; import org.spiderflow.core.mapper.SpiderFlowMapper; import org.spiderflow.core.model.SpiderFlow; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * 爬虫流程执行服务 * @author Administrator * */ @Service public class SpiderFlowService extends ServiceImpl { @Autowired private SpiderFlowMapper sfMapper; @Autowired private SpiderJobManager spiderJobManager; @Autowired private FlowNoticeMapper flowNoticeMapper; private static Logger logger = LoggerFactory.getLogger(SpiderFlowService.class); @Value("${spider.workspace}") private String workspace; //项目启动后自动查询需要执行的任务进行爬取 @PostConstruct private void initJobs(){ //清空所有任务下次执行时间 sfMapper.resetNextExecuteTime(); //获取启用corn的任务 List spiderFlows = sfMapper.selectList(new QueryWrapper().eq("enabled", "1")); if(spiderFlows != null && !spiderFlows.isEmpty()){ for (SpiderFlow sf : spiderFlows) { if(StringUtils.isNotEmpty(sf.getCron())){ Date nextExecuteTimt = spiderJobManager.addJob(sf); if (nextExecuteTimt != null) { sf.setNextExecuteTime(nextExecuteTimt); sfMapper.updateById(sf); } } } } } public IPage selectSpiderPage(Page page, String name){ return sfMapper.selectSpiderPage(page,name); } public int executeCountIncrement(String id, Date lastExecuteTime, Date nextExecuteTime){ if(nextExecuteTime == null){ return sfMapper.executeCountIncrement(id, lastExecuteTime); } return sfMapper.executeCountIncrementAndExecuteTime(id, lastExecuteTime, nextExecuteTime); } /** * 重置定时任务 * @param id 爬虫的ID * @param cron 定时器 */ public void resetCornExpression(String id, String cron){ CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("Caclulate Next Execute Date") .withSchedule(CronScheduleBuilder.cronSchedule(cron)) .build(); sfMapper.resetCornExpression(id, cron, trigger.getFireTimeAfter(null)); spiderJobManager.remove(id); SpiderFlow spiderFlow = getById(id); if("1".equals(spiderFlow.getEnabled()) && StringUtils.isNotEmpty(spiderFlow.getCron())){ spiderJobManager.addJob(spiderFlow); } } @Override public boolean save(SpiderFlow spiderFlow){ //解析corn,获取并设置任务的开始时间 if(StringUtils.isNotEmpty(spiderFlow.getCron())){ CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("Caclulate Next Execute Date") .withSchedule(CronScheduleBuilder.cronSchedule(spiderFlow.getCron())) .build(); spiderFlow.setNextExecuteTime(trigger.getStartTime()); } if(StringUtils.isNotEmpty(spiderFlow.getId())){ //update 任务 sfMapper.updateSpiderFlow(spiderFlow.getId(), spiderFlow.getName(), spiderFlow.getXml()); spiderJobManager.remove(spiderFlow.getId()); spiderFlow = getById(spiderFlow.getId()); if("1".equals(spiderFlow.getEnabled()) && StringUtils.isNotEmpty(spiderFlow.getCron())){ spiderJobManager.addJob(spiderFlow); } }else{//insert 任务 String id = UUID.randomUUID().toString().replace("-", ""); sfMapper.insertSpiderFlow(id, spiderFlow.getName(), spiderFlow.getXml()); spiderFlow.setId(id); } File file = new File(workspace,spiderFlow.getId() + File.separator + "xmls" + File.separator + System.currentTimeMillis() + ".xml"); try { FileUtils.write(file,spiderFlow.getXml(),"UTF-8"); } catch (IOException e) { logger.error("保存历史记录出错",e); } return true; } public void stop(String id){ sfMapper.resetSpiderStatus(id,"0"); sfMapper.resetNextExecuteTime(id); spiderJobManager.remove(id); } public void copy(String id){ // 复制ID SpiderFlow spiderFlow = sfMapper.selectById(id); String new_id = UUID.randomUUID().toString().replace("-", ""); sfMapper.insertSpiderFlow(new_id, spiderFlow.getName() + "-copy", spiderFlow.getXml()); } public void start(String id){ spiderJobManager.remove(id); SpiderFlow spiderFlow = getById(id); Date nextExecuteTime = spiderJobManager.addJob(spiderFlow); if (nextExecuteTime != null) { spiderFlow.setNextExecuteTime(nextExecuteTime); sfMapper.updateById(spiderFlow); sfMapper.resetSpiderStatus(id, "1"); } } public void run(String id){ spiderJobManager.run(id); } public void resetExecuteCount(String id){ sfMapper.resetExecuteCount(id); } public void remove(String id){ sfMapper.deleteById(id); spiderJobManager.remove(id); flowNoticeMapper.deleteById(id); } public List selectOtherFlows(String id){ return sfMapper.selectOtherFlows(id); } public List selectFlows(){ return sfMapper.selectFlows(); } /** * 根据表达式获取最近几次运行时间 * @param cron 表达式 * @param numTimes 几次 * @return */ public List getRecentTriggerTime(String cron,int numTimes) { List list = new ArrayList<>(); CronTrigger trigger; try { trigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule(cron)) .build(); }catch (Exception e) { list.add("cron表达式 "+cron+" 有误:" + e.getCause()); return list; } List dates = TriggerUtils.computeFireTimes((OperableTrigger) trigger, null, numTimes); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Date date : dates) { list.add(dateFormat.format(date)); } return list; } public List historyList(String id){ File directory = new File(workspace, id + File.separator + "xmls"); if(directory.exists() && directory.isDirectory()){ File[] files = directory.listFiles((dir, name) -> name.endsWith(".xml")); if(files != null && files.length > 0){ return Arrays.stream(files).map(f-> Long.parseLong(f.getName().replace(".xml",""))).sorted().collect(Collectors.toList()); } } return Collections.emptyList(); } public String readHistory(String id,String timestamp){ File file = new File(workspace, id + File.separator + "xmls" + File.separator + timestamp + ".xml"); if(file.exists()){ try { return FileUtils.readFileToString(file,"UTF-8"); } catch (IOException e) { logger.error("读取历史版本出错",e); } } return null; } public Integer getFlowMaxTaskId(String flowId){ return sfMapper.getFlowMaxTaskId(flowId); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/TaskService.java ================================================ package org.spiderflow.core.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.spiderflow.core.mapper.TaskMapper; import org.spiderflow.core.model.Task; import org.springframework.stereotype.Service; @Service public class TaskService extends ServiceImpl { } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/service/VariableService.java ================================================ package org.spiderflow.core.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.spiderflow.core.expression.ExpressionGlobalVariables; import org.spiderflow.core.mapper.VariableMapper; import org.spiderflow.core.model.Variable; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.Serializable; import java.util.Map; import java.util.stream.Collectors; @Service public class VariableService extends ServiceImpl { @Override public boolean removeById(Serializable id) { boolean ret = super.removeById(id); this.resetGlobalVariables(); return ret; } @Override public boolean saveOrUpdate(Variable entity) { boolean ret = super.saveOrUpdate(entity); this.resetGlobalVariables(); return ret; } @PostConstruct private void resetGlobalVariables(){ Map variables = this.list().stream().collect(Collectors.toMap(Variable::getName, Variable::getValue)); ExpressionGlobalVariables.reset(variables); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/DataSourceUtils.java ================================================ package org.spiderflow.core.utils; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.spiderflow.core.service.DataSourceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.druid.pool.DruidDataSource; /** * 数据库连接工具类 * @author jmxd * */ @Component public class DataSourceUtils { private static final Map datasources = new HashMap<>(); private static DataSourceService dataSourceService; public static DataSource createDataSource(String className,String url,String username,String password){ DruidDataSource datasource = new DruidDataSource(); datasource.setDriverClassName(className); datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); datasource.setDefaultAutoCommit(true); datasource.setMinIdle(1); datasource.setInitialSize(2); return datasource; } public static void remove(String dataSourceId){ DataSource dataSource = datasources.get(dataSourceId); if(dataSource != null){ DruidDataSource ds = (DruidDataSource) dataSource; ds.close(); datasources.remove(dataSourceId); } } public synchronized static DataSource getDataSource(String dataSourceId){ DataSource dataSource = datasources.get(dataSourceId); if(dataSource == null){ org.spiderflow.core.model.DataSource ds = dataSourceService.getById(dataSourceId); if(ds != null){ dataSource = createDataSource(ds.getDriverClassName(), ds.getJdbcUrl(), ds.getUsername(), ds.getPassword()); datasources.put(dataSourceId, dataSource); } } return dataSource; } @Autowired public void setDataSourceService(DataSourceService dataSourceService) { DataSourceUtils.dataSourceService = dataSourceService; } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/EmailUtils.java ================================================ package org.spiderflow.core.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; /** * 邮件发送工具类 * * @author BillDowney * @date 2020年4月4日 上午12:31:09 */ @Component public class EmailUtils { // 发送邮件服务 @Autowired private JavaMailSender javaMailSender; // 发送者 @Value("${spring.mail.username}") private String from; /** * 发送简单文本邮件 * * @param subject 主题 * @param content 内容 * @param to 收件人列表 * @author BillDowney * @date 2020年4月4日 上午12:40:42 */ public void sendSimpleMail(String subject, String content, String... to) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setSubject(subject); message.setText(content); message.setTo(to); javaMailSender.send(message); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/ExecutorsUtils.java ================================================ package org.spiderflow.core.utils; import org.spiderflow.executor.ShapeExecutor; import org.spiderflow.model.Shape; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Created on 2020-03-11 * * @author Octopus */ @Component public class ExecutorsUtils implements ApplicationContextAware { /** * 节点执行器列表 当前爬虫的全部流程 */ private static List executors; private static Map executorMap; private static ApplicationContext applicationContext; @Autowired ExecutorsUtils(List executors){ ExecutorsUtils.executors = executors; } @PostConstruct private void init() { executorMap = executors.stream().collect(Collectors.toMap(ShapeExecutor::supportShape, v -> v)); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ExecutorsUtils.applicationContext = applicationContext; } public static List shapes(){ return executors.stream().filter(e-> e.shape() !=null).map(executor -> executor.shape()).collect(Collectors.toList()); } public static ShapeExecutor get(String shape){ return executorMap.get(shape); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/ExpressionUtils.java ================================================ package org.spiderflow.core.utils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.ExpressionEngine; import org.spiderflow.model.SpiderNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.Objects; /** * Created on 2020-03-11 * * @author Octopus */ @Component public class ExpressionUtils { private static Logger logger = LoggerFactory.getLogger(ExpressionUtils.class); /** * 选择器 */ private static ExpressionEngine engine; @Autowired private ExpressionUtils(ExpressionEngine engine){ ExpressionUtils.engine = engine; } public static boolean executeCondition(SpiderNode fromNode, SpiderNode node, Map variables) { if (fromNode != null) { String condition = node.getCondition(fromNode.getNodeId()); if (StringUtils.isNotBlank(condition)) { // 判断是否有条件 Object result = null; try { result = engine.execute(condition, variables); } catch (Exception e) { logger.error("判断{}出错,异常信息:{}", condition, e); } if (result != null) { boolean isContinue = "true".equals(result) || Objects.equals(result, true); logger.debug("判断{}={}", condition, isContinue); return isContinue; } return false; } } return true; } public static Object execute(String expression, Map variables) { return engine.execute(expression, variables); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/ExtractUtils.java ================================================ package org.spiderflow.core.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.alibaba.fastjson.JSONPath; import us.codecraft.xsoup.Xsoup; /** * 抽取数据工具类 * @author jmxd * */ public class ExtractUtils { private static Map patterns = new HashMap<>(); private static Pattern compile(String regx){ Pattern pattern = patterns.get(regx); if(pattern == null){ pattern = Pattern.compile(regx,Pattern.DOTALL); patterns.put(regx, pattern); } return pattern; } public static List getMatchers(String content,String regx,boolean isGroup){ return getMatchers(content,regx,isGroup ? 1: 0); } public static List getMatchers(String content,String regx,int groupIndex){ Matcher matcher = compile(regx).matcher(content); List results = new ArrayList<>(); while(matcher.find()){ results.add(matcher.group(groupIndex)); } return results; } public static List> getMatchers(String content,String regx,List groups){ Matcher matcher = compile(regx).matcher(content); List> results = new ArrayList<>(); while(matcher.find()){ List matches = new ArrayList<>(); for (Integer groupIndex : groups) { matches.add(matcher.group(groupIndex)); } results.add(matches); } return results; } public static String getFirstMatcher(String content,String regx,boolean isGroup){ return getFirstMatcher(content,regx,isGroup ? 1 : 0); } public static String getFirstMatcher(String content,String regx,int groupIndex){ Matcher matcher = compile(regx).matcher(content); if(matcher.find()){ return matcher.group(groupIndex); } return null; } public static List getFirstMatcher(String content,String regx,List groups){ Matcher matcher = compile(regx).matcher(content); List matches = new ArrayList<>(); if(matcher.find()){ for (Integer groupIndex : groups) { matches.add(matcher.group(groupIndex)); } } return matches; } public static String getHostFromURL(String url){ return getFirstMatcher(url, "(?<=//|)((\\w)+\\.)+\\w+", false); } public static String getFirstHTMLBySelector(Element element,String selector){ element = getFirstElement(element,selector); return element == null ? null : element.html(); } public static String getFirstOuterHTMLBySelector(Element element,String selector){ element = getFirstElement(element,selector); return element == null ? null : element.outerHtml(); } public static String getFirstTextBySelector(Element element,String selector){ element = getFirstElement(element,selector); return element == null ? null : element.text(); } public static String getFirstAttrBySelector(Element element,String selector,String attr){ element = getFirstElement(element,selector); return element == null ? null : element.attr(attr); } public static Element getFirstElement(Element element,String selector){ return element.selectFirst(selector); } public static List getElements(Element element,String selector){ return element.select(selector); } public static List getHTMLBySelector(Element element,String selector){ Elements elements = element.select(selector); List result = new ArrayList<>(); for (Element elem : elements) { result.add(elem.html()); } return result; } public static List getOuterHTMLBySelector(Element element,String selector){ Elements elements = element.select(selector); List result = new ArrayList<>(); for (Element elem : elements) { result.add(elem.outerHtml()); } return result; } public static List getTextBySelector(Element element,String selector){ Elements elements = element.select(selector); List result = new ArrayList<>(); for (Element elem : elements) { result.add(elem.text()); } return result; } public static List getAttrBySelector(Element element,String selector,String attr){ Elements elements = element.select(selector); List result = new ArrayList<>(); for (Element elem : elements) { result.add(elem.attr(attr)); } return result; } public static Object getValueByJsonPath(Object root,String jsonPath){ return JSONPath.eval(root, jsonPath); } public static List getValuesByXPath(Element element,String xpath){ return Xsoup.select(element,xpath).list(); } public static List getValuesByXPath(Elements elements,String xpath){ return Xsoup.select(elements.html(),xpath).list(); } public static String getValueByXPath(Element element,String xpath){ return Xsoup.select(element,xpath).get(); } public static String getValueByXPath(Elements elements,String xpath){ return Xsoup.select(elements.html(),xpath).get(); } public static String getElementByXPath(Element element,String xpath){ return Xsoup.select(element,xpath).get(); } public static boolean isNumber(String str) { return compile("^(\\-|\\+)?\\d+(\\.\\d+)?$").matcher(str).matches(); } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/FileUtils.java ================================================ package org.spiderflow.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.*; /** * 文件处理工具类 * * @author ruoyi */ public class FileUtils { private static Logger logger = LoggerFactory.getLogger(FileUtils.class); public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 * * @param filePath 文件路径 * @param os 输出流 * @return */ public static void writeBytes(String filePath, OutputStream os) throws IOException { FileInputStream fis = null; try { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } fis = new FileInputStream(file); byte[] b = new byte[1024]; int length; while ((length = fis.read(b)) > 0) { os.write(b, 0, length); } } catch (IOException e) { throw e; } finally { if (os != null) { try { os.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } /** * 删除文件 * * @param filePath 文件 * @return */ public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(filePath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * 文件名称验证 * * @param filename 文件名称 * @return true 正常 false 非法 */ public static boolean isValidFilename(String filename) { return filename.matches(FILENAME_PATTERN); } /** * 下载文件名重新编码 * * @param request 请求对象 * @param fileName 文件名 * @return 编码后的文件名 */ public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException { final String agent = request.getHeader("USER-AGENT"); String filename = fileName; if (agent.contains("MSIE")) { // IE浏览器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+", " "); } else if (agent.contains("Firefox")) { // 火狐浏览器 filename = new String(fileName.getBytes(), "ISO8859-1"); } else if (agent.contains("Chrome")) { // google浏览器 filename = URLEncoder.encode(filename, "utf-8"); } else { // 其它浏览器 filename = URLEncoder.encode(filename, "utf-8"); } return filename; } /** * 文件下载状态 */ public enum DownloadStatus { URL_ERROR(1, "URL错误"), FILE_EXIST(2,"文件存在"), TIME_OUT(3,"连接超时"), DOWNLOAD_FAIL(4,"下载失败"), DOWNLOAD_SUCCESS(5,"下载成功"); private int code; private String name; DownloadStatus(int code, String name){ this.code = code; this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static DownloadStatus downloadFile(String savePath, String fileUrl, boolean downNew) { URL urlfile = null; HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; if (fileUrl.startsWith("//")) { fileUrl = "http:" + fileUrl; } String fileName; try { urlfile = new URL(fileUrl); String urlPath = urlfile.getPath(); fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1); } catch (MalformedURLException e) { logger.error("URL异常", e); return DownloadStatus.URL_ERROR; } File path = new File(savePath); if (!path.exists()) { path.mkdirs(); } File file = new File(savePath + File.separator + fileName); if (file.exists()) { if (downNew) { file.delete(); } else { logger.info("文件已存在不重新下载!"); return DownloadStatus.FILE_EXIST; } } try { httpUrl = (HttpURLConnection) urlfile.openConnection(); httpUrl.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0"); //读取超时时间 httpUrl.setReadTimeout(60000); //连接超时时间 httpUrl.setConnectTimeout(60000); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(file)); int len = 2048; byte[] b = new byte[len]; long readLen = 0; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); } logger.info("远程文件下载成功:" + fileUrl); bos.flush(); bis.close(); httpUrl.disconnect(); return DownloadStatus.DOWNLOAD_SUCCESS; } catch (SocketTimeoutException e) { logger.error("读取文件超时", e); return DownloadStatus.TIME_OUT; } catch (Exception e) { logger.error("远程文件下载失败", e); return DownloadStatus.DOWNLOAD_FAIL; } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } catch (Exception e) { logger.error("下载出错", e); } } } } ================================================ FILE: spider-flow-core/src/main/java/org/spiderflow/core/utils/SpiderFlowUtils.java ================================================ package org.spiderflow.core.utils; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.spiderflow.model.SpiderNode; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSON; /** * 爬虫流程图工具类 * @author jmxd * */ public class SpiderFlowUtils { /** * 加载流程图 * @param xmlString string类型保存的XML流程图 * @return SpiderNode 爬虫的开始节点 */ public static SpiderNode loadXMLFromString(String xmlString){ Document document = Jsoup.parse(xmlString); Elements cells = document.getElementsByTag("mxCell"); Map nodeMap = new HashMap<>(); SpiderNode root = null; SpiderNode firstNode = null; Map> edgeMap = new HashMap<>(); for (Element element : cells) { Map jsonProperty = getSpiderFlowJsonProperty(element); SpiderNode node = new SpiderNode(); node.setJsonProperty(jsonProperty); String nodeId = element.attr("id"); node.setNodeName(element.attr("value")); node.setNodeId(nodeId); nodeMap.put(nodeId, node); if(element.hasAttr("edge")){ //判断是否是连线 edgeMap.put(nodeId, Collections.singletonMap(element.attr("source"), element.attr("target"))); } else if (jsonProperty != null && node.getStringJsonValue("shape") != null) { if ("start".equals(node.getStringJsonValue("shape"))) { root = node; } } if("0".equals(nodeId)){ firstNode = node; } } //处理连线 Set edges = edgeMap.keySet(); for (String edgeId : edges) { Set> entries = edgeMap.get(edgeId).entrySet(); SpiderNode edgeNode = nodeMap.get(edgeId); for (Entry edge : entries) { SpiderNode sourceNode = nodeMap.get(edge.getKey()); SpiderNode targetNode = nodeMap.get(edge.getValue()); //设置流转条件 targetNode.setCondition(sourceNode.getNodeId(),edgeNode.getStringJsonValue("condition")); //设置流转特性 targetNode.setExceptionFlow(sourceNode.getNodeId(),edgeNode.getStringJsonValue("exception-flow")); targetNode.setTransmitVariable(sourceNode.getNodeId(),edgeNode.getStringJsonValue("transmit-variable")); sourceNode.addNextNode(targetNode); } } firstNode.addNextNode(root); return firstNode; } /** * 提取配置的json属性 */ @SuppressWarnings("unchecked") private static Map getSpiderFlowJsonProperty(Element element){ Elements elements = element.getElementsByTag("JsonProperty"); if(!CollectionUtils.isEmpty(elements)){ return JSON.parseObject(elements.get(0).html(),Map.class); } return null; } } ================================================ FILE: spider-flow-web/pom.xml ================================================ 4.0.0 org.spiderflow spider-flow 0.5.0 spider-flow-web spider-flow-web https://gitee.com/jmxd/spider-flow/tree/master/spider-flow-web UTF-8 org.spiderflow spider-flow-core org.springframework.boot spring-boot-maven-plugin spider-flow org.spiderflow.SpiderApplication ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/SpiderApplication.java ================================================ package org.spiderflow; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; @SpringBootApplication @EnableScheduling @MapperScan("org.spiderflow.*.mapper") public class SpiderApplication implements ServletContextInitializer{ public static void main(String[] args) throws IOException { SpringApplication.run(SpiderApplication.class, args); } @Override public void onStartup(ServletContext servletContext) throws ServletException { //设置文本缓存1M servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", Integer.toString((1024 * 1024))); } @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/configuration/ResourcesConfiguration.java ================================================ package org.spiderflow.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置放行静态资源文件 * @author Administrator * */ @Configuration public class ResourcesConfiguration implements WebMvcConfigurer{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET","POST","OPTIONS") .allowCredentials(true); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/configuration/WebSocketConfiguration.java ================================================ package org.spiderflow.configuration; import org.spiderflow.core.Spider; import org.spiderflow.websocket.WebSocketEditorServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * 配置WebSocket * @author Administrator * */ @Configuration public class WebSocketConfiguration { @Bean public ServerEndpointExporter endpointExporter(){ return new ServerEndpointExporter(); } @Autowired public void setSpider(Spider spider) { WebSocketEditorServer.spider = spider; } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/DataSourceController.java ================================================ package org.spiderflow.controller; import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.spiderflow.core.model.DataSource; import org.spiderflow.core.service.DataSourceService; import org.spiderflow.core.utils.DataSourceUtils; import org.spiderflow.model.JsonBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @RestController @RequestMapping("/datasource") public class DataSourceController { @Autowired private DataSourceService dataSourceService; @RequestMapping("/list") public IPage list(@RequestParam(name = "page",defaultValue = "1")Integer page, @RequestParam(name = "limit",defaultValue = "1")Integer size) { return dataSourceService.page(new Page(page, size), new QueryWrapper().select("id", "name", "driver_class_name", "create_date").orderByDesc("create_date")); } @RequestMapping("/all") public List all(){ return dataSourceService.list(); } @RequestMapping("/save") public String save(DataSource dataSource){ if(StringUtils.isNotBlank(dataSource.getId())){ DataSourceUtils.remove(dataSource.getId()); } dataSourceService.saveOrUpdate(dataSource); return dataSource.getId(); } @RequestMapping("/get") public DataSource get(String id){ DataSource dataSource = dataSourceService.getById(id); dataSource.setPassword(null); return dataSource; } @RequestMapping("/remove") public void remove(String id){ DataSourceUtils.remove(id); dataSourceService.removeById(id); } @RequestMapping("/test") public JsonBean test(DataSource dataSource){ if(StringUtils.isBlank(dataSource.getDriverClassName())){ return new JsonBean<>(0, "DriverClassName不能为空!"); } if(StringUtils.isBlank(dataSource.getJdbcUrl())){ return new JsonBean<>(0, "jdbcUrl不能为空!"); } Connection connection = null; try { Class.forName(dataSource.getDriverClassName()); String url = dataSource.getJdbcUrl(); String username = dataSource.getUsername(); String password = dataSource.getPassword(); if(StringUtils.isNotBlank(username)){ connection = DriverManager.getConnection(url,username,password); }else{ connection = DriverManager.getConnection(url); } return new JsonBean<>(1, "测试连接成功"); } catch (ClassNotFoundException e) { return new JsonBean<>(0, "找不到驱动包:" + dataSource.getDriverClassName()); } catch (Exception e){ return new JsonBean<>(0, "连接失败,"+ e.getMessage()); } finally{ if(connection != null){ try { connection.close(); } catch (Exception e) { } } } } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/FlowNoticeController.java ================================================ package org.spiderflow.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.core.model.FlowNotice; import org.spiderflow.core.service.FlowNoticeService; import org.spiderflow.enums.FlowNoticeWay; import org.spiderflow.model.JsonBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/flowNotice") public class FlowNoticeController { private static final Logger logger = LoggerFactory.getLogger(FlowNoticeController.class); @Autowired private FlowNoticeService flowNoticeService; @RequestMapping("/save") public JsonBean save(FlowNotice entity) { if (StringUtils.isEmpty(entity.getId())) { return new JsonBean(0, "流程id不能为空"); } try { flowNoticeService.saveOrUpdate(entity); } catch (RuntimeException e) { logger.error(e.getMessage(), e); return new JsonBean(0, e.getMessage() == null ? "发生错误" : e.getMessage()); } return new JsonBean(entity); } @RequestMapping("/find") public JsonBean find(String id) { FlowNotice data = flowNoticeService.getById(id); if (data == null) { data = new FlowNotice(); data.setId(id); } return new JsonBean(data); } @RequestMapping("/getNoticeWay") public JsonBean> getNoticeWay(String id) { return new JsonBean>(FlowNoticeWay.getMap()); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/FunctionController.java ================================================ package org.spiderflow.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.commons.lang3.StringUtils; import org.spiderflow.core.model.DataSource; import org.spiderflow.core.model.Function; import org.spiderflow.core.service.FunctionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/function") public class FunctionController { @Autowired private FunctionService functionService; @RequestMapping("/list") public IPage list(@RequestParam(name = "page",defaultValue = "1")Integer page, @RequestParam(name = "limit",defaultValue = "1")Integer size,String name) { QueryWrapper select = new QueryWrapper().select("id", "name", "parameter", "create_date"); if(StringUtils.isNotBlank(name)){ select.like("name",name); } select.orderByDesc("create_date"); return functionService.page(new Page(page, size), select); } @RequestMapping("/save") public String save(Function function){ return functionService.saveFunction(function); } @RequestMapping("/get") public Function get(String id){ return functionService.getById(id); } @RequestMapping("/remove") public void remove(String id){ functionService.removeById(id); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/SpiderFlowController.java ================================================ package org.spiderflow.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.Grammerable; import org.spiderflow.annotation.Comment; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.service.SpiderFlowService; import org.spiderflow.core.utils.ExecutorsUtils; import org.spiderflow.executor.FunctionExecutor; import org.spiderflow.executor.FunctionExtension; import org.spiderflow.executor.PluginConfig; import org.spiderflow.io.Line; import org.spiderflow.io.RandomAccessFileReader; import org.spiderflow.model.Grammer; import org.spiderflow.model.JsonBean; import org.spiderflow.model.Plugin; import org.spiderflow.model.Shape; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * 爬虫Controller * @author Administrator * */ @RestController @RequestMapping("/spider") public class SpiderFlowController { @Autowired private List functionExecutors; @Autowired private List functionExtensions; @Autowired private List grammerables; @Autowired private SpiderFlowService spiderFlowService; @Autowired(required = false) private List pluginConfigs; @Value("${spider.workspace}") private String workspace; private final List grammers = new ArrayList(); private static Logger logger = LoggerFactory.getLogger(SpiderFlowController.class); @PostConstruct private void init(){ for (FunctionExecutor executor : functionExecutors) { String function = executor.getFunctionPrefix(); grammers.addAll(Grammer.findGrammers(executor.getClass(),function,function,true)); Comment comment = executor.getClass().getAnnotation(Comment.class); Grammer grammer = new Grammer(); if(comment!= null){ grammer.setComment(comment.value()); } grammer.setFunction(function); grammers.add(grammer); } for (FunctionExtension extension : functionExtensions) { String owner = extension.support().getSimpleName(); grammers.addAll(Grammer.findGrammers(extension.getClass(),null,owner,true)); } for (Grammerable grammerable : grammerables) { grammers.addAll(grammerable.grammers()); } } /** * 爬虫列表 * @param page 页数 * @param size 每页显示条数 * @return Page 所有爬虫的列表页 */ @RequestMapping("/list") public IPage list(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "limit", defaultValue = "1") Integer size, @RequestParam(name = "name", defaultValue = "") String name) { return spiderFlowService.selectSpiderPage(new Page<>(page, size), name); } @RequestMapping("/save") public String save(SpiderFlow spiderFlow){ spiderFlowService.save(spiderFlow); return spiderFlow.getId(); } @RequestMapping("/history") public JsonBean history(String id,String timestamp){ if(StringUtils.isNotBlank(timestamp)){ return new JsonBean<>(spiderFlowService.readHistory(id,timestamp)); }else{ return new JsonBean<>(spiderFlowService.historyList(id)); } } @RequestMapping("/get") public SpiderFlow get(String id){ return spiderFlowService.getById(id); } @RequestMapping("/other") public List other(String id){ if(StringUtils.isBlank(id)){ return spiderFlowService.selectFlows(); } return spiderFlowService.selectOtherFlows(id); } @RequestMapping("/remove") public void remove(String id){ spiderFlowService.remove(id); } @RequestMapping("/start") public void start(String id){ spiderFlowService.start(id); } @RequestMapping("/stop") public void stop(String id){ spiderFlowService.stop(id); } @RequestMapping("/copy") public void copy(String id){ spiderFlowService.copy(id); } @RequestMapping("/run") public void run(String id){ spiderFlowService.run(id); } @RequestMapping("/cron") public void cron(String id,String cron){ spiderFlowService.resetCornExpression(id, cron); } @RequestMapping("/xml") public String xml(String id){ return spiderFlowService.getById(id).getXml(); } @RequestMapping("/log/download") public ResponseEntity download(String id, String taskId) { if (StringUtils.isBlank(taskId) || NumberUtils.toInt(taskId,0) == 0) { Integer maxId = spiderFlowService.getFlowMaxTaskId(id); taskId = maxId == null ? "" : maxId.toString(); } File file = new File(workspace, id + File.separator + "logs" + File.separator + taskId + ".log"); return ResponseEntity.ok() .header("Content-Disposition","attachment; filename=spider.log") .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file)); } @RequestMapping("/log") public JsonBean> log(String id, String taskId, String keywords, Long index, Integer count, Boolean reversed, Boolean matchcase, Boolean regx) { if (StringUtils.isBlank(taskId)) { Integer maxId = spiderFlowService.getFlowMaxTaskId(id); taskId = maxId == null ? "" : maxId.toString(); } File logFile = new File(workspace, id + File.separator + "logs" + File.separator + taskId + ".log"); try (RandomAccessFileReader reader = new RandomAccessFileReader(new RandomAccessFile(logFile,"r"), index == null ? -1 : index, reversed == null || reversed)){ return new JsonBean<>(reader.readLine(count == null ? 10 : count,keywords,matchcase != null && matchcase,regx != null && regx)); } catch(FileNotFoundException e){ return new JsonBean<>(0,"日志文件不存在"); } catch (IOException e) { logger.error("读取日志文件出错",e); return new JsonBean<>(-1,"读取日志文件出错"); } } @RequestMapping("/shapes") public List shapes(){ return ExecutorsUtils.shapes(); } @RequestMapping("/pluginConfigs") public List pluginConfigs(){ return null == pluginConfigs ? Collections.emptyList() : pluginConfigs.stream().filter(e-> e.plugin() != null).map(plugin -> plugin.plugin()).collect(Collectors.toList()); } @RequestMapping("/grammers") public JsonBean> grammers(){ return new JsonBean<>(this.grammers); } @GetMapping("/recent5TriggerTime") public List getRecent5TriggerTime(String cron){ return spiderFlowService.getRecentTriggerTime(cron,5); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/SpiderRestController.java ================================================ package org.spiderflow.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.Spider; import org.spiderflow.core.job.SpiderJob; import org.spiderflow.core.job.SpiderJobContext; import org.spiderflow.core.model.SpiderFlow; import org.spiderflow.core.model.Task; import org.spiderflow.core.service.SpiderFlowService; import org.spiderflow.core.service.TaskService; import org.spiderflow.model.JsonBean; import org.spiderflow.model.SpiderOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; import java.util.List; import java.util.Map; @RestController @RequestMapping("/rest") public class SpiderRestController { private static Logger logger = LoggerFactory.getLogger(SpiderRestController.class); @Autowired private SpiderFlowService spiderFlowService; @Autowired private Spider spider; @Value("${spider.workspace}") private String workspace; @Autowired private SpiderJob spiderJob; @Autowired private TaskService taskService; /** * 异步运行 * @param id * @return */ @RequestMapping("/runAsync/{id}") public JsonBean runAsync(@PathVariable("id")String id){ SpiderFlow flow = spiderFlowService.getById(id); if(flow == null){ return new JsonBean<>(0, "找不到此爬虫信息"); } Task task = new Task(); task.setFlowId(flow.getId()); task.setBeginTime(new Date()); taskService.save(task); Spider.executorInstance.submit(()->{ spiderJob.run(flow,task,null); }); return new JsonBean<>(task.getId()); } /** * 停止运行任务 * @param taskId */ @RequestMapping("/stop/{taskId}") public JsonBean stop(@PathVariable("taskId")Integer taskId){ SpiderContext context = SpiderJob.getSpiderContext(taskId); if(context == null){ return new JsonBean<>(0,"任务不存在!"); } context.setRunning(false); return new JsonBean<>(1,"停止成功!"); } /** * 查询任务状态 * @param taskId */ @RequestMapping("/status/{taskId}") public JsonBean status(@PathVariable("taskId")Integer taskId){ SpiderContext context = SpiderJob.getSpiderContext(taskId); if(context == null){ return new JsonBean<>(0); // } return new JsonBean<>(1); //正在运行中 } /** * 同步运行 * @param id * @param params * @return */ @RequestMapping("/run/{id}") public JsonBean> run(@PathVariable("id")String id,@RequestBody(required = false)Map params){ SpiderFlow flow = spiderFlowService.getById(id); if(flow == null){ return new JsonBean<>(0, "找不到此爬虫信息"); } List outputs; Integer maxId = spiderFlowService.getFlowMaxTaskId(id); SpiderJobContext context = SpiderJobContext.create(workspace, id,maxId,true); try{ outputs = spider.run(flow,context, params); }catch(Exception e){ logger.error("执行爬虫失败",e); return new JsonBean<>(-1, "执行失败"); } finally{ context.close(); } return new JsonBean<>(outputs); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/TaskController.java ================================================ package org.spiderflow.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.job.SpiderJob; import org.spiderflow.core.model.Task; import org.spiderflow.core.service.TaskService; import org.spiderflow.model.JsonBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/task") public class TaskController { @Autowired private TaskService taskService; @RequestMapping("/list") public IPage list(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "limit", defaultValue = "1") Integer size,String flowId){ return taskService.page(new Page<>(page,size),new QueryWrapper().eq("flow_id",flowId).last("order by isnull(end_time) desc,end_time desc")); } /** * 停止执行任务 * @param id * @return */ @RequestMapping("/stop") public JsonBean stop(Integer id){ SpiderContext context = SpiderJob.getSpiderContext(id); if(context != null){ context.setRunning(false); } return new JsonBean<>(context != null); } @RequestMapping("/remove") public JsonBean remove(Integer id){ //删除任务记录之前先停止 SpiderContext context = SpiderJob.getSpiderContext(id); if(context != null){ context.setRunning(false); } return new JsonBean<>(taskService.removeById(id)); } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/controller/VariableController.java ================================================ package org.spiderflow.controller; import org.spiderflow.common.CURDController; import org.spiderflow.core.mapper.VariableMapper; import org.spiderflow.core.model.Variable; import org.spiderflow.core.service.VariableService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/variable") public class VariableController extends CURDController { } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/logback/SpiderFlowFileAppender.java ================================================ package org.spiderflow.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.spi.DeferredProcessingAware; import ch.qos.logback.core.status.ErrorStatus; import org.spiderflow.context.SpiderContext; import org.spiderflow.context.SpiderContextHolder; import org.spiderflow.core.job.SpiderJobContext; import java.io.IOException; import java.io.OutputStream; public class SpiderFlowFileAppender extends FileAppender { @Override protected void subAppend(ILoggingEvent event) { SpiderContext context = SpiderContextHolder.get(); OutputStream os = getOutputStream(); if (context instanceof SpiderJobContext) { SpiderJobContext jobContext = (SpiderJobContext) context; os = jobContext.getOutputstream(); } try { if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } byte[] byteArray = this.encoder.encode(event); writeBytes(os, byteArray); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus("IO failure in appender", this, ioe)); } } private void writeBytes(OutputStream os, byte[] byteArray) throws IOException { if (byteArray == null || byteArray.length == 0) return; lock.lock(); try { os.write(byteArray); if (isImmediateFlush()) { os.flush(); } } finally { lock.unlock(); } } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/logback/SpiderFlowWebSocketAppender.java ================================================ package org.spiderflow.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; import ch.qos.logback.core.UnsynchronizedAppenderBase; import org.spiderflow.context.SpiderContext; import org.spiderflow.context.SpiderContextHolder; import org.spiderflow.model.SpiderLog; import org.spiderflow.model.SpiderWebSocketContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class SpiderFlowWebSocketAppender extends UnsynchronizedAppenderBase { @Override protected void append(ILoggingEvent event) { SpiderContext context = SpiderContextHolder.get(); if(context instanceof SpiderWebSocketContext){ SpiderWebSocketContext socketContext = (SpiderWebSocketContext) context; Object[] argumentArray = event.getArgumentArray(); List arguments = argumentArray == null ? Collections.emptyList() : new ArrayList<>(Arrays.asList(argumentArray)); ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy(); if(throwableProxy != null){ arguments.add(throwableProxy.getThrowable()); } socketContext.log(new SpiderLog(event.getLevel().levelStr.toLowerCase(),event.getMessage(),arguments)); } } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/model/SpiderWebSocketContext.java ================================================ package org.spiderflow.model; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.time.DateFormatUtils; import org.spiderflow.context.SpiderContext; import org.spiderflow.core.serializer.FastJsonSerializer; import javax.websocket.Session; import java.util.Date; /** * WebSocket通讯中爬虫的上下文域 * * @author Administrator */ public class SpiderWebSocketContext extends SpiderContext { private static final long serialVersionUID = -1205530535069540245L; private Session session; private boolean debug; private Object lock = new Object(); public SpiderWebSocketContext(Session session) { this.session = session; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } @Override public void addOutput(SpiderOutput output) { this.write(new WebSocketEvent<>("output", output)); } public void log(SpiderLog log) { write(new WebSocketEvent<>("log", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"), log)); } public void write(WebSocketEvent event) { try { String message = JSON.toJSONString(event, FastJsonSerializer.serializeConfig); if(session.isOpen()){ synchronized (session){ session.getBasicRemote().sendText(message); } } } catch (Throwable ignored) { } } @Override public void pause(String nodeId, String event, String key, Object value) { if(this.debug && this.isRunning()) { synchronized (this) { if(this.debug && this.isRunning()) { synchronized (lock) { try { write(new WebSocketEvent<>("debug", new DebugInfo(nodeId, event, key, value))); lock.wait(); } catch (InterruptedException ignored) { } } } } } } @Override public void resume() { if(this.debug){ synchronized (lock){ lock.notify(); } } } @Override public void stop() { if(this.debug){ synchronized (lock){ lock.notifyAll(); } } } class DebugInfo{ private String nodeId; private String event; private String key; private Object value; public DebugInfo(String nodeId, String event, String key, Object value) { this.nodeId = nodeId; this.event = event; this.key = key; this.value = value; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/model/WebSocketEvent.java ================================================ package org.spiderflow.model; /** * WebSocket事件 * @author Administrator * * @param */ public class WebSocketEvent { private String eventType; private String timestamp; private T message; public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public WebSocketEvent(String eventType, T message) { this.eventType = eventType; this.message = message; } public WebSocketEvent(String eventType, String timestamp, T message) { this.eventType = eventType; this.timestamp = timestamp; this.message = message; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public T getMessage() { return message; } public void setMessage(T message) { this.message = message; } } ================================================ FILE: spider-flow-web/src/main/java/org/spiderflow/websocket/WebSocketEditorServer.java ================================================ package org.spiderflow.websocket; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.spiderflow.core.Spider; import org.spiderflow.core.utils.SpiderFlowUtils; import org.spiderflow.model.SpiderWebSocketContext; import org.spiderflow.model.WebSocketEvent; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * WebSocket通讯编辑服务 * * @author Administrator */ @ServerEndpoint("/ws") @Component public class WebSocketEditorServer { public static Spider spider; private SpiderWebSocketContext context; @OnMessage public void onMessage(String message, Session session) { JSONObject event = JSON.parseObject(message); String eventType = event.getString("eventType"); boolean isDebug = "debug".equalsIgnoreCase(eventType); if ("test".equalsIgnoreCase(eventType) || isDebug) { context = new SpiderWebSocketContext(session); context.setDebug(isDebug); context.setRunning(true); new Thread(() -> { String xml = event.getString("message"); if (xml != null) { spider.runWithTest(SpiderFlowUtils.loadXMLFromString(xml), context); context.write(new WebSocketEvent<>("finish", null)); } else { context.write(new WebSocketEvent<>("error", "xml不正确!")); } context.setRunning(false); }).start(); } else if ("stop".equals(eventType) && context != null) { context.setRunning(false); context.stop(); } else if("resume".equalsIgnoreCase(eventType) && context != null){ context.resume(); } } @OnClose public void onClose(Session session) { context.setRunning(false); context.stop(); } } ================================================ FILE: spider-flow-web/src/main/resources/application.properties ================================================ server.port=8088 logging.level.root=INFO #logging.level.org.spiderflow=DEBUG #平台最大线程数 spider.thread.max=64 #单任务默认最大线程数 spider.thread.default=8 #设置为true时定时任务才生效 spider.job.enable=false #爬虫任务的工作空间 spider.workspace=/data/spider #布隆过滤器默认容量 spider.bloomfilter.capacity=1000000 #布隆过滤器默认容错率 spider.bloomfilter.error-rate=0.0001 #死循环检测(节点执行次数超过该值时认为是死循环)默认值为5000 #spider.detect.dead-cycle=5000 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.fail_on_empty_beans=false spring.mvc.favicon.enabled=false spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456789 spring.datasource.url=jdbc:mysql://localhost:3306/spiderflow?useSSL=false&useUnicode=true&characterEncoding=UTF8&autoReconnect=true #JavaMailSender 邮件发送的配置 spring.mail.protocol=smtp spring.mail.host=smtp.qq.com spring.mail.port=465 spring.mail.username=xxxx@qq.com spring.mail.password=xxxx spring.mail.default-encoding=UTF-8 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.smtp.socketFactory.port=465 spring.mail.properties.mail.smtp.socketFactory.fallback=false spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration #selenium 插件配置 #设置chrome的WebDriver驱动路径,下载地址:http://npm.taobao.org/mirrors/chromedriver/,注意版本问题 selenium.driver.chrome=E:/driver/chromedriver.exe #设置fireFox的WebDriver驱动路径,下载地址:https://github.com/mozilla/geckodriver/releases selenium.driver.firefox=E:/driver/geckodriver.exe #爬虫通知相关内容配置,可使用SpiderFlow中的变量名和以下变量名:currentDate:当前发送时间 spider.notice.subject=spider-flow流程通知 spider.notice.content.start=流程开始执行:{name},开始时间:{currentDate} spider.notice.content.end=流程执行完毕:{name},结束时间:{currentDate} spider.notice.content.exception=流程发生异常:{name},异常时间:{currentDate} ================================================ FILE: spider-flow-web/src/main/resources/logback-spring.xml ================================================ %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n ${WORKSPACE}/logs/spider-flow.log true %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{50} - %msg%n ================================================ FILE: spider-flow-web/src/main/resources/static/css/easyui.css ================================================ .panel{overflow:hidden;text-align:left}.panel-header,.panel-body{border-width:1px;border-style:solid}.panel-header{padding:5px;position:relative}.panel-title{background:url('images/blank.gif') no-repeat}.panel-header-noborder{border-width:0 0 1px 0}.panel-body{overflow:auto;border-top-width:0}.panel-body-noheader{border-top-width:1px}.panel-body-noborder{border-width:0}.panel-with-icon{padding-left:18px}.panel-icon,.panel-tool{position:absolute;top:50%;margin-top:-8px;height:16px;overflow:hidden}.panel-icon{left:5px;width:16px}.panel-tool{right:5px;width:auto}.panel-tool a{display:inline-block;width:16px;height:16px;opacity:.6;filter:alpha(opacity=60);margin:0 0 0 2px;vertical-align:top}.panel-tool a:hover{opacity:1;filter:alpha(opacity=100);background-color:#e6e6e6;-moz-border-radius:3px 3px 3px 3px;-webkit-border-radius:3px 3px 3px 3px;border-radius:3px 3px 3px 3px}.panel-loading{padding:11px 0 10px 30px}.panel-noscroll{overflow:hidden}.panel-fit,.panel-fit body{height:100%;margin:0;padding:0;border:0;overflow:hidden}.panel-loading{background:url('images/loading.gif') no-repeat 10px 10px}.panel-tool-close{background:url('images/panel_tools.png') no-repeat -16px 0}.panel-tool-min{background:url('images/panel_tools.png') no-repeat 0 0}.panel-tool-max{background:url('images/panel_tools.png') no-repeat 0 -16px}.panel-tool-restore{background:url('images/panel_tools.png') no-repeat -16px -16px}.panel-tool-collapse{background:url('images/panel_tools.png') no-repeat -32px 0}.panel-tool-expand{background:url('images/panel_tools.png') no-repeat -32px -16px}.panel-header,.panel-body{border-color:#d4d4d4}.panel-header{background-color:#f2f2f2;background:-webkit-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-moz-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-o-linear-gradient(top,#fff 0,#f2f2f2 100%);background:linear-gradient(to bottom,#fff 0,#f2f2f2 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F2F2F2,GradientType=0)}.panel-title{font-size:12px;font-weight:bold;color:#777;height:16px;line-height:16px}.panel-body{background-color:#fff;color:#333;font-size:12px;padding:10px 8px 8px 8px}.panel-body .line{height:25px;margin:3px}.panel-body .imp{padding-left:25px}.panel-body .col{width:60px}.panel-body ul{list-style:none;padding-left:10px}.panel-body li{height:20px}.accordion{overflow:hidden;border-width:1px;border-style:solid}.accordion .accordion-header{border-width:0 0 1px;cursor:pointer}.accordion .accordion-body{border-width:0 0 1px}.accordion-noborder{border-width:0}.accordion-noborder .accordion-header{border-width:0 0 1px}.accordion-noborder .accordion-body{border-width:0 0 1px}.accordion-collapse{background:url('images/accordion_arrows.png') no-repeat 0 0}.accordion-expand{background:url('images/accordion_arrows.png') no-repeat -16px 0}.accordion{background:#fff;border-color:#d4d4d4}.accordion .accordion-header{background:#f2f2f2;filter:none}.accordion .accordion-header-selected{background:#0081c2}.accordion .accordion-header-selected .panel-title{color:#fff}.window{overflow:hidden;padding:5px;border-width:1px;border-style:solid}.window .window-header{background:transparent;padding:0 0 6px 0}.window .window-body{border-width:1px;border-style:solid;border-top-width:0}.window .window-body-noheader{border-top-width:1px}.window .window-header .panel-icon,.window .window-header .panel-tool{top:50%;margin-top:-11px}.window .window-header .panel-icon{left:1px}.window .window-header .panel-tool{right:1px}.window .window-header .panel-with-icon{padding-left:18px}.window-proxy{position:absolute;overflow:hidden}.window-proxy-mask{position:absolute;filter:alpha(opacity=5);opacity:.05}.window-mask{position:absolute;left:0;top:0;width:100%;height:100%;filter:alpha(opacity=40);opacity:.40;font-size:1px;*zoom:1;overflow:hidden}.window,.window-shadow{position:absolute;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.window-shadow{background:#ccc;-moz-box-shadow:2px 2px 3px #ccc;-webkit-box-shadow:2px 2px 3px #ccc;box-shadow:2px 2px 3px #ccc;filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2)}.window,.window .window-body{border-color:#d4d4d4}.window{background-color:#f2f2f2;background:-webkit-linear-gradient(top,#fff 0,#f2f2f2 20%);background:-moz-linear-gradient(top,#fff 0,#f2f2f2 20%);background:-o-linear-gradient(top,#fff 0,#f2f2f2 20%);background:linear-gradient(to bottom,#fff 0,#f2f2f2 20%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F2F2F2,GradientType=0)}.window-proxy{border:1px dashed #d4d4d4}.window-proxy-mask,.window-mask{background:#ccc}.dialog-content{overflow:auto}.dialog-toolbar{padding:2px 5px}.dialog-tool-separator{float:left;height:24px;border-left:1px solid #ccc;border-right:1px solid #fff;margin:2px 1px}.dialog-button{padding:5px;text-align:right}.dialog-button .l-btn{margin-left:5px}.dialog-toolbar,.dialog-button{background:#f5f5f5}.dialog-toolbar{border-bottom:1px solid #e6e6e6}.dialog-button{border-top:1px solid #e6e6e6}.combo{display:inline-block;white-space:nowrap;margin:0;padding:0;border-width:1px;border-style:solid;overflow:hidden;vertical-align:middle}.combo .combo-text{font-size:12px;border:0;line-height:20px;height:20px;margin:0;padding:0 2px;*margin-top:-1px;*height:18px;*line-height:18px;_height:18px;_line-height:18px;vertical-align:baseline}.combo-arrow{width:18px;height:20px;overflow:hidden;display:inline-block;vertical-align:top;cursor:pointer;opacity:.6;filter:alpha(opacity=60)}.combo-arrow-hover{opacity:1.0;filter:alpha(opacity=100)}.combo-panel{overflow:auto}.combo-arrow{background:url('images/combo_arrow.png') no-repeat center center}.combo,.combo-panel{background-color:#fff}.combo{border-color:#d4d4d4;background-color:#fff}.combo-arrow{background-color:#f2f2f2}.combo-arrow-hover{background-color:#e6e6e6}.combobox-item{padding:2px;font-size:12px;padding:3px;padding-right:0}.combobox-item-hover{background-color:#e6e6e6;color:#00438a}.combobox-item-selected{background-color:#0081c2;color:#fff}.layout{position:relative;overflow:hidden;margin:0;padding:0;z-index:0}.layout-panel{position:absolute;overflow:hidden}.layout-panel-east,.layout-panel-west{z-index:2}.layout-panel-north,.layout-panel-south{z-index:3}.layout-expand{position:absolute;padding:0;font-size:1px;cursor:pointer;z-index:1}.layout-expand .panel-header,.layout-expand .panel-body{background:transparent;filter:none;overflow:hidden}.layout-expand .panel-header{border-bottom-width:0}.layout-split-proxy-h,.layout-split-proxy-v{position:absolute;font-size:1px;display:none;z-index:5}.layout-split-proxy-h{width:5px;cursor:e-resize}.layout-split-proxy-v{height:5px;cursor:n-resize}.layout-mask{position:absolute;background:#fafafa;filter:alpha(opacity=10);opacity:.10;z-index:4}.layout-button-up{background:url('images/layout_arrows.png') no-repeat -16px -16px}.layout-button-down{background:url('images/layout_arrows.png') no-repeat -16px 0}.layout-button-left{background:url('images/layout_arrows.png') no-repeat 0 0}.layout-button-right{background:url('images/layout_arrows.png') no-repeat 0 -16px}.layout-split-proxy-h,.layout-split-proxy-v{background-color:#bbb}.layout-split-north{border-bottom:5px solid #eee}.layout-split-south{border-top:5px solid #eee}.layout-split-east{border-left:5px solid #eee}.layout-split-west{border-right:5px solid #eee}.layout-expand{background-color:#f2f2f2}.layout-expand-over{background-color:#f2f2f2}.tabs-container{overflow:hidden}.tabs-header{border-width:1px;border-style:solid;border-bottom-width:0;position:relative;padding:0;padding-top:2px;overflow:hidden}.tabs-header-plain{border:0;background:transparent}.tabs-scroller-left,.tabs-scroller-right{position:absolute;top:auto;bottom:0;width:18px;height:28px!important;height:30px;font-size:1px;display:none;cursor:pointer;border-width:1px;border-style:solid}.tabs-scroller-left{left:0}.tabs-scroller-right{right:0}.tabs-header-plain .tabs-scroller-left,.tabs-header-plain .tabs-scroller-right{height:25px!important;height:27px}.tabs-tool{position:absolute;bottom:0;padding:1px;overflow:hidden;border-width:1px;border-style:solid}.tabs-header-plain .tabs-tool{padding:0 1px}.tabs-wrap{position:relative;left:0;overflow:hidden;width:100%;margin:0;padding:0}.tabs-scrolling{margin-left:18px;margin-right:18px}.tabs-disabled{opacity:.3;filter:alpha(opacity=30)}.tabs{list-style-type:none;height:26px;margin:0;padding:0;padding-left:4px;width:5000px;border-style:solid;border-width:0 0 1px 0}.tabs li{float:left;display:inline-block;margin:0 4px -1px 0;padding:0;position:relative;border:0}.tabs li a.tabs-inner{display:inline-block;text-decoration:none;margin:0;padding:0 10px;height:25px;line-height:25px;text-align:center;white-space:nowrap;border-width:1px;border-style:solid;-moz-border-radius:5px 5px 0 0;-webkit-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.tabs li.tabs-selected a.tabs-inner{font-weight:bold;outline:0}.tabs li.tabs-selected a:hover.tabs-inner{cursor:default;pointer:default}.tabs li a.tabs-close,.tabs-p-tool{position:absolute;font-size:1px;display:block;height:12px;padding:0;top:50%;margin-top:-6px;overflow:hidden}.tabs li a.tabs-close{width:12px;right:5px;opacity:.6;filter:alpha(opacity=60)}.tabs-p-tool{right:16px}.tabs-p-tool a{display:inline-block;font-size:1px;width:12px;height:12px;margin:0;opacity:.6;filter:alpha(opacity=60)}.tabs li a:hover.tabs-close,.tabs-p-tool a:hover{opacity:1;filter:alpha(opacity=100);cursor:hand;cursor:pointer}.tabs-with-icon{padding-left:18px}.tabs-icon{position:absolute;width:16px;height:16px;left:10px;top:50%;margin-top:-8px}.tabs-title{font-size:12px}.tabs-closable{padding-right:8px}.tabs-panels{margin:0;padding:0;border-width:1px;border-style:solid;border-top-width:0;overflow:hidden}.tabs-header-bottom{border-width:0 1px 1px 1px;padding:0 0 2px 0}.tabs-header-bottom .tabs{border-width:1px 0 0 0}.tabs-header-bottom .tabs li{margin:-1px 4px 0 0}.tabs-header-bottom .tabs li a.tabs-inner{-moz-border-radius:0 0 5px 5px;-webkit-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px}.tabs-header-bottom .tabs-tool{top:0}.tabs-header-bottom .tabs-scroller-left,.tabs-header-bottom .tabs-scroller-right{top:0;bottom:auto}.tabs-panels-top{border-width:1px 1px 0 1px}.tabs-header-left{float:left;border-width:1px 0 1px 1px;padding:0}.tabs-header-right{float:right;border-width:1px 1px 1px 0;padding:0}.tabs-header-left .tabs-wrap,.tabs-header-right .tabs-wrap{height:100%}.tabs-header-left .tabs{height:100%;padding:4px 0 0 4px;border-width:0 1px 0 0}.tabs-header-right .tabs{height:100%;padding:4px 4px 0 0;border-width:0 0 0 1px}.tabs-header-left .tabs li,.tabs-header-right .tabs li{display:block;width:100%;position:relative}.tabs-header-left .tabs li{left:auto;right:0;margin:0 -1px 4px 0;float:right}.tabs-header-right .tabs li{left:0;right:auto;margin:0 0 4px -1px;float:left}.tabs-header-left .tabs li a.tabs-inner{display:block;text-align:left;-moz-border-radius:5px 0 0 5px;-webkit-border-radius:5px 0 0 5px;border-radius:5px 0 0 5px}.tabs-header-right .tabs li a.tabs-inner{display:block;text-align:left;-moz-border-radius:0 5px 5px 0;-webkit-border-radius:0 5px 5px 0;border-radius:0 5px 5px 0}.tabs-panels-right{float:right;border-width:1px 1px 1px 0}.tabs-panels-left{float:left;border-width:1px 0 1px 1px}.tabs-header-noborder,.tabs-panels-noborder{border:0}.tabs-header-plain{border:0;background:transparent}.tabs-scroller-left{background:#f2f2f2 url('images/tabs_icons.png') no-repeat 1px center}.tabs-scroller-right{background:#f2f2f2 url('images/tabs_icons.png') no-repeat -15px center}.tabs li a.tabs-close{background:url('images/tabs_icons.png') no-repeat -34px center}.tabs li a.tabs-inner:hover{background:#e6e6e6;color:#00438a;filter:none}.tabs li.tabs-selected a.tabs-inner{background-color:#fff;color:#777;background:-webkit-linear-gradient(top,#fff 0,#fff 100%);background:-moz-linear-gradient(top,#fff 0,#fff 100%);background:-o-linear-gradient(top,#fff 0,#fff 100%);background:linear-gradient(to bottom,#fff 0,#fff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=0)}.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner{background:-webkit-linear-gradient(top,#fff 0,#fff 100%);background:-moz-linear-gradient(top,#fff 0,#fff 100%);background:-o-linear-gradient(top,#fff 0,#fff 100%);background:linear-gradient(to bottom,#fff 0,#fff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=0)}.tabs-header-left .tabs li.tabs-selected a.tabs-inner{background:-webkit-linear-gradient(left,#fff 0,#fff 100%);background:-moz-linear-gradient(left,#fff 0,#fff 100%);background:-o-linear-gradient(left,#fff 0,#fff 100%);background:linear-gradient(to right,#fff 0,#fff 100%);background-repeat:repeat-y;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=1)}.tabs-header-right .tabs li.tabs-selected a.tabs-inner{background:-webkit-linear-gradient(left,#fff 0,#fff 100%);background:-moz-linear-gradient(left,#fff 0,#fff 100%);background:-o-linear-gradient(left,#fff 0,#fff 100%);background:linear-gradient(to right,#fff 0,#fff 100%);background-repeat:repeat-y;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#ffffff,GradientType=1)}.tabs li a.tabs-inner{color:#777;background-color:#f2f2f2;background:-webkit-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-moz-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-o-linear-gradient(top,#fff 0,#f2f2f2 100%);background:linear-gradient(to bottom,#fff 0,#f2f2f2 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F2F2F2,GradientType=0)}.tabs-header,.tabs-tool{background-color:#f2f2f2}.tabs-header-plain{background:transparent}.tabs-header,.tabs-scroller-left,.tabs-scroller-right,.tabs-tool,.tabs,.tabs-panels,.tabs li a.tabs-inner,.tabs li.tabs-selected a.tabs-inner,.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner,.tabs-header-left .tabs li.tabs-selected a.tabs-inner,.tabs-header-right .tabs li.tabs-selected a.tabs-inner{border-color:#d4d4d4}.tabs-p-tool a:hover,.tabs li a:hover.tabs-close,.tabs-scroller-over{background-color:#e6e6e6}.tabs li.tabs-selected a.tabs-inner{border-bottom:1px solid #fff}.tabs-header-bottom .tabs li.tabs-selected a.tabs-inner{border-top:1px solid #fff}.tabs-header-left .tabs li.tabs-selected a.tabs-inner{border-right:1px solid #fff}.tabs-header-right .tabs li.tabs-selected a.tabs-inner{border-left:1px solid #fff}a.l-btn{background-position:right 0;text-decoration:none;display:inline-block;zoom:1;height:24px;padding-right:18px;cursor:pointer;outline:0}a.l-btn-plain{padding-right:5px;border:0;padding:1px 6px 1px 1px}a.l-btn-disabled{color:#ccc;opacity:.5;filter:alpha(opacity=50);cursor:default}a.l-btn span.l-btn-left{display:inline-block;background-position:0 -48px;padding:4px 0 4px 18px;line-height:16px;height:16px}a.l-btn-plain span.l-btn-left{padding-left:5px}a.l-btn span span.l-btn-text{display:inline-block;vertical-align:baseline;width:auto;height:16px;line-height:16px;font-size:12px;padding:0;margin:0}a.l-btn span span.l-btn-icon-left{padding:0 0 0 20px;background-position:left center}a.l-btn span span.l-btn-icon-right{padding:0 20px 0 0;background-position:right center}a.l-btn span span span.l-btn-empty{display:inline-block;margin:0;padding:0;width:16px}a:hover.l-btn{background-position:right -24px;outline:0;text-decoration:none}a:hover.l-btn span.l-btn-left{background-position:0 bottom}a:hover.l-btn-plain{padding:0 5px 0 0}a:hover.l-btn-disabled{background-position:right 0}a:hover.l-btn-disabled span.l-btn-left{background-position:0 -48px}a.l-btn .l-btn-focus{outline:#00f dotted thin}a.l-btn{color:#444;background-image:url('images/linkbutton_bg.png');background-repeat:no-repeat;background:#f5f5f5;background-repeat:repeat-x;border:1px solid #bbb;background:-webkit-linear-gradient(top,#fff 0,#e6e6e6 100%);background:-moz-linear-gradient(top,#fff 0,#e6e6e6 100%);background:-o-linear-gradient(top,#fff 0,#e6e6e6 100%);background:linear-gradient(to bottom,#fff 0,#e6e6e6 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#e6e6e6,GradientType=0);-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}a.l-btn span.l-btn-left{background-image:url('images/linkbutton_bg.png');background-repeat:no-repeat;background-image:none}a:hover.l-btn{background:#e6e6e6;color:#00438a;border:1px solid #ddd;filter:none}a.l-btn-plain,a.l-btn-plain span.l-btn-left{background:transparent;border:0;filter:none}a:hover.l-btn-plain{background:#e6e6e6;color:#00438a;border:1px solid #ddd;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}a.l-btn-disabled,a:hover.l-btn-disabled{color:#444;filter:alpha(opacity=50);background:#f5f5f5;color:#444;background:-webkit-linear-gradient(top,#fff 0,#e6e6e6 100%);background:-moz-linear-gradient(top,#fff 0,#e6e6e6 100%);background:-o-linear-gradient(top,#fff 0,#e6e6e6 100%);background:linear-gradient(to bottom,#fff 0,#e6e6e6 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#e6e6e6,GradientType=0);filter:alpha(opacity=50) progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#e6e6e6,GradientType=0)}a.l-btn-plain-disabled,a:hover.l-btn-plain-disabled{background:transparent;filter:alpha(opacity=50)}a.l-btn-selected,a:hover.l-btn-selected{background-position:right -24px;background:#ddd;filter:none}a.l-btn-selected span.l-btn-left,a:hover.l-btn-selected span.l-btn-left{background-position:0 bottom;background-image:none}a.l-btn-plain-selected,a:hover.l-btn-plain-selected{background:#ddd}.datagrid .panel-body{overflow:hidden;position:relative}.datagrid-view{position:relative;overflow:hidden}.datagrid-view1,.datagrid-view2{position:absolute;overflow:hidden;top:0}.datagrid-view1{left:0}.datagrid-view2{right:0}.datagrid-mask{position:absolute;left:0;top:0;width:100%;height:100%;opacity:.3;filter:alpha(opacity=30);display:none}.datagrid-mask-msg{position:absolute;top:50%;margin-top:-20px;padding:12px 5px 10px 30px;width:auto;height:16px;border-width:2px;border-style:solid;display:none}.datagrid-sort-icon{padding:0}.datagrid-toolbar{height:auto;padding:1px 2px;border-width:0 0 1px 0;border-style:solid}.datagrid-btn-separator{float:left;height:24px;border-left:1px solid #ccc;border-right:1px solid #fff;margin:2px 1px}.datagrid .datagrid-pager{margin:0;border-width:1px 0 0 0;border-style:solid}.datagrid .datagrid-pager-top{border-width:0 0 1px 0}.datagrid-header{overflow:hidden;cursor:default;border-width:0 0 1px 0;border-style:solid}.datagrid-header-inner{float:left;width:10000px}.datagrid-header-row,.datagrid-row{height:25px}.datagrid-header td,.datagrid-body td,.datagrid-footer td{border-width:0 1px 1px 0;border-style:dotted;margin:0;padding:0}.datagrid-cell,.datagrid-cell-group,.datagrid-header-rownumber,.datagrid-cell-rownumber{margin:0;padding:0 4px;white-space:nowrap;word-wrap:normal;overflow:hidden;height:18px;line-height:18px;font-weight:normal;font-size:12px}.datagrid-header .datagrid-cell{height:auto}.datagrid-header .datagrid-cell span{font-size:12px}.datagrid-cell-group{text-align:center}.datagrid-header-rownumber,.datagrid-cell-rownumber{width:25px;text-align:center;margin:0;padding:0}.datagrid-body{margin:0;padding:0;overflow:auto;zoom:1}.datagrid-view1 .datagrid-body-inner{padding-bottom:20px}.datagrid-view1 .datagrid-body{overflow:hidden}.datagrid-footer{overflow:hidden}.datagrid-footer-inner{border-width:1px 0 0 0;border-style:solid;width:10000px;float:left}.datagrid-row-editing .datagrid-cell{height:auto}.datagrid-header-check,.datagrid-cell-check{padding:0;width:27px;height:18px;font-size:1px;text-align:center;overflow:hidden}.datagrid-header-check input,.datagrid-cell-check input{margin:0;padding:0;width:15px;height:18px}.datagrid-resize-proxy{position:absolute;width:1px;height:10000px;top:0;cursor:e-resize;display:none}.datagrid-body .datagrid-editable{margin:0;padding:0}.datagrid-body .datagrid-editable table{width:100%;height:100%}.datagrid-body .datagrid-editable td{border:0;margin:0;padding:0}.datagrid-body .datagrid-editable .datagrid-editable-input{margin:0;padding:2px;border-width:1px;border-style:solid}.datagrid-sort-desc .datagrid-sort-icon{padding:0 13px 0 0;background:url('images/datagrid_icons.png') no-repeat -16px center}.datagrid-sort-asc .datagrid-sort-icon{padding:0 13px 0 0;background:url('images/datagrid_icons.png') no-repeat 0 center}.datagrid-row-collapse{background:url('images/datagrid_icons.png') no-repeat -48px center}.datagrid-row-expand{background:url('images/datagrid_icons.png') no-repeat -32px center}.datagrid-mask-msg{background:#fff url('images/loading.gif') no-repeat scroll 5px center}.datagrid-header,.datagrid-td-rownumber{background-color:#f2f2f2;background:-webkit-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-moz-linear-gradient(top,#fff 0,#f2f2f2 100%);background:-o-linear-gradient(top,#fff 0,#f2f2f2 100%);background:linear-gradient(to bottom,#fff 0,#f2f2f2 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff,endColorstr=#F2F2F2,GradientType=0)}.datagrid-cell-rownumber{color:#333}.datagrid-resize-proxy{background:#bbb}.datagrid-mask{background:#ccc}.datagrid-mask-msg{border-color:#d4d4d4}.datagrid-toolbar,.datagrid-pager{background:#f5f5f5}.datagrid-header,.datagrid-toolbar,.datagrid-pager,.datagrid-footer-inner{border-color:#e6e6e6}.datagrid-header td,.datagrid-body td,.datagrid-footer td{border-color:#ccc}.datagrid-htable,.datagrid-btable,.datagrid-ftable{color:#333}.datagrid-row-alt{background:#f5f5f5}.datagrid-row-over,.datagrid-header td.datagrid-header-over{background:#e6e6e6;color:#00438a;cursor:default}.datagrid-row-selected{background:#0081c2;color:#fff}.datagrid-body .datagrid-editable .datagrid-editable-input{border-color:#d4d4d4}.propertygrid .datagrid-view1 .datagrid-body td{padding-bottom:1px;border-width:0 1px 0 0}.propertygrid .datagrid-group{height:21px;overflow:hidden;border-width:0 0 1px 0;border-style:solid}.propertygrid .datagrid-group span{font-weight:bold}.propertygrid .datagrid-view1 .datagrid-body td{border-color:#e6e6e6}.propertygrid .datagrid-view1 .datagrid-group{border-color:#f2f2f2}.propertygrid .datagrid-view2 .datagrid-group{border-color:#e6e6e6}.propertygrid .datagrid-group,.propertygrid .datagrid-view1 .datagrid-body,.propertygrid .datagrid-view1 .datagrid-row-over,.propertygrid .datagrid-view1 .datagrid-row-selected{background:#f2f2f2}.pagination{zoom:1}.pagination table{float:left;height:30px}.pagination td{border:0}.pagination-btn-separator{float:left;height:24px;border-left:1px solid #ccc;border-right:1px solid #fff;margin:3px 1px}.pagination .pagination-num{border-width:1px;border-style:solid;margin:0 2px;padding:2px;width:2em;height:auto}.pagination-page-list{margin:0 6px;padding:1px 2px;width:auto;height:auto;border-width:1px;border-style:solid}.pagination-info{float:right;margin:0 6px 0 0;padding:0;height:30px;line-height:30px;font-size:12px}.pagination span{font-size:12px}.pagination-first{background:url('images/pagination_icons.png') no-repeat 0 0}.pagination-prev{background:url('images/pagination_icons.png') no-repeat -16px 0}.pagination-next{background:url('images/pagination_icons.png') no-repeat -32px 0}.pagination-last{background:url('images/pagination_icons.png') no-repeat -48px 0}.pagination-load{background:url('images/pagination_icons.png') no-repeat -64px 0}.pagination-loading{background:url('images/loading.gif') no-repeat}.pagination-page-list,.pagination .pagination-num{border-color:#d4d4d4}.calendar{border-width:1px;border-style:solid;padding:1px;overflow:hidden}.calendar table{border-collapse:separate;font-size:12px;width:100%;height:100%}.calendar table td,.calendar table th{font-size:12px}.calendar-noborder{border:0}.calendar-header{position:relative;height:22px}.calendar-title{text-align:center;height:22px}.calendar-title span{position:relative;display:inline-block;top:2px;padding:0 3px;height:18px;line-height:18px;font-size:12px;cursor:pointer;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear{position:absolute;top:50%;margin-top:-7px;width:14px;height:14px;cursor:pointer;font-size:1px;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.calendar-prevmonth{left:20px;background:url('images/calendar_arrows.png') no-repeat -18px -2px}.calendar-nextmonth{right:20px;background:url('images/calendar_arrows.png') no-repeat -34px -2px}.calendar-prevyear{left:3px;background:url('images/calendar_arrows.png') no-repeat -1px -2px}.calendar-nextyear{right:3px;background:url('images/calendar_arrows.png') no-repeat -49px -2px}.calendar-body{position:relative}.calendar-body th,.calendar-body td{text-align:center}.calendar-day{border:0;padding:1px;cursor:pointer;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.calendar-other-month{opacity:.3;filter:alpha(opacity=30)}.calendar-menu{position:absolute;top:0;left:0;width:180px;height:150px;padding:5px;font-size:12px;display:none;overflow:hidden}.calendar-menu-year-inner{text-align:center;padding-bottom:5px}.calendar-menu-year{width:40px;text-align:center;border-width:1px;border-style:solid;margin:0;padding:2px;font-weight:bold;font-size:12px}.calendar-menu-prev,.calendar-menu-next{display:inline-block;width:21px;height:21px;vertical-align:top;cursor:pointer;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.calendar-menu-prev{margin-right:10px;background:url('images/calendar_arrows.png') no-repeat 2px 2px}.calendar-menu-next{margin-left:10px;background:url('images/calendar_arrows.png') no-repeat -45px 2px}.calendar-menu-month{text-align:center;cursor:pointer;font-weight:bold;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.calendar-body th,.calendar-menu-month{color:#808080}.calendar-day{color:#333}.calendar-sunday{color:#c22}.calendar-saturday{color:#0e0}.calendar-today{color:#00f}.calendar-menu-year{border-color:#d4d4d4}.calendar{border-color:#d4d4d4}.calendar-header{background:#f2f2f2}.calendar-body,.calendar-menu{background:#fff}.calendar-body th{background:#f5f5f5}.calendar-hover,.calendar-nav-hover,.calendar-menu-hover{background-color:#e6e6e6;color:#00438a}.calendar-hover{border:1px solid #ddd;padding:0}.calendar-selected{background-color:#0081c2;color:#fff;border:1px solid #0070a9;padding:0}.datebox-calendar-inner{height:180px}.datebox-button{height:18px;padding:2px 5px;text-align:center}.datebox-button a{font-size:12px}.datebox-current,.datebox-close,.datebox-ok{text-decoration:none;font-weight:bold;opacity:.6;filter:alpha(opacity=60)}.datebox-current,.datebox-close{float:left}.datebox-close{float:right}.datebox-button-hover{opacity:1.0;filter:alpha(opacity=100)}.datebox .combo-arrow{background-image:url('images/datebox_arrow.png');background-position:center center}.datebox-button{background-color:#f5f5f5}.datebox-current,.datebox-close,.datebox-ok{color:#444}.spinner{display:inline-block;white-space:nowrap;margin:0 5px;padding:0;border-width:1px;border-style:solid;overflow:hidden;vertical-align:middle}.spinner .spinner-text{font-size:12px;border:0;line-height:20px;height:20px;margin:0;padding:0 2px;*margin-top:-1px;*height:18px;*line-height:18px;_height:18px;_line-height:18px;vertical-align:baseline}.spinner-arrow{display:inline-block;overflow:hidden;vertical-align:top;margin:0;padding:0}.spinner-arrow-up,.spinner-arrow-down{opacity:.6;filter:alpha(opacity=60);display:block;font-size:1px;width:18px;height:10px}.spinner-arrow-hover{opacity:1.0;filter:alpha(opacity=100)}.spinner-arrow-up{background:url('images/spinner_arrows.png') no-repeat 1px center}.spinner-arrow-down{background:url('images/spinner_arrows.png') no-repeat -15px center}.spinner{border-color:#d4d4d4}.spinner-arrow{background-color:#f2f2f2}.spinner-arrow-hover{background-color:#e6e6e6}.progressbar{border-width:1px;border-style:solid;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px;overflow:hidden}.progressbar-text{text-align:center;position:absolute}.progressbar-value{position:relative;overflow:hidden;width:0;-moz-border-radius:5px 0 0 5px;-webkit-border-radius:5px 0 0 5px;border-radius:5px 0 0 5px}.progressbar{border-color:#d4d4d4}.progressbar-text{color:#333;font-size:12px}.progressbar-value .progressbar-text{background-color:#0081c2;color:#fff}.searchbox{display:inline-block;white-space:nowrap;margin:0;padding:0;border-width:1px;border-style:solid;overflow:hidden}.searchbox .searchbox-text{font-size:12px;border:0;margin:0;padding:0;line-height:20px;height:20px;*margin-top:-1px;*height:18px;*line-height:18px;_height:18px;_line-height:18px;vertical-align:baseline}.searchbox .searchbox-prompt{font-size:12px;color:#ccc}.searchbox-button{width:18px;height:20px;overflow:hidden;display:inline-block;vertical-align:top;cursor:pointer;opacity:.6;filter:alpha(opacity=60)} .searchbox-button-hover{opacity:1.0;filter:alpha(opacity=100)}.searchbox a.l-btn-plain{height:20px;border:0;padding:0 6px 0 0;vertical-align:top;-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;opacity:.6;filter:alpha(opacity=60)}.searchbox a.l-btn .l-btn-left{padding:2px 0 2px 4px}.searchbox a.l-btn-plain:hover{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border:0;padding:0 6px 0 0;opacity:1.0;filter:alpha(opacity=100)}.searchbox a.m-btn-plain-active{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0}.searchbox-button{background:url('images/searchbox_button.png') no-repeat center center}.searchbox{border-color:#d4d4d4;background-color:#fff}.searchbox a.l-btn-plain{background:#f2f2f2}.slider-disabled{opacity:.5;filter:alpha(opacity=50)}.slider-h{height:22px}.slider-v{width:22px}.slider-inner{position:relative;height:6px;top:7px;border-width:1px;border-style:solid;border-radius:5px}.slider-handle{position:absolute;display:block;outline:0;width:20px;height:20px;top:-7px;margin-left:-10px}.slider-tip{position:absolute;display:inline-block;line-height:12px;font-size:12px;white-space:nowrap;top:-22px}.slider-rule{position:relative;top:15px}.slider-rule span{position:absolute;display:inline-block;font-size:0;height:5px;border-width:0 0 0 1px;border-style:solid}.slider-rulelabel{position:relative;top:20px}.slider-rulelabel span{position:absolute;display:inline-block;font-size:12px}.slider-v .slider-inner{width:6px;left:7px;top:0;float:left}.slider-v .slider-handle{left:3px;margin-top:-10px}.slider-v .slider-tip{left:-10px;margin-top:-6px}.slider-v .slider-rule{float:left;top:0;left:16px}.slider-v .slider-rule span{width:5px;height:'auto';border-left:0;border-width:1px 0 0 0;border-style:solid}.slider-v .slider-rulelabel{float:left;top:0;left:23px}.slider-handle{background:url('images/slider_handle.png') no-repeat}.slider-inner{border-color:#d4d4d4;background:#f2f2f2}.slider-rule span{border-color:#d4d4d4}.slider-rulelabel span{color:#333}.menu{position:absolute;margin:0;padding:2px;border-width:1px;border-style:solid;overflow:hidden}.menu-item{position:relative;margin:0;padding:0;overflow:hidden;white-space:nowrap;cursor:pointer;border-width:1px;border-style:solid}.menu-text{height:20px;line-height:20px;float:left;padding-left:28px}.menu-icon{position:absolute;width:16px;height:16px;left:2px;top:50%;margin-top:-8px}.menu-rightarrow{position:absolute;width:16px;height:16px;right:0;top:50%;margin-top:-8px}.menu-line{position:absolute;left:26px;top:0;height:2000px;font-size:1px}.menu-sep{margin:3px 0 3px 25px;font-size:1px}.menu-active{-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.menu-item-disabled{opacity:.5;filter:alpha(opacity=50);cursor:default}.menu-text,.menu-text span{font-size:12px}.menu-shadow{position:absolute;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px;background:#ccc;-moz-box-shadow:2px 2px 3px #ccc;-webkit-box-shadow:2px 2px 3px #ccc;box-shadow:2px 2px 3px #ccc;filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2)}.menu-rightarrow{background:url('images/menu_arrows.png') no-repeat -32px center}.menu-line{border-left:1px solid #ccc;border-right:1px solid #fff}.menu-sep{border-top:1px solid #ccc;border-bottom:1px solid #fff}.menu{background-color:#fff;border-color:#e6e6e6;color:#333}.menu-content{background:#fff}.menu-item{border-color:transparent;_border-color:#fff}.menu-active{border-color:#ddd;color:#00438a;background:#e6e6e6}.menu-active-disabled{border-color:transparent;background:transparent;color:#333}.m-btn-downarrow{display:inline-block;width:16px;height:16px;line-height:16px;font-size:12px;_vertical-align:middle}a.m-btn-active{background-position:bottom right}a.m-btn-active span.l-btn-left{background-position:bottom left}a.m-btn-plain-active{background:transparent;padding:0 5px 0 0;border-width:1px;border-style:solid;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.m-btn-downarrow{background:url('images/menu_arrows.png') no-repeat 2px center}a.m-btn-plain-active{border-color:#ddd;background-color:#e6e6e6;color:#00438a}.s-btn-downarrow{display:inline-block;margin:0 0 0 4px;padding:0 0 0 1px;width:14px;height:16px;line-height:16px;border-width:0;border-style:solid;font-size:12px;_vertical-align:middle}a.s-btn-active{background-position:bottom right}a.s-btn-active span.l-btn-left{background-position:bottom left}a.s-btn-plain-active{background:transparent;padding:0 5px 0 0;border-width:1px;border-style:solid;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.s-btn-downarrow{background:url('images/menu_arrows.png') no-repeat 2px center;border-color:#bbb}a:hover.l-btn .s-btn-downarrow,a.s-btn-active .s-btn-downarrow,a.s-btn-plain-active .s-btn-downarrow{background-position:1px center;padding:0;border-width:0 0 0 1px}a.s-btn-plain-active{border-color:#ddd;background-color:#e6e6e6;color:#00438a}.messager-body{padding:10px;overflow:hidden}.messager-button{text-align:center;padding-top:10px}.messager-icon{float:left;width:32px;height:32px;margin:0 10px 10px 0}.messager-error{background:url('images/messager_icons.png') no-repeat scroll -64px 0}.messager-info{background:url('images/messager_icons.png') no-repeat scroll 0 0}.messager-question{background:url('images/messager_icons.png') no-repeat scroll -32px 0}.messager-warning{background:url('images/messager_icons.png') no-repeat scroll -96px 0}.messager-progress{padding:10px}.messager-p-msg{margin-bottom:5px}.messager-body .messager-input{width:100%;padding:1px 0;border:1px solid #d4d4d4}.tree{margin:0;padding:0;list-style-type:none}.tree li{white-space:nowrap}.tree li ul{list-style-type:none;margin:0;padding:0}.tree-node{height:18px;white-space:nowrap;cursor:pointer}.tree-hit{cursor:pointer}.tree-expanded,.tree-collapsed,.tree-folder,.tree-file,.tree-checkbox,.tree-indent{display:inline-block;width:16px;height:18px;vertical-align:top;overflow:hidden}.tree-expanded{background:url('images/tree_icons.png') no-repeat -18px 0}.tree-expanded-hover{background:url('images/tree_icons.png') no-repeat -50px 0}.tree-collapsed{background:url('images/tree_icons.png') no-repeat 0 0}.tree-collapsed-hover{background:url('images/tree_icons.png') no-repeat -32px 0}.tree-lines .tree-expanded,.tree-lines .tree-root-first .tree-expanded{background:url('images/tree_icons.png') no-repeat -144px 0}.tree-lines .tree-collapsed,.tree-lines .tree-root-first .tree-collapsed{background:url('images/tree_icons.png') no-repeat -128px 0}.tree-lines .tree-node-last .tree-expanded,.tree-lines .tree-root-one .tree-expanded{background:url('images/tree_icons.png') no-repeat -80px 0}.tree-lines .tree-node-last .tree-collapsed,.tree-lines .tree-root-one .tree-collapsed{background:url('images/tree_icons.png') no-repeat -64px 0}.tree-line{background:url('images/tree_icons.png') no-repeat -176px 0}.tree-join{background:url('images/tree_icons.png') no-repeat -192px 0}.tree-joinbottom{background:url('images/tree_icons.png') no-repeat -160px 0}.tree-folder{background:url('images/tree_icons.png') no-repeat -208px 0}.tree-folder-open{background:url('images/tree_icons.png') no-repeat -224px 0}.tree-file{background:url('images/tree_icons.png') no-repeat -240px 0}.tree-loading{background:url('images/loading.gif') no-repeat center center}.tree-checkbox0{background:url('images/tree_icons.png') no-repeat -208px -18px}.tree-checkbox1{background:url('images/tree_icons.png') no-repeat -224px -18px}.tree-checkbox2{background:url('images/tree_icons.png') no-repeat -240px -18px}.tree-title{font-size:12px;display:inline-block;text-decoration:none;vertical-align:top;white-space:nowrap;padding:0 2px;height:18px;line-height:18px}.tree-node-proxy{font-size:12px;line-height:20px;padding:0 2px 0 20px;border-width:1px;border-style:solid;z-index:9900000}.tree-dnd-icon{display:inline-block;position:absolute;width:16px;height:18px;left:2px;top:50%;margin-top:-9px}.tree-dnd-yes{background:url('images/tree_icons.png') no-repeat -256px 0}.tree-dnd-no{background:url('images/tree_icons.png') no-repeat -256px -18px}.tree-node-top{border-top:1px dotted red}.tree-node-bottom{border-bottom:1px dotted red}.tree-node-append .tree-title{border:1px dotted red}.tree-editor{border:1px solid #ccc;font-size:12px;height:14px!important;height:18px;line-height:14px;padding:1px 2px;width:80px;position:absolute;top:0}.tree-node-proxy{background-color:#fff;color:#333;border-color:#d4d4d4}.tree-node-hover{background:#e6e6e6;color:#00438a}.tree-node-selected{background:#0081c2;color:#fff}.validatebox-invalid{background-image:url('images/validatebox_warning.png');background-repeat:no-repeat;background-position:right center;border-color:#ffa8a8;background-color:#fff3f3;color:#000}.tooltip{position:absolute;display:none;z-index:9900000;outline:0;padding:5px;border-width:1px;border-style:solid;border-radius:5px;-moz-border-radius:5px 5px 5px 5px;-webkit-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px}.tooltip-content{font-size:12px}.tooltip-arrow-outer,.tooltip-arrow{position:absolute;width:0;height:0;line-height:0;font-size:0;border-style:solid;border-width:6px;border-color:transparent;_border-color:tomato;_filter:chroma(color=tomato)}.tooltip-right .tooltip-arrow-outer{left:0;top:50%;margin:-6px 0 0 -13px}.tooltip-right .tooltip-arrow{left:0;top:50%;margin:-6px 0 0 -12px}.tooltip-left .tooltip-arrow-outer{right:0;top:50%;margin:-6px -13px 0 0}.tooltip-left .tooltip-arrow{right:0;top:50%;margin:-6px -12px 0 0}.tooltip-top .tooltip-arrow-outer{bottom:0;left:50%;margin:0 0 -13px -6px}.tooltip-top .tooltip-arrow{bottom:0;left:50%;margin:0 0 -12px -6px}.tooltip-bottom .tooltip-arrow-outer{top:0;left:50%;margin:-13px 0 0 -6px}.tooltip-bottom .tooltip-arrow{top:0;left:50%;margin:-12px 0 0 -6px}.tooltip{background-color:#fff;border-color:#d4d4d4;color:#333}.tooltip-right .tooltip-arrow-outer{border-right-color:#d4d4d4}.tooltip-right .tooltip-arrow{border-right-color:#fff}.tooltip-left .tooltip-arrow-outer{border-left-color:#d4d4d4}.tooltip-left .tooltip-arrow{border-left-color:#fff}.tooltip-top .tooltip-arrow-outer{border-top-color:#d4d4d4}.tooltip-top .tooltip-arrow{border-top-color:#fff}.tooltip-bottom .tooltip-arrow-outer{border-bottom-color:#d4d4d4}.tooltip-bottom .tooltip-arrow{border-bottom-color:#fff}.tabs-panels{border-color:transparent}.tabs li a.tabs-inner{border-color:transparent;background:transparent;filter:none;color:#08c}.menu-active{background-color:#0081c2;border-color:#0081c2;color:#fff}.menu-active-disabled{border-color:transparent;background:transparent;color:#333} ================================================ FILE: spider-flow-web/src/main/resources/static/css/editor.css ================================================ *{ margin : 0; padding : 0; } html,body{ width : 100%; height : 100%; overflow: hidden; font-family: Microsoft YaHei; } .text-center{ text-align: center; } .main-container{ width : 100%; height : 100%; } .main-container .sidebar-container{ position: absolute; width : 46px; left : 0px; top : 30px; bottom:200px; max-height: 100%; overflow: auto; background: #F6F6F6; z-index: 1; border-radius: 2px; overflow-x: hidden; writing-mode: vertical-lr; -webkit-writing-mode: vertical-lr; -ms-writing-mode: vertical-lr; } .main-container .sidebar-container::-webkit-scrollbar { width: 3px; } .main-container .sidebar-container::-webkit-scrollbar-track { background-color:#ccc; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .main-container .sidebar-container::-webkit-scrollbar-thumb { background-color:#999; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .main-container .sidebar-container img{ padding: 5px; margin : 2px; border-radius: 3px; width : 32px; height : 32px; } .main-container .sidebar-container img:hover{ background:#ccc; } .main-container .resize-container{ cursor: n-resize; position: absolute; bottom : 190px; width : 100%; height : 20px; background: transparent; } .editor-container,.xml-container{ position: absolute; left : 38px; width : 100%; top : 30px; bottom : 200px; background-image: linear-gradient(90deg, rgba(153, 153, 153, 0.3) 1px, rgba(0, 0, 0, 0) 1px),linear-gradient(rgba(153, 153, 153, 0.3) 1px, rgba(0, 0, 0, 0) 1px); background-size: 8px 8px; overflow: auto; } .properties-container{ position: absolute; width : 100%; bottom : 0px; height : 200px; box-shadow: -2px 1px 3px #eee; overflow: auto; } .properties-container .layui-form-selectup dl{ top:auto; bottom:auto; } .properties-container .layui-table-cell{ height:32px; line-height: 32px; overflow: visible !important; } .properties-container .layui-table-box,.properties-container .layui-table-body { overflow: visible; } .properties-container .layui-table-cell{ padding : 0 5px; } .properties-container .layui-table .layui-input-block{ margin-left:0px; min-height: 32px; height: 32px; } .properties-container .layui-table,.properties-container .layui-table-view{ margin-top:0px; } .properties-container .layui-table .layui-input,.properties-container .layui-table .layui-select,.properties-container .layui-table .layui-textarea{ height:32px; } .properties-container .editor-form-node .layui-form-relative{ position: relative; } .properties-container .editor-form-node input,.properties-container .editor-form-node textarea{ font-family: 'Consolas'; font-size : 14px; } .properties-container .editor-form-node .layui-form-relative .layui-icon-close{ position: absolute; left : 10px; font-size:28px; top : 30px; color : #333; cursor: pointer; z-index: 1; } .properties-container .editor-form-node .layui-form-relative .layui-icon-close.function-remove{ top : 5px; } .properties-container .editor-form-node .layui-form-relative .layui-icon-close.cmd-remove{ top : 5px; } .properties-container .layui-tab{ margin : 0px; } .toolbar-container ul li{ float : left; padding : 0 10px; cursor: pointer; margin-top:5px; /*margin-right: 5px;*/ color:#333; } .toolbar-container ul span{ float: left; line-height: 30px; font-size: large; margin:0 5px 0 5px; color: #ccc; } .toolbar-container ul li:hover{ color : #ff4d02; background-color: rgb(204,204,204); } .toolbar-container ul li:not(:first-child){ /*border-left: 1px solid #ccc;*/ } .test-window-container .output-container{ /* height: 320px; */ } .test-window-container .log-container{ border: 1px solid #ccc; } .test-window-container .log-container textarea{ width : 100%; height : 100%; } .xml-container{ display: none; } .xml-container textarea{ width: 100%; height: 99.6%; border:none; padding: 10px 20px; box-sizing: border-box; } .xml-container textarea::-webkit-scrollbar { width: 5px; } .xml-container textarea::-webkit-scrollbar-track { background-color:#ccc; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .xml-container textarea::-webkit-scrollbar-thumb { background-color:#999; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .log-container span{ display:inline-block; vertical-align: middle; font-weight: bold; } .log-container .test-log > span{ height:24px; line-height:24px; float : left; font-family: 'Consolas'; } .log-container .test-log{ height:24px; line-height:24px; width:100%; clear:both; } .log-container .test-log.log-error{ color : red; } .log-container span.level{ text-align:center; width:60px; } .log-container span.timestamp{ margin-right:5px; } .log-container span.variable{ margin:0 2px; max-width: 230px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor:pointer; color: #025900; } .log-container span.variable-object,.log-container span.variable-array{ color : #2a00ff; } .log-container span.variable.variable-boolean{ color : #600100; } .log-container span.variable.variable-number{ color : #000E59; } .jsontree_value-wrapper{ overflow: unset !important; } .jsontree_value_string,.jsontree_node{ white-space: nowrap; } #test-window{ padding:0px 0px; overflow: hidden; } .layui-layer.codemirror .layui-input-block{ margin-left:0px; } .hint-grammer{ width : 100%; color : #333; } .hint-grammer:not(:first-child){ border-top:1px solid #ccc; margin-top:5px; padding-top:5px; } .hint-grammer .hint-owner span{ color : #600100 } .hint-grammer .hint-return span{ color : #0000C0 } .hint-grammer .hint-example{ padding:2px 5px; color : #000; } .layui-layer-tips{ word-break: break-all; } .toolbar-container ul li { background-repeat: no-repeat; background-size: 18px 18px; background-position: center center; width: 20px; height: 20px; padding : 0 4px; } .toolbar-container ul li.btn-save{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABAUlEQVRYR+2XwRHCIBBF/3ZBCdqFHXjSOvDi1ViB1KE3G9Au9OjJoQscMyFDIggkgUxmkmOym33z9wMLYeSHRq6PGoAJdQOwSgj0ArCXnC5mDRNAJSxu/nprQvwASE6NtjChSrD2ex9sO48JdQawqfJqiGwA38I2iKwANojsAA0IwnsUgAqi9NYMMB0FfOve9d21f+h9wq/ASRUgHDoBKBzljgpbbjBAp8IBSTPAdBRgfUyovWAxY7ACOjDAV39DXMe8fxl2nAc0jWueiFYgdiBJBsCEegBYeFrylJyW5qk3WAsCAa6S0zoJQKwZZw8MrsDsgeQmjC3QNz7n5dTGev8AcqN8CWX2vpEAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-return{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACF0lEQVRYR8WWvWtTURjGf09UcGtBNAEdMjmpdOjm4qj4QZcWN8Gl6OK9QdAt6eLg0HsXwep/0A4iFbWTbjrpUARxcNDivRHBj8FBwn3lxiRc0zTJTZPTs95zzvO7z/txXrHHS3usT1+AUmirwFrsaW1SoDsCtMTngQXnAK7EU1e3OeBSfBtAR9xYyhtziZ8GW4UGm19u6v2w5zsOlEJL450m3TjWa4yNBqx88xX1u/C/EGQg0sxfyEMyHdj0ASjvFycMThtclvhNwsPYV22nu3rlQNuJ3BBZkcOBzRREVTAHPI09ne8F0bMMd+NEt0g7r8x4UPe12P29Xx8YixOpYCmwGqKKsdQdjkGdcH5cTagU2mPEbCNhNpuYzt6CUmBnEC+6XXAG0AxFaKsyjke+Ztq54BrgOnDPEk7VK9rs2Yrz1H7evWlp7hNvsw+cUwfSZnVQfBdUIk+BcwdaeWDZRHTqwLFlO9oosKWEa1FF95070C5FJZyLKnruHKAY2m1B9dAPpt7V9Mc5QCm0Z8DX2NMV532gGJgnERhcrHt64hSgGNoFwTpiPb6hS9n+MfEqaNd+K95nI08bzgCOBDZXEI+agsat2NfdoeeBvG02u7+4bCcpcFXgYXwAFmNfLwdORM3BYcRlYgooC9KXrvzvp1kpwJ3I06ehZsLO5DIaxC/gM+IjCW8kXnXHe6ADo+nu7tTEq2AQ3l/lPMsh86zkIgAAAABJRU5ErkJggg=="); } .toolbar-container ul li.btn-selectAll{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAClklEQVRYR82XsYsTURDGv1krK8HCbBqx1r/AszCK3IGoYKEgnHAWHlhI3p5coSCXAwsb3V0rBQsb4cRGLEywMYWgB6IWdygiaqG3LwhaiFoc5pONSdjdZDcvyeLdtu/NfL83M2/mrWCDP9lgfWw+ANtliYIrAuwbJzpaSc/hbJcVCBaia7FN9g3uRhOrAJZB1EYGEKxqJfej9h1xEIvakUpnLQZQ9HibwLRFTKw58nJkgIRhmni4LR4Bn3UQTa3k4P8Q7wEoeHxqAb8CJZN5AGSdvG8KbI/PAXzTSg6PC2Ai3psCjy8gWNNlOTYOgKl4D0DR5eum4GNDyfFRAYYR7xeBFRBvtCMnwsWWM2BZO1I1AbJ9LoCoJK9alm38Fnh8C+CVVnKqBfDP4SUQU9qRepajNPH2Iepp9kmA9wSeNZSc7oi1e8Pklj849OWCvOsHkXVy2yOzIhIHcPkJgidayZmuUIVWYRuqItjOdZQa8/Iz1uEGhH0ogILLz5aFalCWs1GRosedBGogPmhHjnTWTHI+FIDtMwDxQCs5lwz1Dp8TFlETYClQMmsi3qqjSApslzMQ7I9GOFkDXwEsaSXn++b6Ok/Cwr0wp+FUM6n2BEA4DUOAA2nD6HsTuNNQ4qRVfNHlHAXXTMT7RCAbwPb4A4KbuizzmVfOZWnQtezWSTwFAwB8/hbCC5RcNGk8JnuGSoHtcZ3A1YaSyybOTfYMC5DZNEwEk3uGA/D5EMRRIaYDR+6OIhhrUu03oDQxFczJ4/agSr8F7apdAbBnXPGufeQNaATQnoIzAHblABGbpMYAOQj3dWF7fARga2oj6slfniSC8J25N/NZ3h3BPmdJ3MpTH2j9bywm/xc2369Zzqce6G7DI/AXxriYMP/Ruk8AAAAASUVORK5CYII="); } .toolbar-container ul li.btn-console-xml{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACmUlEQVRYR+2XTUgVURTHf2cQI6NPwjdai2iRkWCBUhRBukkkqEUQRItqGYaO0aaVti/fSBhEiwxaGbUoiKCFRiuxIiHDkMg+vRVoazFP3Ekfj+nNOPN85qa7Gobz8Ztzz9z/ucIKL1nh/MQCVHXrYXXoAvanBVX4KTCk0PnNk6Eo/1gA19fnwE5gOC0AsAbYBYwZTxpSA1T6WufACHDVeHKxCABcX28BZ0RomGyXF4ViRFbAzWojwgDKZdMhdhtSLzerXQidKE2mQwb/AySqQFWP1uscaxX2iJAF+lBup66/dRBO2x5QpUPglVPOu6+t8ik/Vq4HMr7uE+gF6otKltRJeFj2i3OfL8iXP4zzy/X1MXAAuIfyIXgtHBJlxP7TSeOHvm6DCrtRngbhhB0KJ4H7xpPjYQAFBo0nTcUkS+rj+joANBpPgo/Pr0AOwM3qEYSbwDjKNYRehJemXVqSJoqySwRgnatvaMXGSWZHu2TGPpdNserjJZn+ZwBLTbTkCpQKoLZfy0dPyExesy/eA9Z4a7eunnV4DWyPgHmb974mBviB8eRYaoBSVSAcJ3ETLjhW+dqsUIcG8pp42bNDhdHvnjzJd0oFkFOzxGkLGIbUNDFA9RXdPFfGD+AuyiNgIhWHQwXKeaAFh0rTJjaWnRGSNeFyzQORABlfpwXGjSd7A9JlGkhcX98Dm4wn68NHsRWjg/Mlt2K0LZDT0kxEVs4nYsUoRo77jCdnU+3/vHHBJo6S49xvFx5ISlCBRAPJXwfGMvVAOE/kVFzta80cjAHXjSetxWxBpkfviHIKh1rTJm8KxYi/mGR1HGFLMBfAVEqIhYvJcNyQs+jd0PW1H2gG1qUBCK5mwjPTLkfj/BYFSJO0GNsVB/gNWbh3MAOKB3oAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-graphical-xml{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABXklEQVRYR+2Xr0/DUBSFv1sLAgFbg0KDQaOYRCDBMIMjEKDVCEayhASzjgRIUAhmkDjU9lcQCAZHsYQExyGvsGU/UKt4E72uL733fu/0tj3P8BzmuT+TBRAm2gCOgZLBvUQ9je01j0phQwsKqJtYM3iSOEpj63Rr9hQoNbUSiAdguq9hJ42skgsgURtYHagRsJQe2KNb6wGEia6AHWCTgA7fXABOkdwhcW1wimX1zmS03g+tOgzgGu4iKk6iclO3JrZyd/8tcJlGtlduat/EOXCTRrY9DODo7oAP4BlYBKYcUC4Iwz2CL+AFYxYxb6L6FltrAMBdhA3VsGwIXXwi1vsHZhyQuYaWA6NtMJPli5M0ttrIEHYXwkT678Zxmvdq9m0sjWzg1R/5DhQAhQKFAoUChQKFAl4V8Po7/jOk/gxJmMi7JfNrSr3b8swT+jyY5PF8eXIn62yYZyfj5v4A3Ho4MJVAO+EAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-edit-xml{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAC/0lEQVRYR82XTWgTURDHf7NNrRelgtJFWhHtqYLQYkXwYIsHrR4UrRf1IHgR1HaTHrzWm1U0acWzBT9Ai3oSBQWrCOIXiIgnkWqUblH8qAc9NDvyNh+mcbNJa2r6YCHsznvzy7w3/5knlBj2kLaQ4hDQhdBcyj7z/REQdx0ZKWUvYQZ2XPsRosDiUgsFfleOu1HpD5tbFKBhUDeLcjdv8gjK65IgQjewJmunEJ9wJFZsXlEAe1BPo6QnKp1uVEZLOgeWn9WNXoqHBbYPXEc2Bc0vDpDQa8AuYNR1pLMc58Zm6YAuitQxGWD/1HVkfeH7MIB7QAdl7GPhonZCNRBYuO/2Skf+t/8LkPZ823WkKwtRDQDj+7rryG7zo1oA5mBvc6Nya64AzgEtBefABlYCC/3EEi5N9Mr+OQEIFbeEJoHGbHZVAyCdXZn0nj8Avu5PT1CjXL4OlCtCObsarro9EijbdkL/joCd0PPADuAj8EEhKYrZq6RaJCNTJFM1flFqBdqAWpTvCBHwn1rAygdV2DDhyOMAkQoEyL409kbzzWk1z1tVxlEGxPLrQlbFjE0TsDpjP03dwupHsQjkA/xAOIoyrMpeEYZQ9lgw6QnPffHwaFeLYb/qWXTg+dDTR5ECVg6AkacLKE0oNxFOmWroeXyVmrQjEfahnDQAIqxT5VllAQDXEckVFaUTi+0ogrJAhTaBBUC7Z9FsebypKIAofWq6IOEncCIT5iuexRYrxRKEYwq/BHZaUyzzInyqHIDyWaFHhMsCWxUuYtFt9jmltEYsDqv6veEr4Ij7jVq7njsZgD+H8R/OgNnnFcAqkwXAO79kmW1IZ8ha4GXOYUYnRGhUOJiLxAwBjA4cmLHghEyYkQ6YdaqqhEF/JJevs2jJSlTDeVqMimp2FSMwq7Y8LPymZa+p471AfbYvrPjFJAygIa6OCHHfRjjj9kpf5a9mxQiEdH+RHl/w6HJj8mRuL6fBMGPiERuPyY10IEqMWV7PA0oDL4ySijLoRmUsa/Ab6oa/MD/ej0IAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-copy{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACcElEQVRYR82XPYgTURSFz4kWdqZw1wluIbiVKyK4CoLgLhY21lY2guBWZkYLrWRtFzQTQQRRWFCrRWwstHIrQVBQMRZuky4vKiu4YOFPjkyS2fxN8t6sA2a6zDv33u/+vMx7xH9+6BK/ECoQcAzAhIveovkA4bEJuBrprACFshYk3MkgcK+LHGbMRX60AnglrYGYzhpAxKN6kWftAKHUDl6FMG8CVrcK45U0B+JF237V+JxPA9A02Grw2M7rJDQIUAh1vCHMdgchcQpqzYqAZy4AOeJrzefDJO1QAC/UGpBpr39AuGECXusGSQTwynoF4ahLdik1343PnVaA3aG+Eci3hRUJ91IG2pSTOAngdPzC+OyZs8QKdAP0G2wFZJS/8QTwQkV7cy7KNq5AvqT8DuJJ/N5SiYqAq3WfTyNdkr+R2zDJYDLUwRzwLkULVozPM5kBNB2VtAjihA1Cwqd6wAtdWQ5UNHUFbEFHrWfSgrEAcG0BgC9x/zObgUJZhyW8dq2EhLvxHGTSgqmb2vM7h+cAZhwg1iFcNgGXM6uAQ9ChkkwqMBYAE7c1ve0npmwwDWL9s8/3Sf8D0Smq86XCEQBL7d+dA0lSybxb2o8GKrbgm+vCdRNwsX8GhtoTS6bIK81PZRJAM/tfiA4pbk86gGXj81zkeChAEyyqwh9M2giYw0atyDfWFrQE1e6D7UgAW+Bh66N2Qb/NAACJ2e5s0kLsKqmwnXgJYG9kazvgxADRzWchbTAHfcX4PDBK1wLovTA4+HWTELhf83neChAPHBu4JGCfm/uWSsAhAm97bIgNNrBSC/jA5st6M7I5+Nf1v3QzjDCiAQFdAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-paste{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACkElEQVRYR+2Xv08TYRjHP0+BkBg1JAZ7YMKEizoYcdBJnAy7Pwpuarqo5Yp/ALBr7trEgX/AARYXQ+JCFwdM1EkHo3EpchVjTJCwwD3mmvZyLde7XltMSLz1nud5P8/3ed/nfV4h4TdS0Al1OeG5SYrtzVl5lzBEg7kkcR619JIrNCyYUia+5+V9kjhB27YA0pYuiZCNXERZdPKykBQkFsDPWlmMDC7cc0wZ6wrAsHQKKCKMHwikXHfyUgpbwLB0AWE+5N/q/gC5rYfypRWYr8BpW9MpcIAVlE9NO2WedgCaVRJuAmOOKSdjAepZOKY0lGV0SY+5u+y0Ie1Hx5QLQTvD0kmEtSh4f7FWAF5Aw9ZbKOdjINadvKweCsB4UQf/7HO1DRUOmtQUCP7oV9bLc7Jb7SX1H60USNt6B3gmcKYjgHCnHRWylVl5EQtg2PoUeOLVsWcAghcTx5TL7QCs1Yx7BhBU+z/A0VLAKOo5XJYhtieE7td6k+tqD1SdO/kEr1OuVBtb7e7wgI5WCTpJPOr2TKzAkKVDg8KawMUImJJjSmTP6KoEhq3eJhyOuF6/bpryIEqtrgB6UYZ/BjBi6V2Fs6HQwnziPZAke8NWjbGvDjCHcgxHCppVZal5uqoONrCM8KGvj8zGI/nsA0Q4Jb4Nw2aLwOJvNUWm8li+NQwktdGrlWyxR6tpFKtOyX7rrWWu8KY/RWYjJ+W6fcMAOvxcx1N7TInLKT+gcC3pPBBUwM8cSi5kfphSCcLGPkwMWzsuAXDbq7kKrwf2mS7Pya/mjXnYAN7U+WrvONM/78t22KmIBUjbmhMoAKGvooijNqnwcsBlpj4BdwTgPS5EuKFwJUkfALac38ywIHtRfn8Bx9qgMJt6UN8AAAAASUVORK5CYII="); } .toolbar-container ul li.btn-delete{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACBElEQVRYR+2XsWsUQRTGfy+msNMqmZgDIyJYiDYWYnX5C6wEsRADtuosiq2nrfFuEms1doKdtZBUgpUoiEVAUyjM+Q9oIfdk1t3l7ty9nbjYyE6zw843M9987z3ee0LEWNzQ63PKJYXzEXAEXo+E58Ob8qgOL3WABaen5+Bdhtupw2fr3fAdwZlvVt7P2lNLwDi9BawruKGVJIbAotOBgAVueysPmxEYaA/hLso9n0gvhoDZxx4xTp8CVyMOjpU/Pyo1Q83YCQQ+Ayt1yH+0viedvi7/FE4UFwjbQW5gvy+ezTGYEbooqzlwXtmdcEIz0C4ZgVh7xypjnG4HAt7KxJ0tgSgFzECDk4ZI2fKJ7OWyG6cXw9xbeVH8q8b+vQnGQnXLW1kLl6WkhBBBoBzLiZVhU3wTH8g3h8jwVlIvLhz2N4FVn0gaNWXYlkCrQKtAq0CrwH+gQEWRaZxqlg2LrFpVkDZKRnnyyRNOnnqXN7UT5l9vyJfxyigkqmlsYwKxpVcVLorAkXU9OZrnI/DBWznV9NKiSNnQNZQnwBtv5dz4uRMV0UpPD/44zC7QUbg2tPK4KYmlvp5V4RXCobLm5o/WbMlpotDPKp3obmia6MKmHj8w4r7C5WztgbdyZxpX2hsap8+AK01fP7b/pbdyoey8yuY0C6ejDbqm7yifVHg7y5S/AHMyMO8AdUhTAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-cut{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEFElEQVRYR+2WXYhUZRjHf8/sLn1BbNrunFkjAlGEwDYTytxALyo30FpNQYoipfWiZefMIlZIZV1YYuw5sxK1ZUkQIipKaUJdtNInIUkiRKGlRe6cUXMJoRLW848zzsjs7MzuzAh50wvn5jxfP56v9zWu8rGrHJ8JAZwBtQS9duZKIB1PG4KUbajkY0KARFrfZ5LWXi9AIq1uhbTVDeD4Og4cC1zrrBUi3q/FFuMjxMt1AyTS6pLYA2wLXFtVLUSiX3MV45Bgb9a1pRPZTdqEUQ0xXhJszLq2fjKIqf2a1hTjMHD+YsiiM30WZbHimRQgsoz72mPQhdETJO2Nit4kS6Q5LGg3Y2kmaXsnA64KoG2LZoUX2Q9MN7Esk7KoLOOO4+sA0DlZ3YsNqwKIDBxfy4GdgEIx/3TKvil2lPC1VbC6mrrXBZCD8PQKxguCUyY6gpSdLP4P/KyQrmyfHZ0s9QV51RnIGQypMX6EXQaPAIemttFxLsMqiTcjsYzHsknbXm3wSK82AKBtQHeGIbty/WB8KPFw3tFrGdeeryV4XQD5fngCeP9yMPFxo1j+e5/9/Z8AtKQ1owE+CJJ2t+PpoBmfZlzbWGvwujIwZUA3NoXsNri/OKDE09mUba0VouYeSPjaLliZD/Q50AzMzjVhyJJsn+2rBaImAMfXFqAnH2AkNspMGpkawo+Ff4LOrGvfVgtRESDh60GJecSYgxhBnIjuhILjmOgYTtlX+T2wDmNTXnYcy92C04BGxP6GJvad6rE/ykGVBYh7GjSjG9hhcBJxs4x5wO25VIvV2ZS9V+ww7utLg/n5f98BRxG/YixC3ASsCVJ2sBRiHIDj6wugA7Gw2KDZU/M1xpDBtMC11lJHhVvTjDWZpL1dLE94cmV4obi3dIWPAUj06wHF+CQGs4Zd+6lcyhxfQ8APgWvPFMsdT8eAwSBlr5e18zSA4QSurSiWjwFwPK3FuCdw7dFKTZQYkKuQpwLX7ijoOJ46MfaMXqD17LN2vgJApHMgNkrL8Fo7W9AZAxD3tdcuPcHWVQJw0noIsTtw7fqCTtyTa8bjgWtzK9lFJbzWGAljtJ/utSNlARxPm/JperJiBtLqDsWLWdduuZyBS1f1YODalIrgnm7DOKGQ2cW35dge8LVMsD52HR3Da+yvsqlM613EzMC1+wryNk9zQuNrM3pLG7CoTAswhi78Q/PIc/Zn2QzkZvpSkxG4trBSp8tYmU3ajjGd7utViegBWnbc8vtiQekojhvDuK8lBtuADPCWhUSLpUXGYmD5RM8tx9dOIr2Qd0L4rAFuEMwADpbbARFU2UXUOqDpFrLZLLd4bgXOIX4JxbrSOR6XJV/RGN6V/6Iy/gZsDlyL3hDjTk13QaUGu5L//wP8C7qXoDBLpnUnAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-undo{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACrklEQVRYR8WWTUhUURTHf2cccxEtMmPeiAmFi8iVQRREkBBFXxBBGZFEUBBIzRtBo2gT0cIPZt4IGRUECZG6KyIwNwURBEEthHBtOi+ClhUoc+I9dZrvN+9BM297/ud/f++ec++5QoAvktLzkmHJjsvbAOl5KeLXwLB0ABhG6a45QMTSpIDpQtcawEjpFMrZ7I7VCiAyohsJMyPC/rxy1QJga0I7GkK8AbYX9cr/BoiO6QHNMAs0lWzU/wkQsbRHYNLjhExJhtF0v3zye5Jy9UXHMJpUU4WkD9OvwHiokRdLfbLgI8+V5gEYSR1CGPRrkqOfFLifNuV9tR5ZACOlEyi91SaW1Ql/JMPNdFysarykfVw3Ly8zrcqhahKq1ajw7HtMLnjpxbB0Duj0EgaMz9um7KyUK62j2pIJMw10B1zEK+2nbcqWcqJ/PWCpc+x6vNyCxCuVo/AUjCFcC7KIZ44wYMdktFBXfA9YelvhrqdhMMFF25SJiheRE4yk9LIojz3W+Ay0A2XrW5ivsCghuuzr8mM9VvZBErX0iMJLYENJkPVZ8FAbo7/oUNiLcAY4VhFcuGHHZNgTwBEYY7qLDDNAW5FpmWFkWLoHXJA4EC4BMx/O0PWtX347Mc8nWcuQbgo34bz9dueZeUzDiKUnBJ4CzSUg+mxTxqsCWE82UvoK5XjWrIpx3JbQ5pUQzrQsfE98tE3Z5wvALYmlD4CrLkQVAFl4S18DR3N3okHpWozLF88SFG5fxNJbAvf8AKzBPwEu5fgN2qaM+AZwDKJJ7VVY8PssNyx9Dpxb2/rZtCmHAwG4f5TUg34BIkndIeI29DbHY0VpDQwQ7CKEqKVXFB6tthEnaw6w1g+rg0+5Ux+AhHYS4h3Ch7oAuPMmoTEJcapuAGulmKsrQDSpp/8CHSTrKGEN0hMAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-redo{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACv0lEQVRYR7WWTWgTURSFzxksqEtROmntWgQXCoIggtnUboqCi1oQBBcqKiQzsT8LEV2IYoVmohQERZRKoRZEFBeKUkGFgmA3VlwUBRXnDf5sxEVNmisTkxjSzPTNpHnL5Jxzv7lz33tDrMAys5IUAx1emhNR4xjV0EjvA4CYBjCkLF6OkrnSABDA8SzauhArDlAqTNxVaR7QgWgNAAARvEIBPd4gf4eBtAygXPTjYhF7vmU4HwTRagC/7gINdLspvmgE0TRAYlS2i4EBAKHvXIB+z+JkPUQsgI4x6SrmsQ/ACQCbdYatNJsC27Xp1OojASQc2SXASQD9ukWX6AQjyuZw5XdtgERWLDFwEYLVsYv/rzqu0jz0b8dqrPac3KHgoIZUW0LiaVsb+pYFMB15D2CTdnI04VwogOnIDwDromVqq6eNQkgHWtH2GrRJZbE0yA07YOZkAIJIt5r2cwuuKpupwF1gOuJP523twAhCAmdci+cDzwHzimyQImYJdEbI9efkE4BtYR4hjnhp3gg9Cc2cDEFwKSzI3z4CTLCIGXct5nGM+ZoPkkbWPwT2uhYfh94FG0dlTcHAbOCWI276hb00n9UHhQB8gYEeleK7oIeqDqHpiH+ujzUQ/oTglLJ5KygkAOBNYQHJ78P8FdrRyp+mIzMAdtSJXwLIKIuvw0KWABCPVJq9OnNU6kBnVrYustT+2jUleRxe7ovGN9QBXFMWj+sUr54DpiODAEZqTFPKYp9uSAVAgNOexQu6vipAwpEnAnSXjZGKVzpAoMu1OR6leAlgfVYSq4ivZeNnESQ9mx+iBPkdUDafR/FUtGx3pJfAw3I7jroWr8cJiuuhmZVzIM4CqF4QccPi+Gjm5AEEO1HEbpXhXJyQZjw0HZmWIu57GeaaCYrr9QHeKotb4gY062MiK/tdm/eaDYrr/wsm9/oZYCxm5gAAAABJRU5ErkJggg=="); } .toolbar-container ul li.btn-debug{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACDElEQVRYR+2XvW7TUBTHf/++AhJxXgJegCEMiIGlDEgMgICFIiFiV7AgJFoJiQWwqy7tUIH4WFhg6dKFDrwAfQnbPAPyQY6S4hTfe50QFITwmHs+fj7nf65PRODpZ5ZU4lQ51OOQbfO8t2VPVfG9SLTh85PvsJfabYm92sYgLWOtd4HoZfZSkIxsjU0fhBMgyuwK8KGZ0GC3jLXmhc5sR3BnysYD4a1AGwTG2yLRjTaIKLU3iOsnzh4UsV64oL0AtVMrBHwB+kBvHLgEcuBcM5FgLY+1O7cGJo4OCK8cZFzLE70PaSZYgXEVai3Umuj8mHhUDvUs5BAEiDKbOfkkqYmDcqiLc7cgSm0D8ST0Ft4EFXfzde04RRilNvAkGfxO8obvYWscY1NjgM8LSjRbGOP8XwPQ1mdX+dvL+fPdu/vVLWir2enUVlfER1ffXHe7T7SVcflbok8nY7YCeNXvudfn8Vs+gGcMu/dyuq6d/YpYy52CIpaWOoZNgKWM4agFjsXC/Q3456bAUYGbiFeLvIgwbhWJXv9yEf0fw2V+jkNjWLfrjy4kzjE83oYXsJIhnhdDPXSuZKEVpp/ZgcGFkJ3jvCxiRXMvpceVyOwesD0ThLFdJLof8gmu5ZMAvS27Khv95wvp4lCwl8d6F0pen3cGaOhiwAqXDM7IOFv/buKr4IiK/SJRaGWb4voBFz7zud8HAWwAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-debug.disabled{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB+klEQVRYR+2XvWpUURDHZ/YVUqgvYV4gxfnfRSxskiKQQkVtTCAICaaRQLIQSONHkcYUQclHY2OaNIG9cwpfwLyE5B3CHTlhL1zXc87sXlauoKedr9/Omf/ZuUzG8d5vqOocgG3Lt2kXkb2qqm76/f5uLo5zxrIsXzDzUfBh5g/Ouc1JILz371V1I/hWVTXIQSQBvPfLqvplrOAhgNUchIh8JKKXTZ8cRLYDMQhVPSmK4mkMoizLY2Z+MmZ7DeBdCjoLEIISnfhGRPeI6M4o8TUR/SCihbFCqwAOW89AHZiAsMbhMYAzy8nsQEggImEWlq1kTTszv3HO7VsxJkCb4nVRZr50zj1sfQXD4XC31+vtWL/CsK8BCMqIHhYRR0SpIsE2i+MTSQY1gMyiSosc+GsAYleQan+qnXUDpokbRFUgIotE9DXW0tyzagztEoDz8ZxRgFyitgCpuO4BMjKc5i6bnZ04DkC3Kgj1O5VhE6ATGd5eQUxq/5YKYh0QkWdE9GnGD9FzAJ9/e4j+y3DUgU7+ji0Zhuv6owtJUob1oMxoJXsLYCu5kllbjPf+UlUfWH4J+zWAu62X0jpQRNaJ6GAaCFU9KIrilRVjruUNiJXRN581F2FjOgJwahUP9okBGiAB4BEz31fV+dskzN9V9YqILgBYK9svXD8BsfwbJJRBMOgAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-stop{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAA7UlEQVRYR+2XMQ4BQRSG/zcnUGklknUBbkGosCqTLWk4AU6g0gqVDRXhFhyASSRalRPME8ui06yd5m31spm8/59vm/0IX8/Jb5eJKGcZ2e/3Sc2KcGXmSyGc7+KdFA/G13sAxaTCfuw5eOGs9DgTFTAtvQSjnlL4M4aw8hazBhk/qAJ2nWr4O0zVyDR1D4SxkwKMPh19PVTAwEUBC4ykgBAQAkJACAgBISAEhIAQcE/AtHQHjImLv2IQuhT5IGjrogCDK081S9cL47tGfviR0zT98OWFbzn9GHJQBdu8JWT+8UkU4wZSZy+cbuL9d70ElVavuQ4NAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-stop.disabled{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAA60lEQVRYR+2XIQ7CQBBFZ6YXQGFJuAL4ZmshoOAQYOAEwAlQXAIUBGQ7rYcrkGBRXKCzpA1L6jCla6Zq0mzm/301fQiVJ0mSARF18jxvV9/XNQdB8BSRRxRFF7cT3cDMVwDo1RX2Y8/NGNMvzpQFmHkPAJOGwl3MwRgzxSzLRiJybDi8jCOiMTLzAgC2PgoAwBLjOF4T0cpHARHZaAEloASUgBJQAkpACSgBJeCfQJqmM2vtzsdfMSLOsfBBRDz7KGCtHTo1a9IL3V1LP6zKaZN+WHrhV05dpY8ndkWk9Y9PQkQvIrqHYXhy+9/sjtdIJLkrLAAAAABJRU5ErkJggg=="); } .toolbar-container ul li.btn-test{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABSUlEQVRYR+2XoU7DUBSGv1MUT8D2NmgUCkGCxbH0PgFDoNjNhkBiZ0hAAQ4cFgwgQbE2kDCJ4pDL1oSQbu26tndi1W3+7/z3/uecCp4f8azPEmDxHWh2dUfhIzJyXcV9mepAo6tthH0nLHCHYgdGzssEmQ7Q00tg46+gQn8loPPWkvsyQLIAboH1FKEvVewqdF6NDOcBKQqQaD4r2DiU06IQ8wIkulfOkdjIzawgZQGMdIUTDbDxnrzkBSkXYKQ6AGwUis0DUQXA2Ix8sa0MIKnexfZbOXo38pDmSOUATlRhKMp2WjetBeC3cuUgMtL+70JdAI8EbEUteaodwN0BCThMEx/PmMlhafR0UivOTFje4VXFEXjsAx47obdZ4G0a1rMPrPX0QmDT30bkeyd0lTePdVeVzyiUs8zwF3hh8f8LChQ10ydLB34An+qlIUX4b60AAAAASUVORK5CYII="); } .toolbar-container ul li.btn-test.disabled{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABRElEQVRYR+2XoU/EMBTG39fu71rb1KFQCBIs/waHQHGTSCyGBBScauewYACJxJBwErOV9MKSC1m63a5bT1z1lu/Xb+977w2U+CCxPu0Bdt8BY8wJ5/xLSrkYo16CDhhjZoyxMy8M4AlAIYS4iwkSBLDWPgA4WBd0zt1wzudCiOcYIEGAsixLIpItQj9EVBDRXCm13AZkKECj+e5BlFLXQyG2BVjpAnisqqrQWttNQaIArIleMcZ8oX70BYkN4N34dM75z+JrpPNEB2gU+8Z2NIAGxMcWwKVS6qXNjtEB/kSXAI7buulUAFTX9bnWevbfhakAXjnnR3mev00O4Gsgy7KLNvFVDwnlJNCKu+PVc3hFB0jdB9J0wpSzINk0nGwfuCeiw2QbUfKd0N/cWnvKGPuWUt52hn/AA7v/XzDgUhu9snfgFw99pCHdhM6eAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-resume{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAgCAYAAAB+ZAqzAAACIElEQVRYR83Yz2vTYBzH8fcnivgXaI/eBcHjQGSCRw/C8OBhZ0GkTdUJCo0TxSkIrSJ4ENGDFxl4UWSi4A/cScSLguJBFG1SGYrDH1DtvpKu3WZZ0zZr0+QU8jxJXvnky/M8PALYVLS9jjgGjBjMGpz64upB2NbuyJRsH7BTMO27ehrVN06bMkUbRTxquXnOgR1lV28jYO+BLUDNwKu4OhsH0O4eZS7aeaye1n+HQbHi6nAEzFra7kl4fk4v+gFUpmRhWqOrPOxx4GpXD7Cw67xBoeLq0lpx/YY1PdMOFKJKoRN8ULDwveVG7V3rhFitfZCw5vuur3PwPmf1qRdgEjAE7xYWa+9Wt7hEYCswlzf8xvt4XN86AZOGgXhpVh/37kbhkoc1NBLn/I14HNCfYRV/VDDPqOEFR9Q68zC0xJa0wmR4vqszK79g+LBlzX2gELh6Hl5KEyz0/BD19Ippg9XzsxojqYTVjO3pgxkHg7yupAcmPlTFtq9Zzaem+CWm/JxOpGm4CFjP7uCQXreOwkP7lQY3K67G200Lw4DNSYz7Oc2kaRK/Hbga67TkSbL4vwsmfFdXu0ElAxN3rMr+yoR+dosaNOwX4mSQ04VeQM2+gyr+Gecv+fJRvYmDGkRiVTMmK3lNxQUtJ9anLQKJh1pgspzX7FpRi4nF31R5BWwNVymNWjrdD9BSYuFJnG2ozSXbIxjD4UaQ1ZN+osJn/QMBvnXeD1WGKgAAAABJRU5ErkJggg=="); } .toolbar-container ul li.btn-resume.disabled{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAgCAYAAAB+ZAqzAAAC5UlEQVRYR7WYy2oUQRSG/9N5AN/DhRsfYOpUWpGgSPCKBGMUFYJ4JagoiToQogQSEVGiGDFIUIxIIEiYpKqYLIKKILh34yqoIEIWCp0jPc6EcZjO1NRMatX0ufxfna4+XV1UKBS2RFF0IYqi/QC+AZhJkmQ6juMfyBjOuQMAxkXkg4jktdYfs3xD75MxpouI5moS9DHz06yk1loLQJXtqwDyzHw7FKJeHFlrJwEcqzHOMHNawbrDWmsAcI1xIYqifC6XK7YDMAWrnn0lp2PmWuF1PWttAUBcd6ZEeaXUYKtwQWDOuXkR2ZklTkTLIjLIzAuhgEFg1tq3AHY1EhWRMa31xUZ+WWus6UdpjJkjoi5Pwc9JkpyL4zjV8R5BFXPOzYrIHm8VAEQ0oZQ67RsTBGatfQNgr69IxY+IvqQdQCm11Cg2FOw1gO5GybPsIjKltT66UXwo2CsA+0LBynErRNStlFpu2+J3zr0QkYMtgpXCRWRSa328NldoxaYBHG4HWDnH6tramu7s7Hy/vh5DOr9z7rmIHGkjWCkVET1SSp0qXYeAWWunAPS0G6ySj5kpFCzdefRuFljavIPAnHNPRKRvs8A6Ojq2B4FZax8DOLEZYETUr5R6EARmjJkgopPtBCOiryKyjZl/trL4HwLw/u41mgAR3VFKXa72C6qYc+6+iPQ3EvSwfwewg5k/tavB3gNwxkM404WIXiqlDmU5BFXMGHOXiM6GgBHRLxHpZeZ0h5INHthgxwCcDwCbY+bdPnFBFbPWjgK45CNQ9vkN4Aozj/vGBIEZY+4Q0YCnyEKSJD1xHK94+v/7bgY+yhEA/73e9URFZEhrfasZoIpvEJgxZpiIrm4guCQiA1rrdyFQrVQsD+B6RpWGtdbXQoGqK9b0EYFz7mb6Q1stLiLpJm9Qaz3fKlSpYiGHKouLizeiKBqqAhhlZt+XwYubQo6hisXi1iRJnhHRHyIayeVys15qTTj9BSbJmzEMQ5JCAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-history{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADWUlEQVRYR8WXW2gUZxTHf2c2iRQvRFEz24JgKwoKKih9qOCNolgUH4qhor55AZXsRBRpXxpBFBGzk6CC2gdfpHhB0AdbEGl8qL644AWVSr2gmJ0YqVRtITW7p3zDLG6WmZ1xkGSeFr7zne/3nXO+8z8rjPAnI3w+oQC2q78ZMM+RJdWAnx3W6aVBVgErUT5FyILvo0+gT+F8qZEL/dvkz6QXiwLQAMBfz3bqMs2wHmVDQscXVejuy8mVOPu6AOUSczMZdiusDRz1C1wG7pfhZkkp8B9vR40mW3rnR8REZhXCdGMvwk/FnGyqB1EXAOgHJgUOjpYtOl+0ycO4W2W7dLMqm4F5wG3PkTlRe+IAzL6LKHnfQYYXXpvciwOorNuungHWVKezdm8SgCF7RJhfzEkhMUReOxB+BH7xHPkmKcARYGbIIfcGlb0v26WYFMAv4i7dp8r3YTWRug9k87pOLV55ObmUBMZ29RYwW4Wvq19HKgA7r4sRTK/oqe0VUTB2XnciHDQ15TmyumI3bACTXW2xhPso47GYVSnmYQMwN7ZdPQd8i7LHa5cOv1ckyV+tTZoUGB8tnfqdWPwscK3oyIJhB7C7dSZl7gIPPUemDQGIEqCwCKWNwIRuHddU5m/grefI2FqAN8CYwQHGvdwt5nfklxZg4gEd2zCK11EARkK/yDQw4/l2eZAUAOVqHdser116KuuBnP8RmoKsq78rfIWypHpTTArq13BVtfuvIOgfoUVYaZfAIc+RnXGvw3Z1K8rkGLshEch26QlVNoY+w6yryxV+RXngtcuMOIA067arj4CpoY0oqNA7wBQRthRzcjzNIVF7ghnhWN1W7IcVjBIWPEfmf0wA29UbZkCJFSPbVaNuK4CzniOtHwPiw+S4QxvsZt75B9dUcRoY+/1AUrA+YWHvFvm32k/4RNSlrSin/U4l7C/m5IdUh1eNZFYjU3q3ybNaP5Fi1JLXpSJUxuqCCMeTFmbNUOqJsDJqjKuvhms0Yy9gP7ArIH9soLTMqUwjvQP/4I9mUWM5cLKpiR1Pt8qrqAgmkmO7U1uxfJDPE6biSVA/J+PsEwEYJ815bW6CxSIssuBLhRYj8cEB/l8zhKtGGwYsrv/VJkZ0Yr/EALGeUhqMOMD/LOV+MJQ5P0UAAAAASUVORK5CYII="); } .toolbar-container ul li.btn-dock-right{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAqElEQVRYR+2XwQlCMRAFZ1tQhJTzLUILsAFzsQo/qG3YhJYTFGwhEvDg10BEAnt5OSabzWRyeTGchzmfjwCqBsIp78lsgFmnJ7oD1xRt/dnvCyAc8xlYdTp42sYY09Z275M1gBuwKMR/QAyNPY8Ubd4CyK+Comz5K0Q45AHj0qpP0SaXrhkQgAzIgAzIgAzIgAy4G3CPZL6htGQ611jeCpW91/U1czfwBJRbxiFeN0yUAAAAAElFTkSuQmCC"); } .toolbar-container ul li.btn-dock-bottom{ background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAA1UlEQVRYR+2XwQnCQBBF37SgKClHi9ACbMA9mLN41kNswAK0CC1nMZgWVhaDmE0gKCO5TI5LmHnzFnb/CgN/MnB/DKDTQFaEMzADJkpbVAI372SZ1msBZMewJ7BRatwsIxz8WvLPxTZAER7AKBIrQ0SjlXcy7gMI9Q9R2VwDIivCtd5SvJPG0F0GDMAMmAEzYAbeBgjsNI5ihO0vR7FK77TIN3eBAZiBwQzcFcNoOkTpnUz7IllMxIu/jA+XNBl3x/JXMl7V4VSDpUI4pYk4FraXkRl4Aos4pSGe+LbHAAAAAElFTkSuQmCC"); } .spiderflow-debug-tooltip{ position: absolute; z-index: 2147483647; background: #fefefe; border-radius: 2px; padding: 5px; border: 1px solid #eee; box-shadow : 2px 0px 5px 1px rgba(0, 0, 0, 0.6) } .spiderflow-debug-tooltip .content{ max-height: 500px; overflow: auto; max-width: 500px; } .spiderflow-debug-tooltip .content::-webkit-scrollbar { width: 5px; height: 5px; } .spiderflow-debug-tooltip .content::-webkit-scrollbar-track { background-color:#ccc; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .spiderflow-debug-tooltip .content::-webkit-scrollbar-thumb { background-color:#999; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .spiderflow-debug-tooltip::before{ content: ' '; width: 0px; height: 0px; position: absolute; bottom: -17px; left: 50%; border-width: 8px; border-style: solid; border-color: #ccc transparent transparent transparent; margin-left: -4px; } .spiderflow-debug-tooltip::after{ content: ' '; width: 0px; height: 0px; position: absolute; bottom: -16px; left: 50%; border-width: 8px; border-style: solid; border-color: #fefefe transparent transparent transparent; margin-left: -4px; } /*样式调整*/ .properties-container .editor-form-node input, .properties-container .editor-form-node textarea{ font-size : 12px; } .properties-container .editor-form-node .layui-input,.properties-container .editor-form-node .layui-select,.properties-container .editor-form-node .layui-textarea{ height : 24px; } .layui-form-label{ padding : 0 5px; line-height: 24px; } .layui-input-block{ min-height: 24px; line-height: 24px; } .layui-input-block{ margin-left : 100px; } .layui-tab-title li{ font-size:12px; line-height:24px; } .layui-tab-title{ height :24px; } .layui-tab-title .layui-this:after{ height : 25px; } .layui-form-select dl{ top : 26px; } .layui-form-select dl dd, .layui-form-select dl dt{ line-height: 24px; } .layui-table td, .layui-table th{ font-size : 12px; padding : 0; } .properties-container .layui-table-cell{ height : 24px; line-height: 24px; } .properties-container .layui-table .layui-input, .properties-container .layui-table .layui-select, .properties-container .layui-table .layui-textarea{ height : 24px; } .properties-container .layui-table .layui-input-block{ height : 24px; min-height: 24px; } .layui-table-view .layui-table td, .layui-table-view .layui-table th{ padding : 2px 0; } .layui-form-item{ margin-bottom : 5px; } .CodeMirror{ padding-top : 0px !important; font-size : 12px; } .CodeMirror-lines{ padding : 0px !important; } .CodeMirror-cursor{ height : 16px !important; margin-top: 3px; } .layui-form-item .layui-form-checkbox[lay-skin=primary]{ margin-top : -2px; } .layui-colorpicker{ width : 16px; height : 16px; padding : 4px; } .layui-icon-down:before{ position: absolute; top : 2px; left : 6.5px; } .properties-container button.layui-btn{ height: 24px; line-height: 24px; padding: 0px 5px; } .properties-container .layui-form-item .layui-input-inline{ width : auto; } .layer-test .layui-layer-title{ height: 24px; line-height: 24px; } .layer-test .layui-layer-setwin{ top : 6px; } .layer-test .layui-tab{ margin : 0px; } .layer-test .layui-tab-content{ padding : 2px; } .layer-test .layui-layer-btn{ padding-top:2px !important; margin-top:-5px; } .layer-test .layui-layer-btn .layui-inline{ margin-top:5px; } .layer-test .layui-layer-btn .layui-inline input{ font-size:12px; height : 26px; } .layer-test .layui-layer-btn a{ height: 24px; line-height: 24px; margin: 5px 5px 0; padding: 0px 10px; font-size:12px; } .layer-test .layui-layer-max{ display: none; } .layer-test .layui-layer-max.layui-layer-maxmin{ display: inline-block; } #test-window{ height:340px !important; } .history-version{ list-style: disc; padding : 2px 5px; max-height: 200px; overflow: auto; } .history-version::-webkit-scrollbar { width: 4px; } .history-version::-webkit-scrollbar-track { background-color:#ccc; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .history-version::-webkit-scrollbar-thumb { background-color:#999; -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius:2em; } .history-version li{ color: #333; cursor: pointer; font-size: 12px; height:22px; line-height: 22px; border-bottom: 1px solid #eee; list-style: disc inside; } .history-version li:nth-last-child(1){ border-bottom: none; } .history-version li:hover{ color : #1890FF; } .main-container.right .sidebar-container{ bottom: 0px!important; width: 50px!important; } .main-container.right .editor-container{ bottom:0px!important; left:38px!important; } .main-container.right .properties-container{ right: 0px; height: 100%!important; background: white; } .main-container.right .layui-col-md2, .main-container.right .layui-col-md3, .main-container.right .layui-col-md4, .main-container.right .layui-col-md10{ width: 100%!important; } .main-container.right .resize-container{ height:100%!important; right:40%!important; width: 20px; bottom:0px; cursor: e-resize; } .layui-table-body.layui-table-main .layui-table, .layui-table-body.layui-table-main .layui-table input, .layui-table-box .layui-table-header .layui-table{ width: 100%; } ================================================ FILE: spider-flow-web/src/main/resources/static/css/index.css ================================================ .layui-body .layui-tab{margin:0px;height:100%;} .layui-body .layui-tab .layui-tab-content{position: absolute;top: 40px;bottom: 0px;width: 100%;padding:0px;overflow: hidden;} .layui-body .layui-tab .layui-tab-content .layui-tab-item{height:100%;} /***********************/ .layui-layout-admin .layui-search-menu{ width:200px; padding:2px 5px; border-bottom:1px solid #eee; box-sizing: border-box; } .layui-layout-admin .layui-search-menu .layui-input{ margin:0; padding-left:10px; } .layui-layout-admin .layui-search-menu .layui-form-select .layui-anim{ max-width: 195px; max-height: 360px; } .layui-layout-right .layui-nav-item a{ padding : 0 10px; } .layui-layout-right .layui-nav-item a img{ background : #fff; border-radius : 4px; } a{ cursor:pointer; } ================================================ FILE: spider-flow-web/src/main/resources/static/css/layui-black-gray.css ================================================ .menu-list, .layui-nav.layui-nav-tree, .layui-layout-admin .layui-logo{ background: #304156; } .layui-nav-tree .layui-this, .layui-nav-tree .layui-this>a{ background: transparent; color:#1890ff!important; } .layui-nav-tree .layui-nav-item.layui-nav-itemed > a:hover{ background: #263445; } .layui-nav-bar{ display: none; } .layui-layout-admin .layui-logo{ color:#fff!important; font-size: 18px; font-weight: 600; } .layui-layout-admin .layui-header{ background: #fff; box-shadow: 0 1px 4px rgba(0,21,41,.08); } .layui-nav .layui-nav-item a{ color:black; } .version-no{ font-size: 12px; text-indent: 5px; display: inline-block; } .layui-layout-right .layui-nav-item a:hover{ color:black!important; } .layui-nav .layui-nav-more{ border-color: black transparent transparent; } .layui-nav .layui-nav-mored{ transform: rotate(180deg); } ================================================ FILE: spider-flow-web/src/main/resources/static/css/layui-blue.css ================================================ /* start */ iframe{ background:#fff; } .layui-layout-admin .layui-header,.layui-laypage .layui-laypage-curr .layui-laypage-em,.layui-form-checked[lay-skin=primary] i{ background-color:#1890FF; } .layui-layout-admin .layui-layout-right.layui-nav .layui-nav-child dd.layui-this a, .layui-layout-admin .layui-layout-right.layui-nav .layui-nav-child dd.layui-this{ background-color:#1890FF; } .layui-laydate li.layui-this,.layui-laydate td.layui-this{ background-color:#1890FF !important; color : #fff !important; } .layui-laydate .layui-laydate-header i:hover, .layui-laydate .layui-laydate-header span:hover,.layui-laydate .layui-laydate-footer span:hover{ color : #1890FF; } .layui-btn.layui-btn-normal,.layui-form-select dl dd.layui-this{ background-color:#1890FF; color : #fff; } .layui-btn{ background-color: transparent; color : #1890FF } .layui-btn-danger{ background-color: #FF5722; color : #fff } .layui-btn-common{ background-color: #009688; color : #fff } .layui-btn.layui-btn-normal:hover{ color : #fff; } .layui-btn-sm{ padding:0; } .layui-btn-sm.layui-btn-normal{ padding:0 10px; } .layui-table-cell .layui-btn:not(:last-child){ margin-right:3px; } .layui-table tbody tr:hover, .layui-table-click, .layui-table-header, .layui-table-hover, .layui-table-mend, .layui-table-patch, .layui-table-tool, .layui-table-total, .layui-table-total tr, .layui-table[lay-even] tr:nth-child(even){ background-color: rgb(230, 247, 255); } .layui-table thead tr{ background-color:#fafafa !important; } .layui-btn-primary:hover,.layui-form-checked[lay-skin=primary] i,.layui-form-checkbox[lay-skin=primary]:hover i{ border-color:#1890FF; } .layui-input:hover,.layui-textarea:hover,.layui-laypage input:focus, .layui-laypage select:focus{ border-color:#40a9ff !important; } .layui-input:hover,.layui-textarea{ -webkit-box-shadow: 0 0 0 2px rgba(24,144,255,.2); box-shadow: 0 0 0 2px rgba(24,144,255,.2); border-right-width: 1px!important; } .layui-table-cell .layui-btn:not(:last-child)::after{ display: inline-block; content : ' '; position: absolute; top:5px; padding-right:5px; bottom:5px; border-right:1px solid #e8e8e8; } .layui-btn:hover,.layui-laypage a:hover,.layui-tab-brief>.layui-tab-title .layui-this{ color : #40a9ff; } .layui-nav .layui-nav-item a,.layui-layout-admin .layui-logo{ color : #fff; } .layui-nav .layui-nav-item.layui-this{ background-color: rgba(255,255,255,.2); } .layui-nav .layui-this:after, .layui-nav-bar, .layui-nav-tree .layui-nav-itemed:after{ display: none; } .layui-tab-title li{ padding: 0 5px; } .layui-tab-title li .layui-tab-close{ visibility: hidden; } .layui-tab-title li:hover,.layui-tab-title .layui-this,.layui-form-radio>i:hover, .layui-form-radioed>i{ color : #1890FF; } .layui-treeSelect .ztree li a.curSelectedNode{ color : #1890FF !important; } .layui-tab-title li .layui-tab-close:hover{ background: transparent; color:#231f1f; } .layui-nav .layui-nav-child a{ color:rgba(0, 0, 0, 0.65); } .layui-body .layui-tab .layui-tab-content{ top:41px !important; left:1px; } .layui-layout-admin .layui-body,.layui-layout-admin .layui-footer{ background-color: #f0f2f5; } .layui-layout-admin .layui-tab-title{ background-color: #fff; } .layui-tab-title li:hover .layui-tab-close{ visibility: visible; } .layui-nav{ background:#fff; } .layui-nav-itemed>.layui-nav-child{ background-color : transparent !important; margin-left:15px; } .layui-nav-tree .layui-nav-item a{ color : rgba(0, 0, 0, 0.65) !important; } .layui-nav-tree .layui-nav-item a:hover{ background-color: transparent !important; color : #1890FF !important; } .layui-nav .layui-nav-more{ border-color : rgba(0, 0, 0, 0.3) transparent transparent; } .layui-nav-tree .layui-nav-child dd.layui-this, .layui-nav-tree .layui-nav-child dd.layui-this a, .layui-nav-tree .layui-this, .layui-nav-tree .layui-this>a, .layui-nav-tree .layui-this>a:hover{ color : #1890FF !important; background-color: #e6f7ff; border-right: 2px solid #1890FF; } .layui-nav .layui-nav-mored, .layui-nav-itemed>a .layui-nav-more{ border-color : transparent transparent rgba(0, 0, 0, 0.3); } .layui-nav-tree .layui-nav-bar{ display: none; } .menu-list{ border-right: 1px solid #e8e8e8; } .layui-tab-brief>.layui-tab-more li.layui-this:after, .layui-tab-brief>.layui-tab-title .layui-this:after{ border-bottom-color: #1890FF; } .layui-tab-title .layui-tab-bar{ display: none; } .layui-tab .layui-tab-title{ overflow-x: auto; overflow-y: hidden; } .layui-tab[overflow]>.layui-tab-title{ overflow : auto; overflow-y: hidden; } .layui-tab .layui-tab-title::-webkit-scrollbar{ width: 3px; height: 2px; } .layui-tab .layui-tab-title::-webkit-scrollbar-thumb{ border-radius: 10px; -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2); background: #1890ff; } .layui-tab .layui-tab-title::-webkit-scrollbar-track{ -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2); border-radius: 10px; background: #EDEDED; } ================================================ FILE: spider-flow-web/src/main/resources/static/datasource-edit.html ================================================ DataSource
================================================ FILE: spider-flow-web/src/main/resources/static/datasources.html ================================================ DataSource 添加数据源
================================================ FILE: spider-flow-web/src/main/resources/static/editCron.html ================================================  Cron表达式生成器
每秒 允许的通配符[, - * /]
周期从 -
秒开始,每 秒执行一次
指定
00 01 02 03 04 05 06 07 08 09
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
分钟 允许的通配符[, - * /]
周期从 - 分钟
分钟开始,每 分钟执行一次
指定
00 01 02 03 04 05 06 07 08 09
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
小时 允许的通配符[, - * /]
周期从 - 小时
小时开始,每 小时执行一次
指定
AM: 00 01 02 03 04 05 06 07 08 09 10 11
PM: 12 13 14 15 16 17 18 19 20 21 22 23
日 允许的通配符[, - * / L W]
不指定
周期从 -
日开始,每 天执行一次
每月 号最近的那个工作日
每月最后一天
指定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
月 允许的通配符[, - * /]
不指定
周期从 -
日开始,每 月执行一次
指定
1 2 3 4 5 6 7 8 9 10 11 12
周 允许的通配符[, - * / L #]
不指定
周期 从星期 -
周 的星期
本月最后一个星期
指定
1 2 3 4 5 6 7
不指定 允许的通配符[, - * /] 非必填
每年
周期 从 -
表达式
分钟 小时
星期
表达式字段:
Cron 表达式:
最近5次运行时间:
================================================ FILE: spider-flow-web/src/main/resources/static/editor.html ================================================ SpiderFlow-Editor
  • |
  • |
  • |
  • |
  • |
  • |
================================================ FILE: spider-flow-web/src/main/resources/static/function-edit.html ================================================ DataSource
================================================ FILE: spider-flow-web/src/main/resources/static/functions.html ================================================ DataSource
================================================ FILE: spider-flow-web/src/main/resources/static/index.html ================================================ SpiderFlow
  • 爬虫列表
================================================ FILE: spider-flow-web/src/main/resources/static/js/canvas-viewer.js ================================================ window.requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback,element){ window.setTimeout(callback, 1000 / 60); } window.cancelAnimationFrame=window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function( id ){ window.clearTimeout( id ); } var canvas = document.getElementById('logviewer'); function CanvasText(options){ options = options || {}; this.maxWidth = options.maxWidth || 2147483648; this.color = options.color; this.text = options.text === undefined || options.text === null ? '': options.text.toString(); this.click = options.click; this.startX = 0; this.endX = 0; } function CanvasViewer(options){ options = options || {}; this.canvas = options.element; this.context = this.canvas.getContext('2d'); this.style = options.style || {}; this.context.font = this.style.font || 'bold 14px Consolas'; this.context.textBaseline = this.style.textBaseLine || 'middle'; this.lines = []; this.sourceLines = []; this.lineHeight = 24; this.maxRows = Math.ceil(this.canvas.height / this.lineHeight); this.scrollHeight = this.canvas.height; this.scrollTop = 0; var _this = this; this.mouseEvent = 0; this.mouseDownX = 0; this.mouseDownY = 0; this.startIndex = 0; this.startX = 5; this.mouseX = 0; this.mouseY = 0; this.colsOffsetX = [0]; this.filterText = ''; this.maxWidth = this.canvas.width - 8; this.onClick = options.onClick || function(){}; this.grid = options.grid; this.header = options.header; this.canvas.onmousemove = function(e){ var x = e.offsetX; var y = e.offsetY; _this.mouseX = x; _this.mouseY = y; var _hover = false; if(x < _this.canvas.width - 8 && y < _this.canvas.height - 8){ var row = _this.startIndex + parseInt(y / _this.lineHeight) + (y % _this.lineHeight == 0 ? 0 : 1) - 1; var texts = _this.lines[row]; if(texts){ for(var i =0,len = texts.length;i x){ _hover = true; break; } } } } if(_hover){ _this.canvas.style.cursor = 'pointer'; }else{ _this.canvas.style.cursor = 'default'; } //鼠标按下且有纵向滚动条 if(_this.mouseEvent == 1 && _this.hasScroll){ _this.scrollTo(Math.max(Math.min(Math.floor((y / (_this.canvas.height - 8)) * _this.lines.length - _this.maxRows / 2),_this.lines.length - _this.maxRows),0)); } //鼠标按下且有横向滚动条 if(_this.mouseEvent == 2 && _this.hasXScroll){ var delta = e.offsetX - _this.mouseDownX; _this.mouseDownX = e.offsetX; var canvasWidth = _this.canvas.width - 8; _this.startX = Math.max(Math.min(_this.startX - (canvasWidth / _this.slideWidth) * delta,_this.grid ? 5 : 0),canvasWidth - _this.maxWidth) } } this.canvas.onmousewheel = function(e){ if(e.wheelDelta > 0){ //向上滚动 _this.scrollTo(Math.max(_this.startIndex - 2,0)); }else{ _this.scrollTo(Math.max(Math.min(_this.startIndex + 1,_this.lines.length - _this.maxRows),0)); } } this.canvas.onmousedown = function(e){ if(e.offsetX > _this.canvas.width - 8 && e.offsetY < _this.canvas.height - 8){ _this.mouseEvent = 1; _this.mouseDownX = e.offsetX; _this.mouseDownY = e.offsetY; } if(e.offsetX < _this.canvas.width - 8 && e.offsetY > _this.canvas.height - 8){ _this.mouseEvent = 2; _this.mouseDownX = e.offsetX; _this.mouseDownY = e.offsetY; } } this.canvas.onmouseup = this.canvas.onmouseout = function(){ _this.mouseEvent = 0; _this.mouseDownX = 0; _this.mouseDownY = 0; } this.canvas.onclick = function(e){ var x = e.offsetX; var y = e.offsetY; if(x < _this.canvas.width - 8 && y < _this.canvas.height - 8){ var row = _this.startIndex + parseInt(y / _this.lineHeight) + (y % _this.lineHeight == 0 ? 0 : 1) - 1; var _hover = false; var texts = _this.lines[row]; if(texts){ for(var i =0,len = texts.length;i x){ _this.onClick(text); break; } } } } } var animate = function(){ _this.animateIndex = requestAnimFrame(animate); _this.redraw(); } animate(); } CanvasViewer.prototype.destory = function(){ cancelAnimationFrame(this.animateIndex); this.texts = null; } CanvasViewer.prototype.append = function(texts){ this.sourceLines.push(texts); if(this.filterLine(texts)){ this.calcMaxWidth(texts); this.lines.push(texts); } } CanvasViewer.prototype.calcMaxWidth = function(texts){ var width = texts.length * 10 - 10; for(var i =0,len = texts.length;i 0){ w = this._drawLongText(text.text,0,0,text.maxWidth,true); }else{ w = this.context.measureText(content).width; } this.colsOffsetX[i] = Math.max(this.colsOffsetX[i] || 0,w); width += ((this.grid ? this.colsOffsetX[i] : 0) || w); } this.maxWidth = Math.max(this.maxWidth,width); } CanvasViewer.prototype.filter = function(content){ this.filterText = content; var nLines = []; for(var i=0,len = this.sourceLines.length;i -1; } CanvasViewer.prototype.resize = function(){ var prevMaxRows = this.maxRows; this.maxRows = Math.ceil(this.canvas.height / this.lineHeight); this.context = this.canvas.getContext('2d'); this.context.font = 'bold 14px Consolas'; this.context.textBaseline = 'middle'; this.scrollTo(this.startIndex + (prevMaxRows - this.maxRows)); this.redraw(); } CanvasViewer.prototype._drawScroll = function(){ var surplus = this.lines.length - this.maxRows; this.hasScroll = surplus > 0; this.context.clearRect(x,canvasHeight,8,8); if(this.hasScroll){ var canvasHeight = this.canvas.height - 8; this.scrollHeight = canvasHeight + this.lineHeight * surplus; this.slideHeight = Math.max(canvasHeight * (canvasHeight / this.scrollHeight),10); this.scrollTop = Math.min(this.startIndex / this.lines.length * canvasHeight,canvasHeight - this.slideHeight); this.context.save(); this.context.beginPath(); var x = this.canvas.width - 8; var y = this.scrollTop; var r = 4; var width = 8; var height = this.slideHeight; this.context.fillStyle = '#f1f1f1'; this.context.fillRect(x,0,8,canvasHeight); this.context.moveTo(x + r, y); this.context.arcTo(x + width, y, x + width, y + r, r); this.context.arcTo(x + width, y + height, x + width - r, y + height, r); this.context.arcTo(x, y + height, x, y + height - r, r); this.context.arcTo(x, y, x + r, y, r); if(this.mouseEvent == 1){ this.context.fillStyle = '#787878'; }else if(this.mouseX > x && this.mouseY > y &&this.mouseY < y + height){ this.context.fillStyle = '#a8a8a8'; }else{ this.context.fillStyle = '#c1c1c1'; } this.context.fill(); this.context.restore(); } // this.hasXScroll = this.maxWidth > this.canvas.width - 8; if(this.hasXScroll){ var canvasWidth = this.canvas.width - 8; this.scrollWidth = this.maxWidth; this.slideWidth = Math.max(canvasWidth * (canvasWidth / this.scrollWidth),10); this.scrollLeft = Math.min(-this.startX / this.maxWidth * canvasWidth,canvasWidth - this.slideWidth); this.context.save(); this.context.beginPath(); var x = this.scrollLeft; var y = this.canvas.height - 8; var r = 4; var width = this.slideWidth; var height = 8; this.context.fillStyle = '#f1f1f1'; this.context.fillRect(0,this.canvas.height - 8,canvasWidth,8); this.context.moveTo(x + r, y); this.context.arcTo(x + width, y, x + width, y + r, r); this.context.arcTo(x + width, y + height, x + width - r, y + height, r); this.context.arcTo(x, y + height, x, y + height - r, r); this.context.arcTo(x, y, x + r, y, r); if(this.mouseEvent == 2){ this.context.fillStyle = '#787878'; }else if(this.mouseX > x && this.mouseY > y &&this.mouseX < x + width){ this.context.fillStyle = '#a8a8a8'; }else{ this.context.fillStyle = '#c1c1c1'; } this.context.fill(); this.context.restore(); } } CanvasViewer.prototype.scrollTo = function(index){ if(index < 0){ index = this.lines.length - 1; } this.startIndex = Math.max(Math.min(Math.max(index,0),this.lines.length - this.maxRows),0); if(this.startIndex > 0){ this.startIndex = this.startIndex + 1; } } CanvasViewer.prototype.redraw = function(){ var lines = this.lines.slice(this.startIndex,this.startIndex + this.maxRows); this.context.clearRect(0,0,this.canvas.width,this.canvas.height); this.context.lineWidth = 1; this.context.strokeStyle = '#e6e6e6'; this.context.font = this.style.font || 'bold 14px Consolas'; this.context.textBaseline = this.style.textBaseLine || 'middle'; var cols = [0]; var maxY = 0; var maxX = 0; for(var i=0,l =lines.length;i 0){ width = this._drawLongText(content,x,y,text.maxWidth); }else{ this.context.fillText(content,x,y); } text.startX = x; text.endX = x + width; x = x + ((this.grid ? this.colsOffsetX[j] : 0) || width) + 10; maxX = x - 5; if(this.grid){ cols[j + 1] = Math.max(cols[j + 1] || 0,maxX); } } } if(this.grid && lines.length > 0){ for(var i=0;i<=lines.length;i++){ if(this.grid){ this.context.save(); this.context.beginPath(); this.context.moveTo(2.5,i * 24 + 0.5); this.context.lineTo(maxX + 0.5, i * 24 + 0.5); this.context.stroke(); this.context.restore(); } } for(var i=0;i < cols.length;i++){ var x = cols[i]; this.context.save(); this.context.beginPath(); this.context.moveTo(x + 0.5,0.5); this.context.lineTo(x + 0.5, maxY); this.context.stroke(); this.context.restore(); } } this._drawScroll(); } CanvasViewer.prototype._drawLongText = function(text,x,y,maxWidth,calcWidth){ var length = text.length; var index = 0; var width = 0; while(index < length){ var str = text.substr(index,1); var w = this.context.measureText(str).width; width+= w; if(width > maxWidth){ width-=w; break; } if(calcWidth === undefined){ this.context.fillText(str,x + width - w,y); } index++; } if(index < length){ var w = this.context.measureText('...').width; width+=w; if(calcWidth === undefined){ this.context.fillText('...',x + width - w,y); } } return width; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/codemirror.css ================================================ /* BASICS */ .CodeMirror { /* Set height, width, borders, and global font properties here */ font-family: monospace; color: black; direction: ltr; border: 1px solid #e6e6e6; height: 100%; padding-left: 7px; padding-top: 4px; box-sizing: border-box; } /* PADDING */ .CodeMirror-lines { padding: 8px 0; /* Vertical padding around content */ } .layui-table .CodeMirror-lines { padding: 0px 0; /* Vertical padding around content */ } .CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { padding: 0 4px; /* Horizontal padding of content */ } .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { background-color: white; /* The little square between H and V scrollbars */ } /* GUTTER */ .CodeMirror-gutters { border-right: 1px solid #ddd; background-color: #f7f7f7; white-space: nowrap; } .CodeMirror-linenumbers {} .CodeMirror-linenumber { padding: 0 3px 0 5px; min-width: 20px; text-align: right; color: #999; white-space: nowrap; } .CodeMirror-guttermarker { color: black; } .CodeMirror-guttermarker-subtle { color: #999; } /* CURSOR */ .CodeMirror-cursor { border-left: 1px solid black; border-right: none; width: 0; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } .cm-fat-cursor .CodeMirror-cursor { width: auto; border: 0 !important; background: #7e7; } .cm-fat-cursor div.CodeMirror-cursors { z-index: 1; } .cm-fat-cursor-mark { background-color: rgba(20, 255, 20, 0.5); -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; } .cm-animate-fat-cursor { width: auto; border: 0; -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; background-color: #7e7; } @-moz-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @-webkit-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } /* Can style cursor different in overwrite (non-insert) mode */ .CodeMirror-overwrite .CodeMirror-cursor {} .cm-tab { display: inline-block; text-decoration: inherit; } .CodeMirror-rulers { position: absolute; left: 0; right: 0; top: -50px; bottom: 0; overflow: hidden; } .CodeMirror-ruler { border-left: 1px solid #ccc; top: 0; bottom: 0; position: absolute; } /* DEFAULT THEME */ .cm-s-default .cm-header {color: blue;} .cm-s-default .cm-quote {color: #090;} .cm-negative {color: #d44;} .cm-positive {color: #292;} .cm-header, .cm-strong {font-weight: bold;} .cm-em {font-style: italic;} .cm-link {text-decoration: underline;} .cm-strikethrough {text-decoration: line-through;} .cm-s-default .cm-keyword {color: #708;} .cm-s-default .cm-atom {color: #219;} .cm-s-default .cm-number {color: #164;} .cm-s-default .cm-def {color: #00f;} .cm-s-default .cm-variable, .cm-s-default .cm-punctuation, .cm-s-default .cm-property, .cm-s-default .cm-operator {} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} .cm-s-default .cm-comment {color: #a50;} .cm-s-default .cm-string {color: #a11;} .cm-s-default .cm-string-2 {color: #f50;} .cm-s-default .cm-meta {color: #555;} .cm-s-default .cm-qualifier {color: #555;} .cm-s-default .cm-builtin {color: #30a;} .cm-s-default .cm-bracket {color: #997;} .cm-s-default .cm-tag {color: #170;} .cm-s-default .cm-attribute {color: #00c;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} .cm-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} .CodeMirror-composing { border-bottom: 2px solid; } /* Default styles for common addons */ div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-activeline-background {background: #e8f2ff;} /* STOP */ /* The rest of this file contains styles related to the mechanics of the editor. You probably shouldn't touch them. */ .CodeMirror { position: relative; overflow: hidden; background: white; } .CodeMirror-scroll { overflow: scroll !important; /* Things will break if this is overridden */ /* 30px is the magic margin used to hide the element's real scrollbars */ /* See overflow: hidden in .CodeMirror */ margin-bottom: -30px; margin-right: -30px; padding-bottom: 30px; height: 100%; outline: none; /* Prevent dragging from highlighting the element */ position: relative; } .CodeMirror-sizer { position: relative; border-right: 30px solid transparent; } /* The fake, visible scrollbars. Used to force redraw during scrolling before actual scrolling happens, thus preventing shaking and flickering artifacts. */ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { position: absolute; z-index: 6; display: none; } .CodeMirror-vscrollbar { right: 0; top: 0; overflow-x: hidden; overflow-y: scroll; } .CodeMirror-hscrollbar { bottom: 0; left: 0; overflow-y: hidden; overflow-x: scroll; } .CodeMirror-scrollbar-filler { right: 0; bottom: 0; } .CodeMirror-gutter-filler { left: 0; bottom: 0; } .CodeMirror-gutters { position: absolute; left: 0; top: 0; min-height: 100%; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; display: inline-block; vertical-align: top; margin-bottom: -30px; } .CodeMirror-gutter-wrapper { position: absolute; z-index: 4; background: none !important; border: none !important; } .CodeMirror-gutter-background { position: absolute; top: 0; bottom: 0; z-index: 4; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } .CodeMirror-gutter-wrapper ::selection { background-color: transparent } .CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } .CodeMirror-lines { cursor: text; min-height: 1px; /* prevents collapsing before first draw */ } .CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { /* Reset some styles that the rest of the page might have set */ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; border-width: 0; background: transparent; font-family: inherit; font-size: inherit; margin: 0; white-space: pre; word-wrap: normal; line-height: inherit; color: inherit; z-index: 2; position: relative; overflow: visible; -webkit-tap-highlight-color: transparent; -webkit-font-variant-ligatures: contextual; font-variant-ligatures: contextual; } .CodeMirror-wrap pre.CodeMirror-line, .CodeMirror-wrap pre.CodeMirror-line-like { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 0; } .CodeMirror-linewidget { position: relative; z-index: 2; padding: 0.1px; /* Force widget margins to stay inside of the container */ } .CodeMirror-widget {} .CodeMirror-rtl pre { direction: rtl; } .CodeMirror-code { outline: none; } /* Force content-box sizing for the elements where we expect it */ .CodeMirror-scroll, .CodeMirror-sizer, .CodeMirror-gutter, .CodeMirror-gutters, .CodeMirror-linenumber { -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-measure { position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; } .CodeMirror-cursor { position: absolute; pointer-events: none; } .CodeMirror-measure pre { position: static; } div.CodeMirror-cursors { visibility: hidden; position: relative; z-index: 3; } div.CodeMirror-dragcursors { visibility: visible; } .CodeMirror-focused div.CodeMirror-cursors { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } .CodeMirror-crosshair { cursor: crosshair; } .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } .cm-searching { background-color: #ffa; background-color: rgba(255, 255, 0, .4); } /* Used to force a border model for a node */ .cm-force-border { padding-right: .1px; } @media print { /* Hide the cursor when printing */ .CodeMirror div.CodeMirror-cursors { visibility: hidden; } } /* See issue #2901 */ .cm-tab-wrap-hack:after { content: ''; } /* Help users use markselection to safely style text background */ span.CodeMirror-selectedtext { background: none; } .CodeMirror pre.CodeMirror-placeholder { color: #666; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/codemirror.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // This is CodeMirror (https://codemirror.net), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.CodeMirror = factory()); }(this, (function () { 'use strict'; // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. var userAgent = navigator.userAgent; var platform = navigator.platform; var gecko = /gecko\/\d/i.test(userAgent); var ie_upto10 = /MSIE \d/.test(userAgent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); var edge = /Edge\/(\d+)/.exec(userAgent); var ie = ie_upto10 || ie_11up || edge; var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); var webkit = !edge && /WebKit\//.test(userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); var chrome = !edge && /Chrome\//.test(userAgent); var presto = /Opera\//.test(userAgent); var safari = /Apple Computer/.test(navigator.vendor); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); var phantom = /PhantomJS/.test(userAgent); var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); var android = /Android/.test(userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); var mac = ios || /Mac/.test(platform); var chromeOS = /\bCrOS\b/.test(userAgent); var windows = /win/i.test(platform); var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); if (presto_version) { presto_version = Number(presto_version[1]); } if (presto_version && presto_version >= 15) { presto = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); var captureRightClick = gecko || (ie && ie_version >= 9); function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } var rmClass = function(node, cls) { var current = node.className; var match = classTest(cls).exec(current); if (match) { var after = current.slice(match.index + match[0].length); node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } }; function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) { e.removeChild(e.firstChild); } return e } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e) } function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) { e.className = className; } if (style) { e.style.cssText = style; } if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } return e } // wrapper for elt, which removes the elt from the accessibility tree function eltP(tag, content, className, style) { var e = elt(tag, content, className, style); e.setAttribute("role", "presentation"); return e } var range; if (document.createRange) { range = function(node, start, end, endNode) { var r = document.createRange(); r.setEnd(endNode || node, end); r.setStart(node, start); return r }; } else { range = function(node, start, end) { var r = document.body.createTextRange(); try { r.moveToElementText(node.parentNode); } catch(e) { return r } r.collapse(true); r.moveEnd("character", end); r.moveStart("character", start); return r }; } function contains(parent, child) { if (child.nodeType == 3) // Android browser always returns false when child is a textnode { child = child.parentNode; } if (parent.contains) { return parent.contains(child) } do { if (child.nodeType == 11) { child = child.host; } if (child == parent) { return true } } while (child = child.parentNode) } function activeElt() { // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. // IE < 10 will throw when accessed while the page is loading or in an iframe. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. var activeElement; try { activeElement = document.activeElement; } catch(e) { activeElement = document.body || null; } while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { activeElement = activeElement.shadowRoot.activeElement; } return activeElement } function addClass(node, cls) { var current = node.className; if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } } function joinClasses(a, b) { var as = a.split(" "); for (var i = 0; i < as.length; i++) { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } return b } var selectInput = function(node) { node.select(); }; if (ios) // Mobile Safari apparently has a bug where select() is broken. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } else if (ie) // Suppress mysterious IE10 errors { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args)} } function copyObj(obj, target, overwrite) { if (!target) { target = {}; } for (var prop in obj) { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) { target[prop] = obj[prop]; } } return target } // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) { end = string.length; } } for (var i = startIndex || 0, n = startValue || 0;;) { var nextTab = string.indexOf("\t", i); if (nextTab < 0 || nextTab >= end) { return n + (end - i) } n += nextTab - i; n += tabSize - (n % tabSize); i = nextTab + 1; } } var Delayed = function() {this.id = null;}; Delayed.prototype.set = function (ms, f) { clearTimeout(this.id); this.id = setTimeout(f, ms); }; function indexOf(array, elt) { for (var i = 0; i < array.length; ++i) { if (array[i] == elt) { return i } } return -1 } // Number of pixels added to scroller and sizer to hide scrollbar var scrollerGap = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = {toString: function(){return "CodeMirror.Pass"}}; // Reused option objects for setSelection & friends var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; // The inverse of countColumn -- find the offset that corresponds to // a particular column. function findColumn(string, goal, tabSize) { for (var pos = 0, col = 0;;) { var nextTab = string.indexOf("\t", pos); if (nextTab == -1) { nextTab = string.length; } var skipped = nextTab - pos; if (nextTab == string.length || col + skipped >= goal) { return pos + Math.min(skipped, goal - col) } col += nextTab - pos; col += tabSize - (col % tabSize); pos = nextTab + 1; if (col >= goal) { return pos } } } var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) { spaceStrs.push(lst(spaceStrs) + " "); } return spaceStrs[n] } function lst(arr) { return arr[arr.length-1] } function map(array, f) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } return out } function insertSorted(array, value, score) { var pos = 0, priority = score(value); while (pos < array.length && score(array[pos]) <= priority) { pos++; } array.splice(pos, 0, value); } function nothing() {} function createObj(base, props) { var inst; if (Object.create) { inst = Object.create(base); } else { nothing.prototype = base; inst = new nothing(); } if (props) { copyObj(props, inst); } return inst } var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordCharBasic(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) } function isWordChar(ch, helper) { if (!helper) { return isWordCharBasic(ch) } if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } return helper.test(ch) } function isEmpty(obj) { for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } return true } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. function skipExtendingChars(str, pos, dir) { while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } return pos } // Returns the value from the range [`from`; `to`] that satisfies // `pred` and is closest to `from`. Assumes that at least `to` // satisfies `pred`. Supports `from` being greater than `to`. function findFirst(pred, from, to) { // At any point we are certain `to` satisfies `pred`, don't know // whether `from` does. var dir = from > to ? -1 : 1; for (;;) { if (from == to) { return from } var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); if (mid == from) { return pred(mid) ? from : to } if (pred(mid)) { to = mid; } else { from = mid + dir; } } } // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) { return f(from, to, "ltr", 0) } var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); found = true; } } if (!found) { f(from, to, "ltr"); } } var bidiOther = null; function getBidiPartAt(order, ch, sticky) { var found; bidiOther = null; for (var i = 0; i < order.length; ++i) { var cur = order[i]; if (cur.from < ch && cur.to > ch) { return i } if (cur.to == ch) { if (cur.from != cur.to && sticky == "before") { found = i; } else { bidiOther = i; } } if (cur.from == ch) { if (cur.from != cur.to && sticky != "before") { found = i; } else { bidiOther = i; } } } return found != null ? found : bidiOther } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; // Character types for codepoints 0x600 to 0x6f9 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; function charType(code) { if (code <= 0xf7) { return lowTypes.charAt(code) } else if (0x590 <= code && code <= 0x5f4) { return "R" } else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } else if (0x6ee <= code && code <= 0x8ac) { return "r" } else if (0x2000 <= code && code <= 0x200b) { return "w" } else if (code == 0x200c) { return "b" } else { return "L" } } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; function BidiSpan(level, from, to) { this.level = level; this.from = from; this.to = to; } return function(str, direction) { var outerType = direction == "ltr" ? "L" : "R"; if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } var len = str.length, types = []; for (var i = 0; i < len; ++i) { types.push(charType(str.charCodeAt(i))); } // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { var type = types[i$1]; if (type == "m") { types[i$1] = prev; } else { prev = type; } } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { var type$1 = types[i$2]; if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { var type$2 = types[i$3]; if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } else if (type$2 == "," && prev$1 == types[i$3+1] && (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } prev$1 = type$2; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i$4 = 0; i$4 < len; ++i$4) { var type$3 = types[i$4]; if (type$3 == ",") { types[i$4] = "N"; } else if (type$3 == "%") { var end = (void 0); for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; for (var j = i$4; j < end; ++j) { types[j] = replace; } i$4 = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { var type$4 = types[i$5]; if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } else if (isStrong.test(type$4)) { cur$1 = type$4; } } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i$6 = 0; i$6 < len; ++i$6) { if (isNeutral.test(types[i$6])) { var end$1 = (void 0); for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} var before = (i$6 ? types[i$6-1] : outerType) == "L"; var after = (end$1 < len ? types[end$1] : outerType) == "L"; var replace$1 = before == after ? (before ? "L" : "R") : outerType; for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } i$6 = end$1 - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i$7 = 0; i$7 < len;) { if (countsAsLeft.test(types[i$7])) { var start = i$7; for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} order.push(new BidiSpan(0, start, i$7)); } else { var pos = i$7, at = order.length; for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} for (var j$2 = pos; j$2 < i$7;) { if (countsAsNum.test(types[j$2])) { if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } var nstart = j$2; for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} order.splice(at, 0, new BidiSpan(2, nstart, j$2)); pos = j$2; } else { ++j$2; } } if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } } } if (direction == "ltr") { if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift(new BidiSpan(0, 0, m[0].length)); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push(new BidiSpan(0, len - m[0].length, len)); } } return direction == "rtl" ? order.reverse() : order } })(); // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. function getOrder(line, direction) { var order = line.order; if (order == null) { order = line.order = bidiOrdering(line.text, direction); } return order } // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. var noHandlers = []; var on = function(emitter, type, f) { if (emitter.addEventListener) { emitter.addEventListener(type, f, false); } else if (emitter.attachEvent) { emitter.attachEvent("on" + type, f); } else { var map$$1 = emitter._handlers || (emitter._handlers = {}); map$$1[type] = (map$$1[type] || noHandlers).concat(f); } }; function getHandlers(emitter, type) { return emitter._handlers && emitter._handlers[type] || noHandlers } function off(emitter, type, f) { if (emitter.removeEventListener) { emitter.removeEventListener(type, f, false); } else if (emitter.detachEvent) { emitter.detachEvent("on" + type, f); } else { var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; if (arr) { var index = indexOf(arr, f); if (index > -1) { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } } } } function signal(emitter, type /*, values...*/) { var handlers = getHandlers(emitter, type); if (!handlers.length) { return } var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. function signalDOMEvent(cm, e, override) { if (typeof e == "string") { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore } function signalCursorActivity(cm) { var arr = cm._handlers && cm._handlers.cursorActivity; if (!arr) { return } var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) { set.push(arr[i]); } } } function hasHandler(emitter, type) { return getHandlers(emitter, type).length > 0 } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. function e_preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } function e_stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } } function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} function e_target(e) {return e.target || e.srcElement} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) { b = 1; } else if (e.button & 2) { b = 3; } else if (e.button & 4) { b = 2; } } if (mac && e.ctrlKey && b == 1) { b = 3; } return b } // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) { return false } var div = elt('div'); return "draggable" in div || "dragDrop" in div }(); var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } } var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); node.setAttribute("cm-text", ""); return node } // Feature-detect IE's crummy client rect reporting for bidi text var badBidiRects; function hasBadBidiRects(measure) { if (badBidiRects != null) { return badBidiRects } var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); var r0 = range(txt, 0, 1).getBoundingClientRect(); var r1 = range(txt, 1, 2).getBoundingClientRect(); removeChildren(measure); if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) return badBidiRects = (r1.right - r0.right < 3) } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) { nl = string.length; } var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result } : function (string) { return string.split(/\r\n?|\n/); }; var hasSelection = window.getSelection ? function (te) { try { return te.selectionStart != te.selectionEnd } catch(e) { return false } } : function (te) { var range$$1; try {range$$1 = te.ownerDocument.selection.createRange();} catch(e) {} if (!range$$1 || range$$1.parentElement() != te) { return false } return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 }; var hasCopyEvent = (function () { var e = elt("div"); if ("oncopy" in e) { return true } e.setAttribute("oncopy", "return;"); return typeof e.oncopy == "function" })(); var badZoomedRects = null; function hasBadZoomedRects(measure) { if (badZoomedRects != null) { return badZoomedRects } var node = removeChildrenAndAdd(measure, elt("span", "x")); var normal = node.getBoundingClientRect(); var fromRange = range(node, 0, 1).getBoundingClientRect(); return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 } // Known modes, by name and by MIME var modes = {}, mimeModes = {}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) function defineMode(name, mode) { if (arguments.length > 2) { mode.dependencies = Array.prototype.slice.call(arguments, 2); } modes[name] = mode; } function defineMIME(mime, spec) { mimeModes[mime] = spec; } // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. function resolveMode(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; if (typeof found == "string") { found = {name: found}; } spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return resolveMode("application/xml") } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { return resolveMode("application/json") } if (typeof spec == "string") { return {name: spec} } else { return spec || {name: "null"} } } // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. function getMode(options, spec) { spec = resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) { return getMode(options, "text/plain") } var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) { continue } if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; if (spec.helperType) { modeObj.helperType = spec.helperType; } if (spec.modeProps) { for (var prop$1 in spec.modeProps) { modeObj[prop$1] = spec.modeProps[prop$1]; } } return modeObj } // This can be used to attach properties to mode objects from // outside the actual mode definition. var modeExtensions = {}; function extendMode(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); } function copyState(mode, state) { if (state === true) { return state } if (mode.copyState) { return mode.copyState(state) } var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) { val = val.concat([]); } nstate[n] = val; } return nstate } // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. function innerMode(mode, state) { var info; while (mode.innerMode) { info = mode.innerMode(state); if (!info || info.mode == mode) { break } state = info.state; mode = info.mode; } return info || {mode: mode, state: state} } function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true } // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. var StringStream = function(string, tabSize, lineOracle) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; this.lineStart = 0; this.lineOracle = lineOracle; }; StringStream.prototype.eol = function () {return this.pos >= this.string.length}; StringStream.prototype.sol = function () {return this.pos == this.lineStart}; StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; StringStream.prototype.next = function () { if (this.pos < this.string.length) { return this.string.charAt(this.pos++) } }; StringStream.prototype.eat = function (match) { var ch = this.string.charAt(this.pos); var ok; if (typeof match == "string") { ok = ch == match; } else { ok = ch && (match.test ? match.test(ch) : match(ch)); } if (ok) {++this.pos; return ch} }; StringStream.prototype.eatWhile = function (match) { var start = this.pos; while (this.eat(match)){} return this.pos > start }; StringStream.prototype.eatSpace = function () { var this$1 = this; var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } return this.pos > start }; StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; StringStream.prototype.skipTo = function (ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true} }; StringStream.prototype.backUp = function (n) {this.pos -= n;}; StringStream.prototype.column = function () { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.indentation = function () { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.match = function (pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) { this.pos += pattern.length; } return true } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) { return null } if (match && consume !== false) { this.pos += match[0].length; } return match } }; StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; StringStream.prototype.hideFirstChars = function (n, inner) { this.lineStart += n; try { return inner() } finally { this.lineStart -= n; } }; StringStream.prototype.lookAhead = function (n) { var oracle = this.lineOracle; return oracle && oracle.lookAhead(n) }; StringStream.prototype.baseToken = function () { var oracle = this.lineOracle; return oracle && oracle.baseToken(this.pos) }; // Find the line object corresponding to the given line number. function getLine(doc, n) { n -= doc.first; if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } var chunk = doc; while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break } n -= sz; } } return chunk.lines[n] } // Get the part of a document between two positions, as an array of // strings. function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function (line) { var text = line.text; if (n == end.line) { text = text.slice(0, end.ch); } if (n == start.line) { text = text.slice(start.ch); } out.push(text); ++n; }); return out } // Get the lines between from and to, as array of strings. function getLines(doc, from, to) { var out = []; doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value return out } // Update the height of a line, propagating the height change // upwards to parent nodes. function updateLineHeight(line, height) { var diff = height - line.height; if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } } // Given a line object, find its line number by walking up through // its parent links. function lineNo(line) { if (line.parent == null) { return null } var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) { break } no += chunk.children[i].chunkSize(); } } return no + cur.first } // Find the line at the given vertical position, using the height // information in the document tree. function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { var child = chunk.children[i$1], ch = child.height; if (h < ch) { chunk = child; continue outer } h -= ch; n += child.chunkSize(); } return n } while (!chunk.lines) var i = 0; for (; i < chunk.lines.length; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) { break } h -= lh; } return n + i } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)) } // A Pos instance represents a position within the text. function Pos(line, ch, sticky) { if ( sticky === void 0 ) sticky = null; if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } this.line = line; this.ch = ch; this.sticky = sticky; } // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. function cmp(a, b) { return a.line - b.line || a.ch - b.ch } function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } function copyPos(x) {return Pos(x.line, x.ch)} function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } function minPos(a, b) { return cmp(a, b) < 0 ? a : b } // Most of the external API clips given positions to make sure they // actually exist within the document. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} function clipPos(doc, pos) { if (pos.line < doc.first) { return Pos(doc.first, 0) } var last = doc.first + doc.size - 1; if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } return clipToLen(pos, getLine(doc, pos.line).text.length) } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } else if (ch < 0) { return Pos(pos.line, 0) } else { return pos } } function clipPosArray(doc, array) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } return out } var SavedContext = function(state, lookAhead) { this.state = state; this.lookAhead = lookAhead; }; var Context = function(doc, state, line, lookAhead) { this.state = state; this.doc = doc; this.line = line; this.maxLookAhead = lookAhead || 0; this.baseTokens = null; this.baseTokenPos = 1; }; Context.prototype.lookAhead = function (n) { var line = this.doc.getLine(this.line + n); if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } return line }; Context.prototype.baseToken = function (n) { var this$1 = this; if (!this.baseTokens) { return null } while (this.baseTokens[this.baseTokenPos] <= n) { this$1.baseTokenPos += 2; } var type = this.baseTokens[this.baseTokenPos + 1]; return {type: type && type.replace(/( |^)overlay .*/, ""), size: this.baseTokens[this.baseTokenPos] - n} }; Context.prototype.nextLine = function () { this.line++; if (this.maxLookAhead > 0) { this.maxLookAhead--; } }; Context.fromSaved = function (doc, saved, line) { if (saved instanceof SavedContext) { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } else { return new Context(doc, copyState(doc.mode, saved), line) } }; Context.prototype.save = function (copy) { var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state }; // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. function highlightLine(cm, line, context, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen], lineClasses = {}; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, lineClasses, forceToEnd); var state = context.state; // Run overlays, adjust style array. var loop = function ( o ) { context.baseTokens = st; var overlay = cm.state.overlays[o], i = 1, at = 0; context.state = true; runMode(cm, line.text, overlay.mode, context, function (end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) { st.splice(i, 1, end, st[i+1], i_end); } i += 2; at = Math.min(end, i_end); } if (!style) { return } if (overlay.opaque) { st.splice(start, i - start, end, "overlay " + style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = (cur ? cur + " " : "") + "overlay " + style; } } }, lineClasses); context.state = state; context.baseTokens = null; context.baseTokenPos = 1; }; for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} } function getLineStyles(cm, line, updateFrontier) { if (!line.styles || line.styles[0] != cm.state.modeGen) { var context = getContextBefore(cm, lineNo(line)); var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); var result = highlightLine(cm, line, context); if (resetState) { context.state = resetState; } line.stateAfter = context.save(!resetState); line.styles = result.styles; if (result.classes) { line.styleClasses = result.classes; } else if (line.styleClasses) { line.styleClasses = null; } if (updateFrontier === cm.doc.highlightFrontier) { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } } return line.styles } function getContextBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) { return new Context(doc, true, n) } var start = findStartLine(cm, n, precise); var saved = start > doc.first && getLine(doc, start - 1).stateAfter; var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); doc.iter(start, n, function (line) { processLine(cm, line.text, context); var pos = context.line; line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; context.nextLine(); }); if (precise) { doc.modeFrontier = context.line; } return context } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. function processLine(cm, text, context, startAt) { var mode = cm.doc.mode; var stream = new StringStream(text, cm.options.tabSize, context); stream.start = stream.pos = startAt || 0; if (text == "") { callBlankLine(mode, context.state); } while (!stream.eol()) { readToken(mode, stream, context.state); stream.start = stream.pos; } } function callBlankLine(mode, state) { if (mode.blankLine) { return mode.blankLine(state) } if (!mode.innerMode) { return } var inner = innerMode(mode, state); if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } } function readToken(mode, stream, state, inner) { for (var i = 0; i < 10; i++) { if (inner) { inner[0] = innerMode(mode, state).mode; } var style = mode.token(stream, state); if (stream.pos > stream.start) { return style } } throw new Error("Mode " + mode.name + " failed to advance stream.") } var Token = function(stream, type, state) { this.start = stream.start; this.end = stream.pos; this.string = stream.current(); this.type = type || null; this.state = state; }; // Utility for getTokenAt and getLineTokens function takeToken(cm, pos, precise, asArray) { var doc = cm.doc, mode = doc.mode, style; pos = clipPos(doc, pos); var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; if (asArray) { tokens = []; } while ((asArray || stream.pos < pos.ch) && !stream.eol()) { stream.start = stream.pos; style = readToken(mode, stream, context.state); if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } } return asArray ? tokens : new Token(stream, style, context.state) } function extractLineClasses(type, output) { if (type) { for (;;) { var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); if (!lineClass) { break } type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (output[prop] == null) { output[prop] = lineClass[2]; } else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) { output[prop] += " " + lineClass[2]; } } } return type } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize, context), style; var inner = cm.options.addModeClass && [null]; if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; if (forceToEnd) { processLine(cm, text, context, stream.pos); } stream.pos = text.length; style = null; } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); } if (inner) { var mName = inner[0].name; if (mName) { style = "m-" + (style ? mName + " " + style : mName); } } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000); f(curStart, curStyle); } curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. var pos = Math.min(stream.pos, curStart + 5000); f(pos, curStyle); curStart = pos; } } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); for (var search = n; search > lim; --search) { if (search <= doc.first) { return doc.first } var line = getLine(doc, search - 1), after = line.stateAfter; if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { return search } var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline } function retreatFrontier(doc, n) { doc.modeFrontier = Math.min(doc.modeFrontier, n); if (doc.highlightFrontier < n - 10) { return } var start = doc.first; for (var line = n - 1; line > start; line--) { var saved = getLine(doc, line).stateAfter; // change is on 3 // state on line 1 looked ahead 2 -- so saw 3 // test 1 + 2 < 3 should cover this if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { start = line + 1; break } } doc.highlightFrontier = Math.min(doc.highlightFrontier, start); } // Optimize some code when these features are not used. var sawReadOnlySpans = false, sawCollapsedSpans = false; function seeReadOnlySpans() { sawReadOnlySpans = true; } function seeCollapsedSpans() { sawCollapsedSpans = true; } // TEXTMARKER SPANS function MarkedSpan(marker, from, to) { this.marker = marker; this.from = from; this.to = to; } // Search an array of spans for a span matching the given marker. function getMarkedSpanFor(spans, marker) { if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) { return span } } } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). function removeMarkedSpan(spans, span) { var r; for (var i = 0; i < spans.length; ++i) { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } return r } // Add a span to a line. function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } } } return nw } function markedSpansAfter(old, endCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } } } return nw } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. function stretchSpansOverChange(doc, change) { if (change.full) { return null } var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) { return null } var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) { span.to = startCh; } else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i$1 = 0; i$1 < last.length; ++i$1) { var span$1 = last[i$1]; if (span$1.to != null) { span$1.to += offset; } if (span$1.from == null) { var found$1 = getMarkedSpanFor(first, span$1.marker); if (!found$1) { span$1.from = offset; if (sameLine) { (first || (first = [])).push(span$1); } } } else { span$1.from += offset; if (sameLine) { (first || (first = [])).push(span$1); } } } } // Make sure we didn't create any zero-length spans if (first) { first = clearEmptySpans(first); } if (last && last != first) { last = clearEmptySpans(last); } var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) { for (var i$2 = 0; i$2 < first.length; ++i$2) { if (first[i$2].to == null) { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } for (var i$3 = 0; i$3 < gap; ++i$3) { newMarkers.push(gapMarkers); } newMarkers.push(last); } return newMarkers } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { spans.splice(i--, 1); } } if (!spans.length) { return null } return spans } // Used to 'clip' out readOnly ranges when making a change. function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function (line) { if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { (markers || (markers = [])).push(mark); } } } }); if (!markers) { return null } var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(0); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { newParts.push({from: p.from, to: m.from}); } if (dto > 0 || !mk.inclusiveRight && !dto) { newParts.push({from: m.to, to: p.to}); } parts.splice.apply(parts, newParts); j += newParts.length - 3; } } return parts } // Connect or disconnect spans from a line. function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.detachLine(line); } line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.attachLine(line); } line.markedSpans = spans; } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. function compareCollapsedMarkers(a, b) { var lenDiff = a.lines.length - b.lines.length; if (lenDiff != 0) { return lenDiff } var aPos = a.find(), bPos = b.find(); var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); if (fromCmp) { return -fromCmp } var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); if (toCmp) { return toCmp } return b.id - a.id } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } function collapsedSpanAround(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { var line = getLine(doc, lineNo$$1); var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (!sp.marker.collapsed) { continue } var found = sp.marker.find(0); var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { return true } } } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). function visualLine(line) { var merged; while (merged = collapsedSpanAtStart(line)) { line = merged.find(-1, true).line; } return line } function visualLineEnd(line) { var merged; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return line } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. function visualLineContinued(line) { var merged, lines; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line ;(lines || (lines = [])).push(line); } return lines } // Get the line number of the start of the visual line that the // given line number is part of. function visualLineNo(doc, lineN) { var line = getLine(doc, lineN), vis = visualLine(line); if (line == vis) { return lineN } return lineNo(vis) } // Get the line number of the start of the next visual line after // the given line. function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) { return lineN } var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) { return lineN } while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return lineNo(line) + 1 } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) { continue } if (sp.from == null) { return true } if (sp.marker.widgetNode) { continue } if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { return true } } } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find(1, true); return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) } if (span.marker.inclusiveRight && span.to == line.text.length) { return true } for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { return true } } } // Find the height above the given line. function heightAtLine(lineObj) { lineObj = visualLine(lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) { break } else { h += line.height; } } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i$1 = 0; i$1 < p.children.length; ++i$1) { var cur = p.children[i$1]; if (cur == chunk) { break } else { h += cur.height; } } } return h } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. function lineLength(line) { if (line.height == 0) { return 0 } var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(0, true); cur = found.from.line; len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found$1 = merged.find(0, true); len -= cur.text.length - found$1.from.ch; cur = found$1.to.line; len += cur.text.length - found$1.to.ch; } return len } // Find the longest line in the document. function findMaxLine(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(d.maxLine); d.maxLineChanged = true; doc.iter(function (line) { var len = lineLength(line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; Line.prototype.lineNo = function () { return lineNo(this) }; eventMixin(Line); // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } if (line.order != null) { line.order = null; } detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) { updateLineHeight(line, estHeight); } } // Detach a line from the document tree and its markers. function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. var styleToClassCache = {}, styleToClassCacheWithMode = {}; function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) { return null } var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")) } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption("lineWrapping")}; lineView.measure = {}; // Iterate over the logical lines that make up this visual line. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); builder.pos = 0; builder.addToken = buildToken; // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { builder.addToken = buildTokenBadBidi(builder.addToken, order); } builder.map = []; var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); if (line.styleClasses) { if (line.styleClasses.bgClass) { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } if (line.styleClasses.textClass) { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map; lineView.measure.cache = {}; } else { (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); } } // See issue #2901 if (webkit) { var last = builder.content.lastChild; if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) { builder.content.className = "cm-tab-wrap-hack"; } } signal(cm, "renderLine", cm, lineView.line, builder.pre); if (builder.pre.className) { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } return builder } function defaultSpecialCharPlaceholder(ch) { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + ch.charCodeAt(0).toString(16); token.setAttribute("aria-label", token.title); return token } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { if (!text) { return } var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; var special = builder.cm.state.specialChars, mustWrap = false; var content; if (!special.test(text)) { builder.col += text.length; content = document.createTextNode(displayText); builder.map.push(builder.pos, builder.pos + text.length, content); if (ie && ie_version < 9) { mustWrap = true; } builder.pos += text.length; } else { content = document.createDocumentFragment(); var pos = 0; while (true) { special.lastIndex = pos; var m = special.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } else { content.appendChild(txt); } builder.map.push(builder.pos, builder.pos + skipped, txt); builder.col += skipped; builder.pos += skipped; } if (!m) { break } pos += skipped + 1; var txt$1 = (void 0); if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); txt$1.setAttribute("role", "presentation"); txt$1.setAttribute("cm-text", "\t"); builder.col += tabWidth; } else if (m[0] == "\r" || m[0] == "\n") { txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); txt$1.setAttribute("cm-text", m[0]); builder.col += 1; } else { txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); txt$1.setAttribute("cm-text", m[0]); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } else { content.appendChild(txt$1); } builder.col += 1; } builder.map.push(builder.pos, builder.pos + 1, txt$1); builder.pos++; } } builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; if (style || startStyle || endStyle || mustWrap || css) { var fullStyle = style || ""; if (startStyle) { fullStyle += startStyle; } if (endStyle) { fullStyle += endStyle; } var token = elt("span", [content], fullStyle, css); if (attributes) { for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { token.setAttribute(attr, attributes[attr]); } } } return builder.content.appendChild(token) } builder.content.appendChild(content); } // Change some spaces to NBSP to prevent the browser from collapsing // trailing spaces at the end of a line when rendering text (issue #1362). function splitSpaces(text, trailingBefore) { if (text.length > 1 && !/ /.test(text)) { return text } var spaceBefore = trailingBefore, result = ""; for (var i = 0; i < text.length; i++) { var ch = text.charAt(i); if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) { ch = "\u00a0"; } result += ch; spaceBefore = ch == " "; } return result } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return function (builder, text, style, startStyle, endStyle, css, attributes) { style = style ? style + " cm-force-border" : "cm-force-border"; var start = builder.pos, end = start + text.length; for (;;) { // Find the part that overlaps with the start of this text var part = (void 0); for (var i = 0; i < order.length; i++) { part = order[i]; if (part.to > start && part.from <= start) { break } } if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); startStyle = null; text = text.slice(part.to - start); start = part.to; } } } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.widgetNode; if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { if (!widget) { widget = builder.content.appendChild(document.createElement("span")); } widget.setAttribute("cm-marker", marker.id); } if (widget) { builder.cm.display.input.setUneditable(widget); builder.content.appendChild(widget); } builder.pos += size; builder.trailingSpace = false; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i$1 = 1; i$1 < styles.length; i$1+=2) { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } return } var len = allText.length, pos = 0, i = 1, text = "", style, css; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = css = ""; attributes = null; collapsed = null; nextChange = Infinity; var foundBookmarks = [], endStyles = (void 0); for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { foundBookmarks.push(m); } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { if (sp.to != null && sp.to != pos && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) { spanStyle += " " + m.className; } if (m.css) { css = (css ? css + ";" : "") + m.css; } if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } // support for the old title property // https://github.com/codemirror/CodeMirror/pull/5673 if (m.title) { (attributes || (attributes = {})).title = m.title; } if (m.attributes) { for (var attr in m.attributes) { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } } if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { collapsed = sp; } } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } } if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) { return } if (collapsed.to == pos) { collapsed = false; } } } if (pos >= len) { break } var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = interpretTokenStyle(styles[i++], builder.cm.options); } } } // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. function LineView(doc, line, lineN) { // The starting line this.line = line; // Continuing lines, if any this.rest = visualLineContinued(line); // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; this.node = this.text = null; this.hidden = lineIsHidden(doc, line); } // Create a range of LineView objects for the given lines. function buildViewArray(cm, from, to) { var array = [], nextPos; for (var pos = from; pos < to; pos = nextPos) { var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); nextPos = pos + view.size; array.push(view); } return array } var operationGroup = null; function pushOperation(op) { if (operationGroup) { operationGroup.ops.push(op); } else { op.ownsGroup = operationGroup = { ops: [op], delayedCallbacks: [] }; } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear var callbacks = group.delayedCallbacks, i = 0; do { for (; i < callbacks.length; i++) { callbacks[i].call(null); } for (var j = 0; j < group.ops.length; j++) { var op = group.ops[j]; if (op.cursorActivityHandlers) { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } } } while (i < callbacks.length) } function finishOperation(op, endCb) { var group = op.ownsGroup; if (!group) { return } try { fireCallbacksForOps(group); } finally { operationGroup = null; endCb(group); } } var orphanDelayedCallbacks = null; // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. function signalLater(emitter, type /*, values...*/) { var arr = getHandlers(emitter, type); if (!arr.length) { return } var args = Array.prototype.slice.call(arguments, 2), list; if (operationGroup) { list = operationGroup.delayedCallbacks; } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks; } else { list = orphanDelayedCallbacks = []; setTimeout(fireOrphanDelayed, 0); } var loop = function ( i ) { list.push(function () { return arr[i].apply(null, args); }); }; for (var i = 0; i < arr.length; ++i) loop( i ); } function fireOrphanDelayed() { var delayed = orphanDelayedCallbacks; orphanDelayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) { delayed[i](); } } // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. function updateLineForChanges(cm, lineView, lineN, dims) { for (var j = 0; j < lineView.changes.length; j++) { var type = lineView.changes[j]; if (type == "text") { updateLineText(cm, lineView); } else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } else if (type == "class") { updateLineClasses(cm, lineView); } else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } } lineView.changes = null; } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative"); if (lineView.text.parentNode) { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } lineView.node.appendChild(lineView.text); if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } } return lineView.node } function updateLineBackground(cm, lineView) { var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; if (cls) { cls += " CodeMirror-linebackground"; } if (lineView.background) { if (cls) { lineView.background.className = cls; } else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } } else if (cls) { var wrap = ensureLineWrapped(lineView); lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); cm.display.input.setUneditable(lineView.background); } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built } return buildLineContent(cm, lineView) } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { var cls = lineView.text.className; var built = getLineContent(cm, lineView); if (lineView.text == lineView.node) { lineView.node = built.pre; } lineView.text.parentNode.replaceChild(built.pre, lineView.text); lineView.text = built.pre; if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass; lineView.textClass = built.textClass; updateLineClasses(cm, lineView); } else if (cls) { lineView.text.className = cls; } } function updateLineClasses(cm, lineView) { updateLineBackground(cm, lineView); if (lineView.line.wrapClass) { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } else if (lineView.node != lineView.text) { lineView.node.className = ""; } var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; lineView.text.className = textClass || ""; } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter); lineView.gutter = null; } if (lineView.gutterBackground) { lineView.node.removeChild(lineView.gutterBackground); lineView.gutterBackground = null; } if (lineView.line.gutterClass) { var wrap = ensureLineWrapped(lineView); lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(lineView.gutterBackground); wrap.insertBefore(lineView.gutterBackground, lineView.text); } var markers = lineView.line.gutterMarkers; if (cm.options.lineNumbers || markers) { var wrap$1 = ensureLineWrapped(lineView); var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(gutterWrap); wrap$1.insertBefore(gutterWrap, lineView.text); if (lineView.line.gutterClass) { gutterWrap.className += " " + lineView.line.gutterClass; } if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; if (found) { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } } } } } function updateLineWidgets(cm, lineView, dims) { if (lineView.alignable) { lineView.alignable = null; } for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { next = node.nextSibling; if (node.className == "CodeMirror-linewidget") { lineView.node.removeChild(node); } } insertLineWidgets(cm, lineView, dims); } // Build a line's DOM representation from scratch function buildLineElement(cm, lineView, lineN, dims) { var built = getLineContent(cm, lineView); lineView.text = lineView.node = built.pre; if (built.bgClass) { lineView.bgClass = built.bgClass; } if (built.textClass) { lineView.textClass = built.textClass; } updateLineClasses(cm, lineView); updateLineGutter(cm, lineView, lineN, dims); insertLineWidgets(cm, lineView, dims); return lineView.node } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(cm, lineView, dims) { insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } } function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { if (!line.widgets) { return } var wrap = ensureLineWrapped(lineView); for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } positionLineWidget(widget, node, lineView, dims); cm.display.input.setUneditable(node); if (allowAbove && widget.above) { wrap.insertBefore(node, lineView.gutter || lineView.text); } else { wrap.appendChild(node); } signalLater(widget, "redraw"); } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { (lineView.alignable || (lineView.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } } function widgetHeight(widget) { if (widget.height != null) { return widget.height } var cm = widget.doc.cm; if (!cm) { return 0 } if (!contains(document.body, widget.node)) { var parentStyle = "position: relative;"; if (widget.coverGutter) { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } if (widget.noHScroll) { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); } return widget.height = widget.node.parentNode.offsetHeight } // Return true when the given mouse event happened in a widget function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || (n.parentNode == display.sizer && n != display.mover)) { return true } } } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} function paddingH(display) { if (display.cachedPaddingH) { return display.cachedPaddingH } var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } return data } function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } function displayWidth(cm) { return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth } function displayHeight(cm) { return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { var wrapping = cm.options.lineWrapping; var curWidth = wrapping && displayWidth(cm); if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { var heights = lineView.measure.heights = []; if (wrapping) { lineView.measure.width = curWidth; var rects = lineView.text.firstChild.getClientRects(); for (var i = 0; i < rects.length - 1; i++) { var cur = rects[i], next = rects[i + 1]; if (Math.abs(cur.bottom - next.bottom) > 2) { heights.push((cur.bottom + next.top) / 2 - rect.top); } } } heights.push(rect.bottom - rect.top); } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) { return {map: lineView.measure.map, cache: lineView.measure.cache} } for (var i = 0; i < lineView.rest.length; i++) { if (lineView.rest[i] == line) { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) { if (lineNo(lineView.rest[i$1]) > lineN) { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line); var lineN = lineNo(line); var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); view.lineN = lineN; var built = view.built = buildLineContent(cm, view); view.text = built.pre; removeChildrenAndAdd(cm.display.lineMeasure, built.pre); return view } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) } // Find a line view that corresponds to the given line number. function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { return cm.display.view[findViewIndex(cm, lineN)] } var ext = cm.display.externalMeasured; if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { return ext } } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) { view = null; } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)); cm.curOp.forceUpdate = true; } if (!view) { view = updateExternalMeasurement(cm, line); } var info = mapFromLineView(view, line, lineN); return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false } } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) { ch = -1; } var key = ch + (bias || ""), found; if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key]; } else { if (!prepared.rect) { prepared.rect = prepared.view.text.getBoundingClientRect(); } if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect); prepared.hasHeights = true; } found = measureCharInner(cm, prepared, ch, bias); if (!found.bogus) { prepared.cache[key] = found; } } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom} } var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; function nodeAndOffsetInLineMap(map$$1, ch, bias) { var node, start, end, collapse, mStart, mEnd; // First, search the line map for the text node corresponding to, // or closest to, the target character. for (var i = 0; i < map$$1.length; i += 3) { mStart = map$$1[i]; mEnd = map$$1[i + 1]; if (ch < mStart) { start = 0; end = 1; collapse = "left"; } else if (ch < mEnd) { start = ch - mStart; end = start + 1; } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { end = mEnd - mStart; start = end - 1; if (ch >= mEnd) { collapse = "right"; } } if (start != null) { node = map$$1[i + 2]; if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { collapse = bias; } if (bias == "left" && start == 0) { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { node = map$$1[(i -= 3) + 2]; collapse = "left"; } } if (bias == "right" && start == mEnd - mStart) { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { node = map$$1[(i += 3) + 2]; collapse = "right"; } } break } } return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} } function getUsefulRect(rects, bias) { var rect = nullRect; if (bias == "left") { for (var i = 0; i < rects.length; i++) { if ((rect = rects[i]).left != rect.right) { break } } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { if ((rect = rects[i$1]).left != rect.right) { break } } } return rect } function measureCharInner(cm, prepared, ch, bias) { var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); var node = place.node, start = place.start, end = place.end, collapse = place.collapse; var rect; if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { rect = node.parentNode.getBoundingClientRect(); } else { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } if (rect.left || rect.right || start == 0) { break } end = start; start = start - 1; collapse = "right"; } if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) { collapse = bias = "right"; } var rects; if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { rect = rects[bias == "right" ? rects.length - 1 : 0]; } else { rect = node.getBoundingClientRect(); } } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { var rSpan = node.parentNode.getClientRects()[0]; if (rSpan) { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } else { rect = nullRect; } } var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; var mid = (rtop + rbot) / 2; var heights = prepared.view.measure.heights; var i = 0; for (; i < heights.length - 1; i++) { if (mid < heights[i]) { break } } var top = i ? heights[i - 1] : 0, bot = heights[i]; var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot}; if (!rect.left && !rect.right) { result.bogus = true; } if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } return result } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { return rect } var scaleX = screen.logicalXDPI / screen.deviceXDPI; var scaleY = screen.logicalYDPI / screen.deviceYDPI; return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY} } function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {}; lineView.measure.heights = null; if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { lineView.measure.caches[i] = {}; } } } } function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null; removeChildren(cm.display.lineMeasure); for (var i = 0; i < cm.display.view.length; i++) { clearLineMeasurementCacheFor(cm.display.view[i]); } } function clearCaches(cm) { clearLineMeasurementCache(cm); cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } cm.display.lineNumChars = null; } function pageScrollX() { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 // which causes page_Offset and bounding client rects to use // different reference viewports and invalidate our calculations. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } return window.pageXOffset || (document.documentElement || document.body).scrollLeft } function pageScrollY() { if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } return window.pageYOffset || (document.documentElement || document.body).scrollTop } function widgetTopHeight(lineObj) { var height = 0; if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { height += widgetHeight(lineObj.widgets[i]); } } } return height } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"./null (editor), "window", // or "page". function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { if (!includeWidgets) { var height = widgetTopHeight(lineObj); rect.top += height; rect.bottom += height; } if (context == "line") { return rect } if (!context) { context = "local"; } var yOff = heightAtLine(lineObj); if (context == "local") { yOff += paddingTop(cm.display); } else { yOff -= cm.display.viewOffset; } if (context == "page" || context == "window") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"./null. function fromCoordSystem(cm, coords, context) { if (context == "div") { return coords } var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(); top -= pageScrollY(); } else if (context == "local" || !context) { var localBox = cm.display.sizer.getBoundingClientRect(); left += localBox.left; top += localBox.top; } var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` // and after `char - 1` in writing order of `char - 1` // A cursor Pos(line, char, "after") is on the same visual line as `char` // and before `char` in writing order of `char` // Examples (upper-case letters are RTL, lower-case are LTR): // Pos(0, 1, ...) // before after // ab a|b a|b // aB a|B aB| // Ab |Ab A|b // AB B|A B|A // Every position after the last character on a line is considered to stick // to the last character on the line. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } function get(ch, right) { var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); if (right) { m.left = m.right; } else { m.right = m.left; } return intoCoordSystem(cm, lineObj, m, context) } var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; if (ch >= lineObj.text.length) { ch = lineObj.text.length; sticky = "before"; } else if (ch <= 0) { ch = 0; sticky = "after"; } if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } function getBidi(ch, partPos, invert) { var part = order[partPos], right = part.level == 1; return get(invert ? ch - 1 : ch, right != invert) } var partPos = getBidiPartAt(order, ch, sticky); var other = bidiOther; var val = getBidi(ch, partPos, sticky == "before"); if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } return val } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. function estimateCoords(cm, pos) { var left = 0; pos = clipPos(cm.doc, pos); if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } var lineObj = getLine(cm.doc, pos.line); var top = heightAtLine(lineObj) + paddingTop(cm.display); return {left: left, right: left, top: top, bottom: top + lineObj.height} } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, sticky, outside, xRel) { var pos = Pos(line, ch, sticky); pos.xRel = xRel; if (outside) { pos.outside = outside; } return pos } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineN > last) { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } if (x < 0) { x = 0; } var lineObj = getLine(doc, lineN); for (;;) { var found = coordsCharInner(cm, lineObj, lineN, x, y); var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); if (!collapsed) { return found } var rangeEnd = collapsed.find(1); if (rangeEnd.line == lineN) { return rangeEnd } lineObj = getLine(doc, lineN = rangeEnd.line); } } function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { y -= widgetTopHeight(lineObj); var end = lineObj.text.length; var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); return {begin: begin, end: end} } function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) } // Returns true if the given side of a box is after the given // coordinates, in top-to-bottom, left-to-right order. function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x } function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { // Move y into line-local coordinate space y -= heightAtLine(lineObj); var preparedMeasure = prepareMeasureForLine(cm, lineObj); // When directly calling `measureCharPrepared`, we have to adjust // for the widgets at this line. var widgetHeight$$1 = widgetTopHeight(lineObj); var begin = 0, end = lineObj.text.length, ltr = true; var order = getOrder(lineObj, cm.doc.direction); // If the line isn't plain left-to-right text, first figure out // which bidi section the coordinates fall into. if (order) { var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); ltr = part.level != 1; // The awkward -1 offsets are needed because findFirst (called // on these below) will treat its first bound as inclusive, // second as exclusive, but we want to actually address the // characters in the part's range begin = ltr ? part.from : part.to - 1; end = ltr ? part.to : part.from - 1; } // A binary search to find the first character whose bounding box // starts after the coordinates. If we run across any whose box wrap // the coordinates, store that. var chAround = null, boxAround = null; var ch = findFirst(function (ch) { var box = measureCharPrepared(cm, preparedMeasure, ch); box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; if (!boxIsAfter(box, x, y, false)) { return false } if (box.top <= y && box.left <= x) { chAround = ch; boxAround = box; } return true }, begin, end); var baseX, sticky, outside = false; // If a box around the coordinates was found, use that if (boxAround) { // Distinguish coordinates nearer to the left or right side of the box var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; ch = chAround + (atStart ? 0 : 1); sticky = atStart ? "after" : "before"; baseX = atLeft ? boxAround.left : boxAround.right; } else { // (Adjust for extended bound, if necessary.) if (!ltr && (ch == end || ch == begin)) { ch++; } // To determine which side to associate with, get the box to the // left of the character and compare it's vertical position to the // coordinates sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? "after" : "before"; // Now get accurate coordinates for this place, in order to get a // base X position var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); baseX = coords.left; outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; } ch = skipExtendingChars(lineObj.text, ch, 1); return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) } function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { // Bidi parts are sorted left-to-right, and in a non-line-wrapping // situation, we can take this ordering to correspond to the visual // ordering. This finds the first part whose end is after the given // coordinates. var index = findFirst(function (i) { var part = order[i], ltr = part.level != 1; return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true) }, 0, order.length - 1); var part = order[index]; // If this isn't the first part, the part's start is also after // the coordinates, and the coordinates aren't on the same line as // that start, move one part back. if (index > 0) { var ltr = part.level != 1; var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); if (boxIsAfter(start, x, y, true) && start.top > y) { part = order[index - 1]; } } return part } function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { // In a wrapped line, rtl text on wrapping boundaries can do things // that don't correspond to the ordering in our `order` array at // all, so a binary search doesn't work, and we want to return a // part that only spans one line so that the binary search in // coordsCharInner is safe. As such, we first find the extent of the // wrapped line, and then do a flat search in which we discard any // spans that aren't on the line. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); var begin = ref.begin; var end = ref.end; if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } var part = null, closestDist = null; for (var i = 0; i < order.length; i++) { var p = order[i]; if (p.from >= end || p.to <= begin) { continue } var ltr = p.level != 1; var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; // Weigh against spans ending before this, so that they are only // picked if nothing ends after var dist = endX < x ? x - endX + 1e9 : endX - x; if (!part || closestDist > dist) { part = p; closestDist = dist; } } if (!part) { part = order[order.length - 1]; } // Clip the part to the wrapped line. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } return part } var measureText; // Compute the default text height. function textHeight(display) { if (display.cachedTextHeight != null) { return display.cachedTextHeight } if (measureText == null) { measureText = elt("pre", null, "CodeMirror-line-like"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) { display.cachedTextHeight = height; } removeChildren(display.measure); return height || 1 } // Compute the default character width. function charWidth(display) { if (display.cachedCharWidth != null) { return display.cachedCharWidth } var anchor = elt("span", "xxxxxxxxxx"); var pre = elt("pre", [anchor], "CodeMirror-line-like"); removeChildrenAndAdd(display.measure, pre); var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; if (width > 2) { display.cachedCharWidth = width; } return width || 10 } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. function getDimensions(cm) { var d = cm.display, left = {}, width = {}; var gutterLeft = d.gutters.clientLeft; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { var id = cm.display.gutterSpecs[i].className; left[id] = n.offsetLeft + n.clientLeft + gutterLeft; width[id] = n.clientWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth} } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function (line) { if (lineIsHidden(cm.doc, line)) { return 0 } var widgetsHeight = 0; if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } } } if (wrapping) { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } else { return widgetsHeight + th } } } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function (line) { var estHeight = est(line); if (estHeight != line.height) { updateLineHeight(line, estHeight); } }); } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. function posFromMouse(cm, e, liberal, forRect) { var display = cm.display; if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null } var coords = coordsChar(cm, x, y), line; if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } return coords } // Find the view element corresponding to a given line. Return null // when the line isn't visible. function findViewIndex(cm, n) { if (n >= cm.display.viewTo) { return null } n -= cm.display.viewFrom; if (n < 0) { return null } var view = cm.display.view; for (var i = 0; i < view.length; i++) { n -= view[i].size; if (n < 0) { return i } } } // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. function regChange(cm, from, to, lendiff) { if (from == null) { from = cm.doc.first; } if (to == null) { to = cm.doc.first + cm.doc.size; } if (!lendiff) { lendiff = 0; } var display = cm.display; if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { display.updateLineNumbers = from; } cm.curOp.viewChanged = true; if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { resetView(cm); } } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm); } else { display.viewFrom += lendiff; display.viewTo += lendiff; } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm); } else if (from <= display.viewFrom) { // Top overlap var cut = viewCuttingPoint(cm, to, to + lendiff, 1); if (cut) { display.view = display.view.slice(cut.index); display.viewFrom = cut.lineN; display.viewTo += lendiff; } else { resetView(cm); } } else if (to >= display.viewTo) { // Bottom overlap var cut$1 = viewCuttingPoint(cm, from, from, -1); if (cut$1) { display.view = display.view.slice(0, cut$1.index); display.viewTo = cut$1.lineN; } else { resetView(cm); } } else { // Gap in the middle var cutTop = viewCuttingPoint(cm, from, from, -1); var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)); display.viewTo += lendiff; } else { resetView(cm); } } var ext = display.externalMeasured; if (ext) { if (to < ext.lineN) { ext.lineN += lendiff; } else if (from < ext.lineN + ext.size) { display.externalMeasured = null; } } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" function regLineChange(cm, line, type) { cm.curOp.viewChanged = true; var display = cm.display, ext = cm.display.externalMeasured; if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { display.externalMeasured = null; } if (line < display.viewFrom || line >= display.viewTo) { return } var lineView = display.view[findViewIndex(cm, line)]; if (lineView.node == null) { return } var arr = lineView.changes || (lineView.changes = []); if (indexOf(arr, type) == -1) { arr.push(type); } } // Clear the view. function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first; cm.display.view = []; cm.display.viewOffset = 0; } function viewCuttingPoint(cm, oldN, newN, dir) { var index = findViewIndex(cm, oldN), diff, view = cm.display.view; if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { return {index: index, lineN: newN} } var n = cm.display.viewFrom; for (var i = 0; i < index; i++) { n += view[i].size; } if (n != oldN) { if (dir > 0) { if (index == view.length - 1) { return null } diff = (n + view[index].size) - oldN; index++; } else { diff = n - oldN; } oldN += diff; newN += diff; } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) { return null } newN += dir * view[index - (dir < 0 ? 1 : 0)].size; index += dir; } return {index: index, lineN: newN} } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. function adjustView(cm, from, to) { var display = cm.display, view = display.view; if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to); display.viewFrom = from; } else { if (display.viewFrom > from) { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } else if (display.viewFrom < from) { display.view = display.view.slice(findViewIndex(cm, from)); } display.viewFrom = from; if (display.viewTo < to) { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } else if (display.viewTo > to) { display.view = display.view.slice(0, findViewIndex(cm, to)); } } display.viewTo = to; } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). function countDirtyView(cm) { var view = cm.display.view, dirty = 0; for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } } return dirty } function updateSelection(cm) { cm.display.input.showSelection(cm.display.input.prepareSelection()); } function prepareSelection(cm, primary) { if ( primary === void 0 ) primary = true; var doc = cm.doc, result = {}; var curFragment = result.cursors = document.createDocumentFragment(); var selFragment = result.selection = document.createDocumentFragment(); for (var i = 0; i < doc.sel.ranges.length; i++) { if (!primary && i == doc.sel.primIndex) { continue } var range$$1 = doc.sel.ranges[i]; if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } var collapsed = range$$1.empty(); if (collapsed || cm.options.showCursorWhenSelecting) { drawSelectionCursor(cm, range$$1.head, curFragment); } if (!collapsed) { drawSelectionRange(cm, range$$1, selFragment); } } return result } // Draws a cursor for the given range function drawSelectionCursor(cm, head, output) { var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); cursor.style.left = pos.left + "px"; cursor.style.top = pos.top + "px"; cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); otherCursor.style.display = ""; otherCursor.style.left = pos.other.left + "px"; otherCursor.style.top = pos.other.top + "px"; otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } } function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range$$1, output) { var display = cm.display, doc = cm.doc; var fragment = document.createDocumentFragment(); var padding = paddingH(cm.display), leftSide = padding.left; var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; var docLTR = doc.direction == "ltr"; function add(left, top, width, bottom) { if (top < 0) { top = 0; } top = Math.round(top); bottom = Math.round(bottom); fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias) } function wrapX(pos, dir, side) { var extent = wrappedLineExtentChar(cm, lineObj, null, pos); var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); return coords(ch, prop)[prop] } var order = getOrder(lineObj, doc.direction); iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { var ltr = dir == "ltr"; var fromPos = coords(from, ltr ? "left" : "right"); var toPos = coords(to - 1, ltr ? "right" : "left"); var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; var first = i == 0, last = !order || i == order.length - 1; if (toPos.top - fromPos.top <= 3) { // Single line var openLeft = (docLTR ? openStart : openEnd) && first; var openRight = (docLTR ? openEnd : openStart) && last; var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; add(left, fromPos.top, right - left, fromPos.bottom); } else { // Multiple lines var topLeft, topRight, botLeft, botRight; if (ltr) { topLeft = docLTR && openStart && first ? leftSide : fromPos.left; topRight = docLTR ? rightSide : wrapX(from, dir, "before"); botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); botRight = docLTR && openEnd && last ? rightSide : toPos.right; } else { topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); topRight = !docLTR && openStart && first ? rightSide : fromPos.right; botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); } add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); } if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } if (cmpCoords(toPos, start) < 0) { start = toPos; } if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } if (cmpCoords(toPos, end) < 0) { end = toPos; } }); return {start: start, end: end} } var sFrom = range$$1.from(), sTo = range$$1.to(); if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); var singleVLine = visualLine(fromLine) == visualLine(toLine); var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) { add(leftSide, leftEnd.bottom, null, rightStart.top); } } output.appendChild(fragment); } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) { return } var display = cm.display; clearInterval(display.blinker); var on = true; display.cursorDiv.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } else if (cm.options.cursorBlinkRate < 0) { display.cursorDiv.style.visibility = "hidden"; } } function ensureFocus(cm) { if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } } function delayBlurEvent(cm) { cm.state.delayingBlurEvent = true; setTimeout(function () { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; onBlur(cm); } }, 100); } function onFocus(cm, e) { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } if (cm.options.readOnly == "nocursor") { return } if (!cm.state.focused) { signal(cm, "focus", cm, e); cm.state.focused = true; addClass(cm.display.wrapper, "CodeMirror-focused"); // This test prevents this from firing when a context // menu is closed (since the input reset would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { cm.display.input.reset(); if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 } cm.display.input.receivedFocus(); } restartBlink(cm); } function onBlur(cm, e) { if (cm.state.delayingBlurEvent) { return } if (cm.state.focused) { signal(cm, "blur", cm, e); cm.state.focused = false; rmClass(cm.display.wrapper, "CodeMirror-focused"); } clearInterval(cm.display.blinker); setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); } // Read the actual heights of the rendered lines, and update their // stored heights to match. function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var i = 0; i < display.view.length; i++) { var cur = display.view[i], wrapping = cm.options.lineWrapping; var height = (void 0), width = 0; if (cur.hidden) { continue } if (ie && ie_version < 8) { var bot = cur.node.offsetTop + cur.node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = cur.node.getBoundingClientRect(); height = box.bottom - box.top; // Check that lines don't extend past the right of the current // editor width if (!wrapping && cur.text.firstChild) { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } } var diff = cur.line.height - height; if (diff > .005 || diff < -.005) { updateLineHeight(cur.line, height); updateWidgetHeight(cur.line); if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) { updateWidgetHeight(cur.rest[j]); } } } if (width > cm.display.sizerWidth) { var chWidth = Math.ceil(width / charWidth(cm.display)); if (chWidth > cm.display.maxLineLength) { cm.display.maxLineLength = chWidth; cm.display.maxLine = cur.line; cm.display.maxLineChanged = true; } } } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i], parent = w.node.parentNode; if (parent) { w.height = parent.offsetHeight; } } } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. function visibleLines(display, doc, viewport) { var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; top = Math.floor(top - paddingTop(display)); var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; if (ensureFrom < from) { from = ensureFrom; to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); } else if (Math.min(ensureTo, doc.lastLine()) >= to) { from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); to = ensureTo; } } return {from: from, to: Math.max(to, from + 1)} } // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. function maybeScrollWindow(cm, rect) { if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; if (rect.top + box.top < 0) { doScroll = true; } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } if (doScroll != null && !phantom) { var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); cm.display.lineSpace.appendChild(scrollNode); scrollNode.scrollIntoView(doScroll); cm.display.lineSpace.removeChild(scrollNode); } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) { margin = 0; } var rect; if (!cm.options.lineWrapping && pos == end) { // Set pos and end to the cursor positions around the character pos sticks to // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch // If pos == Pos(_, 0, "before"), pos and end are unchanged pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; } for (var limit = 0; limit < 5; limit++) { var changed = false; var coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); rect = {left: Math.min(coords.left, endCoords.left), top: Math.min(coords.top, endCoords.top) - margin, right: Math.max(coords.left, endCoords.left), bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; var scrollPos = calculateScrollPos(cm, rect); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } } if (!changed) { break } } return rect } // Scroll a given set of coordinates into view (immediately). function scrollIntoView(cm, rect) { var scrollPos = calculateScrollPos(cm, rect); if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, rect) { var display = cm.display, snapMargin = textHeight(cm.display); if (rect.top < 0) { rect.top = 0; } var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; var screen = displayHeight(cm), result = {}; if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } var docBottom = cm.doc.height + paddingVert(display); var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; if (rect.top < screentop) { result.scrollTop = atTop ? 0 : rect.top; } else if (rect.bottom > screentop + screen) { var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); if (newTop != screentop) { result.scrollTop = newTop; } } var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); var tooWide = rect.right - rect.left > screenw; if (tooWide) { rect.right = rect.left + screenw; } if (rect.left < 10) { result.scrollLeft = 0; } else if (rect.left < screenleft) { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } else if (rect.right > screenw + screenleft - 3) { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } return result } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). function addToScrollTop(cm, top) { if (top == null) { return } resolveScrollToPos(cm); cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; } // Make sure that at the end of the operation the current cursor is // shown. function ensureCursorVisible(cm) { resolveScrollToPos(cm); var cur = cm.getCursor(); cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; } function scrollToCoords(cm, x, y) { if (x != null || y != null) { resolveScrollToPos(cm); } if (x != null) { cm.curOp.scrollLeft = x; } if (y != null) { cm.curOp.scrollTop = y; } } function scrollToRange(cm, range$$1) { resolveScrollToPos(cm); cm.curOp.scrollToPos = range$$1; } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { var range$$1 = cm.curOp.scrollToPos; if (range$$1) { cm.curOp.scrollToPos = null; var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); scrollToCoordsRange(cm, from, to, range$$1.margin); } } function scrollToCoordsRange(cm, from, to, margin) { var sPos = calculateScrollPos(cm, { left: Math.min(from.left, to.left), top: Math.min(from.top, to.top) - margin, right: Math.max(from.right, to.right), bottom: Math.max(from.bottom, to.bottom) + margin }); scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); } // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. function updateScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) { return } if (!gecko) { updateDisplaySimple(cm, {top: val}); } setScrollTop(cm, val, true); if (gecko) { updateDisplaySimple(cm); } startWorker(cm, 100); } function setScrollTop(cm, val, forceScroll) { val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); if (cm.display.scroller.scrollTop == val && !forceScroll) { return } cm.doc.scrollTop = val; cm.display.scrollbars.setScrollTop(val); if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. function setScrollLeft(cm, val, isScroller, forceScroll) { val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } cm.display.scrollbars.setScrollLeft(val); } // SCROLLBARS // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. function measureForScrollbars(cm) { var d = cm.display, gutterW = d.gutters.offsetWidth; var docH = Math.round(cm.doc.height + paddingVert(cm.display)); return { clientHeight: d.scroller.clientHeight, viewHeight: d.wrapper.clientHeight, scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, viewWidth: d.wrapper.clientWidth, barLeft: cm.options.fixedGutter ? gutterW : 0, docHeight: docH, scrollHeight: docH + scrollGap(cm) + d.barHeight, nativeBarWidth: d.nativeBarWidth, gutterWidth: gutterW } } var NativeScrollbars = function(place, scroll, cm) { this.cm = cm; var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); vert.tabIndex = horiz.tabIndex = -1; place(vert); place(horiz); on(vert, "scroll", function () { if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } }); on(horiz, "scroll", function () { if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } }); this.checkedZeroWidth = false; // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } }; NativeScrollbars.prototype.update = function (measure) { var needsH = measure.scrollWidth > measure.clientWidth + 1; var needsV = measure.scrollHeight > measure.clientHeight + 1; var sWidth = measure.nativeBarWidth; if (needsV) { this.vert.style.display = "block"; this.vert.style.bottom = needsH ? sWidth + "px" : "0"; var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); // A bug in IE8 can cause this value to be negative, so guard it. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; } else { this.vert.style.display = ""; this.vert.firstChild.style.height = "0"; } if (needsH) { this.horiz.style.display = "block"; this.horiz.style.right = needsV ? sWidth + "px" : "0"; this.horiz.style.left = measure.barLeft + "px"; var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; } else { this.horiz.style.display = ""; this.horiz.firstChild.style.width = "0"; } if (!this.checkedZeroWidth && measure.clientHeight > 0) { if (sWidth == 0) { this.zeroWidthHack(); } this.checkedZeroWidth = true; } return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} }; NativeScrollbars.prototype.setScrollLeft = function (pos) { if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } }; NativeScrollbars.prototype.setScrollTop = function (pos) { if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } }; NativeScrollbars.prototype.zeroWidthHack = function () { var w = mac && !mac_geMountainLion ? "12px" : "18px"; this.horiz.style.height = this.vert.style.width = w; this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; this.disableHoriz = new Delayed; this.disableVert = new Delayed; }; NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { bar.style.pointerEvents = "auto"; function maybeDisable() { // To find out whether the scrollbar is still visible, we // check whether the element under the pixel in the bottom // right corner of the scrollbar box is the scrollbar box // itself (when the bar is still visible) or its filler child // (when the bar is hidden). If it is still visible, we keep // it enabled, if it's hidden, we disable pointer events. var box = bar.getBoundingClientRect(); var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } else { delay.set(1000, maybeDisable); } } delay.set(1000, maybeDisable); }; NativeScrollbars.prototype.clear = function () { var parent = this.horiz.parentNode; parent.removeChild(this.horiz); parent.removeChild(this.vert); }; var NullScrollbars = function () {}; NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; NullScrollbars.prototype.setScrollLeft = function () {}; NullScrollbars.prototype.setScrollTop = function () {}; NullScrollbars.prototype.clear = function () {}; function updateScrollbars(cm, measure) { if (!measure) { measure = measureForScrollbars(cm); } var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; updateScrollbarsInner(cm, measure); for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { updateHeightsInViewport(cm); } updateScrollbarsInner(cm, measureForScrollbars(cm)); startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; } } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbarsInner(cm, measure) { var d = cm.display; var sizes = d.scrollbars.update(measure); d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; if (sizes.right && sizes.bottom) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = sizes.bottom + "px"; d.scrollbarFiller.style.width = sizes.right + "px"; } else { d.scrollbarFiller.style.display = ""; } if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = sizes.bottom + "px"; d.gutterFiller.style.width = measure.gutterWidth + "px"; } else { d.gutterFiller.style.display = ""; } } var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; function initScrollbars(cm) { if (cm.display.scrollbars) { cm.display.scrollbars.clear(); if (cm.display.scrollbars.addClass) { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); // Prevent clicks in the scrollbars from killing focus on(node, "mousedown", function () { if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } }); node.setAttribute("cm-not-content", "true"); }, function (pos, axis) { if (axis == "horizontal") { setScrollLeft(cm, pos); } else { updateScrollTop(cm, pos); } }, cm); if (cm.display.scrollbars.addClass) { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. var nextOpId = 0; // Start a new operation. function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: 0, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position focus: false, id: ++nextOpId // Unique ID }; pushOperation(cm.curOp); } // Finish an operation, updating the display and signalling delayed events function endOperation(cm) { var op = cm.curOp; if (op) { finishOperation(op, function (group) { for (var i = 0; i < group.ops.length; i++) { group.ops[i].cm.curOp = null; } endOperations(group); }); } } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { var ops = group.ops; for (var i = 0; i < ops.length; i++) // Read DOM { endOperation_R1(ops[i]); } for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) { endOperation_W1(ops[i$1]); } for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM { endOperation_R2(ops[i$2]); } for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) { endOperation_W2(ops[i$3]); } for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM { endOperation_finish(ops[i$4]); } } function endOperation_R1(op) { var cm = op.cm, display = cm.display; maybeClipScrollbars(cm); if (op.updateMaxLine) { findMaxLine(cm); } op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); } function endOperation_R2(op) { var cm = op.cm, display = cm.display; if (op.updatedDisplay) { updateHeightsInViewport(cm); } op.barMeasure = measureForScrollbars(cm); // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; cm.display.sizerWidth = op.adjustWidthTo; op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); } if (op.updatedDisplay || op.selectionChanged) { op.preparedSelection = display.input.prepareSelection(); } } function endOperation_W2(op) { var cm = op.cm; if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; if (op.maxScrollLeft < cm.doc.scrollLeft) { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } cm.display.maxLineChanged = false; } var takeFocus = op.focus && op.focus == activeElt(); if (op.preparedSelection) { cm.display.input.showSelection(op.preparedSelection, takeFocus); } if (op.updatedDisplay || op.startHeight != cm.doc.height) { updateScrollbars(cm, op.barMeasure); } if (op.updatedDisplay) { setDocumentHeight(cm, op.barMeasure); } if (op.selectionChanged) { restartBlink(cm); } if (cm.state.focused && op.updateInput) { cm.display.input.reset(op.typing); } if (takeFocus) { ensureFocus(op.cm); } } function endOperation_finish(op) { var cm = op.cm, display = cm.display, doc = cm.doc; if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { display.wheelStartX = display.wheelStartY = null; } // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); maybeScrollWindow(cm, rect); } // Fire events for markers that are hidden/unidden by editing or // undoing var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) { for (var i = 0; i < hidden.length; ++i) { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } if (display.wrapper.offsetHeight) { doc.scrollTop = cm.display.scroller.scrollTop; } // Fire change events, and delayed event handlers if (op.changeObjs) { signal(cm, "changes", cm, op.changeObjs); } if (op.update) { op.update.finish(); } } // Run the given function in an operation function runInOp(cm, f) { if (cm.curOp) { return f() } startOperation(cm); try { return f() } finally { endOperation(cm); } } // Wraps a function in an operation. Returns the wrapped function. function operation(cm, f) { return function() { if (cm.curOp) { return f.apply(cm, arguments) } startOperation(cm); try { return f.apply(cm, arguments) } finally { endOperation(cm); } } } // Used to add methods to editor and doc instances, wrapping them in // operations. function methodOp(f) { return function() { if (this.curOp) { return f.apply(this, arguments) } startOperation(this); try { return f.apply(this, arguments) } finally { endOperation(this); } } } function docMethodOp(f) { return function() { var cm = this.cm; if (!cm || cm.curOp) { return f.apply(this, arguments) } startOperation(cm); try { return f.apply(this, arguments) } finally { endOperation(cm); } } } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.highlightFrontier < cm.display.viewTo) { cm.state.highlight.set(time, bind(highlightWorker, cm)); } } function highlightWorker(cm) { var doc = cm.doc; if (doc.highlightFrontier >= cm.display.viewTo) { return } var end = +new Date + cm.options.workTime; var context = getContextBefore(cm, doc.highlightFrontier); var changedLines = []; doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { if (context.line >= cm.display.viewFrom) { // Visible var oldStyles = line.styles; var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; var highlighted = highlightLine(cm, line, context, true); if (resetState) { context.state = resetState; } line.styles = highlighted.styles; var oldCls = line.styleClasses, newCls = highlighted.classes; if (newCls) { line.styleClasses = newCls; } else if (oldCls) { line.styleClasses = null; } var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } if (ischange) { changedLines.push(context.line); } line.stateAfter = context.save(); context.nextLine(); } else { if (line.text.length <= cm.options.maxHighlightLength) { processLine(cm, line.text, context); } line.stateAfter = context.line % 5 == 0 ? context.save() : null; context.nextLine(); } if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true } }); doc.highlightFrontier = context.line; doc.modeFrontier = Math.max(doc.modeFrontier, context.line); if (changedLines.length) { runInOp(cm, function () { for (var i = 0; i < changedLines.length; i++) { regLineChange(cm, changedLines[i], "text"); } }); } } // DISPLAY DRAWING var DisplayUpdate = function(cm, viewport, force) { var display = cm.display; this.viewport = viewport; // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport); this.editorIsHidden = !display.wrapper.offsetWidth; this.wrapperHeight = display.wrapper.clientHeight; this.wrapperWidth = display.wrapper.clientWidth; this.oldDisplayWidth = displayWidth(cm); this.force = force; this.dims = getDimensions(cm); this.events = []; }; DisplayUpdate.prototype.signal = function (emitter, type) { if (hasHandler(emitter, type)) { this.events.push(arguments); } }; DisplayUpdate.prototype.finish = function () { var this$1 = this; for (var i = 0; i < this.events.length; i++) { signal.apply(null, this$1.events[i]); } }; function maybeClipScrollbars(cm) { var display = cm.display; if (!display.scrollbarsClipped && display.scroller.offsetWidth) { display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; display.heightForcer.style.height = scrollGap(cm) + "px"; display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; display.scrollbarsClipped = true; } } function selectionSnapshot(cm) { if (cm.hasFocus()) { return null } var active = activeElt(); if (!active || !contains(cm.display.lineDiv, active)) { return null } var result = {activeElt: active}; if (window.getSelection) { var sel = window.getSelection(); if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { result.anchorNode = sel.anchorNode; result.anchorOffset = sel.anchorOffset; result.focusNode = sel.focusNode; result.focusOffset = sel.focusOffset; } } return result } function restoreSelection(snapshot) { if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } snapshot.activeElt.focus(); if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { var sel = window.getSelection(), range$$1 = document.createRange(); range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); range$$1.collapse(false); sel.removeAllRanges(); sel.addRange(range$$1); sel.extend(snapshot.focusNode, snapshot.focusOffset); } } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. function updateDisplayIfNeeded(cm, update) { var display = cm.display, doc = cm.doc; if (update.editorIsHidden) { resetView(cm); return false } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { return false } if (maybeUpdateLineNumberWidth(cm)) { resetView(cm); update.dims = getDimensions(cm); } // Compute a suitable new viewport (from & to) var end = doc.first + doc.size; var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, update.visible.to + cm.options.viewportMargin); if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from); to = visualLineEndNo(cm.doc, to); } var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; adjustView(cm, from, to); display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px"; var toUpdate = countDirtyView(cm); if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { return false } // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. var selSnapshot = selectionSnapshot(cm); if (toUpdate > 4) { display.lineDiv.style.display = "none"; } patchDisplay(cm, display.updateLineNumbers, update.dims); if (toUpdate > 4) { display.lineDiv.style.display = ""; } display.renderedView = display.view; // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. restoreSelection(selSnapshot); // Prevent selection and cursors from interfering with the scroll // width and height. removeChildren(display.cursorDiv); removeChildren(display.selectionDiv); display.gutters.style.height = display.sizer.style.minHeight = 0; if (different) { display.lastWrapHeight = update.wrapperHeight; display.lastWrapWidth = update.wrapperWidth; startWorker(cm, 400); } display.updateLineNumbers = null; return true } function postUpdateDisplay(cm, update) { var viewport = update.viewport; for (var first = true;; first = false) { if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport); if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { break } } if (!updateDisplayIfNeeded(cm, update)) { break } updateHeightsInViewport(cm); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.force = false; } update.signal(cm, "update", cm); if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; } } function updateDisplaySimple(cm, viewport) { var update = new DisplayUpdate(cm, viewport); if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm); postUpdateDisplay(cm, update); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.finish(); } } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { var display = cm.display, lineNumbers = cm.options.lineNumbers; var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; } else { node.parentNode.removeChild(node); } return next } var view = display.view, lineN = display.viewFrom; // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet var node = buildLineElement(cm, lineView, lineN, dims); container.insertBefore(node, cur); } else { // Already drawn while (cur != lineView.node) { cur = rm(cur); } var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } updateLineForChanges(cm, lineView, lineN, dims); } if (updateNumber) { removeChildren(lineView.lineNumber); lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } cur = lineView.node.nextSibling; } lineN += lineView.size; } while (cur) { cur = rm(cur); } } function updateGutterSpace(display) { var width = display.gutters.offsetWidth; display.sizer.style.marginLeft = width + "px"; } function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = measure.docHeight + "px"; cm.display.heightForcer.style.top = measure.docHeight + "px"; cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; } // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. function alignHorizontally(cm) { var display = cm.display, view = display.view; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { if (cm.options.fixedGutter) { if (view[i].gutter) { view[i].gutter.style.left = left; } if (view[i].gutterBackground) { view[i].gutterBackground.style.left = left; } } var align = view[i].alignable; if (align) { for (var j = 0; j < align.length; j++) { align[j].style.left = left; } } } } if (cm.options.fixedGutter) { display.gutters.style.left = (comp + gutterW) + "px"; } } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) { return false } var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; updateGutterSpace(cm.display); return true } return false } function getGutters(gutters, lineNumbers) { var result = [], sawLineNumbers = false; for (var i = 0; i < gutters.length; i++) { var name = gutters[i], style = null; if (typeof name != "string") { style = name.style; name = name.className; } if (name == "CodeMirror-linenumbers") { if (!lineNumbers) { continue } else { sawLineNumbers = true; } } result.push({className: name, style: style}); } if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } return result } // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. function renderGutters(display) { var gutters = display.gutters, specs = display.gutterSpecs; removeChildren(gutters); display.lineGutter = null; for (var i = 0; i < specs.length; ++i) { var ref = specs[i]; var className = ref.className; var style = ref.style; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); if (style) { gElt.style.cssText = style; } if (className == "CodeMirror-linenumbers") { display.lineGutter = gElt; gElt.style.width = (display.lineNumWidth || 1) + "px"; } } gutters.style.display = specs.length ? "" : "none"; updateGutterSpace(display); } function updateGutters(cm) { renderGutters(cm.display); regChange(cm); alignHorizontally(cm); } // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. function Display(place, doc, input, options) { var d = this; this.input = input; // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.scrollbarFiller.setAttribute("cm-not-content", "true"); // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); d.gutterFiller.setAttribute("cm-not-content", "true"); // Will contain the actual code, positioned to cover the viewport. d.lineDiv = eltP("div", null, "CodeMirror-code"); // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); d.cursorDiv = elt("div", null, "CodeMirror-cursors"); // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure"); // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); // Moved around its parent to cover visible view. d.mover = elt("div", [lines], null, "position: relative"); // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); d.sizerWidth = null; // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } if (place) { if (place.appendChild) { place.appendChild(d.wrapper); } else { place(d.wrapper); } } // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first; d.reportedViewFrom = d.reportedViewTo = doc.first; // Information about the rendered lines. d.view = []; d.renderedView = null; // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null; // Empty space (in pixels) above the view d.viewOffset = 0; d.lastWrapHeight = d.lastWrapWidth = 0; d.updateLineNumbers = null; d.nativeBarWidth = d.barHeight = d.barWidth = 0; d.scrollbarsClipped = false; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false; d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; // True when shift is held down. d.shift = false; // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null; d.activeTouch = null; d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); renderGutters(d); input.init(d); } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) { wheelPixelsPerUnit = -.53; } else if (gecko) { wheelPixelsPerUnit = 15; } else if (chrome) { wheelPixelsPerUnit = -.7; } else if (safari) { wheelPixelsPerUnit = -1/3; } function wheelEventDelta(e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } else if (dy == null) { dy = e.wheelDelta; } return {x: dx, y: dy} } function wheelEventPixels(e) { var delta = wheelEventDelta(e); delta.x *= wheelPixelsPerUnit; delta.y *= wheelPixelsPerUnit; return delta } function onScrollWheel(cm, e) { var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here var canScrollX = scroll.scrollWidth > scroll.clientWidth; var canScrollY = scroll.scrollHeight > scroll.clientHeight; if (!(dx && canScrollX || dy && canScrollY)) { return } // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (var i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur; break outer } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { if (dy && canScrollY) { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); // Only prevent default scrolling if vertical scrolling is // actually possible. Otherwise, it causes vertical scroll // jitter on OSX trackpads when deltaX is small and deltaY // is large (issue #3579) if (!dy || (dy && canScrollY)) { e_preventDefault(e); } display.wheelStartX = null; // Abort measurement, if in progress return } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) { top = Math.max(0, top + pixels - 50); } else { bot = Math.min(cm.doc.height, bot + pixels + 50); } updateDisplaySimple(cm, {top: top, bottom: bot}); } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function () { if (display.wheelStartX == null) { return } var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) { return } wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). var Selection = function(ranges, primIndex) { this.ranges = ranges; this.primIndex = primIndex; }; Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; Selection.prototype.equals = function (other) { var this$1 = this; if (other == this) { return true } if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } for (var i = 0; i < this.ranges.length; i++) { var here = this$1.ranges[i], there = other.ranges[i]; if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } } return true }; Selection.prototype.deepCopy = function () { var this$1 = this; var out = []; for (var i = 0; i < this.ranges.length; i++) { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } return new Selection(out, this.primIndex) }; Selection.prototype.somethingSelected = function () { var this$1 = this; for (var i = 0; i < this.ranges.length; i++) { if (!this$1.ranges[i].empty()) { return true } } return false }; Selection.prototype.contains = function (pos, end) { var this$1 = this; if (!end) { end = pos; } for (var i = 0; i < this.ranges.length; i++) { var range = this$1.ranges[i]; if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) { return i } } return -1 }; var Range = function(anchor, head) { this.anchor = anchor; this.head = head; }; Range.prototype.from = function () { return minPos(this.anchor, this.head) }; Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). function normalizeSelection(cm, ranges, primIndex) { var mayTouch = cm && cm.options.selectionsMayTouch; var prim = ranges[primIndex]; ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); primIndex = indexOf(ranges, prim); for (var i = 1; i < ranges.length; i++) { var cur = ranges[i], prev = ranges[i - 1]; var diff = cmp(prev.to(), cur.from()); if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; if (i <= primIndex) { --primIndex; } ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); } } return new Selection(ranges, primIndex) } function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0) } // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). function changeEnd(change) { if (!change.text) { return change.to } return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) } // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) { return pos } if (cmp(pos, change.to) <= 0) { return changeEnd(change) } var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } return Pos(line, ch) } function computeSelAfterChange(doc, change) { var out = []; for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); } return normalizeSelection(doc.cm, out, doc.sel.primIndex) } function offsetPos(pos, old, nw) { if (pos.line == old.line) { return Pos(nw.line, pos.ch - old.ch + nw.ch) } else { return Pos(nw.line + (pos.line - old.line), pos.ch) } } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". function computeReplacedSel(doc, changes, hint) { var out = []; var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var from = offsetPos(change.from, oldPrev, newPrev); var to = offsetPos(changeEnd(change), oldPrev, newPrev); oldPrev = change.to; newPrev = to; if (hint == "around") { var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; out[i] = new Range(inv ? to : from, inv ? from : to); } else { out[i] = new Range(from, from); } } return new Selection(out, doc.sel.primIndex) } // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = getMode(cm.options, cm.doc.modeOption); resetModeState(cm); } function resetModeState(cm) { cm.doc.iter(function (line) { if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } }); cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) { regChange(cm); } } // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore) } // Perform a change on the document data structure. function updateDoc(doc, change, markedSpans, estimateHeight$$1) { function spansFor(n) {return markedSpans ? markedSpans[n] : null} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight$$1); signalLater(line, "change", line, change); } function linesFor(start, end) { var result = []; for (var i = start; i < end; ++i) { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } return result } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // Adjust the line structure if (change.full) { doc.insert(0, linesFor(0, text.length)); doc.remove(text.length, doc.size - text.length); } else if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = linesFor(0, text.length - 1); update(lastLine, lastLine.text, lastSpans); if (nlines) { doc.remove(from.line, nlines); } if (added.length) { doc.insert(from.line, added); } } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { var added$1 = linesFor(1, text.length - 1); added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added$1); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); var added$2 = linesFor(1, text.length - 1); if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } doc.insert(from.line + 1, added$2); } signalLater(doc, "change", doc, change); } // Call f for all linked documents. function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) { continue } var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) { continue } f(rel.doc, shared); propagate(rel.doc, doc, shared); } } } propagate(doc, null, true); } // Attach a document to an editor. function attachDoc(cm, doc) { if (doc.cm) { throw new Error("This document is already in use.") } cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); setDirectionClass(cm); if (!cm.options.lineWrapping) { findMaxLine(cm); } cm.options.mode = doc.modeOption; regChange(cm); } function setDirectionClass(cm) { (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); } function directionChanged(cm) { runInOp(cm, function () { setDirectionClass(cm); regChange(cm); }); } function History(startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = []; this.undoDepth = Infinity; // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0; this.lastOp = this.lastSelOp = null; this.lastOrigin = this.lastSelOrigin = null; // Used by the isClean() method this.generation = this.maxGeneration = startGen || 1; } // Create a history change event from an updateDoc-style change // object. function historyChangeFromChange(doc, change) { var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); return histChange } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { var last = lst(array); if (last.ranges) { array.pop(); } else { break } } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done); return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop(); return lst(hist.done) } } // Register a change in the history. Merges changes that are within // a single operation, or are close together with an origin that // allows merging (starting with "+") into a single event. function addChangeToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur; var last; if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event last = lst(cur.changes); if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } } else { // Can not be merged, start a new event. var before = lst(hist.done); if (!before || !before.ranges) { pushSelectionToHistory(doc.sel, hist.done); } cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation}; hist.done.push(cur); while (hist.done.length > hist.undoDepth) { hist.done.shift(); if (!hist.done[0].ranges) { hist.done.shift(); } } } hist.done.push(selAfter); hist.generation = ++hist.maxGeneration; hist.lastModTime = hist.lastSelTime = time; hist.lastOp = hist.lastSelOp = opId; hist.lastOrigin = hist.lastSelOrigin = change.origin; if (!last) { signal(doc, "historyAdded"); } } function selectionEventCanBeMerged(doc, origin, prev, sel) { var ch = origin.charAt(0); return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). function addSelectionToHistory(doc, sel, opId, options) { var hist = doc.history, origin = options && options.origin; // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) { hist.done[hist.done.length - 1] = sel; } else { pushSelectionToHistory(sel, hist.done); } hist.lastSelTime = +new Date; hist.lastSelOrigin = origin; hist.lastSelOp = opId; if (options && options.clearRedo !== false) { clearSelectionEvents(hist.undone); } } function pushSelectionToHistory(sel, dest) { var top = lst(dest); if (!(top && top.ranges && top.equals(sel))) { dest.push(sel); } } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { if (line.markedSpans) { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } ++n; }); } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) { return null } var out; for (var i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } else if (out) { out.push(spans[i]); } } return !out ? spans : out.length ? out : null } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) { return null } var nw = []; for (var i = 0; i < change.text.length; ++i) { nw.push(removeClearedSpans(found[i])); } return nw } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) { return stretched } if (!stretched) { return old } for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) { if (oldCur[k].marker == span.marker) { continue spans } } oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup, instantiateSel) { var copy = []; for (var i = 0; i < events.length; ++i) { var event = events[i]; if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); continue } var changes = event.changes, newChanges = []; copy.push({changes: newChanges}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m = (void 0); newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } } } return copy } // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. function extendRange(range, head, other, extend) { if (extend) { var anchor = range.anchor; if (other) { var posBefore = cmp(head, anchor) < 0; if (posBefore != (cmp(other, anchor) < 0)) { anchor = head; head = other; } else if (posBefore != (cmp(head, other) < 0)) { head = other; } } return new Range(anchor, head) } else { return new Range(other || head, head) } } // Extend the primary selection range, discard the rest. function extendSelection(doc, head, other, options, extend) { if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); } // Extend all selections (pos is an array of selections with length // equal the number of selections) function extendSelections(doc, heads, options) { var out = []; var extend = doc.cm && (doc.cm.display.shift || doc.extend); for (var i = 0; i < doc.sel.ranges.length; i++) { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); setSelection(doc, newSel, options); } // Updates a single range in the selection. function replaceOneSelection(doc, i, range, options) { var ranges = doc.sel.ranges.slice(0); ranges[i] = range; setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); } // Reset the selection to a single range. function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options); } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel, options) { var obj = { ranges: sel.ranges, update: function(ranges) { var this$1 = this; this.ranges = []; for (var i = 0; i < ranges.length; i++) { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); } }, origin: options && options.origin }; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } else { return sel } } function setSelectionReplaceHistory(doc, sel, options) { var done = doc.history.done, last = lst(done); if (last && last.ranges) { done[done.length - 1] = sel; setSelectionNoUndo(doc, sel, options); } else { setSelection(doc, sel, options); } } // Set a new selection. function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options); addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { sel = filterSelectionChange(doc, sel, options); } var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); if (!(options && options.scroll === false) && doc.cm) { ensureCursorVisible(doc.cm); } } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) { return } doc.sel = sel; if (doc.cm) { doc.cm.curOp.updateInput = 1; doc.cm.curOp.selectionChanged = true; signalCursorActivity(doc.cm); } signalLater(doc, "cursorActivity", doc); } // Verify that the selection does not partially select any atomic // marked ranges. function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) { out = sel.ranges.slice(0, i); } out[i] = new Range(newAnchor, newHead); } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel } function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { var line = getLine(doc, pos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; // Determine if we should prevent the cursor being placed to the left/right of an atomic marker // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it // is with selectLeft/Right var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) { break } else {--i; continue} } } if (!m.atomic) { continue } if (oldPos) { var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); if (dir < 0 ? preventCursorRight : preventCursorLeft) { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { return skipAtomicInner(doc, near, pos, dir, mayClear) } } var far = m.find(dir < 0 ? -1 : 1); if (dir < 0 ? preventCursorLeft : preventCursorRight) { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null } } } return pos } // Ensure a given position is not inside an atomic range. function skipAtomic(doc, pos, oldPos, bias, mayClear) { var dir = bias || 1; var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); if (!found) { doc.cantEdit = true; return Pos(doc.first, 0) } return found } function movePos(doc, pos, dir, line) { if (dir < 0 && pos.ch == 0) { if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } else { return null } } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } else { return null } } else { return new Pos(pos.line, pos.ch + dir) } } function selectAll(cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); } // UPDATING // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function () { return obj.canceled = true; } }; if (update) { obj.update = function (from, to, text, origin) { if (from) { obj.from = clipPos(doc, from); } if (to) { obj.to = clipPos(doc, to); } if (text) { obj.text = text; } if (origin !== undefined) { obj.origin = origin; } }; } signal(doc, "beforeChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } if (obj.canceled) { if (doc.cm) { doc.cm.curOp.updateInput = 2; } return null } return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } if (doc.cm.state.suppressEdits) { return } } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) { return } } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 0; --i) { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } } else { makeChangeInner(doc, change); } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } var selAfter = computeSelAfterChange(doc, change); addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } // Revert a change stored in a document's history. function makeChangeFromHistory(doc, type, allowSelectionOnly) { var suppress = doc.cm && doc.cm.state.suppressEdits; if (suppress && !allowSelectionOnly) { return } var hist = doc.history, event, selAfter = doc.sel; var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) var i = 0; for (; i < source.length; i++) { event = source[i]; if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { break } } if (i == source.length) { return } hist.lastOrigin = hist.lastSelOrigin = null; for (;;) { event = source.pop(); if (event.ranges) { pushSelectionToHistory(event, dest); if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}); return } selAfter = event; } else if (suppress) { source.push(event); return } else { break } } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). var antiChanges = []; pushSelectionToHistory(selAfter, dest); dest.push({changes: antiChanges, generation: hist.generation}); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); var loop = function ( i ) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { source.length = 0; return {} } antiChanges.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change) : lst(source); makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } var rebased = []; // Propagate to the linked documents linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); }; for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { var returned = loop( i$1 ); if ( returned ) return returned.v; } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) { return } doc.first += distance; doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch) ); }), doc.sel.primIndex); if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance); for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { regLineChange(doc.cm, l, "gutter"); } } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return } if (change.from.line > doc.lastLine()) { return } // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } else { updateDoc(doc, change, spans); } setSelectionNoUndo(doc, selAfter, sel_dontScroll); if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { doc.cantEdit = false; } } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function (line) { if (line == display.maxLine) { recomputeMaxLength = true; return true } }); } if (doc.sel.contains(change.from, change.to) > -1) { signalCursorActivity(cm); } updateDoc(doc, change, spans, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function (line) { var len = lineLength(line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } } retreatFrontier(doc, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display if (change.full) { regChange(cm); } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { regLineChange(cm, from.line, "text"); } else { regChange(cm, from.line, to.line + 1, lendiff); } var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); if (changeHandler || changesHandler) { var obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin }; if (changeHandler) { signalLater(cm, "change", cm, obj); } if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } } cm.display.selForContextMenu = null; } function replaceRange(doc, code, from, to, origin) { var assign; if (!to) { to = from; } if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } if (typeof code == "string") { code = doc.splitLines(code); } makeChange(doc, {from: from, to: to, text: code, origin: origin}); } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } for (var j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } continue } for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { var cur = sub.changes[j$1]; if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch); cur.to = Pos(cur.to.line + diff, cur.to.ch); } else if (from <= cur.to.line) { ok = false; break } } if (!ok) { array.splice(0, i + 1); i = 0; } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. function changeLine(doc, handle, changeType, op) { var no = handle, line = handle; if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } else { no = lineNo(handle); } if (no == null) { return null } if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } return line } // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html function LeafChunk(lines) { var this$1 = this; this.lines = lines; this.parent = null; var height = 0; for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length }, // Remove the n lines at offset 'at'. removeInner: function(at, n) { var this$1 = this; for (var i = at, e = at + n; i < e; ++i) { var line = this$1.lines[i]; this$1.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, // Helper used to collapse a small branch into a single leaf. collapse: function(lines) { lines.push.apply(lines, this.lines); }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner: function(at, lines, height) { var this$1 = this; this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } }, // Used to iterate over a part of the tree. iterN: function(at, n, op) { var this$1 = this; for (var e = at + n; at < e; ++at) { if (op(this$1.lines[at])) { return true } } } }; function BranchChunk(children) { var this$1 = this; this.children = children; var size = 0, height = 0; for (var i = 0; i < children.length; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this$1; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size }, removeInner: function(at, n) { var this$1 = this; this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this$1.height -= oldHeight - child.height; if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) { break } at = 0; } else { at -= sz; } } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { var this$1 = this; for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } }, insertInner: function(at, lines, height) { var this$1 = this; this.size += lines.length; this.height += height; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. var remaining = child.lines.length % 25 + 25; for (var pos = remaining; pos < child.lines.length;) { var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); child.height -= leaf.height; this$1.children.splice(++i, 0, leaf); leaf.parent = this$1; } child.lines = child.lines.slice(0, remaining); this$1.maybeSpill(); } break } at -= sz; } }, // When a node has grown, check whether it should be split. maybeSpill: function() { if (this.children.length <= 10) { return } var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10) me.parent.maybeSpill(); }, iterN: function(at, n, op) { var this$1 = this; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) { return true } if ((n -= used) == 0) { break } at = 0; } else { at -= sz; } } } }; // Line widgets are block elements displayed above or below a line. var LineWidget = function(doc, node, options) { var this$1 = this; if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) { this$1[opt] = options[opt]; } } } this.doc = doc; this.node = node; }; LineWidget.prototype.clear = function () { var this$1 = this; var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); if (no == null || !ws) { return } for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } if (!ws.length) { line.widgets = null; } var height = widgetHeight(this); updateLineHeight(line, Math.max(0, line.height - height)); if (cm) { runInOp(cm, function () { adjustScrollWhenAboveVisible(cm, line, -height); regLineChange(cm, no, "widget"); }); signalLater(cm, "lineWidgetCleared", cm, this, no); } }; LineWidget.prototype.changed = function () { var this$1 = this; var oldH = this.height, cm = this.doc.cm, line = this.line; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) { return } if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } if (cm) { runInOp(cm, function () { cm.curOp.forceUpdate = true; adjustScrollWhenAboveVisible(cm, line, diff); signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); }); } }; eventMixin(LineWidget); function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) { addToScrollTop(cm, diff); } } function addLineWidget(doc, handle, node, options) { var widget = new LineWidget(doc, node, options); var cm = doc.cm; if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } changeLine(doc, handle, "widget", function (line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) { widgets.push(widget); } else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } widget.line = line; if (cm && !lineIsHidden(doc, line)) { var aboveVisible = heightAtLine(line) < doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) { addToScrollTop(cm, widget.height); } cm.curOp.forceUpdate = true; } return true }); if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } return widget } // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). var nextMarkerId = 0; var TextMarker = function(doc, type) { this.lines = []; this.type = type; this.doc = doc; this.id = ++nextMarkerId; }; // Clear the marker. TextMarker.prototype.clear = function () { var this$1 = this; if (this.explicitlyCleared) { return } var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) { startOperation(cm); } if (hasHandler(this, "clear")) { var found = this.find(); if (found) { signalLater(this, "clear", found.from, found.to); } } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this$1.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this$1); if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } else if (cm) { if (span.to != null) { max = lineNo(line); } if (span.from != null) { min = lineNo(line); } } line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) { updateLineHeight(line, textHeight(cm.display)); } } if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } } if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) { reCheckSelection(cm.doc); } } if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } if (withOp) { endOperation(cm); } if (this.parent) { this.parent.clear(); } }; // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). TextMarker.prototype.find = function (side, lineObj) { var this$1 = this; if (side == null && this.type == "bookmark") { side = 1; } var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this$1.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this$1); if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from); if (side == -1) { return from } } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to); if (side == 1) { return to } } } return from && {from: from, to: to} }; // Signals that the marker's widget changed, and surrounding layout // should be recomputed. TextMarker.prototype.changed = function () { var this$1 = this; var pos = this.find(-1, true), widget = this, cm = this.doc.cm; if (!pos || !cm) { return } runInOp(cm, function () { var line = pos.line, lineN = lineNo(pos.line); var view = findViewForLine(cm, lineN); if (view) { clearLineMeasurementCacheFor(view); cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; } cm.curOp.updateMaxLine = true; if (!lineIsHidden(widget.doc, line) && widget.height != null) { var oldHeight = widget.height; widget.height = null; var dHeight = widgetHeight(widget) - oldHeight; if (dHeight) { updateLineHeight(line, line.height + dHeight); } } signalLater(cm, "markerChanged", cm, this$1); }); }; TextMarker.prototype.attachLine = function (line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } } this.lines.push(line); }; TextMarker.prototype.detachLine = function (line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; eventMixin(TextMarker); // Create a marker, wire it up to the right lines, and function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) { return markTextShared(doc, from, to, options, type) } // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } var marker = new TextMarker(doc, type), diff = cmp(from, to); if (options) { copyObj(options, marker, false); } // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { return marker } if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true; marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } if (options.insertLeft) { marker.widgetNode.insertLeft = true; } } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { throw new Error("Inserting collapsed marker partially overlapping an existing one") } seeCollapsedSpans(); } if (marker.addToHistory) { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } var curLine = from.line, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function (line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { updateMaxLine = true; } if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null)); ++curLine; }); // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } }); } if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } if (marker.readOnly) { seeReadOnlySpans(); if (doc.history.done.length || doc.history.undone.length) { doc.clearHistory(); } } if (marker.collapsed) { marker.id = ++nextMarkerId; marker.atomic = true; } if (cm) { // Sync editor state if (updateMaxLine) { cm.curOp.updateMaxLine = true; } if (marker.collapsed) { regChange(cm, from.line, to.line + 1); } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } if (marker.atomic) { reCheckSelection(cm.doc); } signalLater(cm, "markerAdded", cm, marker); } return marker } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. var SharedTextMarker = function(markers, primary) { var this$1 = this; this.markers = markers; this.primary = primary; for (var i = 0; i < markers.length; ++i) { markers[i].parent = this$1; } }; SharedTextMarker.prototype.clear = function () { var this$1 = this; if (this.explicitlyCleared) { return } this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) { this$1.markers[i].clear(); } signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function (side, lineObj) { return this.primary.find(side, lineObj) }; eventMixin(SharedTextMarker); function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.widgetNode; linkedDocs(doc, function (doc) { if (widget) { options.widgetNode = widget.cloneNode(true); } markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) { if (doc.linked[i].isParent) { return } } primary = lst(markers); }); return new SharedTextMarker(markers, primary) } function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) } function copySharedMarkers(doc, markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], pos = marker.find(); var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); if (cmp(mFrom, mTo)) { var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); marker.markers.push(subMark); subMark.parent = marker; } } } function detachSharedMarkers(markers) { var loop = function ( i ) { var marker = markers[i], linked = [marker.primary.doc]; linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); for (var j = 0; j < marker.markers.length; j++) { var subMarker = marker.markers[j]; if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null; marker.markers.splice(j--, 1); } } }; for (var i = 0; i < markers.length; i++) loop( i ); } var nextDocId = 0; var Doc = function(text, mode, firstLine, lineSep, direction) { if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } if (firstLine == null) { firstLine = 0; } BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.cleanGeneration = 1; this.modeFrontier = this.highlightFrontier = firstLine; var start = Pos(firstLine, 0); this.sel = simpleSelection(start); this.history = new History(null); this.id = ++nextDocId; this.modeOption = mode; this.lineSep = lineSep; this.direction = (direction == "rtl") ? "rtl" : "ltr"; this.extend = false; if (typeof text == "string") { text = this.splitLines(text); } updateDoc(this, {from: start, to: start, text: text}); setSelection(this, simpleSelection(start), sel_dontScroll); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) { this.iterN(from - this.first, to - from, op); } else { this.iterN(this.first, this.first + this.size, from); } }, // Non-public interface for adding and removing lines. insert: function(at, lines) { var height = 0; for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, setValue: docMethodOp(function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: "setValue", full: true}, true); if (this.cm) { scrollToCoords(this.cm, 0, 0); } setSelection(this, simpleSelection(top), sel_dontScroll); }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, getLineNumber: function(line) {return lineNo(line)}, getLineHandleVisualStart: function(line) { if (typeof line == "number") { line = getLine(this, line); } return visualLine(line) }, lineCount: function() {return this.size}, firstLine: function() {return this.first}, lastLine: function() {return this.first + this.size - 1}, clipPos: function(pos) {return clipPos(this, pos)}, getCursor: function(start) { var range$$1 = this.sel.primary(), pos; if (start == null || start == "head") { pos = range$$1.head; } else if (start == "anchor") { pos = range$$1.anchor; } else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } else { pos = range$$1.from(); } return pos }, listSelections: function() { return this.sel.ranges }, somethingSelected: function() {return this.sel.somethingSelected()}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads), options); }), extendSelectionsBy: docMethodOp(function(f, options) { var heads = map(this.sel.ranges, f); extendSelections(this, clipPosArray(this, heads), options); }), setSelections: docMethodOp(function(ranges, primary, options) { var this$1 = this; if (!ranges.length) { return } var out = []; for (var i = 0; i < ranges.length; i++) { out[i] = new Range(clipPos(this$1, ranges[i].anchor), clipPos(this$1, ranges[i].head)); } if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } setSelection(this, normalizeSelection(this.cm, out, primary), options); }), addSelection: docMethodOp(function(anchor, head, options) { var ranges = this.sel.ranges.slice(0); ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); }), getSelection: function(lineSep) { var this$1 = this; var ranges = this.sel.ranges, lines; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); lines = lines ? lines.concat(sel) : sel; } if (lineSep === false) { return lines } else { return lines.join(lineSep || this.lineSeparator()) } }, getSelections: function(lineSep) { var this$1 = this; var parts = [], ranges = this.sel.ranges; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } parts[i] = sel; } return parts }, replaceSelection: function(code, collapse, origin) { var dup = []; for (var i = 0; i < this.sel.ranges.length; i++) { dup[i] = code; } this.replaceSelections(dup, collapse, origin || "+input"); }, replaceSelections: docMethodOp(function(code, collapse, origin) { var this$1 = this; var changes = [], sel = this.sel; for (var i = 0; i < sel.ranges.length; i++) { var range$$1 = sel.ranges[i]; changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; } var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) { makeChange(this$1, changes[i$1]); } if (newSel) { setSelectionReplaceHistory(this, newSel); } else if (this.cm) { ensureCursorVisible(this.cm); } }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), setExtending: function(val) {this.extend = val;}, getExtending: function() {return this.extend}, historySize: function() { var hist = this.history, done = 0, undone = 0; for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } return {undo: done, redo: undone} }, clearHistory: function() {this.history = new History(this.history.maxGeneration);}, markClean: function() { this.cleanGeneration = this.changeGeneration(true); }, changeGeneration: function(forceSplit) { if (forceSplit) { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } return this.history.generation }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration) }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)} }, setHistory: function(histData) { var hist = this.history = new History(this.history.maxGeneration); hist.done = copyHistoryArray(histData.done.slice(0), null, true); hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); }, setGutterMarker: docMethodOp(function(line, gutterID, value) { return changeLine(this, line, "gutter", function (line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) { line.gutterMarkers = null; } return true }) }), clearGutter: docMethodOp(function(gutterID) { var this$1 = this; this.iter(function (line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { changeLine(this$1, line, "gutter", function () { line.gutterMarkers[gutterID] = null; if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } return true }); } }); }), lineInfo: function(line) { var n; if (typeof line == "number") { if (!isLine(this, line)) { return null } n = line; line = getLine(this, line); if (!line) { return null } } else { n = lineNo(line); if (n == null) { return null } } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets} }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; if (!line[prop]) { line[prop] = cls; } else if (classTest(cls).test(line[prop])) { return false } else { line[prop] += " " + cls; } return true }) }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; var cur = line[prop]; if (!cur) { return false } else if (cls == null) { line[prop] = null; } else { var found = cur.match(classTest(cls)); if (!found) { return false } var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true }) }), addLineWidget: docMethodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options) }), removeLineWidget: function(widget) { widget.clear(); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared, handleMouseEvents: options && options.handleMouseEvents}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark") }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { markers.push(span.marker.parent || span.marker); } } } return markers }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to); var found = [], lineNo$$1 = from.line; this.iter(from.line, to.line + 1, function (line) { var spans = line.markedSpans; if (spans) { for (var i = 0; i < spans.length; i++) { var span = spans[i]; if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || span.from == null && lineNo$$1 != from.line || span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { found.push(span.marker.parent || span.marker); } } } ++lineNo$$1; }); return found }, getAllMarks: function() { var markers = []; this.iter(function (line) { var sps = line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { if (sps[i].from != null) { markers.push(sps[i].marker); } } } }); return markers }, posFromIndex: function(off) { var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; this.iter(function (line) { var sz = line.text.length + sepSize; if (sz > off) { ch = off; return true } off -= sz; ++lineNo$$1; }); return clipPos(this, Pos(lineNo$$1, ch)) }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) { return 0 } var sepSize = this.lineSeparator().length; this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value index += line.text.length + sepSize; }); return index }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = this.sel; doc.extend = false; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc }, linkedDoc: function(options) { if (!options) { options = {}; } var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) { from = options.from; } if (options.to != null && options.to < to) { to = options.to; } var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); if (options.sharedHist) { copy.history = this.history ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; copySharedMarkers(copy, findSharedMarkers(this)); return copy }, unlinkDoc: function(other) { var this$1 = this; if (other instanceof CodeMirror) { other = other.doc; } if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { var link = this$1.linked[i]; if (link.doc != other) { continue } this$1.linked.splice(i, 1); other.unlinkDoc(this$1); detachSharedMarkers(findSharedMarkers(this$1)); break } } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); other.history = new History(null); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode}, getEditor: function() {return this.cm}, splitLines: function(str) { if (this.lineSep) { return str.split(this.lineSep) } return splitLinesAuto(str) }, lineSeparator: function() { return this.lineSep || "\n" }, setDirection: docMethodOp(function (dir) { if (dir != "rtl") { dir = "ltr"; } if (dir == this.direction) { return } this.direction = dir; this.iter(function (line) { return line.order = null; }); if (this.cm) { directionChanged(this.cm); } }) }); // Public alias. Doc.prototype.eachLine = Doc.prototype.iter; // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; clearDragCursor(cm); if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); if (ie) { lastDrop = +new Date; } var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || cm.isReadOnly()) { return } // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function (file, i) { if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { return } var reader = new FileReader; reader.onload = operation(cm, function () { var content = reader.result; if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } text[i] = content; if (++read == n) { pos = clipPos(cm.doc, pos); var change = {from: pos, to: pos, text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), origin: "paste"}; makeChange(cm.doc, change); setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); } }); reader.readAsText(file); }; for (var i = 0; i < n; ++i) { loadFile(files[i], i); } } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(function () { return cm.display.input.focus(); }, 20); return } try { var text$1 = e.dataTransfer.getData("Text"); if (text$1) { var selected; if (cm.state.draggingText && !cm.state.draggingText.copy) { selected = cm.listSelections(); } setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } cm.replaceSelection(text$1, "around", "paste"); cm.display.input.focus(); } } catch(e){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e.dataTransfer.setData("Text", cm.getSelection()); e.dataTransfer.effectAllowed = "copyMove"; // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (presto) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (presto) { img.parentNode.removeChild(img); } } } function onDragOver(cm, e) { var pos = posFromMouse(cm, e); if (!pos) { return } var frag = document.createDocumentFragment(); drawSelectionCursor(cm, pos, frag); if (!cm.display.dragCursor) { cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); } removeChildrenAndAdd(cm.display.dragCursor, frag); } function clearDragCursor(cm) { if (cm.display.dragCursor) { cm.display.lineSpace.removeChild(cm.display.dragCursor); cm.display.dragCursor = null; } } // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.getElementsByClassName) { return } var byClass = document.getElementsByClassName("CodeMirror"), editors = []; for (var i = 0; i < byClass.length; i++) { var cm = byClass[i].CodeMirror; if (cm) { editors.push(cm); } } if (editors.length) { editors[0].operation(function () { for (var i = 0; i < editors.length; i++) { f(editors[i]); } }); } } var globalsRegistered = false; function ensureGlobalHandlers() { if (globalsRegistered) { return } registerGlobalHandlers(); globalsRegistered = true; } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. var resizeTimer; on(window, "resize", function () { if (resizeTimer == null) { resizeTimer = setTimeout(function () { resizeTimer = null; forEachCodeMirror(onResize); }, 100); } }); // When the window loses focus, we want to show the editor as blurred on(window, "blur", function () { return forEachCodeMirror(onBlur); }); } // Called when the window resizes function onResize(cm) { var d = cm.display; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; d.scrollbarsClipped = false; cm.setSize(); } var keyNames = { 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" }; // Number keys for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } // Alphabetic keys for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } // Function keys for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } var keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" }; // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", "fallthrough": "basic" }; // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", "fallthrough": ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; // KEYMAP DISPATCH function normalizeKeyName(name) { var parts = name.split(/-(?!$)/); name = parts[parts.length - 1]; var alt, ctrl, shift, cmd; for (var i = 0; i < parts.length - 1; i++) { var mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } else if (/^a(lt)?$/i.test(mod)) { alt = true; } else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } else if (/^s(hift)?$/i.test(mod)) { shift = true; } else { throw new Error("Unrecognized modifier name: " + mod) } } if (alt) { name = "Alt-" + name; } if (ctrl) { name = "Ctrl-" + name; } if (cmd) { name = "Cmd-" + name; } if (shift) { name = "Shift-" + name; } return name } // This is a kludge to keep keymaps mostly working as raw objects // (backwards compatibility) while at the same time support features // like normalization and multi-stroke key bindings. It compiles a // new normalized keymap, and then updates the old object to reflect // this. function normalizeKeyMap(keymap) { var copy = {}; for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { var value = keymap[keyname]; if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } if (value == "...") { delete keymap[keyname]; continue } var keys = map(keyname.split(" "), normalizeKeyName); for (var i = 0; i < keys.length; i++) { var val = (void 0), name = (void 0); if (i == keys.length - 1) { name = keys.join(" "); val = value; } else { name = keys.slice(0, i + 1).join(" "); val = "..."; } var prev = copy[name]; if (!prev) { copy[name] = val; } else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } } delete keymap[keyname]; } } for (var prop in copy) { keymap[prop] = copy[prop]; } return keymap } function lookupKey(key, map$$1, handle, context) { map$$1 = getKeyMap(map$$1); var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; if (found === false) { return "nothing" } if (found === "...") { return "multi" } if (found != null && handle(found)) { return "handled" } if (map$$1.fallthrough) { if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") { return lookupKey(key, map$$1.fallthrough, handle, context) } for (var i = 0; i < map$$1.fallthrough.length; i++) { var result = lookupKey(key, map$$1.fallthrough[i], handle, context); if (result) { return result } } } } // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. function isModifierKey(value) { var name = typeof value == "string" ? value : keyNames[value.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" } function addModifierNames(name, event, noShift) { var base = name; if (event.altKey && base != "Alt") { name = "Alt-" + name; } if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } return name } // Look up the name of a key as indicated by an event object. function keyName(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) { return false } var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) { return false } // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) if (event.keyCode == 3 && event.code) { name = event.code; } return addModifierNames(name, event, noShift) } function getKeyMap(val) { return typeof val == "string" ? keyMap[val] : val } // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. function deleteNearSelection(cm, compute) { var ranges = cm.doc.sel.ranges, kill = []; // Build up a set of ranges to kill first, merging overlapping // ranges. for (var i = 0; i < ranges.length; i++) { var toKill = compute(ranges[i]); while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { var replaced = kill.pop(); if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from; break } } kill.push(toKill); } // Next, remove those actual ranges. runInOp(cm, function () { for (var i = kill.length - 1; i >= 0; i--) { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } ensureCursorVisible(cm); }); } function moveCharLogically(line, ch, dir) { var target = skipExtendingChars(line.text, ch + dir, dir); return target < 0 || target > line.text.length ? null : target } function moveLogically(line, start, dir) { var ch = moveCharLogically(line, start.ch, dir); return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") } function endOfLine(visually, cm, lineObj, lineNo, dir) { if (visually) { var order = getOrder(lineObj, cm.doc.direction); if (order) { var part = dir < 0 ? lst(order) : order[0]; var moveInStorageOrder = (dir < 0) == (part.level == 1); var sticky = moveInStorageOrder ? "after" : "before"; var ch; // With a wrapped rtl chunk (possibly spanning multiple bidi parts), // it could be that the last bidi part is not on the last visual line, // since visual lines contain content order-consecutive chunks. // Thus, in rtl, we are looking for the first (content-order) character // in the rtl chunk that is on the last line (that is, the same line // as the last (content-order) character). if (part.level > 0 || cm.doc.direction == "rtl") { var prep = prepareMeasureForLine(cm, lineObj); ch = dir < 0 ? lineObj.text.length - 1 : 0; var targetTop = measureCharPrepared(cm, prep, ch).top; ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } } else { ch = dir < 0 ? part.to : part.from; } return new Pos(lineNo, ch, sticky) } } return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") } function moveVisually(cm, line, start, dir) { var bidi = getOrder(line, cm.doc.direction); if (!bidi) { return moveLogically(line, start, dir) } if (start.ch >= line.text.length) { start.ch = line.text.length; start.sticky = "before"; } else if (start.ch <= 0) { start.ch = 0; start.sticky = "after"; } var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, // nothing interesting happens. return moveLogically(line, start, dir) } var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; var prep; var getWrappedLineExtent = function (ch) { if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } prep = prep || prepareMeasureForLine(cm, line); return wrappedLineExtentChar(cm, line, prep, ch) }; var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); if (cm.doc.direction == "rtl" || part.level == 1) { var moveInStorageOrder = (part.level == 1) == (dir < 0); var ch = mv(start, moveInStorageOrder ? 1 : -1); if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { // Case 2: We move within an rtl part or in an rtl editor on the same visual line var sticky = moveInStorageOrder ? "before" : "after"; return new Pos(start.line, ch, sticky) } } // Case 3: Could not move within this bidi part in this visual line, so leave // the current bidi part var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after"); }; for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { var part = bidi[partPos]; var moveInStorageOrder = (dir > 0) == (part.level != 1); var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } ch = moveInStorageOrder ? part.from : mv(part.to, -1); if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } } }; // Case 3a: Look for other bidi parts on the same visual line var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); if (res) { return res } // Case 3b: Look for other bidi parts on the next visual line var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); if (res) { return res } } // Case 4: Nowhere to move return null } // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. var commands = { selectAll: selectAll, singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, killLine: function (cm) { return deleteNearSelection(cm, function (range) { if (range.empty()) { var len = getLine(cm.doc, range.head.line).text.length; if (range.head.ch == len && range.head.line < cm.lastLine()) { return {from: range.head, to: Pos(range.head.line + 1, 0)} } else { return {from: range.head, to: Pos(range.head.line, len)} } } else { return {from: range.from(), to: range.to()} } }); }, deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) }); }); }, delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: range.from() }); }); }, delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var leftPos = cm.coordsChar({left: 0, top: top}, "div"); return {from: leftPos, to: range.from()} }); }, delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); return {from: range.from(), to: rightPos } }); }, undo: function (cm) { return cm.undo(); }, redo: function (cm) { return cm.redo(); }, undoSelection: function (cm) { return cm.undoSelection(); }, redoSelection: function (cm) { return cm.redoSelection(); }, goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, {origin: "+move", bias: 1} ); }, goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, {origin: "+move", bias: 1} ); }, goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, {origin: "+move", bias: -1} ); }, goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") }, sel_move); }, goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: 0, top: top}, "div") }, sel_move); }, goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; var pos = cm.coordsChar({left: 0, top: top}, "div"); if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } return pos }, sel_move); }, goLineUp: function (cm) { return cm.moveV(-1, "line"); }, goLineDown: function (cm) { return cm.moveV(1, "line"); }, goPageUp: function (cm) { return cm.moveV(-1, "page"); }, goPageDown: function (cm) { return cm.moveV(1, "page"); }, goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, goCharRight: function (cm) { return cm.moveH(1, "char"); }, goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, goColumnRight: function (cm) { return cm.moveH(1, "column"); }, goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, goGroupRight: function (cm) { return cm.moveH(1, "group"); }, goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, goWordRight: function (cm) { return cm.moveH(1, "word"); }, delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, indentAuto: function (cm) { return cm.indentSelection("smart"); }, indentMore: function (cm) { return cm.indentSelection("add"); }, indentLess: function (cm) { return cm.indentSelection("subtract"); }, insertTab: function (cm) { return cm.replaceSelection("\t"); }, insertSoftTab: function (cm) { var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].from(); var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); spaces.push(spaceStr(tabSize - col % tabSize)); } cm.replaceSelections(spaces); }, defaultTab: function (cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { cm.execCommand("insertTab"); } }, // Swap the two chars left and right of each selection's head. // Move cursor behind the two swapped characters afterwards. // // Doesn't consider line feeds a character. // Doesn't scan more than one line above to find a character. // Doesn't do anything on an empty line. // Doesn't do anything with non-empty selections. transposeChars: function (cm) { return runInOp(cm, function () { var ranges = cm.listSelections(), newSel = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) { continue } var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; if (line) { if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1); cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); } else if (cur.line > cm.doc.first) { var prev = getLine(cm.doc, cur.line - 1).text; if (prev) { cur = new Pos(cur.line, 1); cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); } } } newSel.push(new Range(cur, cur)); } cm.setSelections(newSel); }); }, newlineAndIndent: function (cm) { return runInOp(cm, function () { var sels = cm.listSelections(); for (var i = sels.length - 1; i >= 0; i--) { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } sels = cm.listSelections(); for (var i$1 = 0; i$1 < sels.length; i$1++) { cm.indentLine(sels[i$1].from().line, null, true); } ensureCursorVisible(cm); }); }, openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } }; function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, visual, lineN, 1) } function lineEnd(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLineEnd(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, line, lineN, -1) } function lineStartSmart(cm, pos) { var start = lineStart(cm, pos.line); var line = getLine(cm.doc, start.line); var order = getOrder(line, cm.doc.direction); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) } return start } // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) { return false } } // Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled(); var prevShift = cm.display.shift, done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } if (dropShift) { cm.display.shift = false; } done = bound(cm) != Pass; } finally { cm.display.shift = prevShift; cm.state.suppressEdits = false; } return done } function lookupKeyForEditor(cm, name, handle) { for (var i = 0; i < cm.state.keyMaps.length; i++) { var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); if (result) { return result } } return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm) } // Note that, despite the name, this function is also used to check // for bound mouse clicks. var stopSeq = new Delayed; function dispatchKey(cm, name, e, handle) { var seq = cm.state.keySeq; if (seq) { if (isModifierKey(name)) { return "handled" } if (/\'$/.test(name)) { cm.state.keySeq = null; } else { stopSeq.set(50, function () { if (cm.state.keySeq == seq) { cm.state.keySeq = null; cm.display.input.reset(); } }); } if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } } return dispatchKeyInner(cm, name, e, handle) } function dispatchKeyInner(cm, name, e, handle) { var result = lookupKeyForEditor(cm, name, handle); if (result == "multi") { cm.state.keySeq = name; } if (result == "handled") { signalLater(cm, "keyHandled", cm, name, e); } if (result == "handled" || result == "multi") { e_preventDefault(e); restartBlink(cm); } return !!result } // Handle a key from the keydown event. function handleKeyBinding(cm, e) { var name = keyName(e, true); if (!name) { return false } if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) || dispatchKey(cm, name, e, function (b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { return doHandleBinding(cm, b) } }) } else { return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) } } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; cm.curOp.focus = activeElt(); if (signalDOMEvent(cm, e)) { return } // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } var code = e.keyCode; cm.display.shift = code == 16 || e.shiftKey; var handled = handleKeyBinding(cm, e); if (presto) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { cm.replaceSelection("", null, "cut"); } } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { showCrossHair(cm); } } function showCrossHair(cm) { var lineDiv = cm.display.lineDiv; addClass(lineDiv, "CodeMirror-crosshair"); function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair"); off(document, "keyup", up); off(document, "mouseover", up); } } on(document, "keyup", up); on(document, "mouseover", up); } function onKeyUp(e) { if (e.keyCode == 16) { this.doc.sel.shift = false; } signalDOMEvent(this, e); } function onKeyPress(e) { var cm = this; if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } var keyCode = e.keyCode, charCode = e.charCode; if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } var ch = String.fromCharCode(charCode == null ? keyCode : charCode); // Some browsers fire keypress events for backspace if (ch == "\x08") { return } if (handleCharBinding(cm, e, ch)) { return } cm.display.input.onKeyPress(e); } var DOUBLECLICK_DELAY = 400; var PastClick = function(time, pos, button) { this.time = time; this.pos = pos; this.button = button; }; PastClick.prototype.compare = function (time, pos, button) { return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button }; var lastClick, lastDoubleClick; function clickRepeat(pos, button) { var now = +new Date; if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { lastClick = lastDoubleClick = null; return "triple" } else if (lastClick && lastClick.compare(now, pos, button)) { lastDoubleClick = new PastClick(now, pos, button); lastClick = null; return "double" } else { lastClick = new PastClick(now, pos, button); lastDoubleClick = null; return "single" } } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. function onMouseDown(e) { var cm = this, display = cm.display; if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } display.input.ensurePolled(); display.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false; setTimeout(function () { return display.scroller.draggable = true; }, 100); } return } if (clickInGutter(cm, e)) { return } var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; window.focus(); // #3261: make sure, that we're not starting a second selection if (button == 1 && cm.state.selectingText) { cm.state.selectingText(e); } if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } if (button == 1) { if (pos) { leftButtonDown(cm, pos, repeat, e); } else if (e_target(e) == display.scroller) { e_preventDefault(e); } } else if (button == 2) { if (pos) { extendSelection(cm.doc, pos); } setTimeout(function () { return display.input.focus(); }, 20); } else if (button == 3) { if (captureRightClick) { cm.display.input.onContextMenu(e); } else { delayBlurEvent(cm); } } } function handleMappedButton(cm, button, pos, repeat, event) { var name = "Click"; if (repeat == "double") { name = "Double" + name; } else if (repeat == "triple") { name = "Triple" + name; } name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { if (typeof bound == "string") { bound = commands[bound]; } if (!bound) { return false } var done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } done = bound(cm, pos) != Pass; } finally { cm.state.suppressEdits = false; } return done }) } function configureMouse(cm, repeat, event) { var option = cm.getOption("configureMouse"); var value = option ? option(cm, repeat, event) : {}; if (value.unit == null) { var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } return value } function leftButtonDown(cm, pos, repeat, event) { if (ie) { setTimeout(bind(ensureFocus, cm), 0); } else { cm.curOp.focus = activeElt(); } var behavior = configureMouse(cm, repeat, event); var sel = cm.doc.sel, contained; if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { leftButtonStartDrag(cm, event, pos, behavior); } else { leftButtonSelect(cm, event, pos, behavior); } } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, event, pos, behavior) { var display = cm.display, moved = false; var dragEnd = operation(cm, function (e) { if (webkit) { display.scroller.draggable = false; } cm.state.draggingText = false; off(display.wrapper.ownerDocument, "mouseup", dragEnd); off(display.wrapper.ownerDocument, "mousemove", mouseMove); off(display.scroller, "dragstart", dragStart); off(display.scroller, "drop", dragEnd); if (!moved) { e_preventDefault(e); if (!behavior.addNew) { extendSelection(cm.doc, pos, null, null, behavior.extend); } // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) if (webkit || ie && ie_version == 9) { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } else { display.input.focus(); } } }); var mouseMove = function(e2) { moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; }; var dragStart = function () { return moved = true; }; // Let the drag handler handle this. if (webkit) { display.scroller.draggable = true; } cm.state.draggingText = dragEnd; dragEnd.copy = !behavior.moveOnDrag; // IE's approach to draggable if (display.scroller.dragDrop) { display.scroller.dragDrop(); } on(display.wrapper.ownerDocument, "mouseup", dragEnd); on(display.wrapper.ownerDocument, "mousemove", mouseMove); on(display.scroller, "dragstart", dragStart); on(display.scroller, "drop", dragEnd); delayBlurEvent(cm); setTimeout(function () { return display.input.focus(); }, 20); } function rangeForUnit(cm, pos, unit) { if (unit == "char") { return new Range(pos, pos) } if (unit == "word") { return cm.findWordAt(pos) } if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } var result = unit(cm, pos); return new Range(result.from, result.to) } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, event, start, behavior) { var display = cm.display, doc = cm.doc; e_preventDefault(event); var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; if (behavior.addNew && !behavior.extend) { ourIndex = doc.sel.contains(start); if (ourIndex > -1) { ourRange = ranges[ourIndex]; } else { ourRange = new Range(start, start); } } else { ourRange = doc.sel.primary(); ourIndex = doc.sel.primIndex; } if (behavior.unit == "rectangle") { if (!behavior.addNew) { ourRange = new Range(start, start); } start = posFromMouse(cm, event, true, true); ourIndex = -1; } else { var range$$1 = rangeForUnit(cm, start, behavior.unit); if (behavior.extend) { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } else { ourRange = range$$1; } } if (!behavior.addNew) { ourIndex = 0; setSelection(doc, new Selection([ourRange], 0), sel_mouse); startSel = doc.sel; } else if (ourIndex == -1) { ourIndex = ranges.length; setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}); } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"}); startSel = doc.sel; } else { replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); } var lastPos = start; function extendTo(pos) { if (cmp(lastPos, pos) == 0) { return } lastPos = pos; if (behavior.unit == "rectangle") { var ranges = [], tabSize = cm.options.tabSize; var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); if (left == right) { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } else if (text.length > leftPos) { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } } if (!ranges.length) { ranges.push(new Range(start, start)); } setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}); cm.scrollIntoView(pos); } else { var oldRange = ourRange; var range$$1 = rangeForUnit(cm, pos, behavior.unit); var anchor = oldRange.anchor, head; if (cmp(range$$1.anchor, anchor) > 0) { head = range$$1.head; anchor = minPos(oldRange.from(), range$$1.anchor); } else { head = range$$1.anchor; anchor = maxPos(oldRange.to(), range$$1.head); } var ranges$1 = startSel.ranges.slice(0); ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); if (!cur) { return } if (cmp(cur, lastPos) != 0) { cm.curOp.focus = activeElt(); extendTo(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) { setTimeout(operation(cm, function () { if (counter != curCount) { return } display.scroller.scrollTop += outside; extend(e); }), 50); } } } function done(e) { cm.state.selectingText = false; counter = Infinity; // If e is null or undefined we interpret this as someone trying // to explicitly cancel the selection rather than the user // letting go of the mouse button. if (e) { e_preventDefault(e); display.input.focus(); } off(display.wrapper.ownerDocument, "mousemove", move); off(display.wrapper.ownerDocument, "mouseup", up); doc.history.lastSelOrigin = null; } var move = operation(cm, function (e) { if (e.buttons === 0 || !e_button(e)) { done(e); } else { extend(e); } }); var up = operation(cm, done); cm.state.selectingText = up; on(display.wrapper.ownerDocument, "mousemove", move); on(display.wrapper.ownerDocument, "mouseup", up); } // Used when mouse-selecting to adjust the anchor to the proper side // of a bidi jump depending on the visual position of the head. function bidiSimplify(cm, range$$1) { var anchor = range$$1.anchor; var head = range$$1.head; var anchorLine = getLine(cm.doc, anchor.line); if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } var order = getOrder(anchorLine); if (!order) { return range$$1 } var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); if (boundary == 0 || boundary == order.length) { return range$$1 } // Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide; if (head.line != anchor.line) { leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; } else { var headIndex = getBidiPartAt(order, head.ch, head.sticky); var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); if (headIndex == boundary - 1 || headIndex == boundary) { leftSide = dir < 0; } else { leftSide = dir > 0; } } var usePart = order[boundary + (leftSide ? -1 : 0)]; var from = leftSide == (usePart.level == 1); var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent) { var mX, mY; if (e.touches) { mX = e.touches[0].clientX; mY = e.touches[0].clientY; } else { try { mX = e.clientX; mY = e.clientY; } catch(e) { return false } } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } if (prevent) { e_preventDefault(e); } var display = cm.display; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.display.gutterSpecs[i]; signal(cm, type, cm, line, gutter.className, e); return e_defaultPrevented(e) } } } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true) } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. function onContextMenu(cm, e) { if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } if (signalDOMEvent(cm, e, "contextmenu")) { return } if (!captureRightClick) { cm.display.input.onContextMenu(e); } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) { return false } return gutterEvent(cm, e, "gutterContextMenu", false) } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } var Init = {toString: function(){return "CodeMirror.Init"}}; var defaults = {}; var optionHandlers = {}; function defineOptions(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) { optionHandlers[name] = notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } } CodeMirror.defineOption = option; // Passed to option handlers when there is no old value. CodeMirror.Init = Init; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function (cm, val) { return cm.setValue(val); }, true); option("mode", null, function (cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function (cm) { resetModeState(cm); clearCaches(cm); regChange(cm); }, true); option("lineSeparator", null, function (cm, val) { cm.doc.lineSep = val; if (!val) { return } var newBreaks = [], lineNo = cm.doc.first; cm.doc.iter(function (line) { for (var pos = 0;;) { var found = line.text.indexOf(val, pos); if (found == -1) { break } pos = found + val.length; newBreaks.push(Pos(lineNo, found)); } lineNo++; }); for (var i = newBreaks.length - 1; i >= 0; i--) { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } }); option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); if (old != Init) { cm.refresh(); } }); option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); option("electricChars", true); option("inputStyle", mobile ? "contenteditable" : "textarea", function () { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true); option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); option("rtlMoveVisually", !windows); option("wholeLineUpdateBefore", true); option("theme", "default", function (cm) { themeChanged(cm); updateGutters(cm); }, true); option("keyMap", "default", function (cm, val, old) { var next = getKeyMap(val); var prev = old != Init && getKeyMap(old); if (prev && prev.detach) { prev.detach(cm, next); } if (next.attach) { next.attach(cm, prev || null); } }); option("extraKeys", null); option("configureMouse", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function (cm, val) { cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); updateGutters(cm); }, true); option("fixedGutter", true, function (cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); option("scrollbarStyle", "native", function (cm) { initScrollbars(cm); updateScrollbars(cm); cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); }, true); option("lineNumbers", false, function (cm, val) { cm.display.gutterSpecs = getGutters(cm.options.gutters, val); updateGutters(cm); }, true); option("firstLineNumber", 1, updateGutters, true); option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); option("showCursorWhenSelecting", false, updateSelection, true); option("resetSelectionOnContextMenu", true); option("lineWiseCopyCut", true); option("pasteLinesPerSelection", true); option("selectionsMayTouch", false); option("readOnly", false, function (cm, val) { if (val == "nocursor") { onBlur(cm); cm.display.input.blur(); } cm.display.input.readOnlyChanged(val); }); option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); option("dragDrop", true, dragDropChanged); option("allowDropFileTypes", null); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1, updateSelection, true); option("singleCursorHeightPerLine", true, updateSelection, true); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true, resetModeState, true); option("addModeClass", false, resetModeState, true); option("pollInterval", 100); option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); option("historyEventDelay", 1250); option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); option("maxHighlightLength", 10000, resetModeState, true); option("moveInputWithCursor", true, function (cm, val) { if (!val) { cm.display.input.resetPosition(); } }); option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); option("autofocus", null); option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); option("phrases", null); } function dragDropChanged(cm, value, old) { var wasOn = old && old != Init; if (!value != !wasOn) { var funcs = cm.display.dragFunctions; var toggle = value ? on : off; toggle(cm.display.scroller, "dragstart", funcs.start); toggle(cm.display.scroller, "dragenter", funcs.enter); toggle(cm.display.scroller, "dragover", funcs.over); toggle(cm.display.scroller, "dragleave", funcs.leave); toggle(cm.display.scroller, "drop", funcs.drop); } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap"); cm.display.sizer.style.minWidth = ""; cm.display.sizerWidth = null; } else { rmClass(cm.display.wrapper, "CodeMirror-wrap"); findMaxLine(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function () { return updateScrollbars(cm); }, 100); } // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. function CodeMirror(place, options) { var this$1 = this; if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } this.options = options = options ? copyObj(options) : {}; // Determine effective options based on given values and defaults. copyObj(defaults, options, false); var doc = options.value; if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } else if (options.mode) { doc.modeOption = options.mode; } this.doc = doc; var input = new CodeMirror.inputStyles[options.inputStyle](this); var display = this.display = new Display(place, doc, input, options); display.wrapper.CodeMirror = this; themeChanged(this); if (options.lineWrapping) { this.display.wrapper.className += " CodeMirror-wrap"; } initScrollbars(this); this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, delayingBlurEvent: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll selectingText: false, draggingText: false, highlight: new Delayed(), // stores highlight worker timeout keySeq: null, // Unfinished key sequence specialChars: null }; if (options.autofocus && !mobile) { display.input.focus(); } // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } registerEventHandlers(this); ensureGlobalHandlers(); startOperation(this); this.curOp.forceUpdate = true; attachDoc(this, doc); if ((options.autofocus && !mobile) || this.hasFocus()) { setTimeout(bind(onFocus, this), 20); } else { onBlur(this); } for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) { optionHandlers[opt](this$1, options[opt], Init); } } maybeUpdateLineNumberWidth(this); if (options.finishInit) { options.finishInit(this); } for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } endOperation(this); // Suppress optimizelegibility in Webkit, since it breaks text // measuring on line wrapping boundaries. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { display.lineDiv.style.textRendering = "auto"; } } // The default configuration options. CodeMirror.defaults = defaults; // Functions to run when options are changed. CodeMirror.optionHandlers = optionHandlers; // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) { on(d.scroller, "dblclick", operation(cm, function (e) { if (signalDOMEvent(cm, e)) { return } var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); var word = cm.findWordAt(pos); extendSelection(cm.doc, word.anchor, word.head); })); } else { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); // Used to suppress mouse event handling when a touch happens var touchFinished, prevTouch = {end: 0}; function finishTouch() { if (d.activeTouch) { touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); prevTouch = d.activeTouch; prevTouch.end = +new Date; } } function isMouseLikeTouchEvent(e) { if (e.touches.length != 1) { return false } var touch = e.touches[0]; return touch.radiusX <= 1 && touch.radiusY <= 1 } function farAway(touch, other) { if (other.left == null) { return true } var dx = other.left - touch.left, dy = other.top - touch.top; return dx * dx + dy * dy > 20 * 20 } on(d.scroller, "touchstart", function (e) { if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { d.input.ensurePolled(); clearTimeout(touchFinished); var now = +new Date; d.activeTouch = {start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null}; if (e.touches.length == 1) { d.activeTouch.left = e.touches[0].pageX; d.activeTouch.top = e.touches[0].pageY; } } }); on(d.scroller, "touchmove", function () { if (d.activeTouch) { d.activeTouch.moved = true; } }); on(d.scroller, "touchend", function (e) { var touch = d.activeTouch; if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date - touch.start < 300) { var pos = cm.coordsChar(d.activeTouch, "page"), range; if (!touch.prev || farAway(touch, touch.prev)) // Single tap { range = new Range(pos, pos); } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap { range = cm.findWordAt(pos); } else // Triple tap { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } cm.setSelection(range.anchor, range.head); cm.focus(); e_preventDefault(e); } finishTouch(); }); on(d.scroller, "touchcancel", finishTouch); // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", function () { if (d.scroller.clientHeight) { updateScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); d.dragFunctions = { enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, start: function (e) { return onDragStart(cm, e); }, drop: operation(cm, onDrop), leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} }; var inp = d.input.getField(); on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); on(inp, "keydown", operation(cm, onKeyDown)); on(inp, "keypress", operation(cm, onKeyPress)); on(inp, "focus", function (e) { return onFocus(cm, e); }); on(inp, "blur", function (e) { return onBlur(cm, e); }); } var initHooks = []; CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. function indentLine(cm, n, how, aggressive) { var doc = cm.doc, state; if (how == null) { how = "add"; } if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) { how = "prev"; } else { state = getContextBefore(cm, n).state; } } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); if (line.stateAfter) { line.stateAfter = null; } var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (!aggressive && !/\S/.test(line.text)) { indentation = 0; how = "not"; } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass || indentation > 150) { if (!aggressive) { return } how = "prev"; } } if (how == "prev") { if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } else { indentation = 0; } } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } if (pos < indentation) { indentString += spaceStr(indentation - pos); } if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; return true } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { var range = doc.sel.ranges[i$1]; if (range.head.line == n && range.head.ch < curSpaceString.length) { var pos$1 = Pos(n, curSpaceString.length); replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); break } } } } // This will be set to a {lineWise: bool, text: [string]} object, so // that, when pasting, we know what kind of selections the copied // text was made out of. var lastCopied = null; function setLastCopied(newLastCopied) { lastCopied = newLastCopied; } function applyTextInput(cm, inserted, deleted, sel, origin) { var doc = cm.doc; cm.display.shift = false; if (!sel) { sel = doc.sel; } var recent = +new Date - 200; var paste = origin == "paste" || cm.state.pasteIncoming > recent; var textLines = splitLinesAuto(inserted), multiPaste = null; // When pasting N lines into N selections, insert one line per selection if (paste && sel.ranges.length > 1) { if (lastCopied && lastCopied.text.join("\n") == inserted) { if (sel.ranges.length % lastCopied.text.length == 0) { multiPaste = []; for (var i = 0; i < lastCopied.text.length; i++) { multiPaste.push(doc.splitLines(lastCopied.text[i])); } } } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { multiPaste = map(textLines, function (l) { return [l]; }); } } var updateInput = cm.curOp.updateInput; // Normal behavior is to insert the new text into every selection for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { var range$$1 = sel.ranges[i$1]; var from = range$$1.from(), to = range$$1.to(); if (range$$1.empty()) { if (deleted && deleted > 0) // Handle deletion { from = Pos(from.line, from.ch - deleted); } else if (cm.state.overwrite && !paste) // Handle overwrite { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) { from = to = Pos(from.line, 0); } } var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; makeChange(cm.doc, changeEvent); signalLater(cm, "inputRead", cm, changeEvent); } if (inserted && !paste) { triggerElectric(cm, inserted); } ensureCursorVisible(cm); if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } cm.curOp.typing = true; cm.state.pasteIncoming = cm.state.cutIncoming = -1; } function handlePaste(e, cm) { var pasted = e.clipboardData && e.clipboardData.getData("Text"); if (pasted) { e.preventDefault(); if (!cm.isReadOnly() && !cm.options.disableInput) { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } return true } } function triggerElectric(cm, inserted) { // When an 'electric' character is inserted, immediately trigger a reindent if (!cm.options.electricChars || !cm.options.smartIndent) { return } var sel = cm.doc.sel; for (var i = sel.ranges.length - 1; i >= 0; i--) { var range$$1 = sel.ranges[i]; if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } var mode = cm.getModeAt(range$$1.head); var indented = false; if (mode.electricChars) { for (var j = 0; j < mode.electricChars.length; j++) { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indented = indentLine(cm, range$$1.head.line, "smart"); break } } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) { indented = indentLine(cm, range$$1.head.line, "smart"); } } if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } } } function copyableRanges(cm) { var text = [], ranges = []; for (var i = 0; i < cm.doc.sel.ranges.length; i++) { var line = cm.doc.sel.ranges[i].head.line; var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; ranges.push(lineRange); text.push(cm.getRange(lineRange.anchor, lineRange.head)); } return {text: text, ranges: ranges} } function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { field.setAttribute("autocorrect", autocorrect ? "" : "off"); field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); field.setAttribute("spellcheck", !!spellcheck); } function hiddenTextarea() { var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) { te.style.width = "1000px"; } else { te.setAttribute("wrap", "off"); } // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) { te.style.border = "1px solid black"; } disableBrowserMagic(te); return div } // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. function addEditorMethods(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; var helpers = CodeMirror.helpers = {}; CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); this.display.input.focus();}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") { return } options[option] = value; if (optionHandlers.hasOwnProperty(option)) { operation(this, optionHandlers[option])(this, value, old); } signal(this, "optionChange", this, option); }, getOption: function(option) {return this.options[option]}, getDoc: function() {return this.doc}, addKeyMap: function(map$$1, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); }, removeKeyMap: function(map$$1) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) { if (maps[i] == map$$1 || maps[i].name == map$$1) { maps.splice(i, 1); return true } } }, addOverlay: methodOp(function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) { throw new Error("Overlays may not be stateful.") } insertSorted(this.state.overlays, {mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0}, function (overlay) { return overlay.priority; }); this.state.modeGen++; regChange(this); }), removeOverlay: methodOp(function(spec) { var this$1 = this; var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this$1.state.modeGen++; regChange(this$1); return } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } else { dir = dir ? "add" : "subtract"; } } if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } }), indentSelection: methodOp(function(how) { var this$1 = this; var ranges = this.doc.sel.ranges, end = -1; for (var i = 0; i < ranges.length; i++) { var range$$1 = ranges[i]; if (!range$$1.empty()) { var from = range$$1.from(), to = range$$1.to(); var start = Math.max(end, from.line); end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; for (var j = start; j < end; ++j) { indentLine(this$1, j, how); } var newRanges = this$1.doc.sel.ranges; if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } } else if (range$$1.head.line > end) { indentLine(this$1, range$$1.head.line, how, true); end = range$$1.head.line; if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { return takeToken(this, pos, precise) }, getLineTokens: function(line, precise) { return takeToken(this, Pos(line), precise, true) }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; var type; if (ch == 0) { type = styles[2]; } else { for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } else { type = styles[mid * 2 + 2]; break } } } var cut = type ? type.indexOf("overlay ") : -1; return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) { return mode } return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0] }, getHelpers: function(pos, type) { var this$1 = this; var found = []; if (!helpers.hasOwnProperty(type)) { return found } var help = helpers[type], mode = this.getModeAt(pos); if (typeof mode[type] == "string") { if (help[mode[type]]) { found.push(help[mode[type]]); } } else if (mode[type]) { for (var i = 0; i < mode[type].length; i++) { var val = help[mode[type][i]]; if (val) { found.push(val); } } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]); } else if (help[mode.name]) { found.push(help[mode.name]); } for (var i$1 = 0; i$1 < help._global.length; i$1++) { var cur = help._global[i$1]; if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) { found.push(cur.val); } } return found }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getContextBefore(this, line + 1, precise).state }, cursorCoords: function(start, mode) { var pos, range$$1 = this.doc.sel.primary(); if (start == null) { pos = range$$1.head; } else if (typeof start == "object") { pos = clipPos(this.doc, start); } else { pos = start ? range$$1.from() : range$$1.to(); } return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset) }, heightAtLine: function(line, mode, includeWidgets) { var end = false, lineObj; if (typeof line == "number") { var last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) { line = this.doc.first; } else if (line > last) { line = last; end = true; } lineObj = getLine(this.doc, line); } else { lineObj = line; } return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, defaultTextHeight: function() { return textHeight(this.display) }, defaultCharWidth: function() { return charWidth(this.display) }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; node.setAttribute("cm-ignore-events", "true"); this.display.input.setUneditable(node); display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { top = pos.top - node.offsetHeight; } else if (pos.bottom + node.offsetHeight <= vspace) { top = pos.bottom; } if (left + node.offsetWidth > hspace) { left = hspace - node.offsetWidth; } } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") { left = 0; } else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } node.style.left = left + "px"; } if (scroll) { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, triggerOnMouseDown: methodOp(onMouseDown), execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) { return commands[cmd].call(null, this) } }, triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), findPosH: function(from, amount, unit, visually) { var this$1 = this; var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { cur = findPosH(this$1.doc, cur, dir, unit, visually); if (cur.hitSide) { break } } return cur }, moveH: methodOp(function(dir, unit) { var this$1 = this; this.extendSelectionsBy(function (range$$1) { if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } else { return dir < 0 ? range$$1.from() : range$$1.to() } }, sel_move); }), deleteH: methodOp(function(dir, unit) { var sel = this.doc.sel, doc = this.doc; if (sel.somethingSelected()) { doc.replaceSelection("", null, "+delete"); } else { deleteNearSelection(this, function (range$$1) { var other = findPosH(doc, range$$1.head, dir, unit, false); return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} }); } }), findPosV: function(from, amount, unit, goalColumn) { var this$1 = this; var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { var coords = cursorCoords(this$1, cur, "div"); if (x == null) { x = coords.left; } else { coords.left = x; } cur = findPosV(this$1, coords, dir, unit); if (cur.hitSide) { break } } return cur }, moveV: methodOp(function(dir, unit) { var this$1 = this; var doc = this.doc, goals = []; var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); doc.extendSelectionsBy(function (range$$1) { if (collapse) { return dir < 0 ? range$$1.from() : range$$1.to() } var headPos = cursorCoords(this$1, range$$1.head, "div"); if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } goals.push(headPos.left); var pos = findPosV(this$1, headPos, dir, unit); if (unit == "page" && range$$1 == doc.sel.primary()) { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } return pos }, sel_move); if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) { doc.sel.ranges[i].goalColumn = goals[i]; } } }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { var doc = this.doc, line = getLine(doc, pos.line).text; var start = pos.ch, end = pos.ch; if (line) { var helper = this.getHelper(pos, "wordChars"); if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } var startChar = line.charAt(start); var check = isWordChar(startChar, helper) ? function (ch) { return isWordChar(ch, helper); } : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; while (start > 0 && check(line.charAt(start - 1))) { --start; } while (end < line.length && check(line.charAt(end))) { ++end; } } return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) { return } if (this.state.overwrite = !this.state.overwrite) { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } else { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } signal(this, "overwriteToggle", this, this.state.overwrite); }, hasFocus: function() { return this.display.input.getField() == activeElt() }, isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, scrollIntoView: methodOp(function(range$$1, margin) { if (range$$1 == null) { range$$1 = {from: this.doc.sel.primary().head, to: null}; if (margin == null) { margin = this.options.cursorScrollMargin; } } else if (typeof range$$1 == "number") { range$$1 = {from: Pos(range$$1, 0), to: null}; } else if (range$$1.from == null) { range$$1 = {from: range$$1, to: null}; } if (!range$$1.to) { range$$1.to = range$$1.from; } range$$1.margin = margin || 0; if (range$$1.from.line != null) { scrollToRange(this, range$$1); } else { scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); } }), setSize: methodOp(function(width, height) { var this$1 = this; var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; if (width != null) { this.display.wrapper.style.width = interpret(width); } if (height != null) { this.display.wrapper.style.height = interpret(height); } if (this.options.lineWrapping) { clearLineMeasurementCache(this); } var lineNo$$1 = this.display.viewFrom; this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } ++lineNo$$1; }); this.curOp.forceUpdate = true; signal(this, "refresh", this); }), operation: function(f){return runInOp(this, f)}, startOperation: function(){return startOperation(this)}, endOperation: function(){return endOperation(this)}, refresh: methodOp(function() { var oldHeight = this.display.cachedTextHeight; regChange(this); this.curOp.forceUpdate = true; clearCaches(this); scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); updateGutterSpace(this.display); if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) { estimateLineHeights(this); } signal(this, "refresh", this); }), swapDoc: methodOp(function(doc) { var old = this.doc; old.cm = null; // Cancel the current text selection if any (#5821) if (this.state.selectingText) { this.state.selectingText(); } attachDoc(this, doc); clearCaches(this); this.display.input.reset(); scrollToCoords(this, doc.scrollLeft, doc.scrollTop); this.curOp.forceScroll = true; signalLater(this, "swapDoc", this, old); return old }), phrase: function(phraseText) { var phrases = this.options.phrases; return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText }, getInputField: function(){return this.display.input.getField()}, getWrapperElement: function(){return this.display.wrapper}, getScrollerElement: function(){return this.display.scroller}, getGutterElement: function(){return this.display.gutters} }; eventMixin(CodeMirror); CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } helpers[type][name] = value; }; CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value); helpers[type]._global.push({pred: predicate, val: value}); }; } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "char", "column" (like char, but doesn't // cross line boundaries), "word" (across next word), or "group" (to // the start of next group of word or non-word-non-whitespace // chars). The visually param controls whether, in right-to-left // text, direction 1 means to move towards the next index in the // string, or towards the character to the right of the current // position. The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { var oldPos = pos; var origDir = dir; var lineObj = getLine(doc, pos.line); function findNextLine() { var l = pos.line + dir; if (l < doc.first || l >= doc.first + doc.size) { return false } pos = new Pos(l, pos.ch, pos.sticky); return lineObj = getLine(doc, l) } function moveOnce(boundToLine) { var next; if (visually) { next = moveVisually(doc.cm, lineObj, pos, dir); } else { next = moveLogically(lineObj, pos, dir); } if (next == null) { if (!boundToLine && findNextLine()) { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } else { return false } } else { pos = next; } return true } if (unit == "char") { moveOnce(); } else if (unit == "column") { moveOnce(true); } else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) { break } var cur = lineObj.text.charAt(pos.ch) || "\n"; var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; if (group && !first && !type) { type = "s"; } if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} break } if (type) { sawType = type; } if (dir > 0 && !moveOnce(!first)) { break } } } var result = skipAtomic(doc, pos, oldPos, origDir, true); if (equalCursorPos(oldPos, result)) { result.hitSide = true; } return result } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } var target; for (;;) { target = coordsChar(cm, x, y); if (!target.outside) { break } if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } y += dir * 5; } return target } // CONTENTEDITABLE INPUT STYLE var ContentEditableInput = function(cm) { this.cm = cm; this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; this.polling = new Delayed(); this.composing = null; this.gracePeriod = false; this.readDOMTimeout = null; }; ContentEditableInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = input.cm; var div = input.div = display.lineDiv; disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); on(div, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } // IE doesn't fire input events, so we schedule a read for the pasted content in this way if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } }); on(div, "compositionstart", function (e) { this$1.composing = {data: e.data, done: false}; }); on(div, "compositionupdate", function (e) { if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } }); on(div, "compositionend", function (e) { if (this$1.composing) { if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } this$1.composing.done = true; } }); on(div, "touchstart", function () { return input.forceCompositionEnd(); }); on(div, "input", function () { if (!this$1.composing) { this$1.readFromDOMSoon(); } }); function onCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.operation(function () { cm.setSelections(ranges.ranges, 0, sel_dontScroll); cm.replaceSelection("", null, "cut"); }); } } if (e.clipboardData) { e.clipboardData.clearData(); var content = lastCopied.text.join("\n"); // iOS exposes the clipboard API, but seems to discard content inserted into it e.clipboardData.setData("Text", content); if (e.clipboardData.getData("Text") == content) { e.preventDefault(); return } } // Old-fashioned briefly-focus-a-textarea hack var kludge = hiddenTextarea(), te = kludge.firstChild; cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); te.value = lastCopied.text.join("\n"); var hadFocus = document.activeElement; selectInput(te); setTimeout(function () { cm.display.lineSpace.removeChild(kludge); hadFocus.focus(); if (hadFocus == div) { input.showPrimarySelection(); } }, 50); } on(div, "copy", onCopyCut); on(div, "cut", onCopyCut); }; ContentEditableInput.prototype.prepareSelection = function () { var result = prepareSelection(this.cm, false); result.focus = this.cm.state.focused; return result }; ContentEditableInput.prototype.showSelection = function (info, takeFocus) { if (!info || !this.cm.display.view.length) { return } if (info.focus || takeFocus) { this.showPrimarySelection(); } this.showMultipleSelections(info); }; ContentEditableInput.prototype.getSelection = function () { return this.cm.display.wrapper.ownerDocument.getSelection() }; ContentEditableInput.prototype.showPrimarySelection = function () { var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); var from = prim.from(), to = prim.to(); if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { sel.removeAllRanges(); return } var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { return } var view = cm.display.view; var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || {node: view[0].measure.map[2], offset: 0}; var end = to.line < cm.display.viewTo && posToDOM(cm, to); if (!end) { var measure = view[view.length - 1].measure; var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; } if (!start || !end) { sel.removeAllRanges(); return } var old = sel.rangeCount && sel.getRangeAt(0), rng; try { rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible if (rng) { if (!gecko && cm.state.focused) { sel.collapse(start.node, start.offset); if (!rng.collapsed) { sel.removeAllRanges(); sel.addRange(rng); } } else { sel.removeAllRanges(); sel.addRange(rng); } if (old && sel.anchorNode == null) { sel.addRange(old); } else if (gecko) { this.startGracePeriod(); } } this.rememberSelection(); }; ContentEditableInput.prototype.startGracePeriod = function () { var this$1 = this; clearTimeout(this.gracePeriod); this.gracePeriod = setTimeout(function () { this$1.gracePeriod = false; if (this$1.selectionChanged()) { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } }, 20); }; ContentEditableInput.prototype.showMultipleSelections = function (info) { removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }; ContentEditableInput.prototype.rememberSelection = function () { var sel = this.getSelection(); this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; }; ContentEditableInput.prototype.selectionInEditor = function () { var sel = this.getSelection(); if (!sel.rangeCount) { return false } var node = sel.getRangeAt(0).commonAncestorContainer; return contains(this.div, node) }; ContentEditableInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor") { if (!this.selectionInEditor()) { this.showSelection(this.prepareSelection(), true); } this.div.focus(); } }; ContentEditableInput.prototype.blur = function () { this.div.blur(); }; ContentEditableInput.prototype.getField = function () { return this.div }; ContentEditableInput.prototype.supportsTouch = function () { return true }; ContentEditableInput.prototype.receivedFocus = function () { var input = this; if (this.selectionInEditor()) { this.pollSelection(); } else { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } function poll() { if (input.cm.state.focused) { input.pollSelection(); input.polling.set(input.cm.options.pollInterval, poll); } } this.polling.set(this.cm.options.pollInterval, poll); }; ContentEditableInput.prototype.selectionChanged = function () { var sel = this.getSelection(); return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset }; ContentEditableInput.prototype.pollSelection = function () { if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } var sel = this.getSelection(), cm = this.cm; // On Android Chrome (version 56, at least), backspacing into an // uneditable block element will put the cursor in that element, // and then, because it's not editable, hide the virtual keyboard. // Because Android doesn't allow us to actually detect backspace // presses in a sane way, this code checks for when that happens // and simulates a backspace press in this case. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); this.blur(); this.focus(); return } if (this.composing) { return } this.rememberSelection(); var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var head = domToPos(cm, sel.focusNode, sel.focusOffset); if (anchor && head) { runInOp(cm, function () { setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } }); } }; ContentEditableInput.prototype.pollContent = function () { if (this.readDOMTimeout != null) { clearTimeout(this.readDOMTimeout); this.readDOMTimeout = null; } var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); var from = sel.from(), to = sel.to(); if (from.ch == 0 && from.line > cm.firstLine()) { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { to = Pos(to.line + 1, 0); } if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } var fromIndex, fromLine, fromNode; if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { fromLine = lineNo(display.view[0].line); fromNode = display.view[0].node; } else { fromLine = lineNo(display.view[fromIndex].line); fromNode = display.view[fromIndex - 1].node.nextSibling; } var toIndex = findViewIndex(cm, to.line); var toLine, toNode; if (toIndex == display.view.length - 1) { toLine = display.viewTo - 1; toNode = display.lineDiv.lastChild; } else { toLine = lineNo(display.view[toIndex + 1].line) - 1; toNode = display.view[toIndex + 1].node.previousSibling; } if (!fromNode) { return false } var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); while (newText.length > 1 && oldText.length > 1) { if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else { break } } var cutFront = 0, cutEnd = 0; var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { ++cutFront; } var newBot = lst(newText), oldBot = lst(oldText); var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { ++cutEnd; } // Try to move start of change to start of selection if ambiguous if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { cutFront--; cutEnd++; } } newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); var chFrom = Pos(fromLine, cutFront); var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { replaceRange(cm.doc, newText, chFrom, chTo, "+input"); return true } }; ContentEditableInput.prototype.ensurePolled = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.reset = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.forceCompositionEnd = function () { if (!this.composing) { return } clearTimeout(this.readDOMTimeout); this.composing = null; this.updateFromDOM(); this.div.blur(); this.div.focus(); }; ContentEditableInput.prototype.readFromDOMSoon = function () { var this$1 = this; if (this.readDOMTimeout != null) { return } this.readDOMTimeout = setTimeout(function () { this$1.readDOMTimeout = null; if (this$1.composing) { if (this$1.composing.done) { this$1.composing = null; } else { return } } this$1.updateFromDOM(); }, 80); }; ContentEditableInput.prototype.updateFromDOM = function () { var this$1 = this; if (this.cm.isReadOnly() || !this.pollContent()) { runInOp(this.cm, function () { return regChange(this$1.cm); }); } }; ContentEditableInput.prototype.setUneditable = function (node) { node.contentEditable = "false"; }; ContentEditableInput.prototype.onKeyPress = function (e) { if (e.charCode == 0 || this.composing) { return } e.preventDefault(); if (!this.cm.isReadOnly()) { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } }; ContentEditableInput.prototype.readOnlyChanged = function (val) { this.div.contentEditable = String(val != "nocursor"); }; ContentEditableInput.prototype.onContextMenu = function () {}; ContentEditableInput.prototype.resetPosition = function () {}; ContentEditableInput.prototype.needsContentAttribute = true; function posToDOM(cm, pos) { var view = findViewForLine(cm, pos.line); if (!view || view.hidden) { return null } var line = getLine(cm.doc, pos.line); var info = mapFromLineView(view, line, pos.line); var order = getOrder(line, cm.doc.direction), side = "left"; if (order) { var partPos = getBidiPartAt(order, pos.ch); side = partPos % 2 ? "right" : "left"; } var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); result.offset = result.collapse == "right" ? result.end : result.start; return result } function isInGutter(node) { for (var scan = node; scan; scan = scan.parentNode) { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } return false } function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } function domTextBetween(cm, from, to, fromLine, toLine) { var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; function recognizeMarker(id) { return function (marker) { return marker.id == id; } } function close() { if (closing) { text += lineSep; if (extraLinebreak) { text += lineSep; } closing = extraLinebreak = false; } } function addText(str) { if (str) { close(); text += str; } } function walk(node) { if (node.nodeType == 1) { var cmText = node.getAttribute("cm-text"); if (cmText) { addText(cmText); return } var markerID = node.getAttribute("cm-marker"), range$$1; if (markerID) { var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); if (found.length && (range$$1 = found[0].find(0))) { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } return } if (node.getAttribute("contenteditable") == "false") { return } var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } if (isBlock) { close(); } for (var i = 0; i < node.childNodes.length; i++) { walk(node.childNodes[i]); } if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } if (isBlock) { closing = true; } } else if (node.nodeType == 3) { addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); } } for (;;) { walk(from); if (from == to) { break } from = from.nextSibling; extraLinebreak = false; } return text } function domToPos(cm, node, offset) { var lineNode; if (node == cm.display.lineDiv) { lineNode = cm.display.lineDiv.childNodes[offset]; if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } node = null; offset = 0; } else { for (lineNode = node;; lineNode = lineNode.parentNode) { if (!lineNode || lineNode == cm.display.lineDiv) { return null } if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } } } for (var i = 0; i < cm.display.view.length; i++) { var lineView = cm.display.view[i]; if (lineView.node == lineNode) { return locateNodeInLineView(lineView, node, offset) } } } function locateNodeInLineView(lineView, node, offset) { var wrapper = lineView.text.firstChild, bad = false; if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } if (node == wrapper) { bad = true; node = wrapper.childNodes[offset]; offset = 0; if (!node) { var line = lineView.rest ? lst(lineView.rest) : lineView.line; return badPos(Pos(lineNo(line), line.text.length), bad) } } var textNode = node.nodeType == 3 ? node : null, topNode = node; if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { textNode = node.firstChild; if (offset) { offset = textNode.nodeValue.length; } } while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } var measure = lineView.measure, maps = measure.maps; function find(textNode, topNode, offset) { for (var i = -1; i < (maps ? maps.length : 0); i++) { var map$$1 = i < 0 ? measure.map : maps[i]; for (var j = 0; j < map$$1.length; j += 3) { var curNode = map$$1[j + 2]; if (curNode == textNode || curNode == topNode) { var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); var ch = map$$1[j] + offset; if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } return Pos(line, ch) } } } } var found = find(textNode, topNode, offset); if (found) { return badPos(found, bad) } // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { found = find(after, after.firstChild, 0); if (found) { return badPos(Pos(found.line, found.ch - dist), bad) } else { dist += after.textContent.length; } } for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { found = find(before, before.firstChild, -1); if (found) { return badPos(Pos(found.line, found.ch + dist$1), bad) } else { dist$1 += before.textContent.length; } } } // TEXTAREA INPUT STYLE var TextareaInput = function(cm) { this.cm = cm; // See input.poll and input.reset this.prevInput = ""; // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. this.pollingFast = false; // Self-resetting timeout for the poller this.polling = new Delayed(); // Used to work around IE issue with selection being forgotten when focus moves away from textarea this.hasSelection = false; this.composing = null; }; TextareaInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = this.cm; this.createField(display); var te = this.textarea; display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) if (ios) { te.style.width = "0px"; } on(te, "input", function () { if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } input.poll(); }); on(te, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } cm.state.pasteIncoming = +new Date; input.fastPoll(); }); function prepareCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.setSelections(ranges.ranges, null, sel_dontScroll); } else { input.prevInput = ""; te.value = ranges.text.join("\n"); selectInput(te); } } if (e.type == "cut") { cm.state.cutIncoming = +new Date; } } on(te, "cut", prepareCopyCut); on(te, "copy", prepareCopyCut); on(display.scroller, "paste", function (e) { if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } if (!te.dispatchEvent) { cm.state.pasteIncoming = +new Date; input.focus(); return } // Pass the `paste` event to the textarea so it's handled by its event listener. var event = new Event("paste"); event.clipboardData = e.clipboardData; te.dispatchEvent(event); }); // Prevent normal selection in the editor (we handle our own) on(display.lineSpace, "selectstart", function (e) { if (!eventInWidget(display, e)) { e_preventDefault(e); } }); on(te, "compositionstart", function () { var start = cm.getCursor("from"); if (input.composing) { input.composing.range.clear(); } input.composing = { start: start, range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) }; }); on(te, "compositionend", function () { if (input.composing) { input.poll(); input.composing.range.clear(); input.composing = null; } }); }; TextareaInput.prototype.createField = function (_display) { // Wraps and hides input textarea this.wrapper = hiddenTextarea(); // The semihidden textarea that is focused when the editor is // focused, and receives input. this.textarea = this.wrapper.firstChild; }; TextareaInput.prototype.prepareSelection = function () { // Redraw the selection and/or cursor var cm = this.cm, display = cm.display, doc = cm.doc; var result = prepareSelection(cm); // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); } return result }; TextareaInput.prototype.showSelection = function (drawn) { var cm = this.cm, display = cm.display; removeChildrenAndAdd(display.cursorDiv, drawn.cursors); removeChildrenAndAdd(display.selectionDiv, drawn.selection); if (drawn.teTop != null) { this.wrapper.style.top = drawn.teTop + "px"; this.wrapper.style.left = drawn.teLeft + "px"; } }; // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) TextareaInput.prototype.reset = function (typing) { if (this.contextMenuPending || this.composing) { return } var cm = this.cm; if (cm.somethingSelected()) { this.prevInput = ""; var content = cm.getSelection(); this.textarea.value = content; if (cm.state.focused) { selectInput(this.textarea); } if (ie && ie_version >= 9) { this.hasSelection = content; } } else if (!typing) { this.prevInput = this.textarea.value = ""; if (ie && ie_version >= 9) { this.hasSelection = null; } } }; TextareaInput.prototype.getField = function () { return this.textarea }; TextareaInput.prototype.supportsTouch = function () { return false }; TextareaInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } }; TextareaInput.prototype.blur = function () { this.textarea.blur(); }; TextareaInput.prototype.resetPosition = function () { this.wrapper.style.top = this.wrapper.style.left = 0; }; TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. TextareaInput.prototype.slowPoll = function () { var this$1 = this; if (this.pollingFast) { return } this.polling.set(this.cm.options.pollInterval, function () { this$1.poll(); if (this$1.cm.state.focused) { this$1.slowPoll(); } }); }; // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. TextareaInput.prototype.fastPoll = function () { var missed = false, input = this; input.pollingFast = true; function p() { var changed = input.poll(); if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} } input.polling.set(20, p); }; // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). TextareaInput.prototype.poll = function () { var this$1 = this; var cm = this.cm, input = this.textarea, prevInput = this.prevInput; // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (this.contextMenuPending || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { return false } var text = input.value; // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) { return false } // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { cm.display.input.reset(); return false } if (cm.doc.sel == cm.display.selForContextMenu) { var first = text.charCodeAt(0); if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } } // Find the part of the input that is actually new var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } runInOp(cm, function () { applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null); // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } else { this$1.prevInput = text; } if (this$1.composing) { this$1.composing.range.clear(); this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"}); } }); return true }; TextareaInput.prototype.ensurePolled = function () { if (this.pollingFast && this.poll()) { this.pollingFast = false; } }; TextareaInput.prototype.onKeyPress = function () { if (ie && ie_version >= 9) { this.hasSelection = null; } this.fastPoll(); }; TextareaInput.prototype.onContextMenu = function (e) { var input = this, cm = input.cm, display = cm.display, te = input.textarea; if (input.contextMenuPending) { input.contextMenuPending(); } var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || presto) { return } // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. var reset = cm.options.resetSelectionOnContextMenu; if (reset && cm.doc.sel.contains(pos) == -1) { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); input.wrapper.style.cssText = "position: static"; te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; var oldScrollY; if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) display.input.focus(); if (webkit) { window.scrollTo(null, oldScrollY); } display.input.reset(); // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } input.contextMenuPending = rehide; display.selForContextMenu = cm.doc.sel; clearTimeout(display.detectingSelectAll); // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (te.selectionStart != null) { var selected = cm.somethingSelected(); var extval = "\u200b" + (selected ? te.value : ""); te.value = "\u21da"; // Used to catch context-menu undo te.value = extval; input.prevInput = selected ? "" : "\u200b"; te.selectionStart = 1; te.selectionEnd = extval.length; // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel; } } function rehide() { if (input.contextMenuPending != rehide) { return } input.contextMenuPending = false; input.wrapper.style.cssText = oldWrapperCSS; te.style.cssText = oldCSS; if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } // Try to detect the user choosing select-all if (te.selectionStart != null) { if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } var i = 0, poll = function () { if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { operation(cm, selectAll)(cm); } else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500); } else { display.selForContextMenu = null; display.input.reset(); } }; display.detectingSelectAll = setTimeout(poll, 200); } } if (ie && ie_version >= 9) { prepareSelectAllHack(); } if (captureRightClick) { e_stop(e); var mouseup = function () { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } }; TextareaInput.prototype.readOnlyChanged = function (val) { if (!val) { this.reset(); } this.textarea.disabled = val == "nocursor"; }; TextareaInput.prototype.setUneditable = function () {}; TextareaInput.prototype.needsContentAttribute = false; function fromTextArea(textarea, options) { options = options ? copyObj(options) : {}; options.value = textarea.value; if (!options.tabindex && textarea.tabIndex) { options.tabindex = textarea.tabIndex; } if (!options.placeholder && textarea.placeholder) { options.placeholder = textarea.placeholder; } // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = activeElt(); options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} var realSubmit; if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form; realSubmit = form.submit; try { var wrappedSubmit = form.submit = function () { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } options.finishInit = function (cm) { cm.save = save; cm.getTextArea = function () { return textarea; }; cm.toTextArea = function () { cm.toTextArea = isNaN; // Prevent this from being ran twice save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") { textarea.form.submit = realSubmit; } } }; }; textarea.style.display = "none"; var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); return cm } function addLegacyProps(CodeMirror) { CodeMirror.off = off; CodeMirror.on = on; CodeMirror.wheelEventPixels = wheelEventPixels; CodeMirror.Doc = Doc; CodeMirror.splitLines = splitLinesAuto; CodeMirror.countColumn = countColumn; CodeMirror.findColumn = findColumn; CodeMirror.isWordChar = isWordCharBasic; CodeMirror.Pass = Pass; CodeMirror.signal = signal; CodeMirror.Line = Line; CodeMirror.changeEnd = changeEnd; CodeMirror.scrollbarModel = scrollbarModel; CodeMirror.Pos = Pos; CodeMirror.cmpPos = cmp; CodeMirror.modes = modes; CodeMirror.mimeModes = mimeModes; CodeMirror.resolveMode = resolveMode; CodeMirror.getMode = getMode; CodeMirror.modeExtensions = modeExtensions; CodeMirror.extendMode = extendMode; CodeMirror.copyState = copyState; CodeMirror.startState = startState; CodeMirror.innerMode = innerMode; CodeMirror.commands = commands; CodeMirror.keyMap = keyMap; CodeMirror.keyName = keyName; CodeMirror.isModifierKey = isModifierKey; CodeMirror.lookupKey = lookupKey; CodeMirror.normalizeKeyMap = normalizeKeyMap; CodeMirror.StringStream = StringStream; CodeMirror.SharedTextMarker = SharedTextMarker; CodeMirror.TextMarker = TextMarker; CodeMirror.LineWidget = LineWidget; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; CodeMirror.e_stop = e_stop; CodeMirror.addClass = addClass; CodeMirror.contains = contains; CodeMirror.rmClass = rmClass; CodeMirror.keyNames = keyNames; } // EDITOR CONSTRUCTOR defineOptions(CodeMirror); addEditorMethods(CodeMirror); // Set up methods on CodeMirror's prototype to redirect to the editor's document. var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments)} })(Doc.prototype[prop]); } } eventMixin(Doc); CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name/*, mode, …*/) { if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } defineMode.apply(this, arguments); }; CodeMirror.defineMIME = defineMIME; // Minimal default mode. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); CodeMirror.defineMIME("text/plain", "null"); // EXTENSIONS CodeMirror.defineExtension = function (name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function (name, func) { Doc.prototype[name] = func; }; CodeMirror.fromTextArea = fromTextArea; addLegacyProps(CodeMirror); CodeMirror.version = "5.48.4"; return CodeMirror; }))); ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/dracula.css ================================================ /* Name: dracula Author: Michael Kaminsky (http://github.com/mkaminsky11) Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme) */ .cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters { background-color: #282a36 !important; color: #f8f8f2 !important; border: none; } .cm-s-dracula .CodeMirror-gutters { color: #282a36; } .cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; } .cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; } .cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula span.cm-comment { color: #6272a4; } .cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; } .cm-s-dracula span.cm-number { color: #bd93f9; } .cm-s-dracula span.cm-variable { color: #50fa7b; } .cm-s-dracula span.cm-variable-2 { color: white; } .cm-s-dracula span.cm-def { color: #50fa7b; } .cm-s-dracula span.cm-operator { color: #ff79c6; } .cm-s-dracula span.cm-keyword { color: #ff79c6; } .cm-s-dracula span.cm-atom { color: #bd93f9; } .cm-s-dracula span.cm-meta { color: #f8f8f2; } .cm-s-dracula span.cm-tag { color: #ff79c6; } .cm-s-dracula span.cm-attribute { color: #50fa7b; } .cm-s-dracula span.cm-qualifier { color: #50fa7b; } .cm-s-dracula span.cm-property { color: #66d9ef; } .cm-s-dracula span.cm-builtin { color: #50fa7b; } .cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; } .cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); } .cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/idea.css ================================================ /** Name: IDEA default theme From IntelliJ IDEA by JetBrains */ .cm-s-idea span.cm-meta { color: #808000; } .cm-s-idea span.cm-number { color: #0000FF; } .cm-s-idea span.cm-keyword { line-height: 1em; font-weight: bold; color: #000080; } .cm-s-idea span.cm-atom { font-weight: bold; color: #000080; } .cm-s-idea span.cm-def { color: #000000; } .cm-s-idea span.cm-variable { color: black; } .cm-s-idea span.cm-variable-2 { color: black; } .cm-s-idea span.cm-variable-3, .cm-s-idea span.cm-type { color: black; } .cm-s-idea span.cm-property { color: black; } .cm-s-idea span.cm-operator { color: black; } .cm-s-idea span.cm-comment { color: #808080; } .cm-s-idea span.cm-string { color: #008000; } .cm-s-idea span.cm-string-2 { color: #008000; } .cm-s-idea span.cm-qualifier { color: #555; } .cm-s-idea span.cm-error { color: #FF0000; } .cm-s-idea span.cm-attribute { color: #0000FF; } .cm-s-idea span.cm-tag { color: #000080; } .cm-s-idea span.cm-link { color: #0000FF; } .cm-s-idea .CodeMirror-activeline-background { background: #FFFAE3; } .cm-s-idea span.cm-builtin { color: #30a; } .cm-s-idea span.cm-bracket { color: #cc7; } .cm-s-idea { font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;} .cm-s-idea .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } .CodeMirror-hints.idea { font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; color: #616569; background-color: #ebf3fd !important; } .CodeMirror-hints.idea .CodeMirror-hint-active { background-color: #a2b8c9 !important; color: #5c6065 !important; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/javascript.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, "await": C }; }(); var isOperatorChar = /[+\-*&%=<>!?|~^@]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (expressionAllowed(stream, state, 1)) { readRegexp(stream); stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eat("="); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) { stream.skipToEnd() return ret("comment", "comment") } else if (isOperatorChar.test(ch)) { if (ch != ">" || !state.lexical || state.lexical.type != ">") { if (stream.eat("=")) { if (ch == "!" || ch == "=") stream.eat("=") } else if (/[<>*+\-]/.test(ch)) { stream.eat(ch) if (ch == ">") stream.eat(ch) } } return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current() if (state.lastType != ".") { if (keywords.propertyIsEnumerable(word)) { var kw = keywords[word] return ret(kw.type, kw.style, word) } if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word) } return ret("variable", "variable", word) } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; if (isTS) { // Try to skip TypeScript return type declarations after the arguments var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) if (m) arrow = m.index } var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/`]/.test(ch)) { for (;; --pos) { if (pos == 0) return var next = stream.string.charAt(pos - 1) if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } } } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function inList(name, list) { for (var v = list; v; v = v.next) if (v.name == name) return true return false; } function register(varname) { var state = cx.state; cx.marked = "def"; if (state.context) { if (state.lexical.info == "var" && state.context && state.context.block) { // FIXME function decls are also not block scoped var newContext = registerVarScoped(varname, state.context) if (newContext != null) { state.context = newContext return } } else if (!inList(varname, state.localVars)) { state.localVars = new Var(varname, state.localVars) return } } // Fall through means this is global if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars) } function registerVarScoped(varname, context) { if (!context) { return null } else if (context.block) { var inner = registerVarScoped(varname, context.prev) if (!inner) return null if (inner == context.prev) return context return new Context(inner, context.vars, true) } else if (inList(varname, context.vars)) { return context } else { return new Context(context.prev, new Var(varname, context.vars), false) } } function isModifier(name) { return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" } // Combinators function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } function Var(name, next) { this.name = name; this.next = next } var defaultVars = new Var("this", new Var("arguments", null)) function pushcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, false) cx.state.localVars = defaultVars } function pushblockcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, true) cx.state.localVars = null } function popcontext() { cx.state.localVars = cx.state.context.vars cx.state.context = cx.state.context.prev } popcontext.lex = true function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); if (type == "debugger") return cont(expect(";")); if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword" return cont(pushlex("form", type == "class" ? type : value), className, poplex) } if (type == "variable") { if (isTS && value == "declare") { cx.marked = "keyword" return cont(statement) } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { cx.marked = "keyword" if (value == "enum") return cont(enumdef); else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) } else if (isTS && value == "namespace") { cx.marked = "keyword" return cont(pushlex("form"), expression, statement, poplex) } else if (isTS && value == "abstract") { cx.marked = "keyword" return cont(statement) } else { return cont(pushlex("stat"), maybelabel); } } if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); if (type == "export") return cont(pushlex("stat"), afterExport, poplex); if (type == "import") return cont(pushlex("stat"), afterImport, poplex); if (type == "async") return cont(statement) if (value == "@") return cont(expression, statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function maybeCatchBinding(type) { if (type == "(") return cont(funarg, expect(")")) } function expression(type, value) { return expressionInner(type, value, false); } function expressionNoComma(type, value) { return expressionInner(type, value, true); } function parenExpr(type) { if (type != "(") return pass() return cont(pushlex(")"), expression, expect(")"), poplex) } function expressionInner(type, value, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") return pass(quasi, maybeop); if (type == "new") return cont(maybeTarget(noComma)); if (type == "import") return cont(expression); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperatorComma(type, value) { if (type == ",") return cont(maybeexpression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } if (type == "regexp") { cx.state.lastType = cx.marked = "operator" cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) return cont(expr) } } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybeTarget(noComma) { return function(type) { if (type == ".") return cont(noComma ? targetNoComma : target); else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) else return pass(noComma ? expressionNoComma : expression); }; } function target(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } } function targetNoComma(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "async") { cx.marked = "property"; return cont(objprop); } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (isTS && isModifier(value)) { cx.marked = "keyword" return cont(objprop) } else if (type == "[") { return cont(expression, maybetype, expect("]"), afterprop); } else if (type == "spread") { return cont(expressionNoComma, afterprop); } else if (value == "*") { cx.marked = "keyword"; return cont(objprop); } else if (type == ":") { return pass(afterprop) } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end, sep) { function proceed(type, value) { if (sep ? sep.indexOf(type) > -1 : type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(function(type, value) { if (type == end || value == end) return pass() return pass(what) }, proceed); } if (type == end || value == end) return cont(); if (sep && sep.indexOf(";") > -1) return pass(what) return cont(expect(end)); } return function(type, value) { if (type == end || value == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type, value) { if (isTS) { if (type == ":") return cont(typeexpr); if (value == "?") return cont(maybetype); } } function maybetypeOrIn(type, value) { if (isTS && (type == ":" || value == "in")) return cont(typeexpr) } function mayberettype(type) { if (isTS && type == ":") { if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) else return cont(typeexpr) } } function isKW(_, value) { if (value == "is") { cx.marked = "keyword" return cont() } } function typeexpr(type, value) { if (value == "keyof" || value == "typeof" || value == "infer") { cx.marked = "keyword" return cont(value == "typeof" ? expressionNoComma : typeexpr) } if (type == "variable" || value == "void") { cx.marked = "type" return cont(afterType) } if (value == "|" || value == "&") return cont(typeexpr) if (type == "string" || type == "number" || type == "atom") return cont(afterType); if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) } function maybeReturnType(type) { if (type == "=>") return cont(typeexpr) } function typeprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property" return cont(typeprop) } else if (value == "?" || type == "number" || type == "string") { return cont(typeprop) } else if (type == ":") { return cont(typeexpr) } else if (type == "[") { return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) } else if (type == "(") { return pass(functiondecl, typeprop) } } function typearg(type, value) { if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) if (type == ":") return cont(typeexpr) if (type == "spread") return cont(typearg) return pass(typeexpr) } function afterType(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) if (value == "|" || type == "." || value == "&") return cont(typeexpr) if (type == "[") return cont(typeexpr, expect("]"), afterType) if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } if (value == "?") return cont(typeexpr, expect(":"), typeexpr) } function maybeTypeArgs(_, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) } function typeparam() { return pass(typeexpr, maybeTypeDefault) } function maybeTypeDefault(_, value) { if (value == "=") return cont(typeexpr) } function vardef(_, value) { if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } if (type == "variable") { register(value); return cont(); } if (type == "spread") return cont(pattern); if (type == "[") return contCommasep(eltpattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; if (type == "spread") return cont(pattern); if (type == "}") return pass(); if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); return cont(expect(":"), pattern, maybeAssign); } function eltpattern() { return pass(pattern, maybeAssign) } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type, value) { if (value == "await") return cont(forspec); if (type == "(") return cont(pushlex(")"), forspec1, poplex); } function forspec1(type) { if (type == "var") return cont(vardef, forspec2); if (type == "variable") return cont(forspec2); return pass(forspec2) } function forspec2(type, value) { if (type == ")") return cont() if (type == ";") return cont(forspec2) if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } return pass(expression, forspec2) } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) } function functiondecl(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} if (type == "variable") {register(value); return cont(functiondecl);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) } function typename(type, value) { if (type == "keyword" || type == "variable") { cx.marked = "type" return cont(typename) } else if (value == "<") { return cont(pushlex(">"), commasep(typeparam, ">"), poplex) } } function funarg(type, value) { if (value == "@") cont(expression, funarg) if (type == "spread") return cont(funarg); if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } if (isTS && type == "this") return cont(maybetype, maybeAssign) return pass(pattern, maybetype, maybeAssign); } function classExpression(type, value) { // Class expressions may have an optional name. if (type == "variable") return className(type, value); return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) if (value == "extends" || value == "implements" || (isTS && type == ",")) { if (value == "implements") cx.marked = "keyword"; return cont(isTS ? typeexpr : expression, classNameAfter); } if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "async" || (type == "variable" && (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { cx.marked = "keyword"; return cont(classBody); } if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; return cont(isTS ? classfield : functiondef, classBody); } if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody); if (type == "[") return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (isTS && type == "(") return pass(functiondecl, classBody) if (type == ";" || type == ",") return cont(classBody); if (type == "}") return cont(); if (value == "@") return cont(expression, classBody) } function classfield(type, value) { if (value == "?") return cont(classfield) if (type == ":") return cont(typeexpr, maybeAssign) if (value == "=") return cont(expressionNoComma) var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" return pass(isInterface ? functiondecl : functiondef) } function afterExport(type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); return pass(statement); } function exportField(type, value) { if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } if (type == "variable") return pass(expressionNoComma, exportField); } function afterImport(type) { if (type == "string") return cont(); if (type == "(") return pass(expression); return pass(importSpec, maybeMoreImports, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); if (value == "*") cx.marked = "keyword"; return cont(maybeAs); } function maybeMoreImports(type) { if (type == ",") return cont(importSpec, maybeMoreImports) } function maybeAs(_type, value) { if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(commasep(expressionNoComma, "]")); } function enumdef() { return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) } function enummember() { return pass(pattern, maybeAssign); } function isContinuedStatement(state, textAfter) { return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); } function expressionAllowed(stream, state, backUp) { return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && new Context(null, null, false), indented: basecolumn || 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter)))) lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", blockCommentContinue: jsonMode ? null : " * ", lineComment: jsonMode ? null : "//", fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode, expressionAllowed: expressionAllowed, skipExpression: function(state) { var top = state.cc[state.cc.length - 1] if (top == expression || top == expressionNoComma) state.cc.pop() } }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); }); ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/placeholder.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { CodeMirror.defineOption("placeholder", "", function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { cm.on("blur", onBlur); cm.on("change", onChange); cm.on("swapDoc", onChange); onChange(cm); } else if (!val && prev) { cm.off("blur", onBlur); cm.off("change", onChange); cm.off("swapDoc", onChange); clearPlaceholder(cm); var wrapper = cm.getWrapperElement(); wrapper.className = wrapper.className.replace(" CodeMirror-empty", ""); } if (val && !cm.hasFocus()) onBlur(cm); }); function clearPlaceholder(cm) { if (cm.state.placeholder) { cm.state.placeholder.parentNode.removeChild(cm.state.placeholder); cm.state.placeholder = null; } } function setPlaceholder(cm) { clearPlaceholder(cm); var elt = cm.state.placeholder = document.createElement("pre"); elt.style.cssText = "height: 0; overflow: visible"; elt.style.direction = cm.getOption("direction"); elt.className = "CodeMirror-placeholder CodeMirror-line-like"; var placeHolder = cm.getOption("placeholder") if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder) elt.appendChild(placeHolder) cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild); } function onBlur(cm) { if (isEmpty(cm)) setPlaceholder(cm); } function onChange(cm) { var wrapper = cm.getWrapperElement(), empty = isEmpty(cm); wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : ""); if (empty) setPlaceholder(cm); else clearPlaceholder(cm); } function isEmpty(cm) { return (cm.lineCount() === 1) && (cm.getLine(0) === ""); } }); ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/show-hint.css ================================================ .CodeMirror-hints { position: absolute; z-index: 214483647; /*overflow: hidden;*/ list-style: none; margin: 0; padding: 2px; -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); box-shadow: 2px 3px 5px rgba(0,0,0,.2); border-radius: 3px; border: 1px solid silver; background: white; font-size: 90%; font-family: monospace; max-height: 20em; overflow-y: auto; } .CodeMirror-hint { margin: 0; padding: 0 4px; border-radius: 2px; /*white-space: pre;*/ color: black; cursor: pointer; } li.CodeMirror-hint-active { background: #08f; color: white; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/show-hint.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var HINT_ELEMENT_CLASS = "CodeMirror-hint"; var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; // This is the old interface, kept around for now to stay // backwards-compatible. CodeMirror.showHint = function(cm, getHints, options) { if (!getHints) return cm.showHint(options); if (options && options.async) getHints.async = true; var newOpts = {hint: getHints}; if (options) for (var prop in options) newOpts[prop] = options[prop]; return cm.showHint(newOpts); }; CodeMirror.defineExtension("showHint", function(options) { options = parseOptions(this, this.getCursor("start"), options); var selections = this.listSelections() if (selections.length > 1) return; // By default, don't allow completion when something is selected. // A hint function can have a `supportsSelection` property to // indicate that it can handle selections. if (this.somethingSelected()) { if (!options.hint.supportsSelection) return; // Don't try with cross-line selections for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; } if (this.state.completionActive) this.state.completionActive.close(); var completion = this.state.completionActive = new Completion(this, options); if (!completion.options.hint) return; CodeMirror.signal(this, "startCompletion", this); completion.update(true); }); CodeMirror.defineExtension("showHint1", function(options,datas) { options = parseOptions(this, this.getCursor("start"), options); var selections = this.listSelections() if (selections.length > 1) return; // By default, don't allow completion when something is selected. // A hint function can have a `supportsSelection` property to // indicate that it can handle selections. if (this.somethingSelected()) { if (!options.hint.supportsSelection) return; // Don't try with cross-line selections for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; } if (this.state.completionActive) this.state.completionActive.close(); var completion = this.state.completionActive = new Completion(this, options); if (!completion.options.hint) return; CodeMirror.signal(this, "startCompletion", this); completion.update1(true,datas); }); function Completion(cm, options) { this.cm = cm; this.options = options; this.widget = null; this.comments = this.options.comments; //this.widget1 = null; this.debounce = 0; this.tick = 0; this.startPos = this.cm.getCursor("start"); this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; var self = this; cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); }); } var requestAnimationFrame = window.requestAnimationFrame || function(fn) { return setTimeout(fn, 1000/60); }; var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; Completion.prototype = { close: function() { if (!this.active()) return; this.cm.state.completionActive = null; this.tick = null; this.cm.off("cursorActivity", this.activityFunc); if (this.widget && this.data) CodeMirror.signal(this.data, "close"); if (this.widget) { this.widget.close(); } CodeMirror.signal(this.cm, "endCompletion", this.cm); }, active: function() { return this.cm.state.completionActive == this; }, pick: function(data, i) { var completion = data.list[i]; if (completion.hint) completion.hint(this.cm, data, completion); else this.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); CodeMirror.signal(data, "pick", completion); this.close(); }, cursorActivity: function() { if (this.debounce) { cancelAnimationFrame(this.debounce); this.debounce = 0; } var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line); if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < this.startPos.ch || this.cm.somethingSelected() || (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) { this.close(); } else { var self = this; this.debounce = requestAnimationFrame(function() {self.update();}); if (this.widget) { this.widget.disable(); } } }, update: function(first) { if (this.tick == null) return; if (!this.options.hint.async) { this.finishUpdate(this.options.hint(this.cm, this.options), first); } else { var myTick = ++this.tick, self = this; this.options.hint(this.cm, function(data) { if (self.tick == myTick) self.finishUpdate(data, first); }, this.options); } }, update1: function(first,datas) { if (this.tick == null) return; if (!this.options.hint.async) { // //datas = JSON.parse(datas); this.finishUpdate1(datas, first); } else { var myTick = ++this.tick, self = this; this.options.hint(this.cm, function(data) { if (self.tick == myTick) self.finishUpdate(data, first); }, this.options); } }, finishUpdate1: function(data, first) { if (this.data) { CodeMirror.signal(this.data, "update"); } var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); if (this.widget) { this.widget.close(); } if (data && this.data && isNewCompletion(this.data, data)) { return; } this.data = data; if (data && data.list.length) { if (picked && data.list.length == 1) { this.pick(data, 0); } else { this.widget = new Widget1(this, data,this.comments); CodeMirror.signal(data, "shown"); } } }, finishUpdate: function(data, first) { if (this.data) { CodeMirror.signal(this.data, "update"); } var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); if (this.widget) { this.widget.close(); } if (data && this.data && isNewCompletion(this.data, data)) { return; } this.data = data; if (data && data.list.length) { if (picked && data.list.length == 1) { this.pick(data, 0); } else { this.widget = new Widget(this, data); CodeMirror.signal(data, "shown"); } } } }; function isNewCompletion(old, nw) { var moved = CodeMirror.cmpPos(nw.from, old.from) return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch } function parseOptions(cm, pos, options) { var editor = cm.options.hintOptions; var out = {}; for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; if (editor) for (var prop in editor) if (editor[prop] !== undefined) out[prop] = editor[prop]; if (options) for (var prop in options) if (options[prop] !== undefined) out[prop] = options[prop]; if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos) return out; } function getText(completion) { if (typeof completion == "string") return completion; else return completion.text; } function buildKeyMap(completion, handle) { var baseMap = { Up: function() {handle.moveFocus(-1);}, Down: function() {handle.moveFocus(1);}, PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);}, PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);}, Home: function() {handle.setFocus(0);}, End: function() {handle.setFocus(handle.length - 1);}, Enter: handle.pick, Tab: handle.pick, Esc: handle.close }; var custom = completion.options.customKeys; var ourMap = custom ? {} : baseMap; function addBinding(key, val) { var bound; if (typeof val != "string") bound = function(cm) { return val(cm, handle); }; // This mechanism is deprecated else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; else bound = val; ourMap[key] = bound; } if (custom) for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); var extra = completion.options.extraKeys; if (extra) for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); return ourMap; } function getHintElement(hintsElement, el) { while (el && el != hintsElement) { if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; el = el.parentNode; } } function Widget1(completion, data,comments) { this.completion = completion; this.data = data; this.comments = comments; this.picked = false; var widget = this, cm = completion.cm; var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var hints = this.hints = document.createElement("ul"); var hints2 = this.hints2 = document.createElement("ul"); //文档说明提示框 var completions = data.list; hints.className = "CodeMirror-hints"; this.selectedHint = data.selectedHint || 0; var completions = data.list; for (var i = 0; i < completions.length; ++i) { var cur = completions[i]; if(!cur){ continue; } var elt = hints.appendChild(document.createElement("li")); var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); if (cur.className != null) className = cur.className + " " + className; elt.className = className; if (cur.render) cur.render(elt, data, cur); else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); elt.hintId = i; } var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); var left = pos.left, top = pos.bottom, below = true; hints.style.left = left + "px"; hints.style.top = top + "px"; // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. // var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); (completion.options.container || document.body).appendChild(hints); var hintsWidth = 0; var box = hints.getBoundingClientRect(); var overlapY = box.bottom - winH; if (overlapY > 0) { var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); if (curTop - height > 0) { // Fits above cursor hints.style.top = (top = pos.top - height) + "px"; hints2.style.top = (top = pos.top - height) + "px"; below = false; } else if (height > winH) { hints.style.height = (winH - 5) + "px"; hints.style.top = (top = pos.bottom - box.top) + "px"; hints2.style.top = (top = pos.bottom - box.top) + "px"; var cursor = cm.getCursor(); if (data.from.ch != cursor.ch) { pos = cm.cursorCoords(cursor); hints.style.left = (left = pos.left) + "px"; box = hints.getBoundingClientRect(); } } } hintsWidth = box.width; var overlapX = box.right - winW; if (overlapX > 0) { if (box.right - box.left > winW) { hints.style.width = (winW - 5) + "px"; overlapX -= (box.right - box.left) - winW; hintsWidth = minW - 5; } hints.style.left = (left = pos.left - overlapX) + "px"; } try{ hints2.className = "CodeMirror-hints"; var elt = hints2.appendChild(document.createElement("li")), cur = completions[0]; var key = data.key; var index = 0; if(typeof(key) != "undefined"){ var showList = data.showList; index = showList[0]; if (cur.render) cur.render(elt, data, cur); else elt.innerHTML = comments[key][index] || ''; elt.hintId = i; var left = hints.style.left; left = Number(left.substring(0,left.length-2)); var top = hints.style.top; top = Number(top.substring(0,top.length-2)); if(document.documentElement.clientWidth - left < 210){ left = left - 207; }else{ left = left + hintsWidth; } hints2.style.left = left + "px"; hints2.style.height = 200 + "px"; hints2.style.width = 200 + "px"; hints2.style.top = top + "px"; (completion.options.container || document.body).appendChild(hints2); } }catch(e) { } cm.addKeyMap(this.keyMap = buildKeyMap(completion, { moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, setFocus: function(n) { widget.changeActive(n); }, menuSize: function() { return widget.screenAmount(); }, length: completions.length, close: function() { completion.close(); }, pick: function() { widget.pick(); }, data: data })); if (completion.options.closeOnUnfocus) { var closingOnBlur; cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); } var startScroll = cm.getScrollInfo(); cm.on("scroll", this.onScroll = function() { var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); var newTop = top + startScroll.top - curScroll.top; var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); if (!below) point += hints.offsetHeight; if (point <= editor.top || point >= editor.bottom) return completion.close(); hints.style.top = newTop + "px"; hints.style.left = (left + startScroll.left - curScroll.left) + "px"; }); CodeMirror.on(hints, "dblclick", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} }); CodeMirror.on(hints, "click", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) { widget.changeActive(t.hintId); if (completion.options.completeOnSingleClick) widget.pick(); } }); CodeMirror.on(hints, "mousedown", function() { setTimeout(function(){cm.focus();}, 20); }); CodeMirror.signal(data, "select", completions[0], hints.firstChild); return true; } function Widget(completion, data) { this.completion = completion; this.data = data; this.picked = false; var widget = this, cm = completion.cm; var hints = this.hints = document.createElement("ul"); hints.className = "CodeMirror-hints"; this.selectedHint = data.selectedHint || 0; var completions = data.list; for (var i = 0; i < completions.length; ++i) { var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); if (cur.className != null) className = cur.className + " " + className; elt.className = className; if (cur.render) cur.render(elt, data, cur); else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); elt.hintId = i; } var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); var left = pos.left, top = pos.bottom, below = true; hints.style.left = left + "px"; hints.style.top = top + "px"; // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); (completion.options.container || document.body).appendChild(hints); var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; if (overlapY > 0) { var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); if (curTop - height > 0) { // Fits above cursor hints.style.top = (top = pos.top - height) + "px"; below = false; } else if (height > winH) { hints.style.height = (winH - 5) + "px"; hints.style.top = (top = pos.bottom - box.top) + "px"; var cursor = cm.getCursor(); if (data.from.ch != cursor.ch) { pos = cm.cursorCoords(cursor); hints.style.left = (left = pos.left) + "px"; box = hints.getBoundingClientRect(); } } } var overlapX = box.right - winW; if (overlapX > 0) { if (box.right - box.left > winW) { hints.style.width = (winW - 5) + "px"; overlapX -= (box.right - box.left) - winW; } hints.style.left = (left = pos.left - overlapX) + "px"; } cm.addKeyMap(this.keyMap = buildKeyMap(completion, { moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, setFocus: function(n) { widget.changeActive(n); }, menuSize: function() { return widget.screenAmount(); }, length: completions.length, close: function() { completion.close(); }, pick: function() { widget.pick(); }, data: data })); if (completion.options.closeOnUnfocus) { var closingOnBlur; cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); } var startScroll = cm.getScrollInfo(); cm.on("scroll", this.onScroll = function() { var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); var newTop = top + startScroll.top - curScroll.top; var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); if (!below) point += hints.offsetHeight; if (point <= editor.top || point >= editor.bottom) return completion.close(); hints.style.top = newTop + "px"; hints.style.left = (left + startScroll.left - curScroll.left) + "px"; }); CodeMirror.on(hints, "dblclick", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} }); CodeMirror.on(hints, "click", function(e) { var t = getHintElement(hints, e.target || e.srcElement); if (t && t.hintId != null) { widget.changeActive(t.hintId); if (completion.options.completeOnSingleClick) widget.pick(); } }); CodeMirror.on(hints, "mousedown", function() { setTimeout(function(){cm.focus();}, 20); }); CodeMirror.signal(data, "select", completions[0], hints.firstChild); return true; } Widget.prototype = { close: function() { if (this.completion.widget != this) return; this.completion.widget = null; this.hints.parentNode.removeChild(this.hints); try{ this.hints2.parentNode.removeChild(this.hints2);//此处消失 }catch(e){ } this.completion.cm.removeKeyMap(this.keyMap); var cm = this.completion.cm; if (this.completion.options.closeOnUnfocus) { cm.off("blur", this.onBlur); cm.off("focus", this.onFocus); } cm.off("scroll", this.onScroll); }, disable: function() { this.completion.cm.removeKeyMap(this.keyMap); var widget = this; this.keyMap = {Enter: function() { widget.picked = true; }}; this.completion.cm.addKeyMap(this.keyMap); }, pick: function() { this.completion.pick(this.data, this.selectedHint); }, changeActive: function(i, avoidWrap) { if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0; else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; if (node.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node.offsetTop - 3; else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, screenAmount: function() { return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; } }; Widget1.prototype = { close: function() { if (this.completion.widget != this) return; this.completion.widget = null; this.hints.parentNode.removeChild(this.hints); try{ this.hints2.parentNode.removeChild(this.hints2);//此处消失 }catch(e){ } this.completion.cm.removeKeyMap(this.keyMap); var cm = this.completion.cm; if (this.completion.options.closeOnUnfocus) { cm.off("blur", this.onBlur); cm.off("focus", this.onFocus); } cm.off("scroll", this.onScroll); }, disable: function() { this.completion.cm.removeKeyMap(this.keyMap); var widget = this; this.keyMap = {Enter: function() { widget.picked = true; }}; this.completion.cm.addKeyMap(this.keyMap); }, pick: function() { this.completion.pick(this.data, this.selectedHint); }, changeActive: function(i, avoidWrap) { if (i >= this.hints.childNodes.length) i = avoidWrap ? this.hints.childNodes.length - 1 : 0; else if (i < 0) i = avoidWrap ? 0 : this.hints.childNodes.length - 1; try{ this.hints2.innerHTML = ""; var key = this.data.key; var index = i; if(typeof(key) != "undefined"){ var showList = this.data.showList; index = showList[i]; var elt = this.hints2.appendChild(document.createElement("li")); elt.innerHTML = this.comments[key][index] || ''; } }catch(e){ } if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; //if(!node) return; node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); node = this.hints.childNodes[this.selectedHint = i]; //if(!node) return; node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; if (node.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node.offsetTop - 3; else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, screenAmount: function() { return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; } }; function applicableHelpers(cm, helpers) { if (!cm.somethingSelected()) return helpers var result = [] for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]) return result } function resolveAutoHints(cm, pos) { var helpers = cm.getHelpers(pos, "hint"), words if (helpers.length) { var async = false, resolved for (var i = 0; i < helpers.length; i++) if (helpers[i].async) async = true if (async) { resolved = function(cm, callback, options) { var app = applicableHelpers(cm, helpers) function run(i, result) { if (i == app.length) return callback(null) var helper = app[i] if (helper.async) { helper(cm, function(result) { if (result) callback(result) else run(i + 1) }, options) } else { var result = helper(cm, options) if (result) callback(result) else run(i + 1) } } run(0) } resolved.async = true } else { resolved = function(cm, options) { var app = applicableHelpers(cm, helpers) for (var i = 0; i < app.length; i++) { var cur = app[i](cm, options) if (cur && cur.list.length) return cur } } } resolved.supportsSelection = true return resolved } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) } } else if (CodeMirror.hint.anyword) { return function(cm, options) { return CodeMirror.hint.anyword(cm, options) } } else { return function() {} } } CodeMirror.registerHelper("hint", "auto", { resolve: resolveAutoHints }); CodeMirror.registerHelper("hint", "fromList", function(cm, options) { var cur = cm.getCursor(), token = cm.getTokenAt(cur); var to = CodeMirror.Pos(cur.line, token.end); if (token.string && /\w/.test(token.string[token.string.length - 1])) { var term = token.string, from = CodeMirror.Pos(cur.line, token.start); } else { var term = "", from = to; } var found = []; for (var i = 0; i < options.words.length; i++) { var word = options.words[i]; if (word.slice(0, term.length) == term) found.push(word); } if (found.length) return {list: found, from: from, to: to}; }); CodeMirror.commands.autocomplete = CodeMirror.showHint; var defaultOptions = { hint: CodeMirror.hint.auto, completeSingle: true, alignWithWord: true, closeCharacters: /[\s()\[\]{};:>,]/, closeOnUnfocus: true, completeOnSingleClick: true, container: null, customKeys: null, extraKeys: null }; CodeMirror.defineOption("hintOptions", null); }); ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/spiderflow-hint.js ================================================ var grammers = []; $.ajax({ url : 'spider/grammers', type : 'post', dataType : 'json', success : function(json){ if(json.code == 1){ grammers = json.data; for(var i =0,len = grammers.length;i 3&&grammer.method.indexOf("get") == 0){ grammer.method = grammer.method.substring(3,4).toLowerCase() + grammer.method.substring(4); }else if(grammer&&grammer.method){ grammer.method = grammer.method + '()'; } } } grammers = grammers || []; } }) function searchGrammer(keyword,isClass){ var list1 = []; var list2 = {}; for(var i =0,len = grammers.length;i -1))){ list1.push(grammer.method); list2[grammer.method] = list2[grammer.method] || []; list2[grammer.method].push(grammer); }else if(keyword == null || (grammer['function']&&grammer['function'].indexOf(keyword) > -1)){ if(grammer['function']&&grammer.method == null){ list1.push(grammer['function']); list2[grammer['function']] = list2[grammer['function']] || []; list2[grammer['function']][0] = {owner:grammer.owner,comment : grammer.comment}; } } } list1 = list1.sort(); var set = []; if(list1.length > 0){ set.push(list1[0]); } for (var i=1, len=list1.length; i'; } if(grammer.comment){ html+= '
说明:'+grammer.comment.replace('<','<')+'
'; } if(grammer.example){ html+= '
'+grammer.example.replace('<','<')+'
'; } if(grammer.returns){ html+= '
返回值:'+grammer.returns.join("/").replace('<','<')+'
'; } html+= ''; } list2[key] = html; } return [set,list2]; } function initHint(cm){ cm.on('keyup',function(cm,e){ if(e.keyCode ==38 || e.keyCode ==40 || e.keyCode == 13){ return; } var cur = cm.getCursor(); var ch = cur.ch; var token = cm.getTokenAt(cur); var curLine = cm.getLine(cur.line); var str1 = curLine.charAt(cur.ch - 1); var str2 = curLine.charAt(cur.ch - 2); if((str1=='{' &&str2=='$')){ var ret = searchGrammer(null,true); var datas = {}; datas.list = ret[0]; datas.from = {}; datas.from.line = cur.line; datas.from.ch = ch; datas.to = {}; datas.to.line = cur.line; datas.to.ch = ch; datas.showList = ret[0]; datas.key = '.'; cm.showHint1({completeSingle: false,comments : {'.':ret[1]}},datas); }if(str1 == '.'){ var ret = searchGrammer(null); var datas = {}; datas.list = ret[0]; datas.from = {}; datas.from.line = cur.line; datas.from.ch = ch; datas.to = {}; datas.to.line = cur.line; datas.to.ch = ch; datas.showList = ret[0]; datas.key = '.'; cm.showHint1({completeSingle: false,comments : {'.':ret[1]}},datas); }else{ var regx = /(\w+)$/g; var line = curLine.substring(0,cur.ch); var keyword = regx.exec(line); if(keyword&&keyword[1]){ keyword = keyword[1]; var ret = searchGrammer(keyword); var datas = {}; datas.list = ret[0]; datas.from = {}; datas.from.line = cur.line; datas.from.ch = token.start; datas.to = {}; datas.to.line = cur.line; datas.to.ch = token.end; datas.showList = ret[0]; datas.key = keyword; var comments = {}; comments[keyword] = ret[1]; cm.showHint1({completeSingle: false,comments : comments},datas); } } }) } ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/spiderflow.js ================================================ /** * freemarker */ (function(mod) { if (typeof exports == "object" && typeof module == "object" ) // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd ) // AMD define([ "../../lib/codemirror" ], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("spiderflow", function(config) { "use strict"; // our default settings; check to see if they're overridden var settings = { leftDelimiter : '<', rightDelimiter : '>', tagSyntax : 1 // 1 angle_bracket,2 square_bracket }; if (config.hasOwnProperty("tagSyntax") ) { if (config.tagSyntax === 2 ) { settings.tagSyntax = 2; settings.leftDelimiter = '['; settings.rightDelimiter = ']'; } } var keyFunctions = [ "assign", "attempt", "autoesc", "break", "case", "compress", "default", "else", "elseif", "escape", "fallback", "function", "flush", "ftl", "global", "if", "import", "include", "items", "list", "local", "lt", "macro", "nested","noautoesc", "noescape", "noparse", "nt","outputformat", "recover", "recurse", "return", "rt", "sep", "setting", "stop", "switch", "t", "visit" ]; var specialVariables = [ "auto_esc" , "current_template_name", "data_model", "error", "globals", "lang", "locale", "locale_object", "locals", "main", "main_template_name", "namespace", "node", "now", "output_encoding " , "output_format" , "template_name", "url_escaping_charset", "vars", "version" ]; var freemarkerStartTagArray = [ "#", "@" ]; var freemarkerEndTagArray = [ "/#", "/@", "/>" ]; var last; var freemarkerMode; var regs = { operatorChars : /[+\-*&%=<>!?:;,|&]/, validIdentifier : /[a-zA-Z0-9_]/, stringChar : /['"]/ }; var helpers = { cont : function(style, lastType, lastFreemarkerMode) { last = lastType; freemarkerMode = lastFreemarkerMode; return style; }, chain : function(stream, state, parser) { state.tokenize = parser; return parser(stream, state); } }; // our various parsers var parsers = { // the main tokenizer tokenizer : function(stream, state) { if (stream.match(settings.leftDelimiter, true) ) { if (stream.match("#--", true) ) { return helpers.chain(stream, state, parsers.inBlock("comment", "--" + settings.rightDelimiter)); } else { for (var i = 0; i < freemarkerStartTagArray.length; i++) { if (stream.match(freemarkerStartTagArray[i], false) ) { state.tokenize = parsers.freemarkerTemplate; if (freemarkerStartTagArray[i] == "@" ) { freemarkerMode = "macro"; } else { freemarkerMode = "tag"; } last = "startTag"; return "tag"; } } for (var i = 0; i < freemarkerEndTagArray.length; i++) { if (stream.match(freemarkerEndTagArray[i], false) ) { state.tokenize = parsers.freemarkerTemplate; if (freemarkerEndTagArray[i] == "/@" ) { freemarkerMode = "macro"; } else { freemarkerMode = "tag"; } last = "endTag"; return "tag"; } } } } else if (stream.match("${", false) ) { state.tokenize = parsers.freemarkerTemplate; last = "startTag"; freemarkerMode = "echo"; return "keyword"; } stream.next(); return null; }, // parsing freemarker content freemarkerTemplate : function(stream, state) { if (stream.match(settings.rightDelimiter, true) ) { state.depth--; if (state.depth <= 0 ) { state.tokenize = parsers.tokenizer; } return helpers.cont("tag", null, null); } else if ("echo" == state.freemarkerMode && stream.match("}", true) ) { state.depth--; if (state.depth <= 0 ) { state.tokenize = parsers.tokenizer; } return helpers.cont("keyword", null, null); } if (stream.match(settings.leftDelimiter, true) ) { for (var i = 0; i < freemarkerStartTagArray.length; i++) { if (stream.match(freemarkerStartTagArray[i], false) ) { state.depth++; if (freemarkerStartTagArray[i] == "@" ) { return helpers.cont("tag", "startTag", "macro"); } else { return helpers.cont("tag", "startTag", "tag"); } } } for (var i = 0; i < freemarkerEndTagArray.length; i++) { if (stream.match(freemarkerEndTagArray[i], false) ) { state.depth++; if (freemarkerEndTagArray[i] == "/@" ) { return helpers.cont("tag", "endTag", "macro"); } else { return helpers.cont("tag", "endTag", "tag"); } } } } else if (stream.match("${", true) ) { state.depth++; return helpers.cont("keyword", "startTag", "echo"); } var ch = stream.next(); if ("." == ch ) { if("echo" == state.freemarkerMode || "whitespace" == state.last ||"operator"== state.last){ for (var i = 0; i < specialVariables.length; i++) { if(stream.match(specialVariables[i],true)){ return helpers.cont("keyword", "variable", state.freemarkerMode); } } } if("keyword"==state.last && stream.eatWhile(regs.validIdentifier)){ return helpers.cont("keyword", null, state.freemarkerMode); }else{ return helpers.cont("operator", "childVariable", state.freemarkerMode); } } else if (regs.stringChar.test(ch) ) { state.tokenize = parsers.inAttribute(ch); return helpers.cont("string", "string", state.freemarkerMode); } else if (regs.operatorChars.test(ch) ) { if ("?" === ch ) { return helpers.cont("operator", "builtin", state.freemarkerMode); } else { return helpers.cont("operator", "operator", state.freemarkerMode); } } else if ("[" == ch || "{" == ch|| "(" == ch ) { return helpers.cont("bracket", "bracket", state.freemarkerMode); } else if ("]" == ch || "}" == ch || ")" == ch ) { return helpers.cont("bracket", "variable", state.freemarkerMode); } else if ("/" == ch ) { return helpers.cont("tag", "endTag", state.freemarkerMode); } else if ("@" == ch && "macro" == state.freemarkerMode ) { stream.eatWhile(regs.validIdentifier) return helpers.cont("keyword", "keyword", state.freemarkerMode); } else if (/\d/.test(ch) ) { stream.eat(/x/i) stream.eatWhile(/\d/); return helpers.cont("number", "number", state.freemarkerMode); } else if("tag" == state.freemarkerMode && "whitespace" == state.last && (stream.match("as",true) || stream.match("in",true)|| stream.match("using",true) )) { return helpers.cont("keyword", "operator", state.freemarkerMode); } else if("tag" == state.freemarkerMode && "whitespace" == state.last && (stream.match("gte",true) || stream.match("lte",true) || stream.match("gt",true) || stream.match("lt",true) )) { return helpers.cont("operator", "operator", state.freemarkerMode); } else { if ("builtin" == state.last ) { stream.eat("?"); stream.eatWhile(regs.validIdentifier); return helpers.cont("builtin", "variable", state.freemarkerMode); } else if ("whitespace" == state.last||"bracket" == state.last) { if ("macro" == state.freemarkerMode ) { stream.eatWhile(regs.validIdentifier); return helpers.cont("attribute", "attribute", state.freemarkerMode); } else { stream.eatWhile(regs.validIdentifier); return helpers.cont("variable-2", "variable", state.freemarkerMode); } } else if ("operator" == state.last ) { stream.eatWhile(regs.validIdentifier); return helpers.cont("variable-2", "variable", state.freemarkerMode); } else if ("childVariable" == state.last ) { stream.eatWhile(regs.validIdentifier); return helpers.cont("variable-3", "variable", state.freemarkerMode); } else if (/\s/.test(ch) ) { last = "whitespace"; return null; } else if ("string" == state.last ) { stream.eatWhile(regs.validIdentifier); return helpers.cont("attribute", "attribute", state.freemarkerMode); } else { if ("startTag" == state.last || "endTag" == state.last ) { if ("echo" == state.freemarkerMode ) { stream.eatWhile(regs.validIdentifier) return helpers.cont("variable-2", "variable", state.freemarkerMode); } } if ("tag" == state.freemarkerMode ) { var str = ""; if (ch != "/" ) { str += ch; } var c = null; while (c = stream.eat(regs.validIdentifier)) { str += c; } for (var i = 0 ; i < keyFunctions.length; i++) { if ("#"+keyFunctions[i] == str ) { return helpers.cont("keyword", "keyword", state.freemarkerMode); } } } } return helpers.cont("error", "tag", state.freemarkerMode); } }, inAttribute : function(quote) { return function(stream, state) { var prevChar = null; var currChar = null; while (!stream.eol()) { currChar = stream.peek(); if (stream.next() == quote && '\\' !== prevChar ) { state.tokenize = parsers.freemarkerTemplate; break; } prevChar = currChar; } return "string"; }; }, inBlock : function(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator) ) { state.tokenize = parsers.tokenizer; break; } stream.next(); } return style; }; } }; // the public API for CodeMirror return { startState : function() { return { tokenize : parsers.tokenizer, mode : "freemarker", last : null, freemarkerMode : null, depth : 0 }; }, token : function(stream, state) { state.last = last; state.freemarkerMode = freemarkerMode; return state.tokenize(stream, state); }, electricChars : "" }; }); CodeMirror.defineMIME("text/spiderflow", "spiderflow"); }); ================================================ FILE: spider-flow-web/src/main/resources/static/js/codemirror/sql.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sql", function(config, parserConfig) { var client = parserConfig.client || {}, atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, builtin = parserConfig.builtin || set(defaultBuiltin), keywords = parserConfig.keywords || set(sqlKeywords), operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^\/]/, support = parserConfig.support || {}, hooks = parserConfig.hooks || {}, dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}, backslashStringEscapes = parserConfig.backslashStringEscapes !== false, brackets = parserConfig.brackets || /^[\{}\(\)\[\]]/, punctuation = parserConfig.punctuation || /^[;.,:]/ function tokenBase(stream, state) { var ch = stream.next(); // call hooks from the mime type if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { // hex // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html return "number"; } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { // bitstring // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html return "number"; } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { // numbers // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); support.decimallessFloat && stream.match(/^\.(?!\.)/); return "number"; } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { // placeholders return "variable-3"; } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { // strings // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if ((((support.nCharCast && (ch == "n" || ch == "N")) || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) && (stream.peek() == "'" || stream.peek() == '"'))) { // charset casting: _utf8'str', N'str', n'str' // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html return "keyword"; } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { // 1-line comment stream.skipToEnd(); return "comment"; } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { // 1-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ stream.skipToEnd(); return "comment"; } else if (ch == "/" && stream.eat("*")) { // multi-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ state.tokenize = tokenComment(1); return state.tokenize(stream, state); } else if (ch == ".") { // .1 for 0.1 if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) return "number"; if (stream.match(/^\.+/)) return null // .table_name (ODBC) // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) return "variable-2"; } else if (operatorChars.test(ch)) { // operators stream.eatWhile(operatorChars); return "operator"; } else if (brackets.test(ch)) { // brackets return "bracket"; } else if (punctuation.test(ch)) { // punctuation stream.eatWhile(punctuation); return "punctuation"; } else if (ch == '{' && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { // dates (weird ODBC syntax) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html return "number"; } else { stream.eatWhile(/^[_\w\d]/); var word = stream.current().toLowerCase(); // dates (standard SQL syntax) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) return "number"; if (atoms.hasOwnProperty(word)) return "atom"; if (builtin.hasOwnProperty(word)) return "builtin"; if (keywords.hasOwnProperty(word)) return "keyword"; if (client.hasOwnProperty(word)) return "string-2"; return null; } } // 'string', with char specified in quote escaped by '\' function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = backslashStringEscapes && !escaped && ch == "\\"; } return "string"; }; } function tokenComment(depth) { return function(stream, state) { var m = stream.match(/^.*?(\/\*|\*\/)/) if (!m) stream.skipToEnd() else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1) else if (depth > 1) state.tokenize = tokenComment(depth - 1) else state.tokenize = tokenBase return "comment" } } function pushContext(stream, state, type) { state.context = { prev: state.context, indent: stream.indentation(), col: stream.column(), type: type }; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; } if (state.tokenize == tokenBase && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style == "comment") return style; if (state.context && state.context.align == null) state.context.align = true; var tok = stream.current(); if (tok == "(") pushContext(stream, state, ")"); else if (tok == "[") pushContext(stream, state, "]"); else if (state.context && state.context.type == tok) popContext(state); return style; }, indent: function(state, textAfter) { var cx = state.context; if (!cx) return CodeMirror.Pass; var closing = textAfter.charAt(0) == cx.type; if (cx.align) return cx.col + (closing ? 0 : 1); else return cx.indent + (closing ? 0 : config.indentUnit); }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--", closeBrackets: "()[]{}''\"\"``" }; }); // `identifier` function hookIdentifier(stream) { // MySQL/MariaDB identifiers // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html var ch; while ((ch = stream.next()) != null) { if (ch == "`" && !stream.eat("`")) return "variable-2"; } stream.backUp(stream.current().length - 1); return stream.eatWhile(/\w/) ? "variable-2" : null; } // "identifier" function hookIdentifierDoublequote(stream) { // Standard SQL /SQLite identifiers // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier // ref: http://sqlite.org/lang_keywords.html var ch; while ((ch = stream.next()) != null) { if (ch == "\"" && !stream.eat("\"")) return "variable-2"; } stream.backUp(stream.current().length - 1); return stream.eatWhile(/\w/) ? "variable-2" : null; } // variable token function hookVar(stream) { // variables // @@prefix.varName @varName // varName can be quoted with ` or ' or " // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html if (stream.eat("@")) { stream.match(/^session\./); stream.match(/^local\./); stream.match(/^global\./); } if (stream.eat("'")) { stream.match(/^.*'/); return "variable-2"; } else if (stream.eat('"')) { stream.match(/^.*"/); return "variable-2"; } else if (stream.eat("`")) { stream.match(/^.*`/); return "variable-2"; } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { return "variable-2"; } return null; }; // short client keyword token function hookClient(stream) { // \N means NULL // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html if (stream.eat("N")) { return "atom"; } // \g, etc // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; } // these keywords are used by all SQL dialects (however, a mode can still overwrite it) var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; // turn a space-separated list into an array function set(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var defaultBuiltin = "bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric" // A generic SQL Mode. It's not a standard, it just try to support what is generally supported CodeMirror.defineMIME("text/x-sql", { name: "sql", keywords: set(sqlKeywords + "begin"), builtin: set(defaultBuiltin), atoms: set("false true null unknown"), dateSQL: set("date time timestamp"), support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") }); CodeMirror.defineMIME("text/x-mssql", { name: "sql", client: set("$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id"), keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with"), builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "), atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"), operatorChars: /^[*+\-%<>!=^\&|\/]/, brackets: /^[\{}\(\)]/, punctuation: /^[;.,:/]/, backslashStringEscapes: false, dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"), hooks: { "@": hookVar } }); CodeMirror.defineMIME("text/x-mysql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); CodeMirror.defineMIME("text/x-mariadb", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); // provided by the phpLiteAdmin project - phpliteadmin.org CodeMirror.defineMIME("text/x-sqlite", { name: "sql", // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"), // ref: http://sqlite.org/lang_keywords.html keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"), // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"), // ref: http://sqlite.org/syntax/literal-value.html atoms: set("null current_date current_time current_timestamp"), // ref: http://sqlite.org/lang_expr.html#binaryops operatorChars: /^[*+\-%<>!=&|/~]/, // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. dateSQL: set("date time timestamp datetime"), support: set("decimallessFloat zerolessFloat"), identifierQuote: "\"", //ref: http://sqlite.org/lang_keywords.html hooks: { // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam "@": hookVar, ":": hookVar, "?": hookVar, "$": hookVar, // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html "\"": hookIdentifierDoublequote, // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html "`": hookIdentifier } }); // the query language used by Apache Cassandra is called CQL, but this mime type // is called Cassandra to avoid confusion with Contextual Query Language CodeMirror.defineMIME("text/x-cassandra", { name: "sql", client: { }, keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"), builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"), atoms: set("false true infinity NaN"), operatorChars: /^[<>=]/, dateSQL: { }, support: set("commentSlashSlash decimallessFloat"), hooks: { } }); // this is based on Peter Raganitsch's 'plsql' mode CodeMirror.defineMIME("text/x-plsql", { name: "sql", client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"), keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"), builtin: set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"), operatorChars: /^[*\/+\-%<>!=~]/, dateSQL: set("date time timestamp"), support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber") }); // Created to support specific hive keywords CodeMirror.defineMIME("text/x-hive", { name: "sql", keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year"), builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=]/, dateSQL: set("date timestamp"), support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") }); CodeMirror.defineMIME("text/x-pgsql", { name: "sql", client: set("source"), // For PostgreSQL - https://www.postgresql.org/docs/11/sql-keywords-appendix.html // For pl/pgsql lang - https://github.com/postgres/postgres/blob/REL_11_2/src/pl/plpgsql/src/pl_scanner.c keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate alias all allocate also alter always analyse analyze and any are array array_agg array_max_cardinality as asc asensitive assert assertion assignment asymmetric at atomic attach attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli between bigint binary bit bit_length blob blocked bom boolean both breadth by c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain char char_length character character_length character_set_catalog character_set_name character_set_schema characteristics characters check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column column_name columns command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constant constraint constraint_catalog constraint_name constraint_schema constraints constructor contains content continue control conversion convert copy corr corresponding cost count covar_pop covar_samp create cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datatype date datetime_interval_code datetime_interval_precision day db deallocate debug dec decimal declare default defaults deferrable deferred defined definer degree delete delimiter delimiters dense_rank depends depth deref derived desc describe descriptor detach detail deterministic diagnostics dictionary disable discard disconnect dispatch distinct dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain double drop dump dynamic dynamic_function dynamic_function_code each element else elseif elsif empty enable encoding encrypted end end_frame end_partition endexec enforced enum equals errcode error escape event every except exception exclude excluding exclusive exec execute exists exit exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreach foreign fortran forward found frame_row free freeze from fs full function functions fusion g general generated get global go goto grant granted greatest group grouping groups handler having header hex hierarchy hint hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import in include including increment indent index indexes indicator info inherit inherits initially inline inner inout input insensitive insert instance instantiable instead int integer integrity intersect intersection interval into invoker is isnull isolation join k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like like_regex limit link listen ln load local localtime localtimestamp location locator lock locked log logged loop lower m map mapping match matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized not nothing notice notify notnull nowait nth_value ntile null nullable nullif nulls number numeric object occurrences_regex octet_length octets of off offset oids old on only open operator option options or order ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password path percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding precision prepare prepared preserve primary print_strict_params prior privileges procedural procedure procedures program public publication query quote raise range rank read reads real reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result result_oid return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns reverse revoke right role rollback rollup routine routine_catalog routine_name routine_schema routines row row_count row_number rows rowtype rule savepoint scale schema schema_name schemas scope scope_catalog scope_name scope_schema scroll search second section security select selective self sensitive sequence sequences serializable server server_name session session_user set setof sets share show similar simple size skip slice smallint snapshot some source space specific specific_name specifictype sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable stacked standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t table table_name tables tablesample tablespace temp template temporary text then ties time timestamp timezone_hour timezone_minute to token top_level_count trailing transaction transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted union unique unknown unlink unlisten unlogged unnamed unnest until untyped update upper uri usage use_column use_variable user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of values var_pop var_samp varbinary varchar variable_conflict variadic varying verbose version versioning view views volatile warning when whenever where while whitespace width_bucket window with within without work wrapper write xml xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes zone"), // https://www.postgresql.org/docs/11/datatype.html builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"), atoms: set("false true null unknown"), operatorChars: /^[*\/+\-%<>!=&|^\/#@?~]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") }); // Google's SQL-like query language, GQL CodeMirror.defineMIME("text/x-gql", { name: "sql", keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"), atoms: set("false true"), builtin: set("blob datetime first key __key__ string integer double boolean null"), operatorChars: /^[*+\-%<>!=]/ }); // Greenplum CodeMirror.defineMIME("text/x-gpsql", { name: "sql", client: set("source"), //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"), builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") }); // Spark SQL CodeMirror.defineMIME("text/x-sparksql", { name: "sql", keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"), builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"), atoms: set("false true null"), operatorChars: /^[*\/+\-%<>!=~&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable doubleQuote zerolessFloat") }); // Esper CodeMirror.defineMIME("text/x-esper", { name: "sql", client: set("source"), // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html keywords: set("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"), builtin: {}, atoms: set("false true null"), operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, dateSQL: set("time"), support: set("decimallessFloat zerolessFloat binaryNumber hexNumber") }); }); /* How Properties of Mime Types are used by SQL Mode ================================================= keywords: A list of keywords you want to be highlighted. builtin: A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword"). operatorChars: All characters that must be handled as operators. client: Commands parsed and executed by the client (not the server). support: A list of supported syntaxes which are not common, but are supported by more than 1 DBMS. * ODBCdotTable: .tableName * zerolessFloat: .1 * doubleQuote * nCharCast: N'string' * charsetCast: _utf8'string' * commentHash: use # char for comments * commentSlashSlash: use // for comments * commentSpaceRequired: require a space after -- for comments atoms: Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others: UNKNOWN, INFINITY, UNDERFLOW, NaN... dateSQL: Used for date/time SQL standard syntax, because not all DBMS's support same temporal types. */ ================================================ FILE: spider-flow-web/src/main/resources/static/js/common.js ================================================ function getQueryString(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; } Date.prototype.format = function(b) { var a = this; var c = { "M+": a.getMonth() + 1, "d+": a.getDate(), "h+": a.getHours(), "m+": a.getMinutes(), "s+": a.getSeconds(), "q+": Math.floor((a.getMonth() + 3) / 3), S: a.getMilliseconds() }; /(y+)/.test(b) && (b = b.replace(RegExp.$1, (a.getFullYear() + "").substr(4 - RegExp.$1.length))); for(var d in c) new RegExp("(" + d + ")").test(b) && (b = b.replace(RegExp.$1, 1 == RegExp.$1.length ? c[d] : ("00" + c[d]).substr(("" + c[d]).length))); return b } var sf = {}; sf.ajax = function(options){ var loading; var loadingInterval; var closeClear = function(){ layui.layer.close(loading); clearInterval(loadingInterval); } var beginTime = +new Date(); var url = options.url; var type = options.type; var data = options.data; var success = options.success; var error = options.error; $.ajax({ url:url, type:type, data:data, success:function(result){ closeClear(); success && success(result); }, error:function(errorInfo){ closeClear(); error && error(errorInfo); }, beforeSend:function(){ loadingInterval = setInterval(function(){ var endTime = +new Date(); if((endTime-beginTime) > 500){ loading = layui.layer.load(1, { shade: [0.1,'#fff'] }); clearInterval(loadingInterval); } },100); } }) } ================================================ FILE: spider-flow-web/src/main/resources/static/js/cron/cron.js ================================================ function btnFan() { // 获取参数中表达式的值 var txt = $("#cron").val(); if (txt) { var regs = txt.split(' '); $("input[name=v_second]").val(regs[0]); $("input[name=v_min]").val(regs[1]); $("input[name=v_hour]").val(regs[2]); $("input[name=v_day]").val(regs[3]); $("input[name=v_mouth]").val(regs[4]); $("input[name=v_week]").val(regs[5]); initObj(regs[0], "second"); initObj(regs[1], "min"); initObj(regs[2], "hour"); initDay(regs[3]); initMonth(regs[4]); initWeek(regs[5]); if (regs.length > 6) { $("input[name=v_year]").val(regs[6]); initYear(regs[6]); } } } function initObj(strVal, strid) { var ary = null; var objRadio = $("input[name='" + strid + "'"); if (strVal == "*") { objRadio.eq(0).attr("checked", "checked"); } else if (strVal.split('-').length > 1) { ary = strVal.split('-'); objRadio.eq(1).attr("checked", "checked"); $("#" + strid + "Start_0").numberspinner('setValue', ary[0]); $("#" + strid + "End_0").numberspinner('setValue', ary[1]); } else if (strVal.split('/').length > 1) { ary = strVal.split('/'); objRadio.eq(2).attr("checked", "checked"); $("#" + strid + "Start_1").numberspinner('setValue', ary[0]); $("#" + strid + "End_1").numberspinner('setValue', ary[1]); } else { objRadio.eq(3).attr("checked", "checked"); if (strVal != "?") { ary = strVal.split(","); for (var i = 0; i < ary.length; i++) { $("." + strid + "List input[value='" + ary[i] + "']").attr( "checked", "checked"); } } } } function initDay(strVal) { var ary = null; var objRadio = $("input[name='day'"); if (strVal == "*") { objRadio.eq(0).attr("checked", "checked"); } else if (strVal == "?") { objRadio.eq(1).attr("checked", "checked"); } else if (strVal.split('-').length > 1) { ary = strVal.split('-'); objRadio.eq(2).attr("checked", "checked"); $("#dayStart_0").numberspinner('setValue', ary[0]); $("#dayEnd_0").numberspinner('setValue', ary[1]); } else if (strVal.split('/').length > 1) { ary = strVal.split('/'); objRadio.eq(3).attr("checked", "checked"); $("#dayStart_1").numberspinner('setValue', ary[0]); $("#dayEnd_1").numberspinner('setValue', ary[1]); } else if (strVal.split('W').length > 1) { ary = strVal.split('W'); objRadio.eq(4).attr("checked", "checked"); $("#dayStart_2").numberspinner('setValue', ary[0]); } else if (strVal == "L") { objRadio.eq(5).attr("checked", "checked"); } else { objRadio.eq(6).attr("checked", "checked"); ary = strVal.split(","); for (var i = 0; i < ary.length; i++) { $(".dayList input[value='" + ary[i] + "']").attr("checked", "checked"); } } } function initMonth(strVal) { var ary = null; var objRadio = $("input[name='mouth'"); if (strVal == "*") { objRadio.eq(0).attr("checked", "checked"); } else if (strVal == "?") { objRadio.eq(1).attr("checked", "checked"); } else if (strVal.split('-').length > 1) { ary = strVal.split('-'); objRadio.eq(2).attr("checked", "checked"); $("#mouthStart_0").numberspinner('setValue', ary[0]); $("#mouthEnd_0").numberspinner('setValue', ary[1]); } else if (strVal.split('/').length > 1) { ary = strVal.split('/'); objRadio.eq(3).attr("checked", "checked"); $("#mouthStart_1").numberspinner('setValue', ary[0]); $("#mouthEnd_1").numberspinner('setValue', ary[1]); } else { objRadio.eq(4).attr("checked", "checked"); ary = strVal.split(","); for (var i = 0; i < ary.length; i++) { $(".mouthList input[value='" + ary[i] + "']").attr("checked", "checked"); } } } function initWeek(strVal) { var ary = null; var objRadio = $("input[name='week'"); if (strVal == "*") { objRadio.eq(0).attr("checked", "checked"); } else if (strVal == "?") { objRadio.eq(1).attr("checked", "checked"); } else if (strVal.split('/').length > 1) { ary = strVal.split('/'); objRadio.eq(2).attr("checked", "checked"); $("#weekStart_0").numberspinner('setValue', ary[0]); $("#weekEnd_0").numberspinner('setValue', ary[1]); } else if (strVal.split('-').length > 1) { ary = strVal.split('-'); objRadio.eq(3).attr("checked", "checked"); $("#weekStart_1").numberspinner('setValue', ary[0]); $("#weekEnd_1").numberspinner('setValue', ary[1]); } else if (strVal.split('L').length > 1) { ary = strVal.split('L'); objRadio.eq(4).attr("checked", "checked"); $("#weekStart_2").numberspinner('setValue', ary[0]); } else { objRadio.eq(5).attr("checked", "checked"); ary = strVal.split(","); for (var i = 0; i < ary.length; i++) { $(".weekList input[value='" + ary[i] + "']").attr("checked", "checked"); } } } function initYear(strVal) { var ary = null; var objRadio = $("input[name='year'"); if (strVal == "*") { objRadio.eq(1).attr("checked", "checked"); } else if (strVal.split('-').length > 1) { ary = strVal.split('-'); objRadio.eq(2).attr("checked", "checked"); $("#yearStart_0").numberspinner('setValue', ary[0]); $("#yearEnd_0").numberspinner('setValue', ary[1]); } } /** * 每周期 */ function everyTime(dom) { var item = $("input[name=v_" + dom.name + "]"); item.val("*"); item.change(); } /** * 不指定 */ function unAppoint(dom) { var name = dom.name; var val = "?"; if (name == "year") val = ""; var item = $("input[name=v_" + name + "]"); item.val(val); item.change(); } function appoint(dom) { } /** * 周期 */ function cycle(dom) { var name = dom.name; var ns = $(dom).parent().find(".numberspinner"); var start = ns.eq(0).numberspinner("getValue"); var end = ns.eq(1).numberspinner("getValue"); var item = $("input[name=v_" + name + "]"); item.val(start + "-" + end); item.change(); } /** * 从开始 */ function startOn(dom) { var name = dom.name; var ns = $(dom).parent().find(".numberspinner"); var start = ns.eq(0).numberspinner("getValue"); var end = ns.eq(1).numberspinner("getValue"); var item = $("input[name=v_" + name + "]"); item.val(start + "/" + end); item.change(); } function lastDay(dom) { var item = $("input[name=v_" + dom.name + "]"); item.val("L"); item.change(); } function weekOfDay(dom) { var name = dom.name; var ns = $(dom).parent().find(".numberspinner"); var start = ns.eq(0).numberspinner("getValue"); var end = ns.eq(1).numberspinner("getValue"); var item = $("input[name=v_" + name + "]"); item.val(start + "#" + end); item.change(); } function lastWeek(dom) { var item = $("input[name=v_" + dom.name + "]"); var ns = $(dom).parent().find(".numberspinner"); var start = ns.eq(0).numberspinner("getValue"); item.val(start + "L"); item.change(); } function workDay(dom) { var name = dom.name; var ns = $(dom).parent().find(".numberspinner"); var start = ns.eq(0).numberspinner("getValue"); var item = $("input[name=v_" + name + "]"); item.val(start + "W"); item.change(); } $(function() { $(".numberspinner").numberspinner({ onChange : function() { $(this).closest("div.line").children().eq(0).click(); } }); var vals = $("input[name^='v_']"); var cron = $("#cron"); vals.change(function() { var item = []; vals.each(function() { item.push(this.value); }); // 修复表达式错误BUG,如果后一项不为* 那么前一项肯定不为为*,要不然就成了每秒执行了 // 获取当前选中tab var currentIndex = 0; $(".tabs>li").each(function(i, item) { if ($(item).hasClass("tabs-selected")) { currentIndex = i; return false; } }); // 当前选中项之前的如果为*,则都设置成0 for (var i = currentIndex; i >= 1; i--) { if (item[i] != "*" && item[i - 1] == "*") { item[i - 1] = "0"; } } // 当前选中项之后的如果不为*则都设置成* if (item[currentIndex] == "*") { for (var i = currentIndex + 1; i < item.length; i++) { if (i == 5) { item[i] = "?"; } else { item[i] = "*"; } } } cron.val(item.join(" ")).change(); }); cron.change(function() { // 获取参数中表达式的值 btnFan(); // 设置最近五次运行时间 $.ajax({ type : 'get', url : "/spider/recent5TriggerTime", dataType : "json", data : { "cron" : $("#cron").val() }, success : function(data) { if (data && data.length == 5) { var strHTML = "
    "; for (var i = 0; i < data.length; i++) { strHTML += "
  • " + data[i] + "
  • "; } strHTML += "
" $("#runTime").html(strHTML); } else { $("#runTime").html(""); } } }); }); var secondList = $(".secondList").children(); $("#sencond_appoint").click(function() { if (this.checked) { if ($(secondList).filter(":checked").length == 0) { $(secondList.eq(0)).attr("checked", true); } secondList.eq(0).change(); } }); secondList.change(function() { var sencond_appoint = $("#sencond_appoint").prop("checked"); if (sencond_appoint) { var vals = []; secondList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 59) { val = vals.join(","); } else if (vals.length == 59) { val = "*"; } var item = $("input[name=v_second]"); item.val(val); item.change(); } }); var minList = $(".minList").children(); $("#min_appoint").click(function() { if (this.checked) { if ($(minList).filter(":checked").length == 0) { $(minList.eq(0)).attr("checked", true); } minList.eq(0).change(); } }); minList.change(function() { var min_appoint = $("#min_appoint").prop("checked"); if (min_appoint) { var vals = []; minList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 59) { val = vals.join(","); } else if (vals.length == 59) { val = "*"; } var item = $("input[name=v_min]"); item.val(val); item.change(); } }); var hourList = $(".hourList").children(); $("#hour_appoint").click(function() { if (this.checked) { if ($(hourList).filter(":checked").length == 0) { $(hourList.eq(0)).attr("checked", true); } hourList.eq(0).change(); } }); hourList.change(function() { var hour_appoint = $("#hour_appoint").prop("checked"); if (hour_appoint) { var vals = []; hourList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 24) { val = vals.join(","); } else if (vals.length == 24) { val = "*"; } var item = $("input[name=v_hour]"); item.val(val); item.change(); } }); var dayList = $(".dayList").children(); $("#day_appoint").click(function() { if (this.checked) { if ($(dayList).filter(":checked").length == 0) { $(dayList.eq(0)).attr("checked", true); } dayList.eq(0).change(); } }); dayList.change(function() { var day_appoint = $("#day_appoint").prop("checked"); if (day_appoint) { var vals = []; dayList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 31) { val = vals.join(","); } else if (vals.length == 31) { val = "*"; } var item = $("input[name=v_day]"); item.val(val); item.change(); } }); var mouthList = $(".mouthList").children(); $("#mouth_appoint").click(function() { if (this.checked) { if ($(mouthList).filter(":checked").length == 0) { $(mouthList.eq(0)).attr("checked", true); } mouthList.eq(0).change(); } }); mouthList.change(function() { var mouth_appoint = $("#mouth_appoint").prop("checked"); if (mouth_appoint) { var vals = []; mouthList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 12) { val = vals.join(","); } else if (vals.length == 12) { val = "*"; } var item = $("input[name=v_mouth]"); item.val(val); item.change(); } }); var weekList = $(".weekList").children(); $("#week_appoint").click(function() { if (this.checked) { if ($(weekList).filter(":checked").length == 0) { $(weekList.eq(0)).attr("checked", true); } weekList.eq(0).change(); } }); weekList.change(function() { var week_appoint = $("#week_appoint").prop("checked"); if (week_appoint) { var vals = []; weekList.each(function() { if (this.checked) { vals.push(this.value); } }); var val = "?"; if (vals.length > 0 && vals.length < 7) { val = vals.join(","); } else if (vals.length == 7) { val = "*"; } var item = $("input[name=v_week]"); item.val(val); item.change(); } }); }); ================================================ FILE: spider-flow-web/src/main/resources/static/js/editor.js ================================================ var $ = layui.$; var editor; var flows; var codeMirrorInstances = {}; var socket; var version = 'lastest'; function renderCodeMirror(){ codeMirrorInstances = {}; $('[codemirror]').each(function(){ var $dom = $(this); if($dom.attr("rendered") == 'true'){ return; } $dom.attr("rendered",true) var cm = CodeMirror(this,{ mode : 'spiderflow', //语法 theme : 'idea', //设置样式 placeholder : $dom.attr("placeholder"), value : $dom.attr('data-value') || '', scrollbarStyle : 'null', //隐藏滚动条 }); initHint(cm); codeMirrorInstances[$(this).attr('codemirror')] = cm; cm.on('change',function(){ $dom.attr('data-value',cm.getValue()); if($dom.attr('codemirror') == 'condition'){ var $select = $('select[name="exception-flow"]'); $select.siblings("div.layui-form-select").find('dl dd[lay-value=' + $select.val() + ']').click(); } serializeForm(); }); codeMirrorInstances[$(this).attr('codemirror')] = cm; }); } function getCellData(cellId,keys){ var cell = editor.getModel().getCell(cellId); var data = []; var object = cell.data.object; for(var k in keys){ var key = keys[k]; if(Array.isArray(object[key])){ var array = object[key]; for(var i =0,len = array.length;i 0){ var array = cell.data.get(name) || []; array.push(value); cell.data.set(name,array); }else{ if(name == 'value'){ if(cell.getValue() != value){ model.beginUpdate(); try{ cell.setValue(value); model.execute(new mxValueChange(model,cell,value)); }finally{ model.endUpdate(); } } } if(name == 'lineWidth'){ editor.graph.setCellStyles('strokeWidth',value,[cell]); } if(name == 'line-style'){ editor.graph.setCellStyles('sharp',undefined,[cell]); editor.graph.setCellStyles('rounded',undefined,[cell]); editor.graph.setCellStyles('curved',undefined,[cell]); editor.graph.setCellStyles(value,1,[cell]); } cell.data.set(name,value); } }); $(".properties-container form [codemirror]").each(function(){ var $dom = $(this); var name = $dom.attr('codemirror'); var value = $dom.attr('data-value'); if($dom.hasClass("array")){ var array = cell.data.get(name) || []; array.push(value); cell.data.set(name,array); }else{ cell.data.set(name,value); } }); $(".properties-container form input[type=checkbox]").each(function(){ if(this.value == 'transmit-variable'){ if($(this).is(":checked")){ editor.graph.setCellStyles('dashed',undefined,[cell]); }else{ editor.graph.setCellStyles('dashed',1,[cell]); } } cell.data.set(this.value,$(this).is(":checked") ? '1': '0'); }); cell.data.set('shape',shape); } function resizeSlideBar(){ var $dom = $(".sidebar-container"); var height = $dom.height(); var len = $dom.find("img").length; var totalHeight = len * 46; var w = Math.ceil(totalHeight / height); $dom.width(w * 50); $(".editor-container,.xml-container").css("left",w * 50 + "px"); } function validXML(callback){ var cell = editor.valid(); if(cell){ layui.layer.confirm("检测到有箭头未连接到节点上,是否处理?",{ title : '异常处理', btn : ['处理','忽略'], },function(index){ layui.layer.close(index); editor.selectCell(cell); },function(){ callback&&callback(); }) }else{ callback&&callback(); } } $(function(){ $.ajax({ url : 'spider/other', type : 'post', data : { id : getQueryString('id') }, dataType : 'json', success : function(others){ flows = others; } }) $.ctrl = function(key, callback, args) { var isCtrl = false; $(document).keydown(function(e) { if(!args) args=[]; if(e.keyCode == 17) isCtrl = true; if(e.keyCode == key.charCodeAt(0) && isCtrl) { callback.apply(this, args); isCtrl = false; return false; } }).keyup(function(e) { if(e.keyCode == 17) isCtrl = false; }); }; $.ctrl('S', function() { $('input,textarea').blur(); Save(); }); $.ctrl('Q', function() { $('input,textarea').blur(); $(".btn-test").click(); }); resizeSlideBar(); var templateCache = {}; function loadTemplate(cell,model,callback){ serializeForm(); var cells = model.cells; var template = cell.data.get('shape') || 'root'; if(cell.isEdge()){ template = 'edge'; } var v = version; var render = function(){ layui.laytpl(templateCache[template]).render({ data : cell.data, value : cell.value, flows : flows || [], model : model, cell : cell },function(html){ $(".properties-container").attr('data-version',v).html(html).attr('data-cellid',cell.id); layui.form.render(); renderCodeMirror(); resizeSlideBar(); callback&&callback(); }) } if(templateCache[template]){ render(); return; } $.ajax({ url : 'resources/templates/' + template +".html", async :false, success : function(content){ templateCache[template] = content; render(); } }); } if (!mxClient.isBrowserSupported()){ layui.layer.msg('浏览器不支持!!'); }else{ editor = new SpiderEditor({ element : $('.editor-container')[0], selectedCellListener : function(cell){ //选中节点后打开属性面板 loadTemplate(cell,editor.getModel(),serializeForm); } }); //绑定工具条点击事件 bindToolbarClickAction(editor); //加载图形 loadShapes(editor,$('.sidebar-container')[0]); layui.form.on('checkbox',function(e){ serializeForm(); }); layui.table.on('tool',function(obj){ layui.layer.confirm('您确定要删除吗?',{ title : '删除' },function(index) { obj.del(); serializeForm(); renderCodeMirror(); layui.layer.close(index); }); }) //节点名称输入框事件 $("body").on("mousewheel",".layui-tab .layui-tab-title",function(e,delta){ var $dom = $(this); var wheel = e.originalEvent.wheelDelta || -e.originalEvent.detail; var delta = Math.max(-1, Math.min(1, wheel) ); e.preventDefault = function(){} if(delta > 0){ $dom.scrollLeft($dom.scrollLeft()-60); }else{ $dom.scrollLeft($dom.scrollLeft()+60); } return false; }).on("dblclick",".layui-input-block[codemirror]",function(){ if($(this).parent().hasClass("layui-layer-content")){ return; } layui.layer.open({ type : 1, title : '请输入'+$(this).prev().html()+'表达式', content : $(this), skin : 'codemirror', area : '800px' }) }).on("blur","input,textarea",function(){ serializeForm(); }).on("click",".history-version li",function(){ var timestamp = $(this).data("timestamp"); layui.layer.confirm('你确定要恢复到该版本吗?',function(index){ layui.layer.close(index); var layerIndex = layui.layer.load(1); $.ajax({ url : 'spider/history', data : { id : id, timestamp : timestamp }, success : function(data){ if(data.code == 1){ version = timestamp; editor.setXML(data.data); layui.layer.close(layerIndex); layui.layer.msg('恢复成功') }else{ layui.layer.msg(data.message); } } }) }); }).on("click",".btn-history",function(){ $.ajax({ url : 'spider/history', data : { id : id }, success : function(data){ if(data.code == 1){ if(data.data.length > 0){ var array = []; for(var i = data.data.length - 1;i >=0;i--){ var timestamp = Number(data.data[i]) array.push({ time : new Date(timestamp).format('yyyy-MM-dd hh:mm:ss'), timestamp : timestamp }) } layui.laytpl($('#history-version-tmpl').html()).render(array,function(html){ layui.layer.open({ type : 1, title : '历史版本', id : 'history-revert', shade : 0, resize : false, content : html, offset : 'rt' }) }) }else{ layui.layer.msg('暂无历史版本!'); } }else{ layui.layer.msg(data.message); } } }) }).on("click",".table-row-add",function(){ //添加一行 serializeForm(); var tableId = $(this).attr('for'); var $table = $('#' + tableId); var cellId = $table.data('cell'); var data = getCellData(cellId,$table.data('keys').split(",")); data.push({}); layui.table.reload(tableId,{ data : data }); renderCodeMirror(); }).on("click",".table-row-up",function(){ //上移 var current = $(this).parent().parent().parent(); //获取当前 var prev = current.prev(); //获取当前前一个元素 if (current.index() > 0) { current.insertBefore(prev); //插入到当前前一个元素前 serializeForm(); } renderCodeMirror(); }).on("click",".table-row-down",function(){ //下移 var current = $(this).parent().parent().parent(); //获取当前 var next = current.next(); //获取当前后面一个元素 if (next) { current.insertAfter(next); //插入到当前后面一个元素后面 serializeForm(); } renderCodeMirror(); }).on("click",".editor-form-node .function-remove,.editor-form-node .cmd-remove",function () { var $dom = $(this).parents(".draggable"); $dom.remove(); serializeForm(); }).on("click",".editor-form-node .cookie-batch",function(){ var tableId = $(this).attr('for'); var $table = $('#' + tableId); var cellId = $table.data('cell'); var data = getCellData(cellId,$table.data('keys').split(",")); layui.layer.open({ type : 1, title : '请输入Cookie', content : ``, area : '800px', btn : ['关闭','设置'], btn2 : function(){ var cookieStr = $("#cookies").val(); var cookieArr = cookieStr.split(";"); var length = $(".draggable").length; serializeForm(); for (var i = 0; i < cookieArr.length; i++) { var cookieItem = cookieArr[i]; var index = cookieItem.indexOf("="); if (index < 0) { layer.alert('cookie数据格式错误'); appendFlag = false; return; } else { data.push({ 'cookie-name' : $.trim(cookieItem.substring(0, index)), 'cookie-value' : $.trim(cookieItem.substring(index + 1)) }) } } layui.table.reload(tableId,{ data : data }); renderCodeMirror(); serializeForm(); } }) }).on("click",".editor-form-node .header-batch",function(){ var tableId = $(this).attr('for'); var $table = $('#' + tableId); var cellId = $table.data('cell'); var data = getCellData(cellId,$table.data('keys').split(",")); layui.layer.open({ type : 1, title : '请输入Header', content : ``, area : '800px', btn : ['关闭','设置'], btn2 : function(){ var headerStr = $("#headers").val(); var headerArr = headerStr.split("\n"); var length = $(".draggable").length; for (var i = 0; i < headerArr.length; i++) { var headerItem = headerArr[i]; var index = headerItem.indexOf(":"); if (index < 0) { layer.alert('header数据格式错误'); return; } else { data.push({ 'header-name' : $.trim(headerItem.substring(0, index)), 'header-value' : $.trim(headerItem.substring(index + 1)) }) } } layui.table.reload(tableId,{ data : data }); renderCodeMirror(); serializeForm(); } }) }).on("click",".editor-form-node .parameter-batch",function () { var tableId = $(this).attr('for'); var $table = $('#' + tableId); var cellId = $table.data('cell'); var data = getCellData(cellId,$table.data('keys').split(",")); layui.layer.open({ type : 1, title : '请输入参数', content : ``, area : '800px', btn : ['关闭','设置'], btn2 : function(){ var paramterStr = $("#paramters").val(); var paramterArr = paramterStr.split("\n"); var length = $(".draggable").length; for (var i = 0; i < paramterArr.length; i++) { var paramterItem = paramterArr[i]; var index = -1; var indexArr = []; indexArr.push(paramterItem.indexOf(":")); indexArr.push(paramterItem.indexOf("=")); indexArr.push(paramterItem.indexOf(" ")); indexArr.push(paramterItem.indexOf("\t")); for (var j = 0; j < indexArr.length; j++) { if (indexArr[j] >= 0) { if (index < 0) { index = indexArr[j]; } index = Math.min(index, indexArr[j]); } } if (index < 0) { layer.alert('参数数据格式错误'); return; } else { data.push({ 'parameter-name' : $.trim(paramterItem.substring(0, index)), 'parameter-value' : $.trim(paramterItem.substring(index + 1)) }) } } layui.table.reload(tableId,{ data : data }); renderCodeMirror(); serializeForm(); } }) }).on("click",".editor-form-node .function-add",function(){ var index = $(".draggable").length; $(this).parent().parent().before('
'); renderCodeMirror(); }).on("click",".editor-form-node .cmd-add",function(){ var index = $(".draggable").length; $(this).parent().parent().before('
'); renderCodeMirror(); }); layui.form.on('select(bodyType)',function(e){ var bodyType = $(e.elem).val(); $(".form-body-raw,.form-body-form-data").hide(); if(bodyType == 'raw'){ $(".form-body-raw").show(); } if(bodyType == 'form-data'){ $(".form-body-form-data").show(); } renderCodeMirror(); serializeForm(); }); layui.form.on('select(targetCheck)', function (data) { var targetDiv = $(data.elem).attr('target-div'); var targetValue = $(data.elem).attr('target-value'); if (targetDiv != null) { if (data.elem.value == targetValue) { $("." + targetDiv).show(); } else { $("." + targetDiv).hide(); } } }); layui.form.on('checkbox(targetCheck)', function (data) { var targetDiv = $(data.elem).attr('target-div'); if (targetDiv != null) { if (data.elem.checked) { $("." + targetDiv).show(); } else { $("." + targetDiv).hide(); } } }); layui.element.on('tab',function(){ for(var key in codeMirrorInstances){ codeMirrorInstances[key].refresh(); } }) layui.form.on('select',serializeForm); var id = getQueryString('id'); if(id != null){ $.ajax({ url : 'spider/xml', async : false, data : { id : id }, success : function(xml){ editor.setXML(xml); } }) //editor.importFromUrl('spider/xml?id=' + id); } editor.onSelectedCell(); } /** * 加载各种图形 */ function loadShapes(editor,container){ //定义图形 var shapes = [{ name : 'start', title : '开始', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABwUlEQVRYR9WXz1XCQBDGv9GD3sSDkpvYAR2IHWAF0oFsBUIFGyoQK1ArECpQK8BjcsMbnj7fRsN7hPDcCRt87nl25jez828FinNq2d0TWAINAR4XhJkbmStUrImK7+WGZeNAMBOgkd8hMUqN9H11lMl5A/x4/1BUsiCOt4mCN0BkOYDgds0L4jIxMqkahX8EEHMGoFX0NOmLtxOVcyCy7EDwXFRA4iM1skzKKs/gRd+M+SJAuwTgKTXSrWI4v/MrQBTzDkCvzAgJkxqJawOILHsQOIDyQ5wnRt5rAWiOeCPEZu+I+8RIaWQ0QGtP4DreocBuCvtSeQDvna4VgGjEaxCDsnLTeOUpO3azJAM4sWzvf3vd8bwcRowYZgBRTFfjuzXuDBNTiSxbELgut/vjIrCpy9VNk4/y0ABZYmnGc2gA966q/lAHwDQx4p3QwQG0a1owADeaAYw/gcFf5cBkQVxpjGetOGQZklDvB6EB1BtSaAD1PyEIAIk3AeLEyFjbQYMAAKiUgHkSBhlG2vpfWUojywkEF9rwrcgTqg5YBGgReBXBUWUIYpgYcduU6ixXsmwXRLaEuk/Ima+WbRLQ2fgC+RzXgT1bPk8AAAAASUVORK5CYII=', hidden : true, defaultAdd : true },{ name : 'request', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACbUlEQVRYR+2XTXLTQBCFX5sF7DALsHaYE+AbxD4ByQlITmDrBCQnGHMClBMkOUHMCRAnIOwU2JhdssCPamnkkmRJM5KTKqpgqryxpqe/7unpH0HHFRhOIXhPYCLARMUJxALEIM6TUFZdjhTfzS8NJ08EBsDUIbP6TYQ/Q4l9zvYCUKspuBBg6HMogbUQRz7ecAKo5QPBta/yHFAhNsTM5QknQLDkNwBjH8tr9twkC3nTJtsKEBgeQ/Cpp/JMjDhJQomazmgFGBleiuDdPgAkrm5DOewFECzJfZTnsslCGg1NPwSGYwqMCOJkLme54GMAvDI8HAjmG+Ljj1AuUwD754VVHCULORkaDp/ZRLOvF+6AeB3KuhRTWdI63rqmct8RBmgMnD5AJCZCLNO4JL7eA1OF2gKoxU+BlQje9lHgK1NUrjKl4OgMQcxsLVj6gFeV7wDYgDyF4IOPRXl0B4YrCA6cMsRZEsppcd/O8wgM/wP8Yx4YGWqiLOZ7rXxe1a9zEAI3yH5ZnSKuZJ902wNg56FImobLKVd7PveTAtAZgPgMYNszbrJesrz+hmeoHrh2JpUeHtgQR1oBXYno0QBAzKqNam2jMDJci+C5ywtdY+COeKEVsNUD+nFkqMVl/pAATa1ZrQfsEPLlIQHq7r+2GqYlOZsD0rGrbXW5Ah3f7olZ6xVUlWv9bqvzXgDEdwhe275hB6LcERUtt/18YBjpMFrnCSeA7fuKvWDVE1uAkqLKMJEeAGiVTC3JVxMAiV8CLIoDSV1DWooBLUqqpCpYVGjTtg4ZY03XJYBsTF8TiKrJJj8jhyAR3oaSNqh/AKendd/nwfiIAAAAAElFTkSuQmCC', title : '开始抓取', desc : '抓取静态HTML页面或者API接口,抓取结果存为resp变量中。
支持方法参考命令提示。' },{ name : 'variable', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACMAAAAgCAYAAACYTcH3AAACe0lEQVRYR+2WMW5TQRCGv0mEoMMUKK80J0joKJBITgCUVAkniLehjQ+A9GwugLlBboA5QZITYLpnaEwXkZhBs+xu1s8vkhMDMpItudh9szP//PPP7Aor9JMVwsLqgmmV2roD7W9OTpsYe1jqzgWMJk4m9e/FO30W986nnDXZ1P2bPzsT480ws9XTE4EdlNeVk0EesCj1AOE9MKw6smffzPk9oQQOGsAPz5WXOajcP4KB9+cUTrng6SyYUici3M8DxiDRkSpnYyc+o+TcHCpnAhOFlgjb4VwCbuuipxr2R0A7T0DhSR1MT4RDb6Q8qpzYIYpS2wif/bbixk56Ram7CB+D7QyTRanDkDlVR1KMDIz5/wAMfhp4aJvPGTBNQT0DpSaQ58oDo95KdBeslKOxk06eZW6Pslc5GdaYIfrJz811U8zK6jjuyOPgxFhpWzaVkxl9eN1sso2ya3+FHYFWCtIERvlUOdmt66wJTBSqL5UHcVWOlKUH2dcjVToxuCrfTW9+/Vug5mOemUXBhLJ4IavSD473Ub5UTpLosu7y9Z9CL7ZoUWoX4ehPgYkaGfnugFYUbuquUo9FeG7rXKQhmfRtaWZyIadBFoQb10WpA4T9vJu8fjY4ROlmmkmdlrrpJmUK7Zzas0m4Nj03hZO6CEP797MRkUSfgZlrBDt37d1kwTZgYIPMJmWcOXnwYNP1UxtsJtm/a7amKYWOQverk+OQoDF2MIUXTVfO6l6UTZT/y701M9exvWZmzcxNO3F1NbPV18OZt8hNU1vCXn/w9upJmD0tl/B566MqvKo/O+3umHuB3TrC4gdHesmb1dXM4on8Hcs1M//FBP4FX81QGwO29kEAAAAASUVORK5CYII=', title : '定义变量', desc : '定义流程变量。
定义变量有先后顺序,先定义变量后续可以使用,拖动可以交换变量顺序。' },{ name : 'loop', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADO0lEQVRYR9WWS2hTURCGvwnVlVjpzgdWxQeo0IWP7rQuRBQVFayLSlUQH5V2UWhzo4takOTGCF1UlOJCKyJiFxUFSwWxioguRBEV31qhVXeKSI3ajJybGxPTJDdpCtUDIeFmZv7vzpmZc4RxXjLO+vzHAH4tZZhySihzsih8JCTPCs1o/hlo0UlE2QlsA2YD0zOI3QV68dFBUD7kA+MN0KIT+U4zwg5gbkrQn8ArYELac2MyCJzClsNeELkB/DoT4SJQ6QZ6AZzFRw8TeEyr/HCeH9YyhqhEWAzUAbNc+26GaSIir7OBZAcIaCXKbaAEGAIaidJJm5jf2ZelRrwFnO0y6wlCNSF5mskpM0CdTmIyX12HAWLs4Khc90rnX/9bagBO/4FQ1hGW9+kxMgNYesEpNuUtw2zimDwqSDxhbOlupxbMUjoIyz5vAEuN0UnXqYawnB+VeBKiCTjqxjNZ6EmNNzIDlt4AqhDaCUlDUeJJiHNATaaYIwECuhClOp8WyhsuoOtRrjhta8u83BnIO2qBhpaq67EUW+4nvP/OgKWm55cBzdjSVaBEZnOzpcoUBDMlTX3tdVs0ii2rkgBx8a0pUcw2FA9h6QAwzZkHsCjlexBbpscBRoonOIqHCOhGlLNAacrLfUGoJSSXBUurAFP55kTrRylH+YwwBegzaSp6K/y6AnGG0hzgDcouwnIrLmmWXyP4uIk6J912FNP7gwjfxqwbDupiYrTjo56gPM5WhHuADicDMZYTkZdFv71HgPQuMMdtXFRpICztYwJgqSnuOpRDhOWO1yS8CqwFerBlXdEAAZ2PYg6yGUBr+paOnIR+rUXodIXbsKWxKIhkhw3gYwlB+eQ9Cf16HOGAa1iPLcdHBWHpEeCQ67sGW66lx8l+IUmdDUITITlWEERAT6Dsd326sWVLJv/cV7Lk/Da+ffiwCUpvTpD4wWO6aYNr14Ut1dl8vC+lliaKMh5DuYQP08cP8HEP5RcxKlAWIKxOETbWFraEcwF7Azhh1LyR+Szx3AYzQ+AMMTqJyEMv+/wAElEs3QxUACvdA2YqEAWeu/Oj3xG35Z2XcOZJmK/XGNoVloExFP5nMvAbItf8IXnK1DcAAAAASUVORK5CYII=', title : '循环', desc : '' },{ name : 'forkJoin', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADWElEQVRYR8WX34sVZRjHP9+tqJtA+uHMuY2gOwkSgugfCLopSLMNE6tNVDwzq6hYrLvBlhvovCNsucUWhiYaeBV40z8Q1E13UXQVnjlh3XQZ7TdGz7F1d+bMnEPie3ne93m+n3eeX+8R93jpHuszMcDjmZ++Tzwn85f+4dr1I7oxyWUmAoiCdwLnBGvAA8B11pgrZnVlXIixATqZpy0uYBaKVPNbMm95SJwDdlpM97v6ahyIsQDi4N3A+aH4eqEo9wWZaeCNItGXbSFaA0RnvVdrrFaJD8Xi4PPAbps3+6k+bwPRCqCTe8ZmZZT4bYjMq4i9Eu/0uvq0CaIRIA7eDyy3ER+KRZlXJGaAA0Wij0dBjASIgg8J8nHE14VjGdhv6PYTna2DqAXoZJ61OD2J+FCsE5wbDkkc7nV1pgqiEiDOfRSzVCceZU40xS7Mkzedil+8xqV+qrBRJM5dXmIWcazo6qON+5sAOsEnDIt14nHmecTJcl/wY+nQsG34W9kbNkFkXkIcFbzbS/TB+v07AOLgOWChVjz4FeBKkaj6ywUb2FEk+nojRBS8KDgBnCwSvT/cv+2ok/sZm+8b6rzc/6bqlqXDwdd5sUi0vSrecfACMCexvdfVD7eiN1hR5rJ2TxWJttZlbBz8p82BfqpLVWeizLsklotEj1TtP7bkh+9/kN+Bw8PyHBfgD5m3e6muVgl0Mr9s8VmR6NHaS2T+GZFtAmgVgtzfsca1kSGY4oWiq2crQ3DGO5jicmUIbsawKQkHFTAqCW3SynL8b5DNF6nKXBhU8AbUpjKMgq8KXiqT1fDTIJGeGlWGw1ki814v1WJtGd5uow2NKM68B3EQeGJg8yuwVFl+ubsyZYM6XiRaamxEwwP/RyuOg48Bp4AjRaLTVXlx94bRIF8skn5XeV1V3JVx3An+0HAcc7BIVU7F2tUIUFp2Ms9Y7R4kUXAmSAT7eolWRonf0QmbDg46ZdOT7BNgn+GtfqLVJp9jAQz6RO2jNA7+AiirY0/RVfk2bLVahWC9pyj3azIX1w+tOLicDa/KvN5LdbGVcl0jamMc32qp5TPrt0E769jM9hNdbmPf2IjaONkavG0Kni//mv0N395I1Wtj17oRTeJsEpuxc2ASkVE2/wK1YaYwksZPTgAAAABJRU5ErkJggg==', title : '执行结束', desc : '' },{ name : 'comment', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD/0lEQVRYR82WT2hcdRDHP9+XGL1YpaTZtzGEotX0UISSih78Uy8t2ksrVPBkVVBKafZtbNOjFUGIjdm3W0xVCjagXrSVglT0orQHlVrQIIoYK2hNXkwo0XowJdmR93Y3vt0k+3aDVn+w8Njf/GY+v5n5zYz4j5eate/6thu4C1gHdBjMCS4a/OSInx1x/pc+XWpUb0MA6bz1mvEkEBoPDddbM4gTBqNTGX2dBFIXIJW3TRTZL/H0MoquAt8jihTpQbTVyMwjjgUZ9dWDWBHAzdlWHN7C6IwUGOOI44Jxc/g26NM3ccWdvvUsQI+MjYh+IFXev6gieyb7dW45kGUB3JwdRjy3eMA4utDGi9P7FCS5NNyPYERBxraYjueDrA7Xnl8CkB62+8zhbOzgw0FWHzRiuFbGzdkAYjCm68Egq0/icksAXN9+AG4NhQJPDSVpEpzrm0UyYsJgezw5qwy4eStg7C/H/FCQ1UsrKe8csvZiC58i5lqL3H+pX5dXknVz9hDiTJRKxutTWT1TkV0E6Mrb7fMwhnGDiY+mMtpe72ZVeWIsG9/4eTdnBVS6nMSWyYwulJxSXjGFUw48MOHpuyTXpvL2powrgae9SbLrXjG35SrnEBuAkcDTvkWADQW7/g+Lbn8HcCDw9HKSwtXsuzk7gDgCTAeeOhYB3JztQLxfjv2STF3O2NqCrWkrcjrc+9PYNZvVbBJUeti2mcOHZblHA0/vRCFwc7YXMRJ+z8+xZuaQriQpiwqV+HgV0L+VdR8JPA1UAAYRA8CFwNOWJONl6KYBonO+fQXcCZwIPD1RAvDtJPBI7RNJeAWrAkj7dtzgKeBM4GlHBJDy7ZRg17UAcH0bAp6VOD2Z0c6KB6I/r0UI0r69bfAY4mjYKSseCD/y/3YSlsMdJu5WjINBVkMRQDpvoftPNZPRq3kFbs7WI34s29kdZPVuCcC3bgvLMNzUaCFaDUAqbxkZPjDT4rA5HN3+LsV5G8EIS2pDpbhZgKpSLIaCjA5W9YK0b/caRFNLg82oqWcYa0bzJjZXWnJVO0759p5gZzlGddtxMx6It2MgqoCVGlMF0FGw21TkC8HNoUC9gaRr2NbOO7yKEdDCC0GfplcqXIsDCXweeLonLrd0JIu/iCge/GMjmQMba9v8/28orbgnnGyLMArcXc6JceA1GWNzrXx2uU+/x13ZPmg3trbRi+gFwgyPxnKDWYn+IKM3lgtR4tDp+hbOhVmgtUbBmOB80VhQyWj4q1phbynCsemsvlwpPxIBomaVt02CxzH2AO1127WYoMhJOYxW5r568g0BVBTcUrCuhQXCLF6PQ7eg24zrgF/DMcvg7JSn0mTV4GoKoEGdTYn9Bf4L6DCOEiGKAAAAAElFTkSuQmCC', title : '注释', desc : '仅仅是注释,毫无作用' },{ name : 'output', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAByUlEQVRYR+WXwVHDMBBF/4YD3AgHwEd3QKiA0IE7IOnAqoCkAqWDmAqACggVJJTAzRku4UYOmWVWloMZgi17bGcGdNGMrZWeVtrdL4JtXc3dI8I9gH76rWIfxSENXW0pHehpHoAwdTXMHccYx4pGLnNlAUYg3BojxtjFODPGB+Hmmw1jGCuKiubZCRCHtP1eNIH89zT3QXgy7IwXIlzYjRRC1A7wwTg5BGauELUDiPfkQrtCNAIg7neFaAzAFaJRAIE41dzrJHfieNfFrB2gMGoYz7GibbL7GwAmjQO9vN0zMDGh2YQHCt2eJKsZCFf/F+A3L9VyCV2OQMLxgKA3DPWmaJHatAbgaTbVloHFmnG9UrQSiDYBfFlcEpL0y5AuWwWQxc40B51EdUkzyqmUB6xs0wB8l3PfNYaBHgFdqx1UKYCs8KgKkLVjYFUKwJbYKN1BFQjjga/CNC4FUGXBrI0NxbmtinexokFrAJ5mnwlz8Z7oxjXQl1BsEyDJA4z3NeC3ngeM+4HJBgj3kgn3XgvONRs9IOe/VBTuoxa46wEQnN51pcKSMTAZNEcR1fc4zSFjxuNSUfDjCKyuezCyqanGeN0AQTYKPgFOSUMAph/CYQAAAABJRU5ErkJggg==', title : '输出', desc : '输出流程中的变量结果(仅测试下有用)' },{ name : 'executeSql', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD1ElEQVRYR7WXUXIaRxCGv4YqR2+WH2zxZukEUU5gdAKjExhfILAnMD7BohMYn8D4BEYnsHQCobfd5CHkDVIFnerZmc0sLAJjMlVUSbszPX93//13r7DnOk319JcGb0TpAOfRzyxMw0+F8WLF7SyR2T6mZdemVqrnCB+A7sZe5dE9E17X2BmhfMwSMXBb11YAzmPhg0DfnVYeFcYKkz8SGddZfJVqR6At0ClBCYP5ipttEakF4C//JnCpyt/AIE9kuCta8fuzVA34QITnCncL5aoOxAaAl6leNgS7/FSVrwvo7pvPdYDOERiJ8FZhtlKu/kzkLt5XAeA9f/CX3+SJFOH/yXWW6lCEnoFYKBexQyWAtbAf7fKAPQJRSUcJoNygfM0TsVI7+jpLdWzp8NUxKAoI8KX2YIRbwPmhOd+F2HNiasREubASDQBGCO9USdbZ3kq1TRPNfpfb9Qsc8CavWfIY17sRudnk+XzJ/bozrVQHTleUz1kiXTFUJ8JfVudZIqZwbjkjwhevePZoulSuA4tLQ36/wjDvS+IjOkF4g3KVJTKpAT41nZgrL8TEoyF8UaVCvFaqbpOVooEQ4Ver57wvv7moCN8sZVKIU8eH9X2WyKiV6i4ALuIr5VpaqZb/BIWLOHGfJ3LpvXKAsr7YGRdGM2Bn1p3YBSDstzSYMYfWDIdQBQ9RbrNE2h6A9YLzLJFBlEcX4vX9uwA4e0NVs28ASs/iXLkN1uWKPFYayrEAWErFI6kQ0IAEXbC/rQmJchMIdRQA3nEHIJCrhq0mFt2ysxXt9TgpKAFsSUElHakaiE+m5XlfXhwlAua4cl9LwjpFi8l6LACBhBtl6EUo9Wo1isUlLkMj6BJmTaHnUuWrZlcVVMqwTog8gO+BG14tv7syjHTApNuGFhMVF7X/OLK/EJVSDNOsLxdR+7wz9aukw+u3CZUrIWsq0QqTzwmMnRRXX8aaUpb+1mbkgMHQZNa3zfEc+qG5mPiY/juJLuR6YvPjEjoN6LrIrIGzAWejGfn82uT7UDex1BHy0GfxxFVpxx6E03cTnbwv14de8tS5iJxOT3xkiyN+WJj4kP5/I5lyv4B2SOXmUApuYon7+89GIxr3Niau+rHcCFWAGC+U94eOaD7nn+xDxWaHFbSfHMuDp5V0wAxhkPfk5kciYWxXoedH/ErYYztPfpqd2GdZ8V1oa2oRQZjkPbGy21he1N4CNkMU453ycQ7DH/o0iy276QisQgq1q64wJ5SzZPla+WznDv44Xb/J0vIM2o1CmEwJT4NSuq5mqYLpCsb/wGRf3vwLgODoY+vqQ1gAAAAASUVORK5CYII=', title : '执行SQL', desc : '执行sql,需配置数据源,sql执行结果存于变量rs中。
语句类型为:select,返回:List<Map<String,Object>>
语句类型为:selectOne,返回:Map<String,Object>
语句类型为:selectInt,返回:Integer
语句类型为:insert、update、delete,返回:int,批量操作返回int数组
sql中变量必须用 # # 包裹,如:#${title}#' },{ name : 'function', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAAgCAYAAACPb1E+AAAC9UlEQVRYR+2YP0zUUBjAf9+RKJPgQK6THptxERPiZOTUxEUj/tlMjCS62xoT3YARl5bJTXByBGcHISQmxhjQ6A6TPRg8JrnE62de6Z0Htne9XhMw4W1N3/u+X7//rwJgzeokygRQMs+HYSksBsr0liNrYrk6gTB3GMBiGNZ9W4al6OqiCOOqfFGYKkD1oIEVRkRwQw5l2FhyCWEMZdp3ZOqgARv6LU/1CDIPbxxZMg8rhmUxj5gcdHWw6khiJSh6+lVgAGXMd2S90/79H9czpOXpd+CsKk7FEe8fBab2whwCdeF6n/ISOFUPuLT1RFbSWLsnSMvTOVUmREJVM74tz1uVGov1C6tR9/rs2zJqefoL6FfYDpSy6SKdQDNDGkAI2yeqvKk4ci/GilMIk40aZ1w95OpIQVgWOKFQDZTLnUAzQbYCorz2HQlhW5flakmFVYFBVWYrjtiN9yEoLIkwkAa0a0jL0x8m4SLrxAKGGenqPMIDVbZrUNqfWE1Qk1AFqAc83HLkVZzrs0AGgKhQDwJG41xluVpGeB99SGKLtTx9i3LTJFUAC5u23MkFcsjTZwWYFjie5CrLUwNYRtnwHYkd+fbENHyr/eZG9als5AJphLSLqdZxL1BubzqyGFP3mkmXFNN74jtrMW8FRdgB7u4EfGiWHGXZd6QcA7iCcBEz1yQkXa7F3ID2wUeEY0HATJ9wRoVxo6SunI+N18gqCu8qtlzrVCNzaYtFVx8BVwJ4UYB5Ec4pfKrYciEOoOiqjXC1ptxv10pzcXccQBQC5VqdhaQkSGO5XN2dRWGWM13XySxKej1zBNmrBRvnYy25fyDIS1kWOdG49zNqseG92xPhcSRsqWuhgoXSn3jOFH3F71Kuaatha91RTpp7d0lhzYxQXQra3W66yO4AHL86vW+nNOpOofgI9JaZAzOAmt80p9tAmgFivlu5Aaw1ZoB2Nkglt/kHJNmSsf08lfBoU2pIy9W/14JuNCTs9e3olpRC1n8B+Qd0Dhp9ddQMugAAAABJRU5ErkJggg==', title : '执行函数', desc : '单独执行函数方法,结果不保存为变量' },{ name : 'process', image : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMklEQVRYR+2WwXHTQBSGv+fMkNwIB7BvMRVgV0DoIFRAUoGlCpJUsKICnApCB4QKcCrAvslwwEebGfyYp2g1QgmytBmPOaCjtLv/t+/9+neFHT+yY31aAxw6PdwXzgVOgH5lA1OEcTqSy6Ybaw3QdZqIMKoTUOX9PJaoCUQIwEKEp7+U4fdYJmWR504He8IXYJpG8tK+9RJVP0ZhIkKSjuTKv9sOgDJLY8naUwYog6yUN4tYFq0Bek4vEM5ry6tcprFclMeYd57AcQcShCOrxjySYWsAWzTzgZlQOPoDRJkB46p4FeQAJtlc5SwIoIm56sa8cHrSEa4zTzx2sZD51o4D4YfN3QlAz2kf4evOAIoWKLetKxCShD2np2ksY9txXn7Lin6QCdsmoYkjfFgqz/Y7vBYlMXFVbuexDB6sQNdphPBOYOBNlkaSje06bZyEXrxqVBNfwfG9IMrL+6ksHASQJ2EVwIQFEt+OeybsOrWsfoUyW0P0E26MsryDtknoIXwFq9UoWmBlF8GZ+BIGVeHyxLZJWDZhHUC2+7Xy9lssH0MCJmROUQF/aplb63YfIlI3598B8AbcWQsKE8J0qQx9G3pO7Xg99WUMScJGLchD5u43hKkK0WrN5/zUGqeRnBV3gW3dCbPdwU0OUQXPINokYRPDPhjF9t8qWC5YNe4e5cpa0QigdCfcBLHxNMx+z1zcFmubhI8HqJiw8EHgnfCvSbiJdFvfN7ZgW8J+3f8AvwFIqFFyobd5IgAAAABJRU5ErkJggg==', title : '子流程', desc : '执行其他spiderFlow流程,父子流程变量共享' }]; var addShape = function(shape){ var image = new Image(); image.src = shape.image; image.title = shape.title; image.id = shape.name; image.onclick = function (ev) { if(shape.desc){ layer.tips("(" + shape.name + ")" + shape.title + "
" + shape.desc, '#' + shape.name,{ tips: [1, '#3595CC'], area: ['auto', 'auto'], time: 4000 }); } } if(!shape.hidden){ container.appendChild(image); } if(!shape.disabled){ editor.addShape(shape.name,shape.title || 'Label',image,shape.defaultAdd); } } for(var i =0,len = shapes.length;imaxT-150) moveLen = maxT-150; if(box.clientWidth - moveLen < 400 || box.clientWidth - moveLen > 800){ return; } resize.style.left = moveLen + 'px'; $(".editor-container").css('right',($('body').width() - moveLen) + 'px') $(".properties-container").width(box.clientWidth - moveLen - 5); $(".xml-container").width($(".main-container").width() - $(".properties-container").width() - $(".sidebar-container").width() + 8); } document.onmouseup = function(evt){ document.onmousemove = null; document.onmouseup = null; resize.releaseCapture && resize.releaseCapture(); } resize.setCapture && resize.setCapture(); return false; } }).on('click','.btn-dock-bottom',function(){ resizeSlideBar(); $('.main-container').removeClass('right'); $('.properties-container').height(200).width('100%'); $('.sidebar-container').css('bottom','200px'); $('.editor-container').css('bottom','200px'); $('.main-container .resize-container').attr('style','left:0px;top:auto;bottom:190px'); var resize = $('.resize-container')[0] resize.onmousedown = function(e){ var startY = e.clientY; resize.top = resize.offsetTop; var box = $("body")[0]; var maxT = box.clientHeight; document.onmousemove = function(e){ var moveLen = e.clientY; if(moveLen<250) moveLen = 250; if(moveLen>maxT-150) moveLen = maxT-150; resize.style.top = moveLen + 'px'; resizeSlideBar(); $(".editor-container,.sidebar-container,.xml-container").css('bottom',($('body').height() - moveLen) + 'px'); $(".properties-container").height(box.clientHeight - moveLen - 5); } document.onmouseup = function(evt){ document.onmousemove = null; document.onmouseup = null; resize.releaseCapture && resize.releaseCapture(); } resize.setCapture && resize.setCapture(); return false; } }) $('.btn-dock-bottom').click(); } function runSpider(debug){ validXML(function(){ $(".btn-debug,.btn-test,.btn-resume").addClass('disabled'); $(".btn-stop").removeClass('disabled'); var LogViewer; var tableMap = {}; var first = true; var filterText = ''; var testWindowIndex = layui.layer.open({ id : 'test-window', type : 1, skin : 'layer-test', content : '
    ', area : ["680px","400px"], shade : 0, offset : 'rt', maxmin :true, maxWidth : 700, maxHeight : 400, title : '测试窗口', btn : ['关闭','显示/隐藏输出','显示/隐藏日志','停止'], btn2 : function(){ var $output = $(".test-window-container .output-container"); var $log = $(".test-window-container .log-container"); if($output.is(":hidden")){ $output.show(); $output.find("canvas").each(function(){ if($log.is(":hidden")){ this.height = 290; }else{ this.height = 200; } }) $log.attr('height',100) LogViewer.resize(); for(var tableId in tableMap){ tableMap[tableId].instance.resize(); } }else{ $output.hide(); $log.attr('height',320); LogViewer.resize(); for(var tableId in tableMap){ tableMap[tableId].instance.resize(); } } return false; }, btn3 : function(){ var $output = $(".test-window-container .output-container"); var $log = $(".test-window-container .log-container"); if($log.is(":hidden")){ $log.show(); $log.attr('height',$output.is(":hidden") ? 320 : 100) $output.find("canvas").each(function(){ this.height = 200; }); LogViewer.resize(); for(var tableId in tableMap){ tableMap[tableId].instance.resize(); } }else{ $log.hide(); $output.find("canvas").each(function(){ this.height = 320; }); LogViewer.resize(); for(var tableId in tableMap){ tableMap[tableId].instance.resize(); } } return false; }, btn4 : function(){ var $btn = $("#layui-layer" + testWindowIndex).find('.layui-layer-btn3'); if($btn.html() == '停止'){ socket.send(JSON.stringify({ eventType : 'stop' })); }else{ $(".btn-debug,.btn-test,.btn-resume").addClass('disabled'); $(".btn-stop").removeClass('disabled'); socket.send(JSON.stringify({ eventType : debug ? 'debug' : 'test', message : editor.getXML() })); $btn.html('停止'); } return false; }, end : function(){ if(socket){ socket.close(); $(".spiderflow-debug-tooltip").remove(); $(".btn-stop,.btn-resume").addClass('disabled'); $(".btn-test,.btn-debug").removeClass('disabled') } if(LogViewer){ LogViewer.destory(); } for(var tableId in tableMap){ tableMap[tableId].instance.destory(); } }, success : function(layero,index){ var logElement = $(".test-window-container .log-container")[0]; var colors = { 'array' : '#2a00ff', 'object' : '#2a00ff', 'boolean' : '#600100', 'number' : '#000E59' } LogViewer = new CanvasViewer({ element : logElement, onClick : function(e){ onCanvasViewerClick(e,'日志'); } }); $(layero).find(".layui-layer-btn") .append('
    ') .on("keyup","input",function(){ LogViewer.filter(this.value); }); socket = createWebSocket({ onopen : function(){ socket.send(JSON.stringify({ eventType : debug ? 'debug' : 'test', message : editor.getXML() })); }, onmessage : function(e){ var event = JSON.parse(e.data); var eventType = event.eventType; var message = event.message; if(eventType == 'finish'){ $(".spiderflow-debug-tooltip").remove(); $("#layui-layer" + testWindowIndex).find('.layui-layer-btn3').html('重新开始'); $(".btn-stop,.btn-resume").addClass('disabled'); $(".btn-test,.btn-debug").removeClass('disabled') }else if(eventType == 'output'){ var tableId = 'output-' + message.nodeId; var $table = $('#' + tableId); if($table.length == 0){ tableMap[tableId] = { index : 0 }; var $tab = $(".test-window-container .output-container .layui-tab") var outputTitle = '输出-'+tableId; var cell = editor.getModel().cells[message.nodeId]; if(cell){ outputTitle = cell.value; } if(first){ $tab.find(".layui-tab-title").append('
  • ' + outputTitle + '
  • '); $tab.find(".layui-tab-content").append('
    '); first = false; }else{ $tab.find(".layui-tab-title").append('
  • ' + outputTitle + '
  • '); $tab.find(".layui-tab-content").append('
    '); } $table = $('').appendTo($(".test-window-container .output-container .layui-tab-item[data-output="+tableId+"]")); $table.attr('id',tableId); tableMap[tableId].instance = new CanvasViewer({ element : document.getElementById(tableId), grid : true, header : true, style : { font : 'bold 13px Consolas' }, onClick : function(e){ onCanvasViewerClick(e,'表格'); } }) var cols = []; var texts = [new CanvasText({ text : '序号', maxWidth : 100 })]; for(var i =0,len = message.outputNames.length;i o2.top + $parent.height()){ $parent[0].scrollTop = o1.top - o2.top; } var msg = message.value; var isJson = Array.isArray(msg) || typeof msg == 'object'; if(!isJson){ var temp = document.createElement("div"); (temp.textContent != null) ? (temp.textContent = msg) : (temp.innerText = msg); msg = temp.innerHTML; temp = null; } var content = '
    '+(isJson ? '' : msg.replace(/\n/g,'
    ')).replace(/ /g,' ').replace(/\t/g,'    ')+'
    '; var tooltip = bindTooltip(content,selector); if(isJson){ var $dom = $(tooltip.dom).find(".message-content"); jsonTree.create(msg,$dom[0]); } } } }); } }) }); } function bindTooltip(content,selector){ var dom = document.createElement('div'); var $target = $(selector); var offset = $target.offset(); dom.className = 'spiderflow-debug-tooltip'; dom.style.bottom = ($("body").height() - offset.top) + 'px'; dom.style.left = (offset.left + $target.width() / 2) + 'px'; dom.innerHTML = '
    ' + content + '
    '; document.body.appendChild(dom); $(selector).offset(); return { dom : dom, close : function(){ document.body.removeChild(dom); } } } //最近点击打开的弹窗 var index; function onCanvasViewerClick(e,source){ var msg = e.text; var json; try{ json = JSON.parse(msg); if(!(Array.isArray(json) || typeof json == 'object')){ json = null; } }catch(e){ } if(!json){ var temp = document.createElement("div"); (temp.textContent != null) ? (temp.textContent = msg) : (temp.innerText = msg); msg = temp.innerHTML; temp = null; } layer.close(index); index = layer.open({ type : 1, title : source +'内容', content: '
    '+(json ? '' : msg.replace(/\n/g,'
    ')).replace(/ /g,' ').replace(/\t/g,'    ')+'
    ', shade : 0, area : json ? ['700px','500px'] : 'auto', maxmin : true, maxWidth : (json ? undefined : 700), maxHeight : (json ? undefined : 400), success : function(dom,index){ var $dom = $(dom).find(".message-content"); if(json){ jsonTree.create(json,$dom[0]); } } }); } function createWebSocket(options){ options = options || {}; var socket; if(location.host === 'demo.spiderflow.org'){ socket = new WebSocket(options.url || 'ws://49.233.182.130:8088/ws'); }else{ socket = new WebSocket(options.url || (location.origin.replace("http",'ws') + '/ws')); } socket.onopen = options.onopen; socket.onmessage = options.onmessage; socket.onerror = options.onerror || function(){ layer.layer.msg('WebSocket错误'); } return socket; } var flowId; function Save(){ validXML(function(){ $.ajax({ url : 'spider/save', type : 'post', data : { id : getQueryString('id') || flowId, xml : editor.getXML(), name : editor.graph.getModel().getRoot().data.get('spiderName') || '未定义名称', }, success : function(id) { flowId = id; layui.layer.msg('保存成功', { time : 800 }, function() { // location.href = "spiderList.html"; }) } }) }); } function allowDrop(ev){ ev.preventDefault(); } function drag(ev){ ev.dataTransfer.setData("moverTarget", ev.target.id); } function drop(ev){ var moverTargetId = ev.dataTransfer.getData("moverTarget"); $(ev.target).parents(".draggable").before($("#" + moverTargetId)); ev.preventDefault(); serializeForm(); } ================================================ FILE: spider-flow-web/src/main/resources/static/js/index.js ================================================ var $ = layui.$; function setCookie(name,value){ var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } function getCookie(name){ var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return unescape(arr[2]); else return null; } function setTheSkin(value){ if(!value){ value = "layui-blue"; } document.querySelector('#theSkin').setAttribute('href','css/'+value+'.css'); } setTheSkin(getCookie('theSkin')); function openTab(title,id,href){ if($(".layui-tab[lay-filter=admin-tab]").find("[lay-id="+id+"]").length > 0){ //判断是否已打开 var $dom = $(".layui-tab[lay-filter=admin-tab]"); var index = $dom.find("[lay-id="+id+"]").index(); $dom.find(".layui-tab-content .layui-tab-item").eq(index).find("iframe").attr("src",href); }else{ var html = ''; layui.element.tabAdd('admin-tab',{ title:title, content:html, id:id, }); } layui.element.tabChange("admin-tab",id); } $(function(){ $.ajax({ url:'spider/pluginConfigs', success:function(data){ for(var i =0;i'+data[i].name+''); } layui.element.init(); initMenu(); } }) }); function initMenu() { $("body").on('click','.menu-list li a',function(){ $(this).parents("ul").siblings().find("li.layui-this,dd.layui-this").removeClass('layui-this') }).on('click','.menu-list > ul',function(){ $(this).siblings().find('.layui-nav-itemed').removeClass('layui-nav-itemed') }).on('click','.menu-list a',function(){ var href = $(this).data('link'); if(href){ var title = $(this).html(); openTab(title, title, href); return false; } }).on('click','.layui-layout-right .layui-nav-child a',function(e){ e.preventDefault(); var value = $(this).data('value'); setTheSkin(value); setCookie('theSkin',value); }); } ================================================ FILE: spider-flow-web/src/main/resources/static/js/jsontree/jsontree.css ================================================ /* * JSON Tree Viewer * http://github.com/summerstyle/jsonTreeViewer * * Copyright 2017 Vera Lobacheva (http://iamvera.com) * Released under the MIT license (LICENSE.txt) */ /* Background for the tree. May use for element */ .jsontree_bg { background: #FFF; } /* Styles for the container of the tree (e.g. fonts, margins etc.) */ .jsontree_tree { margin-left: 30px; font-family: 'PT Mono', monospace; font-size: 14px; } /* Styles for a list of child nodes */ .jsontree_child-nodes { display: none; margin-left: 35px; margin-bottom: 5px; line-height: 2; } .jsontree_node_expanded > .jsontree_value-wrapper > .jsontree_value > .jsontree_child-nodes { display: block; } /* Styles for labels */ .jsontree_label-wrapper { float: left; margin-right: 8px; } .jsontree_label { font-weight: normal; vertical-align: top; color: #000; position: relative; padding: 1px; border-radius: 4px; cursor: default; } .jsontree_node_marked > .jsontree_label-wrapper > .jsontree_label { background: #fff2aa; } /* Styles for values */ .jsontree_value-wrapper { display: block; overflow: hidden; } .jsontree_node_complex > .jsontree_value-wrapper { overflow: inherit; } .jsontree_value { vertical-align: top; display: inline; } .jsontree_value_null { color: #777; font-weight: bold; } .jsontree_value_string { color: #025900; font-weight: bold; } .jsontree_value_number { color: #000E59; font-weight: bold; } .jsontree_value_boolean { color: #600100; font-weight: bold; } /* Styles for active elements */ .jsontree_expand-button { position: absolute; top: 3px; left: -15px; display: block; width: 11px; height: 11px; background-image: url('icons.svg'); } .jsontree_node_expanded > .jsontree_label-wrapper > .jsontree_label > .jsontree_expand-button { background-position: 0 -11px; } .jsontree_show-more { cursor: pointer; } .jsontree_node_expanded > .jsontree_value-wrapper > .jsontree_value > .jsontree_show-more { display: none; } .jsontree_node_empty > .jsontree_label-wrapper > .jsontree_label > .jsontree_expand-button, .jsontree_node_empty > .jsontree_value-wrapper > .jsontree_value > .jsontree_show-more { display: none !important; } .jsontree_node_complex > .jsontree_label-wrapper > .jsontree_label { cursor: pointer; } .jsontree_node_empty > .jsontree_label-wrapper > .jsontree_label { cursor: default !important; } ================================================ FILE: spider-flow-web/src/main/resources/static/js/jsontree/jsontree.js ================================================ /** * JSON Tree library (a part of jsonTreeViewer) * http://github.com/summerstyle/jsonTreeViewer * * Copyright 2017 Vera Lobacheva (http://iamvera.com) * Released under the MIT license (LICENSE.txt) */ var jsonTree = (function() { /* ---------- Utilities ---------- */ var utils = { /* * Returns js-"class" of value * * @param val {any type} - value * @returns {string} - for example, "[object Function]" */ getClass : function(val) { return Object.prototype.toString.call(val); }, /** * Checks for a type of value (for valid JSON data types). * In other cases - throws an exception * * @param val {any type} - the value for new node * @returns {string} ("object" | "array" | "null" | "boolean" | "number" | "string") */ getType : function(val) { if (val === null) { return 'null'; } switch (typeof val) { case 'number': return 'number'; case 'string': return 'string'; case 'boolean': return 'boolean'; } switch(utils.getClass(val)) { case '[object Array]': return 'array'; case '[object Object]': return 'object'; } throw new Error('Bad type: ' + utils.getClass(val)); }, /** * Applies for each item of list some function * and checks for last element of the list * * @param obj {Object | Array} - a list or a dict with child nodes * @param func {Function} - the function for each item */ forEachNode : function(obj, func) { var type = utils.getType(obj), isLast; switch (type) { case 'array': isLast = obj.length - 1; obj.forEach(function(item, i) { func(i, item, i === isLast); }); break; case 'object': var keys = Object.keys(obj).sort(); isLast = keys.length - 1; keys.forEach(function(item, i) { func(item, obj[item], i === isLast); }); break; } }, /** * Implements the kind of an inheritance by * using parent prototype and * creating intermediate constructor * * @param Child {Function} - a child constructor * @param Parent {Function} - a parent constructor */ inherits : (function() { var F = function() {}; return function(Child, Parent) { F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; }; })(), /* * Checks for a valid type of root node* * * @param {any type} jsonObj - a value for root node * @returns {boolean} - true for an object or an array, false otherwise */ isValidRoot : function(jsonObj) { switch (utils.getType(jsonObj)) { case 'object': case 'array': return true; default: return false; } }, /** * Extends some object */ extend : function(targetObj, sourceObj) { for (var prop in sourceObj) { if (sourceObj.hasOwnProperty(prop)) { targetObj[prop] = sourceObj[prop]; } } } }; /* ---------- Node constructors ---------- */ /** * The factory for creating nodes of defined type. * * ~~~ Node ~~~ is a structure element of an onject or an array * with own label (a key of an object or an index of an array) * and value of any json data type. The root object or array * is a node without label. * {... * [+] "label": value, * ...} * * Markup: *
  • * * * * "label" * * : * * <(div|span) class="jsontree_value jsontree_value_(object|array|boolean|null|number|string)"> * ... * *
  • * * @param label {string} - key name * @param val {Object | Array | string | number | boolean | null} - a value of node * @param isLast {boolean} - true if node is last in list of siblings * * @return {Node} */ function Node(label, val, isLast) { var nodeType = utils.getType(val); if (nodeType in Node.CONSTRUCTORS) { return new Node.CONSTRUCTORS[nodeType](label, val, isLast); } else { throw new Error('Bad type: ' + utils.getClass(val)); } } Node.CONSTRUCTORS = { 'boolean' : NodeBoolean, 'number' : NodeNumber, 'string' : NodeString, 'null' : NodeNull, 'object' : NodeObject, 'array' : NodeArray }; /* * The constructor for simple types (string, number, boolean, null) * {... * [+] "label": value, * ...} * value = string || number || boolean || null * * Markup: *
  • * * "age" * : * * 25 * , *
  • * * @abstract * @param label {string} - key name * @param val {string | number | boolean | null} - a value of simple types * @param isLast {boolean} - true if node is last in list of parent childNodes */ function _NodeSimple(label, val, isLast) { if (this.constructor === _NodeSimple) { throw new Error('This is abstract class'); } var self = this, el = document.createElement('li'), labelEl, template = function(label, val) { var str = '\ \ "' + label + '" : \ \ \ ' + val + '' + (!isLast ? ',' : '') + ''; return str; }; self.label = label; self.isComplex = false; el.classList.add('jsontree_node'); el.innerHTML = template(label, val); self.el = el; labelEl = el.querySelector('.jsontree_label'); labelEl.addEventListener('click', function(e) { if (e.altKey) { self.toggleMarked(); return; } if (e.shiftKey) { document.getSelection().removeAllRanges(); alert(self.getJSONPath()); return; } }, false); } _NodeSimple.prototype = { constructor : _NodeSimple, /** * Mark node */ mark : function() { this.el.classList.add('jsontree_node_marked'); }, /** * Unmark node */ unmark : function() { this.el.classList.remove('jsontree_node_marked'); }, /** * Mark or unmark node */ toggleMarked : function() { this.el.classList.toggle('jsontree_node_marked'); }, /** * Expands parent node of this node * * @param isRecursive {boolean} - if true, expands all parent nodes * (from node to root) */ expandParent : function(isRecursive) { if (!this.parent) { return; } this.parent.expand(); this.parent.expandParent(isRecursive); }, /** * Returns JSON-path of this * * @param isInDotNotation {boolean} - kind of notation for returned json-path * (by default, in bracket notation) * @returns {string} */ getJSONPath : function(isInDotNotation) { if (this.isRoot) { return "$"; } var currentPath; if (this.parent.type === 'array') { currentPath = "[" + this.label + "]"; } else { currentPath = isInDotNotation ? "." + this.label : "['" + this.label + "']"; } return this.parent.getJSONPath(isInDotNotation) + currentPath; } }; /* * The constructor for boolean values * {... * [+] "label": boolean, * ...} * boolean = true || false * * @constructor * @param label {string} - key name * @param val {boolean} - value of boolean type, true or false * @param isLast {boolean} - true if node is last in list of parent childNodes */ function NodeBoolean(label, val, isLast) { this.type = "boolean"; _NodeSimple.call(this, label, val, isLast); } utils.inherits(NodeBoolean,_NodeSimple); /* * The constructor for number values * {... * [+] "label": number, * ...} * number = 123 * * @constructor * @param label {string} - key name * @param val {number} - value of number type, for example 123 * @param isLast {boolean} - true if node is last in list of parent childNodes */ function NodeNumber(label, val, isLast) { this.type = "number"; _NodeSimple.call(this, label, val, isLast); } utils.inherits(NodeNumber,_NodeSimple); /* * The constructor for string values * {... * [+] "label": string, * ...} * string = "abc" * * @constructor * @param label {string} - key name * @param val {string} - value of string type, for example "abc" * @param isLast {boolean} - true if node is last in list of parent childNodes */ function NodeString(label, val, isLast) { this.type = "string"; _NodeSimple.call(this, label, '"' + val + '"', isLast); } utils.inherits(NodeString,_NodeSimple); /* * The constructor for null values * {... * [+] "label": null, * ...} * * @constructor * @param label {string} - key name * @param val {null} - value (only null) * @param isLast {boolean} - true if node is last in list of parent childNodes */ function NodeNull(label, val, isLast) { this.type = "null"; _NodeSimple.call(this, label, val, isLast); } utils.inherits(NodeNull,_NodeSimple); /* * The constructor for complex types (object, array) * {... * [+] "label": value, * ...} * value = object || array * * Markup: *
  • * * * * "label" * * : * *
    * { *
      * } * , *
    *
  • * * @abstract * @param label {string} - key name * @param val {Object | Array} - a value of complex types, object or array * @param isLast {boolean} - true if node is last in list of parent childNodes */ function _NodeComplex(label, val, isLast) { if (this.constructor === _NodeComplex) { throw new Error('This is abstract class'); } var self = this, el = document.createElement('li'), template = function(label, sym) { var comma = (!isLast) ? ',' : '', str = '\
    \
    \ ' + sym[0] + '\ \
      \ ' + sym[1] + '' + '
      ' + comma + '
      '; if (label !== null) { str = '\ \ ' + '' + '"' + label + '" : \ ' + str; } return str; }, childNodesUl, labelEl, moreContentEl, childNodes = []; self.label = label; self.isComplex = true; el.classList.add('jsontree_node'); el.classList.add('jsontree_node_complex'); el.innerHTML = template(label, self.sym); childNodesUl = el.querySelector('.jsontree_child-nodes'); if (label !== null) { labelEl = el.querySelector('.jsontree_label'); moreContentEl = el.querySelector('.jsontree_show-more'); labelEl.addEventListener('click', function(e) { if (e.altKey) { self.toggleMarked(); return; } if (e.shiftKey) { document.getSelection().removeAllRanges(); alert(self.getJSONPath()); return; } self.toggle(e.ctrlKey || e.metaKey); }, false); moreContentEl.addEventListener('click', function(e) { self.toggle(e.ctrlKey || e.metaKey); }, false); self.isRoot = false; } else { self.isRoot = true; self.parent = null; el.classList.add('jsontree_node_expanded'); } self.el = el; self.childNodes = childNodes; self.childNodesUl = childNodesUl; utils.forEachNode(val, function(label, node, isLast) { self.addChild(new Node(label, node, isLast)); }); self.isEmpty = !Boolean(childNodes.length); if (self.isEmpty) { el.classList.add('jsontree_node_empty'); } } utils.inherits(_NodeComplex, _NodeSimple); utils.extend(_NodeComplex.prototype, { constructor : _NodeComplex, /* * Add child node to list of child nodes * * @param child {Node} - child node */ addChild : function(child) { this.childNodes.push(child); this.childNodesUl.appendChild(child.el); child.parent = this; }, /* * Expands this list of node child nodes * * @param isRecursive {boolean} - if true, expands all child nodes */ expand : function(isRecursive){ if (this.isEmpty) { return; } if (!this.isRoot) { this.el.classList.add('jsontree_node_expanded'); } if (isRecursive) { this.childNodes.forEach(function(item, i) { if (item.isComplex) { item.expand(isRecursive); } }); } }, /* * Collapses this list of node child nodes * * @param isRecursive {boolean} - if true, collapses all child nodes */ collapse : function(isRecursive) { if (this.isEmpty) { return; } if (!this.isRoot) { this.el.classList.remove('jsontree_node_expanded'); } if (isRecursive) { this.childNodes.forEach(function(item, i) { if (item.isComplex) { item.collapse(isRecursive); } }); } }, /* * Expands collapsed or collapses expanded node * * @param {boolean} isRecursive - Expand all child nodes if this node is expanded * and collapse it otherwise */ toggle : function(isRecursive) { if (this.isEmpty) { return; } this.el.classList.toggle('jsontree_node_expanded'); if (isRecursive) { var isExpanded = this.el.classList.contains('jsontree_node_expanded'); this.childNodes.forEach(function(item, i) { if (item.isComplex) { item[isExpanded ? 'expand' : 'collapse'](isRecursive); } }); } }, /** * Find child nodes that match some conditions and handle it * * @param {Function} matcher * @param {Function} handler * @param {boolean} isRecursive */ findChildren : function(matcher, handler, isRecursive) { if (this.isEmpty) { return; } this.childNodes.forEach(function(item, i) { if (matcher(item)) { handler(item); } if (item.isComplex && isRecursive) { item.findChildren(matcher, handler, isRecursive); } }); } }); /* * The constructor for object values * {... * [+] "label": object, * ...} * object = {"abc": "def"} * * @constructor * @param label {string} - key name * @param val {Object} - value of object type, {"abc": "def"} * @param isLast {boolean} - true if node is last in list of siblings */ function NodeObject(label, val, isLast) { this.sym = ['{', '}']; this.type = "object"; _NodeComplex.call(this, label, val, isLast); } utils.inherits(NodeObject,_NodeComplex); /* * The constructor for array values * {... * [+] "label": array, * ...} * array = [1,2,3] * * @constructor * @param label {string} - key name * @param val {Array} - value of array type, [1,2,3] * @param isLast {boolean} - true if node is last in list of siblings */ function NodeArray(label, val, isLast) { this.sym = ['[', ']']; this.type = "array"; _NodeComplex.call(this, label, val, isLast); } utils.inherits(NodeArray, _NodeComplex); /* ---------- The tree constructor ---------- */ /* * The constructor for json tree. * It contains only one Node (Array or Object), without property name. * CSS-styles of .tree define main tree styles like font-family, * font-size and own margins. * * Markup: *
        * {Node} *
      * * @constructor * @param jsonObj {Object | Array} - data for tree * @param domEl {DOMElement} - DOM-element, wrapper for tree */ function Tree(jsonObj, domEl) { this.wrapper = document.createElement('ul'); this.wrapper.className = 'jsontree_tree clearfix'; this.rootNode = null; this.sourceJSONObj = jsonObj; this.loadData(jsonObj); this.appendTo(domEl); } Tree.prototype = { constructor : Tree, /** * Fill new data in current json tree * * @param {Object | Array} jsonObj - json-data */ loadData : function(jsonObj) { if (!utils.isValidRoot(jsonObj)) { alert('The root should be an object or an array'); return; } this.sourceJSONObj = jsonObj; this.rootNode = new Node(null, jsonObj, 'last'); this.wrapper.innerHTML = ''; this.wrapper.appendChild(this.rootNode.el); }, /** * Appends tree to DOM-element (or move it to new place) * * @param {DOMElement} domEl */ appendTo : function(domEl) { domEl.appendChild(this.wrapper); }, /** * Expands all tree nodes (objects or arrays) recursively * * @param {Function} filterFunc - 'true' if this node should be expanded */ expand : function(filterFunc) { if (this.rootNode.isComplex) { if (typeof filterFunc == 'function') { this.rootNode.childNodes.forEach(function(item, i) { if (item.isComplex && filterFunc(item)) { item.expand(); } }); } else { this.rootNode.expand('recursive'); } } }, /** * Collapses all tree nodes (objects or arrays) recursively */ collapse : function() { if (typeof this.rootNode.collapse === 'function') { this.rootNode.collapse('recursive'); } }, /** * Returns the source json-string (pretty-printed) * * @param {boolean} isPrettyPrinted - 'true' for pretty-printed string * @returns {string} - for exemple, '{"a":2,"b":3}' */ toSourceJSON : function(isPrettyPrinted) { if (!isPrettyPrinted) { return JSON.stringify(this.sourceJSONObj); } var DELIMETER = "[%^$#$%^%]", jsonStr = JSON.stringify(this.sourceJSONObj, null, DELIMETER); jsonStr = jsonStr.split("\n").join("
      "); jsonStr = jsonStr.split(DELIMETER).join("    "); return jsonStr; }, /** * Find all nodes that match some conditions and handle it */ findAndHandle : function(matcher, handler) { this.rootNode.findChildren(matcher, handler, 'isRecursive'); }, /** * Unmark all nodes */ unmarkAll : function() { this.rootNode.findChildren(function(node) { return true; }, function(node) { node.unmark(); }, 'isRecursive'); } }; /* ---------- Public methods ---------- */ return { /** * Creates new tree by data and appends it to the DOM-element * * @param jsonObj {Object | Array} - json-data * @param domEl {DOMElement} - the wrapper element * @returns {Tree} */ create : function(jsonObj, domEl) { return new Tree(jsonObj, domEl); } }; })(); ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/css/layui.css ================================================ /** layui-v2.4.5 MIT License By https://www.layui.com */ .layui-inline,img{display:inline-block;vertical-align:middle}h1,h2,h3,h4,h5,h6{font-weight:400}.layui-edge,.layui-header,.layui-inline,.layui-main{position:relative}.layui-elip,.layui-form-checkbox span,.layui-form-pane .layui-form-label{text-overflow:ellipsis;white-space:nowrap}.layui-btn,.layui-edge,.layui-inline,img{vertical-align:middle}.layui-btn,.layui-disabled,.layui-icon,.layui-unselect{-webkit-user-select:none;-ms-user-select:none;-moz-user-select:none}blockquote,body,button,dd,div,dl,dt,form,h1,h2,h3,h4,h5,h6,input,li,ol,p,pre,td,textarea,th,ul{margin:0;padding:0;-webkit-tap-highlight-color:rgba(0,0,0,0)}a:active,a:hover{outline:0}img{border:none}li{list-style:none}table{border-collapse:collapse;border-spacing:0}h4,h5,h6{font-size:100%}button,input,optgroup,option,select,textarea{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;outline:0}pre{white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word}body{line-height:24px;font:14px Helvetica Neue,Helvetica,PingFang SC,Tahoma,Arial,sans-serif}hr{height:1px;margin:10px 0;border:0;clear:both}a{color:#333;text-decoration:none}a:hover{color:#777}a cite{font-style:normal;*cursor:pointer}.layui-border-box,.layui-border-box *{box-sizing:border-box}.layui-box,.layui-box *{box-sizing:content-box}.layui-clear{clear:both;*zoom:1}.layui-clear:after{content:'\20';clear:both;*zoom:1;display:block;height:0}.layui-inline{*display:inline;*zoom:1}.layui-edge{display:inline-block;width:0;height:0;border-width:6px;border-style:dashed;border-color:transparent;overflow:hidden}.layui-edge-top{top:-4px;border-bottom-color:#999;border-bottom-style:solid}.layui-edge-right{border-left-color:#999;border-left-style:solid}.layui-edge-bottom{top:2px;border-top-color:#999;border-top-style:solid}.layui-edge-left{border-right-color:#999;border-right-style:solid}.layui-elip{overflow:hidden}.layui-disabled,.layui-disabled:hover{color:#d2d2d2!important;cursor:not-allowed!important}.layui-circle{border-radius:100%}.layui-show{display:block!important}.layui-hide{display:none!important}@font-face{font-family:layui-icon;src:url(../font/iconfont.eot?v=240);src:url(../font/iconfont.eot?v=240#iefix) format('embedded-opentype'),url(../font/iconfont.svg?v=240#iconfont) format('svg'),url(../font/iconfont.woff?v=240) format('woff'),url(../font/iconfont.ttf?v=240) format('truetype')}.layui-icon{font-family:layui-icon!important;font-size:16px;font-style:normal;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.layui-icon-reply-fill:before{content:"\e611"}.layui-icon-set-fill:before{content:"\e614"}.layui-icon-menu-fill:before{content:"\e60f"}.layui-icon-search:before{content:"\e615"}.layui-icon-share:before{content:"\e641"}.layui-icon-set-sm:before{content:"\e620"}.layui-icon-engine:before{content:"\e628"}.layui-icon-close:before{content:"\1006"}.layui-icon-close-fill:before{content:"\1007"}.layui-icon-chart-screen:before{content:"\e629"}.layui-icon-star:before{content:"\e600"}.layui-icon-circle-dot:before{content:"\e617"}.layui-icon-chat:before{content:"\e606"}.layui-icon-release:before{content:"\e609"}.layui-icon-list:before{content:"\e60a"}.layui-icon-chart:before{content:"\e62c"}.layui-icon-ok-circle:before{content:"\1005"}.layui-icon-layim-theme:before{content:"\e61b"}.layui-icon-table:before{content:"\e62d"}.layui-icon-right:before{content:"\e602"}.layui-icon-left:before{content:"\e603"}.layui-icon-cart-simple:before{content:"\e698"}.layui-icon-face-cry:before{content:"\e69c"}.layui-icon-face-smile:before{content:"\e6af"}.layui-icon-survey:before{content:"\e6b2"}.layui-icon-tree:before{content:"\e62e"}.layui-icon-upload-circle:before{content:"\e62f"}.layui-icon-add-circle:before{content:"\e61f"}.layui-icon-download-circle:before{content:"\e601"}.layui-icon-templeate-1:before{content:"\e630"}.layui-icon-util:before{content:"\e631"}.layui-icon-face-surprised:before{content:"\e664"}.layui-icon-edit:before{content:"\e642"}.layui-icon-speaker:before{content:"\e645"}.layui-icon-down:before{content:"\e61a"}.layui-icon-file:before{content:"\e621"}.layui-icon-layouts:before{content:"\e632"}.layui-icon-rate-half:before{content:"\e6c9"}.layui-icon-add-circle-fine:before{content:"\e608"}.layui-icon-prev-circle:before{content:"\e633"}.layui-icon-read:before{content:"\e705"}.layui-icon-404:before{content:"\e61c"}.layui-icon-carousel:before{content:"\e634"}.layui-icon-help:before{content:"\e607"}.layui-icon-code-circle:before{content:"\e635"}.layui-icon-water:before{content:"\e636"}.layui-icon-username:before{content:"\e66f"}.layui-icon-find-fill:before{content:"\e670"}.layui-icon-about:before{content:"\e60b"}.layui-icon-location:before{content:"\e715"}.layui-icon-up:before{content:"\e619"}.layui-icon-pause:before{content:"\e651"}.layui-icon-date:before{content:"\e637"}.layui-icon-layim-uploadfile:before{content:"\e61d"}.layui-icon-delete:before{content:"\e640"}.layui-icon-play:before{content:"\e652"}.layui-icon-top:before{content:"\e604"}.layui-icon-friends:before{content:"\e612"}.layui-icon-refresh-3:before{content:"\e9aa"}.layui-icon-ok:before{content:"\e605"}.layui-icon-layer:before{content:"\e638"}.layui-icon-face-smile-fine:before{content:"\e60c"}.layui-icon-dollar:before{content:"\e659"}.layui-icon-group:before{content:"\e613"}.layui-icon-layim-download:before{content:"\e61e"}.layui-icon-picture-fine:before{content:"\e60d"}.layui-icon-link:before{content:"\e64c"}.layui-icon-diamond:before{content:"\e735"}.layui-icon-log:before{content:"\e60e"}.layui-icon-rate-solid:before{content:"\e67a"}.layui-icon-fonts-del:before{content:"\e64f"}.layui-icon-unlink:before{content:"\e64d"}.layui-icon-fonts-clear:before{content:"\e639"}.layui-icon-triangle-r:before{content:"\e623"}.layui-icon-circle:before{content:"\e63f"}.layui-icon-radio:before{content:"\e643"}.layui-icon-align-center:before{content:"\e647"}.layui-icon-align-right:before{content:"\e648"}.layui-icon-align-left:before{content:"\e649"}.layui-icon-loading-1:before{content:"\e63e"}.layui-icon-return:before{content:"\e65c"}.layui-icon-fonts-strong:before{content:"\e62b"}.layui-icon-upload:before{content:"\e67c"}.layui-icon-dialogue:before{content:"\e63a"}.layui-icon-video:before{content:"\e6ed"}.layui-icon-headset:before{content:"\e6fc"}.layui-icon-cellphone-fine:before{content:"\e63b"}.layui-icon-add-1:before{content:"\e654"}.layui-icon-face-smile-b:before{content:"\e650"}.layui-icon-fonts-html:before{content:"\e64b"}.layui-icon-form:before{content:"\e63c"}.layui-icon-cart:before{content:"\e657"}.layui-icon-camera-fill:before{content:"\e65d"}.layui-icon-tabs:before{content:"\e62a"}.layui-icon-fonts-code:before{content:"\e64e"}.layui-icon-fire:before{content:"\e756"}.layui-icon-set:before{content:"\e716"}.layui-icon-fonts-u:before{content:"\e646"}.layui-icon-triangle-d:before{content:"\e625"}.layui-icon-tips:before{content:"\e702"}.layui-icon-picture:before{content:"\e64a"}.layui-icon-more-vertical:before{content:"\e671"}.layui-icon-flag:before{content:"\e66c"}.layui-icon-loading:before{content:"\e63d"}.layui-icon-fonts-i:before{content:"\e644"}.layui-icon-refresh-1:before{content:"\e666"}.layui-icon-rmb:before{content:"\e65e"}.layui-icon-home:before{content:"\e68e"}.layui-icon-user:before{content:"\e770"}.layui-icon-notice:before{content:"\e667"}.layui-icon-login-weibo:before{content:"\e675"}.layui-icon-voice:before{content:"\e688"}.layui-icon-upload-drag:before{content:"\e681"}.layui-icon-login-qq:before{content:"\e676"}.layui-icon-snowflake:before{content:"\e6b1"}.layui-icon-file-b:before{content:"\e655"}.layui-icon-template:before{content:"\e663"}.layui-icon-auz:before{content:"\e672"}.layui-icon-console:before{content:"\e665"}.layui-icon-app:before{content:"\e653"}.layui-icon-prev:before{content:"\e65a"}.layui-icon-website:before{content:"\e7ae"}.layui-icon-next:before{content:"\e65b"}.layui-icon-component:before{content:"\e857"}.layui-icon-more:before{content:"\e65f"}.layui-icon-login-wechat:before{content:"\e677"}.layui-icon-shrink-right:before{content:"\e668"}.layui-icon-spread-left:before{content:"\e66b"}.layui-icon-camera:before{content:"\e660"}.layui-icon-note:before{content:"\e66e"}.layui-icon-refresh:before{content:"\e669"}.layui-icon-female:before{content:"\e661"}.layui-icon-male:before{content:"\e662"}.layui-icon-password:before{content:"\e673"}.layui-icon-senior:before{content:"\e674"}.layui-icon-theme:before{content:"\e66a"}.layui-icon-tread:before{content:"\e6c5"}.layui-icon-praise:before{content:"\e6c6"}.layui-icon-star-fill:before{content:"\e658"}.layui-icon-rate:before{content:"\e67b"}.layui-icon-template-1:before{content:"\e656"}.layui-icon-vercode:before{content:"\e679"}.layui-icon-cellphone:before{content:"\e678"}.layui-icon-screen-full:before{content:"\e622"}.layui-icon-screen-restore:before{content:"\e758"}.layui-icon-cols:before{content:"\e610"}.layui-icon-export:before{content:"\e67d"}.layui-icon-print:before{content:"\e66d"}.layui-icon-slider:before{content:"\e714"}.layui-main{width:1140px;margin:0 auto}.layui-header{z-index:1000;height:60px}.layui-header a:hover{transition:all .5s;-webkit-transition:all .5s}.layui-side{position:fixed;left:0;top:0;bottom:0;z-index:999;width:200px;overflow-x:hidden}.layui-side-scroll{position:relative;width:220px;height:100%;overflow-x:hidden}.layui-body{position:absolute;left:200px;right:0;top:0;bottom:0;z-index:998;width:auto;overflow:hidden;overflow-y:auto;box-sizing:border-box}.layui-layout-body{overflow:hidden}.layui-layout-admin .layui-header{background-color:#23262E}.layui-layout-admin .layui-side{top:60px;width:200px;overflow-x:hidden}.layui-layout-admin .layui-body{top:60px;bottom:44px}.layui-layout-admin .layui-main{width:auto;margin:0 15px}.layui-layout-admin .layui-footer{position:fixed;left:200px;right:0;bottom:0;height:44px;line-height:44px;padding:0 15px;background-color:#eee}.layui-layout-admin .layui-logo{position:absolute;left:0;top:0;width:200px;height:100%;line-height:60px;text-align:center;color:#009688;font-size:16px}.layui-layout-admin .layui-header .layui-nav{background:0 0}.layui-layout-left{position:absolute!important;left:200px;top:0}.layui-layout-right{position:absolute!important;right:0;top:0}.layui-container{position:relative;margin:0 auto;padding:0 15px;box-sizing:border-box}.layui-fluid{position:relative;margin:0 auto;padding:0 15px}.layui-row:after,.layui-row:before{content:'';display:block;clear:both}.layui-col-lg1,.layui-col-lg10,.layui-col-lg11,.layui-col-lg12,.layui-col-lg2,.layui-col-lg3,.layui-col-lg4,.layui-col-lg5,.layui-col-lg6,.layui-col-lg7,.layui-col-lg8,.layui-col-lg9,.layui-col-md1,.layui-col-md10,.layui-col-md11,.layui-col-md12,.layui-col-md2,.layui-col-md3,.layui-col-md4,.layui-col-md5,.layui-col-md6,.layui-col-md7,.layui-col-md8,.layui-col-md9,.layui-col-sm1,.layui-col-sm10,.layui-col-sm11,.layui-col-sm12,.layui-col-sm2,.layui-col-sm3,.layui-col-sm4,.layui-col-sm5,.layui-col-sm6,.layui-col-sm7,.layui-col-sm8,.layui-col-sm9,.layui-col-xs1,.layui-col-xs10,.layui-col-xs11,.layui-col-xs12,.layui-col-xs2,.layui-col-xs3,.layui-col-xs4,.layui-col-xs5,.layui-col-xs6,.layui-col-xs7,.layui-col-xs8,.layui-col-xs9{position:relative;display:block;box-sizing:border-box}.layui-col-xs1,.layui-col-xs10,.layui-col-xs11,.layui-col-xs12,.layui-col-xs2,.layui-col-xs3,.layui-col-xs4,.layui-col-xs5,.layui-col-xs6,.layui-col-xs7,.layui-col-xs8,.layui-col-xs9{float:left}.layui-col-xs1{width:8.33333333%}.layui-col-xs2{width:16.66666667%}.layui-col-xs3{width:25%}.layui-col-xs4{width:33.33333333%}.layui-col-xs5{width:41.66666667%}.layui-col-xs6{width:50%}.layui-col-xs7{width:58.33333333%}.layui-col-xs8{width:66.66666667%}.layui-col-xs9{width:75%}.layui-col-xs10{width:83.33333333%}.layui-col-xs11{width:91.66666667%}.layui-col-xs12{width:100%}.layui-col-xs-offset1{margin-left:8.33333333%}.layui-col-xs-offset2{margin-left:16.66666667%}.layui-col-xs-offset3{margin-left:25%}.layui-col-xs-offset4{margin-left:33.33333333%}.layui-col-xs-offset5{margin-left:41.66666667%}.layui-col-xs-offset6{margin-left:50%}.layui-col-xs-offset7{margin-left:58.33333333%}.layui-col-xs-offset8{margin-left:66.66666667%}.layui-col-xs-offset9{margin-left:75%}.layui-col-xs-offset10{margin-left:83.33333333%}.layui-col-xs-offset11{margin-left:91.66666667%}.layui-col-xs-offset12{margin-left:100%}@media screen and (max-width:768px){.layui-hide-xs{display:none!important}.layui-show-xs-block{display:block!important}.layui-show-xs-inline{display:inline!important}.layui-show-xs-inline-block{display:inline-block!important}}@media screen and (min-width:768px){.layui-container{width:750px}.layui-hide-sm{display:none!important}.layui-show-sm-block{display:block!important}.layui-show-sm-inline{display:inline!important}.layui-show-sm-inline-block{display:inline-block!important}.layui-col-sm1,.layui-col-sm10,.layui-col-sm11,.layui-col-sm12,.layui-col-sm2,.layui-col-sm3,.layui-col-sm4,.layui-col-sm5,.layui-col-sm6,.layui-col-sm7,.layui-col-sm8,.layui-col-sm9{float:left}.layui-col-sm1{width:8.33333333%}.layui-col-sm2{width:16.66666667%}.layui-col-sm3{width:25%}.layui-col-sm4{width:33.33333333%}.layui-col-sm5{width:41.66666667%}.layui-col-sm6{width:50%}.layui-col-sm7{width:58.33333333%}.layui-col-sm8{width:66.66666667%}.layui-col-sm9{width:75%}.layui-col-sm10{width:83.33333333%}.layui-col-sm11{width:91.66666667%}.layui-col-sm12{width:100%}.layui-col-sm-offset1{margin-left:8.33333333%}.layui-col-sm-offset2{margin-left:16.66666667%}.layui-col-sm-offset3{margin-left:25%}.layui-col-sm-offset4{margin-left:33.33333333%}.layui-col-sm-offset5{margin-left:41.66666667%}.layui-col-sm-offset6{margin-left:50%}.layui-col-sm-offset7{margin-left:58.33333333%}.layui-col-sm-offset8{margin-left:66.66666667%}.layui-col-sm-offset9{margin-left:75%}.layui-col-sm-offset10{margin-left:83.33333333%}.layui-col-sm-offset11{margin-left:91.66666667%}.layui-col-sm-offset12{margin-left:100%}}@media screen and (min-width:992px){.layui-container{width:970px}.layui-hide-md{display:none!important}.layui-show-md-block{display:block!important}.layui-show-md-inline{display:inline!important}.layui-show-md-inline-block{display:inline-block!important}.layui-col-md1,.layui-col-md10,.layui-col-md11,.layui-col-md12,.layui-col-md2,.layui-col-md3,.layui-col-md4,.layui-col-md5,.layui-col-md6,.layui-col-md7,.layui-col-md8,.layui-col-md9{float:left}.layui-col-md1{width:8.33333333%}.layui-col-md2{width:16.66666667%}.layui-col-md3{width:25%}.layui-col-md4{width:33.33333333%}.layui-col-md5{width:41.66666667%}.layui-col-md6{width:50%}.layui-col-md7{width:58.33333333%}.layui-col-md8{width:66.66666667%}.layui-col-md9{width:75%}.layui-col-md10{width:83.33333333%}.layui-col-md11{width:91.66666667%}.layui-col-md12{width:100%}.layui-col-md-offset1{margin-left:8.33333333%}.layui-col-md-offset2{margin-left:16.66666667%}.layui-col-md-offset3{margin-left:25%}.layui-col-md-offset4{margin-left:33.33333333%}.layui-col-md-offset5{margin-left:41.66666667%}.layui-col-md-offset6{margin-left:50%}.layui-col-md-offset7{margin-left:58.33333333%}.layui-col-md-offset8{margin-left:66.66666667%}.layui-col-md-offset9{margin-left:75%}.layui-col-md-offset10{margin-left:83.33333333%}.layui-col-md-offset11{margin-left:91.66666667%}.layui-col-md-offset12{margin-left:100%}}@media screen and (min-width:1200px){.layui-container{width:1170px}.layui-hide-lg{display:none!important}.layui-show-lg-block{display:block!important}.layui-show-lg-inline{display:inline!important}.layui-show-lg-inline-block{display:inline-block!important}.layui-col-lg1,.layui-col-lg10,.layui-col-lg11,.layui-col-lg12,.layui-col-lg2,.layui-col-lg3,.layui-col-lg4,.layui-col-lg5,.layui-col-lg6,.layui-col-lg7,.layui-col-lg8,.layui-col-lg9{float:left}.layui-col-lg1{width:8.33333333%}.layui-col-lg2{width:16.66666667%}.layui-col-lg3{width:25%}.layui-col-lg4{width:33.33333333%}.layui-col-lg5{width:41.66666667%}.layui-col-lg6{width:50%}.layui-col-lg7{width:58.33333333%}.layui-col-lg8{width:66.66666667%}.layui-col-lg9{width:75%}.layui-col-lg10{width:83.33333333%}.layui-col-lg11{width:91.66666667%}.layui-col-lg12{width:100%}.layui-col-lg-offset1{margin-left:8.33333333%}.layui-col-lg-offset2{margin-left:16.66666667%}.layui-col-lg-offset3{margin-left:25%}.layui-col-lg-offset4{margin-left:33.33333333%}.layui-col-lg-offset5{margin-left:41.66666667%}.layui-col-lg-offset6{margin-left:50%}.layui-col-lg-offset7{margin-left:58.33333333%}.layui-col-lg-offset8{margin-left:66.66666667%}.layui-col-lg-offset9{margin-left:75%}.layui-col-lg-offset10{margin-left:83.33333333%}.layui-col-lg-offset11{margin-left:91.66666667%}.layui-col-lg-offset12{margin-left:100%}}.layui-col-space1{margin:-.5px}.layui-col-space1>*{padding:.5px}.layui-col-space3{margin:-1.5px}.layui-col-space3>*{padding:1.5px}.layui-col-space5{margin:-2.5px}.layui-col-space5>*{padding:2.5px}.layui-col-space8{margin:-3.5px}.layui-col-space8>*{padding:3.5px}.layui-col-space10{margin:-5px}.layui-col-space10>*{padding:5px}.layui-col-space12{margin:-6px}.layui-col-space12>*{padding:6px}.layui-col-space15{margin:-7.5px}.layui-col-space15>*{padding:7.5px}.layui-col-space18{margin:-9px}.layui-col-space18>*{padding:9px}.layui-col-space20{margin:-10px}.layui-col-space20>*{padding:10px}.layui-col-space22{margin:-11px}.layui-col-space22>*{padding:11px}.layui-col-space25{margin:-12.5px}.layui-col-space25>*{padding:12.5px}.layui-col-space30{margin:-15px}.layui-col-space30>*{padding:15px}.layui-btn,.layui-input,.layui-select,.layui-textarea,.layui-upload-button{outline:0;-webkit-appearance:none;transition:all .3s;-webkit-transition:all .3s;box-sizing:border-box}.layui-elem-quote{margin-bottom:10px;padding:15px;line-height:22px;border-left:5px solid #009688;border-radius:0 2px 2px 0;background-color:#f2f2f2}.layui-quote-nm{border-style:solid;border-width:1px 1px 1px 5px;background:0 0}.layui-elem-field{margin-bottom:10px;padding:0;border-width:1px;border-style:solid}.layui-elem-field legend{margin-left:20px;padding:0 10px;font-size:20px;font-weight:300}.layui-field-title{margin:10px 0 20px;border-width:1px 0 0}.layui-field-box{padding:10px 15px}.layui-field-title .layui-field-box{padding:10px 0}.layui-progress{position:relative;height:6px;border-radius:20px;background-color:#e2e2e2}.layui-progress-bar{position:absolute;left:0;top:0;width:0;max-width:100%;height:6px;border-radius:20px;text-align:right;background-color:#5FB878;transition:all .3s;-webkit-transition:all .3s}.layui-progress-big,.layui-progress-big .layui-progress-bar{height:18px;line-height:18px}.layui-progress-text{position:relative;top:-20px;line-height:18px;font-size:12px;color:#666}.layui-progress-big .layui-progress-text{position:static;padding:0 10px;color:#fff}.layui-collapse{border-width:1px;border-style:solid;border-radius:2px}.layui-colla-content,.layui-colla-item{border-top-width:1px;border-top-style:solid}.layui-colla-item:first-child{border-top:none}.layui-colla-title{position:relative;height:42px;line-height:42px;padding:0 15px 0 35px;color:#333;background-color:#f2f2f2;cursor:pointer;font-size:14px;overflow:hidden}.layui-colla-content{display:none;padding:10px 15px;line-height:22px;color:#666}.layui-colla-icon{position:absolute;left:15px;top:0;font-size:14px}.layui-card{margin-bottom:15px;border-radius:2px;background-color:#fff;box-shadow:0 1px 2px 0 rgba(0,0,0,.05)}.layui-card:last-child{margin-bottom:0}.layui-card-header{position:relative;height:42px;line-height:42px;padding:0 15px;border-bottom:1px solid #f6f6f6;color:#333;border-radius:2px 2px 0 0;font-size:14px}.layui-bg-black,.layui-bg-blue,.layui-bg-cyan,.layui-bg-green,.layui-bg-orange,.layui-bg-red{color:#fff!important}.layui-card-body{position:relative;padding:10px 15px;line-height:24px}.layui-card-body[pad15]{padding:15px}.layui-card-body[pad20]{padding:20px}.layui-card-body .layui-table{margin:5px 0}.layui-card .layui-tab{margin:0}.layui-panel-window{position:relative;padding:15px;border-radius:0;border-top:5px solid #E6E6E6;background-color:#fff}.layui-auxiliar-moving{position:fixed;left:0;right:0;top:0;bottom:0;width:100%;height:100%;background:0 0;z-index:9999999999}.layui-form-label,.layui-form-mid,.layui-form-select,.layui-input-block,.layui-input-inline,.layui-textarea{position:relative}.layui-bg-red{background-color:#FF5722!important}.layui-bg-orange{background-color:#FFB800!important}.layui-bg-green{background-color:#009688!important}.layui-bg-cyan{background-color:#2F4056!important}.layui-bg-blue{background-color:#1E9FFF!important}.layui-bg-black{background-color:#393D49!important}.layui-bg-gray{background-color:#eee!important;color:#666!important}.layui-badge-rim,.layui-colla-content,.layui-colla-item,.layui-collapse,.layui-elem-field,.layui-form-pane .layui-form-item[pane],.layui-form-pane .layui-form-label,.layui-input,.layui-layedit,.layui-layedit-tool,.layui-quote-nm,.layui-select,.layui-tab-bar,.layui-tab-card,.layui-tab-title,.layui-tab-title .layui-this:after,.layui-textarea{border-color:#e6e6e6}.layui-timeline-item:before,hr{background-color:#e6e6e6}.layui-text{line-height:22px;font-size:14px;color:#666}.layui-text h1,.layui-text h2,.layui-text h3{font-weight:500;color:#333}.layui-text h1{font-size:30px}.layui-text h2{font-size:24px}.layui-text h3{font-size:18px}.layui-text a:not(.layui-btn){color:#01AAED}.layui-text a:not(.layui-btn):hover{text-decoration:underline}.layui-text ul{padding:5px 0 5px 15px}.layui-text ul li{margin-top:5px;list-style-type:disc}.layui-text em,.layui-word-aux{color:#999!important;padding:0 5px!important}.layui-btn{display:inline-block;height:38px;line-height:38px;padding:0 18px;background-color:#009688;color:#fff;white-space:nowrap;text-align:center;font-size:14px;border:none;border-radius:2px;cursor:pointer}.layui-btn:hover{opacity:.8;filter:alpha(opacity=80);color:#fff}.layui-btn:active{opacity:1;filter:alpha(opacity=100)}.layui-btn+.layui-btn{margin-left:10px}.layui-btn-container{font-size:0}.layui-btn-container .layui-btn{margin-right:10px;margin-bottom:10px}.layui-btn-container .layui-btn+.layui-btn{margin-left:0}.layui-table .layui-btn-container .layui-btn{margin-bottom:9px}.layui-btn-radius{border-radius:100px}.layui-btn .layui-icon{margin-right:3px;font-size:18px;vertical-align:bottom;vertical-align:middle\9}.layui-btn-primary{border:1px solid #C9C9C9;background-color:#fff;color:#555}.layui-btn-primary:hover{border-color:#009688;color:#333}.layui-btn-normal{background-color:#1E9FFF}.layui-btn-warm{background-color:#FFB800}.layui-btn-danger{background-color:#FF5722}.layui-btn-disabled,.layui-btn-disabled:active,.layui-btn-disabled:hover{border:1px solid #e6e6e6;background-color:#FBFBFB;color:#C9C9C9;cursor:not-allowed;opacity:1}.layui-btn-lg{height:44px;line-height:44px;padding:0 25px;font-size:16px}.layui-btn-sm{height:30px;line-height:30px;padding:0 10px;font-size:12px}.layui-btn-sm i{font-size:16px!important}.layui-btn-xs{height:22px;line-height:22px;padding:0 5px;font-size:12px}.layui-btn-xs i{font-size:14px!important}.layui-btn-group{display:inline-block;vertical-align:middle;font-size:0}.layui-btn-group .layui-btn{margin-left:0!important;margin-right:0!important;border-left:1px solid rgba(255,255,255,.5);border-radius:0}.layui-btn-group .layui-btn-primary{border-left:none}.layui-btn-group .layui-btn-primary:hover{border-color:#C9C9C9;color:#009688}.layui-btn-group .layui-btn:first-child{border-left:none;border-radius:2px 0 0 2px}.layui-btn-group .layui-btn-primary:first-child{border-left:1px solid #c9c9c9}.layui-btn-group .layui-btn:last-child{border-radius:0 2px 2px 0}.layui-btn-group .layui-btn+.layui-btn{margin-left:0}.layui-btn-group+.layui-btn-group{margin-left:10px}.layui-btn-fluid{width:100%}.layui-input,.layui-select,.layui-textarea{height:38px;line-height:1.3;line-height:38px\9;border-width:1px;border-style:solid;background-color:#fff;border-radius:2px}.layui-input::-webkit-input-placeholder,.layui-select::-webkit-input-placeholder,.layui-textarea::-webkit-input-placeholder{line-height:1.3}.layui-input,.layui-textarea{display:block;width:100%;padding-left:10px}.layui-input:hover,.layui-textarea:hover{border-color:#D2D2D2!important}.layui-input:focus,.layui-textarea:focus{border-color:#C9C9C9!important}.layui-textarea{min-height:100px;height:auto;line-height:20px;padding:6px 10px;resize:vertical}.layui-select{padding:0 10px}.layui-form input[type=checkbox],.layui-form input[type=radio],.layui-form select{display:none}.layui-form [lay-ignore]{display:initial}.layui-form-item{margin-bottom:15px;clear:both;*zoom:1}.layui-form-item:after{content:'\20';clear:both;*zoom:1;display:block;height:0}.layui-form-label{float:left;display:block;padding:9px 15px;width:80px;font-weight:400;line-height:20px;text-align:right}.layui-form-label-col{display:block;float:none;padding:9px 0;line-height:20px;text-align:left}.layui-form-item .layui-inline{margin-bottom:5px;margin-right:10px}.layui-input-block{margin-left:110px;min-height:36px}.layui-input-inline{display:inline-block;vertical-align:middle}.layui-form-item .layui-input-inline{float:left;width:190px;margin-right:10px}.layui-form-text .layui-input-inline{width:auto}.layui-form-mid{float:left;display:block;padding:9px 0!important;line-height:20px;margin-right:10px}.layui-form-danger+.layui-form-select .layui-input,.layui-form-danger:focus{border-color:#FF5722!important}.layui-form-select .layui-input{padding-right:30px;cursor:pointer}.layui-form-select .layui-edge{position:absolute;right:10px;top:50%;margin-top:-3px;cursor:pointer;border-width:6px;border-top-color:#c2c2c2;border-top-style:solid;transition:all .3s;-webkit-transition:all .3s}.layui-form-select dl{display:none;position:absolute;left:0;top:42px;padding:5px 0;z-index:899;min-width:100%;border:1px solid #d2d2d2;max-height:300px;overflow-y:auto;background-color:#fff;border-radius:2px;box-shadow:0 2px 4px rgba(0,0,0,.12);box-sizing:border-box}.layui-form-select dl dd,.layui-form-select dl dt{padding:0 10px;line-height:36px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.layui-form-select dl dt{font-size:12px;color:#999}.layui-form-select dl dd{cursor:pointer}.layui-form-select dl dd:hover{background-color:#f2f2f2;-webkit-transition:.5s all;transition:.5s all}.layui-form-select .layui-select-group dd{padding-left:20px}.layui-form-select dl dd.layui-select-tips{padding-left:10px!important;color:#999}.layui-form-select dl dd.layui-this{background-color:#5FB878;color:#fff}.layui-form-checkbox,.layui-form-select dl dd.layui-disabled{background-color:#fff}.layui-form-selected dl{display:block}.layui-form-checkbox,.layui-form-checkbox *,.layui-form-switch{display:inline-block;vertical-align:middle}.layui-form-selected .layui-edge{margin-top:-9px;-webkit-transform:rotate(180deg);transform:rotate(180deg);margin-top:-3px\9}:root .layui-form-selected .layui-edge{margin-top:-9px\0/IE9}.layui-form-selectup dl{top:auto;bottom:42px}.layui-select-none{margin:5px 0;text-align:center;color:#999}.layui-select-disabled .layui-disabled{border-color:#eee!important}.layui-select-disabled .layui-edge{border-top-color:#d2d2d2}.layui-form-checkbox{position:relative;height:30px;line-height:30px;margin-right:10px;padding-right:30px;cursor:pointer;font-size:0;-webkit-transition:.1s linear;transition:.1s linear;box-sizing:border-box}.layui-form-checkbox span{padding:0 10px;height:100%;font-size:14px;border-radius:2px 0 0 2px;background-color:#d2d2d2;color:#fff;overflow:hidden}.layui-form-checkbox:hover span{background-color:#c2c2c2}.layui-form-checkbox i{position:absolute;right:0;top:0;width:30px;height:28px;border:1px solid #d2d2d2;border-left:none;border-radius:0 2px 2px 0;color:#fff;font-size:20px;text-align:center}.layui-form-checkbox:hover i{border-color:#c2c2c2;color:#c2c2c2}.layui-form-checked,.layui-form-checked:hover{border-color:#5FB878}.layui-form-checked span,.layui-form-checked:hover span{background-color:#5FB878}.layui-form-checked i,.layui-form-checked:hover i{color:#5FB878}.layui-form-item .layui-form-checkbox{margin-top:4px}.layui-form-checkbox[lay-skin=primary]{height:auto!important;line-height:normal!important;min-width:18px;min-height:18px;border:none!important;margin-right:0;padding-left:28px;padding-right:0;background:0 0}.layui-form-checkbox[lay-skin=primary] span{padding-left:0;padding-right:15px;line-height:18px;background:0 0;color:#666}.layui-form-checkbox[lay-skin=primary] i{right:auto;left:0;width:16px;height:16px;line-height:16px;border:1px solid #d2d2d2;font-size:12px;border-radius:2px;background-color:#fff;-webkit-transition:.1s linear;transition:.1s linear}.layui-form-checkbox[lay-skin=primary]:hover i{border-color:#5FB878;color:#fff}.layui-form-checked[lay-skin=primary] i{border-color:#5FB878;background-color:#5FB878;color:#fff}.layui-checkbox-disbaled[lay-skin=primary] span{background:0 0!important;color:#c2c2c2}.layui-checkbox-disbaled[lay-skin=primary]:hover i{border-color:#d2d2d2}.layui-form-item .layui-form-checkbox[lay-skin=primary]{margin-top:10px}.layui-form-switch{position:relative;height:22px;line-height:22px;min-width:35px;padding:0 5px;margin-top:8px;border:1px solid #d2d2d2;border-radius:20px;cursor:pointer;background-color:#fff;-webkit-transition:.1s linear;transition:.1s linear}.layui-form-switch i{position:absolute;left:5px;top:3px;width:16px;height:16px;border-radius:20px;background-color:#d2d2d2;-webkit-transition:.1s linear;transition:.1s linear}.layui-form-switch em{position:relative;top:0;width:25px;margin-left:21px;padding:0!important;text-align:center!important;color:#999!important;font-style:normal!important;font-size:12px}.layui-form-onswitch{border-color:#5FB878;background-color:#5FB878}.layui-checkbox-disbaled,.layui-checkbox-disbaled i{border-color:#e2e2e2!important}.layui-form-onswitch i{left:100%;margin-left:-21px;background-color:#fff}.layui-form-onswitch em{margin-left:5px;margin-right:21px;color:#fff!important}.layui-checkbox-disbaled span{background-color:#e2e2e2!important}.layui-checkbox-disbaled:hover i{color:#fff!important}[lay-radio]{display:none}.layui-form-radio,.layui-form-radio *{display:inline-block;vertical-align:middle}.layui-form-radio{line-height:28px;margin:6px 10px 0 0;padding-right:10px;cursor:pointer;font-size:0}.layui-form-radio *{font-size:14px}.layui-form-radio>i{margin-right:8px;font-size:22px;color:#c2c2c2}.layui-form-radio>i:hover,.layui-form-radioed>i{color:#5FB878}.layui-radio-disbaled>i{color:#e2e2e2!important}.layui-form-pane .layui-form-label{width:110px;padding:8px 15px;height:38px;line-height:20px;border-width:1px;border-style:solid;border-radius:2px 0 0 2px;text-align:center;background-color:#FBFBFB;overflow:hidden;box-sizing:border-box}.layui-form-pane .layui-input-inline{margin-left:-1px}.layui-form-pane .layui-input-block{margin-left:110px;left:-1px}.layui-form-pane .layui-input{border-radius:0 2px 2px 0}.layui-form-pane .layui-form-text .layui-form-label{float:none;width:100%;border-radius:2px;box-sizing:border-box;text-align:left}.layui-form-pane .layui-form-text .layui-input-inline{display:block;margin:0;top:-1px;clear:both}.layui-form-pane .layui-form-text .layui-input-block{margin:0;left:0;top:-1px}.layui-form-pane .layui-form-text .layui-textarea{min-height:100px;border-radius:0 0 2px 2px}.layui-form-pane .layui-form-checkbox{margin:4px 0 4px 10px}.layui-form-pane .layui-form-radio,.layui-form-pane .layui-form-switch{margin-top:6px;margin-left:10px}.layui-form-pane .layui-form-item[pane]{position:relative;border-width:1px;border-style:solid}.layui-form-pane .layui-form-item[pane] .layui-form-label{position:absolute;left:0;top:0;height:100%;border-width:0 1px 0 0}.layui-form-pane .layui-form-item[pane] .layui-input-inline{margin-left:110px}@media screen and (max-width:450px){.layui-form-item .layui-form-label{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-form-item .layui-inline{display:block;margin-right:0;margin-bottom:20px;clear:both}.layui-form-item .layui-inline:after{content:'\20';clear:both;display:block;height:0}.layui-form-item .layui-input-inline{display:block;float:none;left:-3px;width:auto;margin:0 0 10px 112px}.layui-form-item .layui-input-inline+.layui-form-mid{margin-left:110px;top:-5px;padding:0}.layui-form-item .layui-form-checkbox{margin-right:5px;margin-bottom:5px}}.layui-layedit{border-width:1px;border-style:solid;border-radius:2px}.layui-layedit-tool{padding:3px 5px;border-bottom-width:1px;border-bottom-style:solid;font-size:0}.layedit-tool-fixed{position:fixed;top:0;border-top:1px solid #e2e2e2}.layui-layedit-tool .layedit-tool-mid,.layui-layedit-tool .layui-icon{display:inline-block;vertical-align:middle;text-align:center;font-size:14px}.layui-layedit-tool .layui-icon{position:relative;width:32px;height:30px;line-height:30px;margin:3px 5px;color:#777;cursor:pointer;border-radius:2px}.layui-layedit-tool .layui-icon:hover{color:#393D49}.layui-layedit-tool .layui-icon:active{color:#000}.layui-layedit-tool .layedit-tool-active{background-color:#e2e2e2;color:#000}.layui-layedit-tool .layui-disabled,.layui-layedit-tool .layui-disabled:hover{color:#d2d2d2;cursor:not-allowed}.layui-layedit-tool .layedit-tool-mid{width:1px;height:18px;margin:0 10px;background-color:#d2d2d2}.layedit-tool-html{width:50px!important;font-size:30px!important}.layedit-tool-b,.layedit-tool-code,.layedit-tool-help{font-size:16px!important}.layedit-tool-d,.layedit-tool-face,.layedit-tool-image,.layedit-tool-unlink{font-size:18px!important}.layedit-tool-image input{position:absolute;font-size:0;left:0;top:0;width:100%;height:100%;opacity:.01;filter:Alpha(opacity=1);cursor:pointer}.layui-layedit-iframe iframe{display:block;width:100%}#LAY_layedit_code{overflow:hidden}.layui-laypage{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;margin:10px 0;font-size:0}.layui-laypage>a:first-child,.layui-laypage>a:first-child em{border-radius:2px 0 0 2px}.layui-laypage>a:last-child,.layui-laypage>a:last-child em{border-radius:0 2px 2px 0}.layui-laypage>:first-child{margin-left:0!important}.layui-laypage>:last-child{margin-right:0!important}.layui-laypage a,.layui-laypage button,.layui-laypage input,.layui-laypage select,.layui-laypage span{border:1px solid #e2e2e2}.layui-laypage a,.layui-laypage span{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;padding:0 15px;height:28px;line-height:28px;margin:0 -1px 5px 0;background-color:#fff;color:#333;font-size:12px}.layui-flow-more a *,.layui-laypage input,.layui-table-view select[lay-ignore]{display:inline-block}.layui-laypage a:hover{color:#009688}.layui-laypage em{font-style:normal}.layui-laypage .layui-laypage-spr{color:#999;font-weight:700}.layui-laypage a{text-decoration:none}.layui-laypage .layui-laypage-curr{position:relative}.layui-laypage .layui-laypage-curr em{position:relative;color:#fff}.layui-laypage .layui-laypage-curr .layui-laypage-em{position:absolute;left:-1px;top:-1px;padding:1px;width:100%;height:100%;background-color:#009688}.layui-laypage-em{border-radius:2px}.layui-laypage-next em,.layui-laypage-prev em{font-family:Sim sun;font-size:16px}.layui-laypage .layui-laypage-count,.layui-laypage .layui-laypage-limits,.layui-laypage .layui-laypage-refresh,.layui-laypage .layui-laypage-skip{margin-left:10px;margin-right:10px;padding:0;border:none}.layui-laypage .layui-laypage-limits,.layui-laypage .layui-laypage-refresh{vertical-align:top}.layui-laypage .layui-laypage-refresh i{font-size:18px;cursor:pointer}.layui-laypage select{height:22px;padding:3px;border-radius:2px;cursor:pointer}.layui-laypage .layui-laypage-skip{height:30px;line-height:30px;color:#999}.layui-laypage button,.layui-laypage input{height:30px;line-height:30px;border-radius:2px;vertical-align:top;background-color:#fff;box-sizing:border-box}.layui-laypage input{width:40px;margin:0 10px;padding:0 3px;text-align:center}.layui-laypage input:focus,.layui-laypage select:focus{border-color:#009688!important}.layui-laypage button{margin-left:10px;padding:0 10px;cursor:pointer}.layui-table,.layui-table-view{margin:10px 0}.layui-flow-more{margin:10px 0;text-align:center;color:#999;font-size:14px}.layui-flow-more a{height:32px;line-height:32px}.layui-flow-more a *{vertical-align:top}.layui-flow-more a cite{padding:0 20px;border-radius:3px;background-color:#eee;color:#333;font-style:normal}.layui-flow-more a cite:hover{opacity:.8}.layui-flow-more a i{font-size:30px;color:#737383}.layui-table{width:100%;background-color:#fff;color:#666}.layui-table tr{transition:all .3s;-webkit-transition:all .3s}.layui-table th{text-align:left;font-weight:400}.layui-table tbody tr:hover,.layui-table thead tr,.layui-table-click,.layui-table-header,.layui-table-hover,.layui-table-mend,.layui-table-patch,.layui-table-tool,.layui-table-total,.layui-table-total tr,.layui-table[lay-even] tr:nth-child(even){background-color:#f2f2f2}.layui-table td,.layui-table th,.layui-table-col-set,.layui-table-fixed-r,.layui-table-grid-down,.layui-table-header,.layui-table-page,.layui-table-tips-main,.layui-table-tool,.layui-table-total,.layui-table-view,.layui-table[lay-skin=line],.layui-table[lay-skin=row]{border-width:1px;border-style:solid;border-color:#e6e6e6}.layui-table td,.layui-table th{position:relative;padding:9px 15px;min-height:20px;line-height:20px;font-size:14px}.layui-table[lay-skin=line] td,.layui-table[lay-skin=line] th{border-width:0 0 1px}.layui-table[lay-skin=row] td,.layui-table[lay-skin=row] th{border-width:0 1px 0 0}.layui-table[lay-skin=nob] td,.layui-table[lay-skin=nob] th{border:none}.layui-table img{max-width:100px}.layui-table[lay-size=lg] td,.layui-table[lay-size=lg] th{padding:15px 30px}.layui-table-view .layui-table[lay-size=lg] .layui-table-cell{height:40px;line-height:40px}.layui-table[lay-size=sm] td,.layui-table[lay-size=sm] th{font-size:12px;padding:5px 10px}.layui-table-view .layui-table[lay-size=sm] .layui-table-cell{height:20px;line-height:20px}.layui-table[lay-data]{display:none}.layui-table-box{position:relative;overflow:hidden}.layui-table-view .layui-table{position:relative;width:auto;margin:0}.layui-table-view .layui-table[lay-skin=line]{border-width:0 1px 0 0}.layui-table-view .layui-table[lay-skin=row]{border-width:0 0 1px}.layui-table-view .layui-table td,.layui-table-view .layui-table th{padding:5px 0;border-top:none;border-left:none}.layui-table-view .layui-table th.layui-unselect .layui-table-cell span{cursor:pointer}.layui-table-view .layui-table td{cursor:default}.layui-table-view .layui-form-checkbox[lay-skin=primary] i{width:18px;height:18px}.layui-table-view .layui-form-radio{line-height:0;padding:0}.layui-table-view .layui-form-radio>i{margin:0;font-size:20px}.layui-table-init{position:absolute;left:0;top:0;width:100%;height:100%;text-align:center;z-index:110}.layui-table-init .layui-icon{position:absolute;left:50%;top:50%;margin:-15px 0 0 -15px;font-size:30px;color:#c2c2c2}.layui-table-header{border-width:0 0 1px;overflow:hidden}.layui-table-header .layui-table{margin-bottom:-1px}.layui-table-tool .layui-inline[lay-event]{position:relative;width:26px;height:26px;padding:5px;line-height:16px;margin-right:10px;text-align:center;color:#333;border:1px solid #ccc;cursor:pointer;-webkit-transition:.5s all;transition:.5s all}.layui-table-tool .layui-inline[lay-event]:hover{border:1px solid #999}.layui-table-tool-temp{padding-right:120px}.layui-table-tool-self{position:absolute;right:17px;top:10px}.layui-table-tool .layui-table-tool-self .layui-inline[lay-event]{margin:0 0 0 10px}.layui-table-tool-panel{position:absolute;top:29px;left:-1px;padding:5px 0;min-width:150px;min-height:40px;border:1px solid #d2d2d2;text-align:left;overflow-y:auto;background-color:#fff;box-shadow:0 2px 4px rgba(0,0,0,.12)}.layui-table-cell,.layui-table-tool-panel li{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.layui-table-tool-panel li{padding:0 10px;line-height:30px;-webkit-transition:.5s all;transition:.5s all}.layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary]{width:100%;padding-left:28px}.layui-table-tool-panel li:hover{background-color:#f2f2f2}.layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary] i{position:absolute;left:0;top:0}.layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary] span{padding:0}.layui-table-tool .layui-table-tool-self .layui-table-tool-panel{left:auto;right:-1px}.layui-table-col-set{position:absolute;right:0;top:0;width:20px;height:100%;border-width:0 0 0 1px;background-color:#fff}.layui-table-sort{width:10px;height:20px;margin-left:5px;cursor:pointer!important}.layui-table-sort .layui-edge{position:absolute;left:5px;border-width:5px}.layui-table-sort .layui-table-sort-asc{top:3px;border-top:none;border-bottom-style:solid;border-bottom-color:#b2b2b2}.layui-table-sort .layui-table-sort-asc:hover{border-bottom-color:#666}.layui-table-sort .layui-table-sort-desc{bottom:5px;border-bottom:none;border-top-style:solid;border-top-color:#b2b2b2}.layui-table-sort .layui-table-sort-desc:hover{border-top-color:#666}.layui-table-sort[lay-sort=asc] .layui-table-sort-asc{border-bottom-color:#000}.layui-table-sort[lay-sort=desc] .layui-table-sort-desc{border-top-color:#000}.layui-table-cell{height:28px;line-height:28px;padding:0 15px;position:relative;box-sizing:border-box}.layui-table-cell .layui-form-checkbox[lay-skin=primary]{top:-1px;padding:0}.layui-table-cell .layui-table-link{color:#01AAED}.laytable-cell-checkbox,.laytable-cell-numbers,.laytable-cell-radio,.laytable-cell-space{padding:0;text-align:center}.layui-table-body{position:relative;overflow:auto;margin-right:-1px;margin-bottom:-1px}.layui-table-body .layui-none{line-height:26px;padding:15px;text-align:center;color:#999}.layui-table-fixed{position:absolute;left:0;top:0;z-index:101}.layui-table-fixed .layui-table-body{overflow:hidden}.layui-table-fixed-l{box-shadow:0 -1px 8px rgba(0,0,0,.08)}.layui-table-fixed-r{left:auto;right:-1px;border-width:0 0 0 1px;box-shadow:-1px 0 8px rgba(0,0,0,.08)}.layui-table-fixed-r .layui-table-header{position:relative;overflow:visible}.layui-table-mend{position:absolute;right:-49px;top:0;height:100%;width:50px}.layui-table-tool{position:relative;z-index:890;width:100%;min-height:50px;line-height:30px;padding:10px 15px;border-width:0 0 1px}.layui-table-tool .layui-btn-container{margin-bottom:-10px}.layui-table-page,.layui-table-total{border-width:1px 0 0;margin-bottom:-1px;overflow:hidden}.layui-table-page{position:relative;width:100%;padding:7px 7px 0;height:41px;font-size:12px;white-space:nowrap}.layui-table-page>div{height:26px}.layui-table-page .layui-laypage{margin:0}.layui-table-page .layui-laypage a,.layui-table-page .layui-laypage span{height:26px;line-height:26px;margin-bottom:10px;border:none;background:0 0}.layui-table-page .layui-laypage a,.layui-table-page .layui-laypage span.layui-laypage-curr{padding:0 12px}.layui-table-page .layui-laypage span{margin-left:0;padding:0}.layui-table-page .layui-laypage .layui-laypage-prev{margin-left:-7px!important}.layui-table-page .layui-laypage .layui-laypage-curr .layui-laypage-em{left:0;top:0;padding:0}.layui-table-page .layui-laypage button,.layui-table-page .layui-laypage input{height:26px;line-height:26px}.layui-table-page .layui-laypage input{width:40px}.layui-table-page .layui-laypage button{padding:0 10px}.layui-table-page select{height:18px}.layui-table-patch .layui-table-cell{padding:0;width:30px}.layui-table-edit{position:absolute;left:0;top:0;width:100%;height:100%;padding:0 14px 1px;border-radius:0;box-shadow:1px 1px 20px rgba(0,0,0,.15)}.layui-table-edit:focus{border-color:#5FB878!important}select.layui-table-edit{padding:0 0 0 10px;border-color:#C9C9C9}.layui-table-view .layui-form-checkbox,.layui-table-view .layui-form-radio,.layui-table-view .layui-form-switch{top:0;margin:0;box-sizing:content-box}.layui-table-view .layui-form-checkbox{top:-1px;height:26px;line-height:26px}.layui-table-view .layui-form-checkbox i{height:26px}.layui-table-grid .layui-table-cell{overflow:visible}.layui-table-grid-down{position:absolute;top:0;right:0;width:26px;height:100%;padding:5px 0;border-width:0 0 0 1px;text-align:center;background-color:#fff;color:#999;cursor:pointer}.layui-table-grid-down .layui-icon{position:absolute;top:50%;left:50%;margin:-8px 0 0 -8px}.layui-table-grid-down:hover{background-color:#fbfbfb}body .layui-table-tips .layui-layer-content{background:0 0;padding:0;box-shadow:0 1px 6px rgba(0,0,0,.12)}.layui-table-tips-main{margin:-44px 0 0 -1px;max-height:150px;padding:8px 15px;font-size:14px;overflow-y:scroll;background-color:#fff;color:#666}.layui-table-tips-c{position:absolute;right:-3px;top:-13px;width:20px;height:20px;padding:3px;cursor:pointer;background-color:#666;border-radius:50%;color:#fff}.layui-table-tips-c:hover{background-color:#777}.layui-table-tips-c:before{position:relative;right:-2px}.layui-upload-file{display:none!important;opacity:.01;filter:Alpha(opacity=1)}.layui-upload-drag,.layui-upload-form,.layui-upload-wrap{display:inline-block}.layui-upload-list{margin:10px 0}.layui-upload-choose{padding:0 10px;color:#999}.layui-upload-drag{position:relative;padding:30px;border:1px dashed #e2e2e2;background-color:#fff;text-align:center;cursor:pointer;color:#999}.layui-upload-drag .layui-icon{font-size:50px;color:#009688}.layui-upload-drag[lay-over]{border-color:#009688}.layui-upload-iframe{position:absolute;width:0;height:0;border:0;visibility:hidden}.layui-upload-wrap{position:relative;vertical-align:middle}.layui-upload-wrap .layui-upload-file{display:block!important;position:absolute;left:0;top:0;z-index:10;font-size:100px;width:100%;height:100%;opacity:.01;filter:Alpha(opacity=1);cursor:pointer}.layui-tree{line-height:26px}.layui-tree li{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-tree li .layui-tree-spread,.layui-tree li a{display:inline-block;vertical-align:top;height:26px;*display:inline;*zoom:1;cursor:pointer}.layui-tree li a{font-size:0}.layui-tree li a i{font-size:16px}.layui-tree li a cite{padding:0 6px;font-size:14px;font-style:normal}.layui-tree li i{padding-left:6px;color:#333;-moz-user-select:none}.layui-tree li .layui-tree-check{font-size:13px}.layui-tree li .layui-tree-check:hover{color:#009E94}.layui-tree li ul{display:none;margin-left:20px}.layui-tree li .layui-tree-enter{line-height:24px;border:1px dotted #000}.layui-tree-drag{display:none;position:absolute;left:-666px;top:-666px;background-color:#f2f2f2;padding:5px 10px;border:1px dotted #000;white-space:nowrap}.layui-tree-drag i{padding-right:5px}.layui-nav{position:relative;padding:0 20px;background-color:#393D49;color:#fff;border-radius:2px;font-size:0;box-sizing:border-box}.layui-nav *{font-size:14px}.layui-nav .layui-nav-item{position:relative;display:inline-block;*display:inline;*zoom:1;vertical-align:middle;line-height:60px}.layui-nav .layui-nav-item a{display:block;padding:0 20px;color:#fff;color:rgba(255,255,255,.7);transition:all .3s;-webkit-transition:all .3s}.layui-nav .layui-this:after,.layui-nav-bar,.layui-nav-tree .layui-nav-itemed:after{position:absolute;left:0;top:0;width:0;height:5px;background-color:#5FB878;transition:all .2s;-webkit-transition:all .2s}.layui-nav-bar{z-index:1000}.layui-nav .layui-nav-item a:hover,.layui-nav .layui-this a{color:#fff}.layui-nav .layui-this:after{content:'';top:auto;bottom:0;width:100%}.layui-nav-img{width:30px;height:30px;margin-right:10px;border-radius:50%}.layui-nav .layui-nav-more{content:'';width:0;height:0;border-style:solid dashed dashed;border-color:#fff transparent transparent;overflow:hidden;cursor:pointer;transition:all .2s;-webkit-transition:all .2s;position:absolute;top:50%;right:3px;margin-top:-3px;border-width:6px;border-top-color:rgba(255,255,255,.7)}.layui-nav .layui-nav-mored,.layui-nav-itemed>a .layui-nav-more{margin-top:-9px;border-style:dashed dashed solid;border-color:transparent transparent #fff}.layui-nav-child{display:none;position:absolute;left:0;top:65px;min-width:100%;line-height:36px;padding:5px 0;box-shadow:0 2px 4px rgba(0,0,0,.12);border:1px solid #d2d2d2;background-color:#fff;z-index:100;border-radius:2px;white-space:nowrap}.layui-nav .layui-nav-child a{color:#333}.layui-nav .layui-nav-child a:hover{background-color:#f2f2f2;color:#000}.layui-nav-child dd{position:relative}.layui-nav .layui-nav-child dd.layui-this a,.layui-nav-child dd.layui-this{background-color:#5FB878;color:#fff}.layui-nav-child dd.layui-this:after{display:none}.layui-nav-tree{width:200px;padding:0}.layui-nav-tree .layui-nav-item{display:block;width:100%;line-height:45px}.layui-nav-tree .layui-nav-item a{position:relative;height:45px;line-height:45px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-nav-tree .layui-nav-item a:hover{background-color:#4E5465}.layui-nav-tree .layui-nav-bar{width:5px;height:0;background-color:#009688}.layui-nav-tree .layui-nav-child dd.layui-this,.layui-nav-tree .layui-nav-child dd.layui-this a,.layui-nav-tree .layui-this,.layui-nav-tree .layui-this>a,.layui-nav-tree .layui-this>a:hover{background-color:#009688;color:#fff}.layui-nav-tree .layui-this:after{display:none}.layui-nav-itemed>a,.layui-nav-tree .layui-nav-title a,.layui-nav-tree .layui-nav-title a:hover{color:#fff!important}.layui-nav-tree .layui-nav-child{position:relative;z-index:0;top:0;border:none;box-shadow:none}.layui-nav-tree .layui-nav-child a{height:40px;line-height:40px;color:#fff;color:rgba(255,255,255,.7)}.layui-nav-tree .layui-nav-child,.layui-nav-tree .layui-nav-child a:hover{background:0 0;color:#fff}.layui-nav-tree .layui-nav-more{right:10px}.layui-nav-itemed>.layui-nav-child{display:block;padding:0;background-color:rgba(0,0,0,.3)!important}.layui-nav-itemed>.layui-nav-child>.layui-this>.layui-nav-child{display:block}.layui-nav-side{position:fixed;top:0;bottom:0;left:0;overflow-x:hidden;z-index:999}.layui-bg-blue .layui-nav-bar,.layui-bg-blue .layui-nav-itemed:after,.layui-bg-blue .layui-this:after{background-color:#93D1FF}.layui-bg-blue .layui-nav-child dd.layui-this{background-color:#1E9FFF}.layui-bg-blue .layui-nav-itemed>a,.layui-nav-tree.layui-bg-blue .layui-nav-title a,.layui-nav-tree.layui-bg-blue .layui-nav-title a:hover{background-color:#007DDB!important}.layui-breadcrumb{visibility:hidden;font-size:0}.layui-breadcrumb>*{font-size:14px}.layui-breadcrumb a{color:#999!important}.layui-breadcrumb a:hover{color:#5FB878!important}.layui-breadcrumb a cite{color:#666;font-style:normal}.layui-breadcrumb span[lay-separator]{margin:0 10px;color:#999}.layui-tab{margin:10px 0;text-align:left!important}.layui-tab[overflow]>.layui-tab-title{overflow:hidden}.layui-tab-title{position:relative;left:0;height:40px;white-space:nowrap;font-size:0;border-bottom-width:1px;border-bottom-style:solid;transition:all .2s;-webkit-transition:all .2s}.layui-tab-title li{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;font-size:14px;transition:all .2s;-webkit-transition:all .2s;position:relative;line-height:40px;min-width:65px;padding:0 15px;text-align:center;cursor:pointer}.layui-tab-title li a{display:block}.layui-tab-title .layui-this{color:#000}.layui-tab-title .layui-this:after{position:absolute;left:0;top:0;content:'';width:100%;height:41px;border-width:1px;border-style:solid;border-bottom-color:#fff;border-radius:2px 2px 0 0;box-sizing:border-box;pointer-events:none}.layui-tab-bar{position:absolute;right:0;top:0;z-index:10;width:30px;height:39px;line-height:39px;border-width:1px;border-style:solid;border-radius:2px;text-align:center;background-color:#fff;cursor:pointer}.layui-tab-bar .layui-icon{position:relative;display:inline-block;top:3px;transition:all .3s;-webkit-transition:all .3s}.layui-tab-item{display:none}.layui-tab-more{padding-right:30px;height:auto!important;white-space:normal!important}.layui-tab-more li.layui-this:after{border-bottom-color:#e2e2e2;border-radius:2px}.layui-tab-more .layui-tab-bar .layui-icon{top:-2px;top:3px\9;-webkit-transform:rotate(180deg);transform:rotate(180deg)}:root .layui-tab-more .layui-tab-bar .layui-icon{top:-2px\0/IE9}.layui-tab-content{padding:10px}.layui-tab-title li .layui-tab-close{position:relative;display:inline-block;width:18px;height:18px;line-height:20px;margin-left:8px;top:1px;text-align:center;font-size:14px;color:#c2c2c2;transition:all .2s;-webkit-transition:all .2s}.layui-tab-title li .layui-tab-close:hover{border-radius:2px;background-color:#FF5722;color:#fff}.layui-tab-brief>.layui-tab-title .layui-this{color:#009688}.layui-tab-brief>.layui-tab-more li.layui-this:after,.layui-tab-brief>.layui-tab-title .layui-this:after{border:none;border-radius:0;border-bottom:2px solid #5FB878}.layui-tab-brief[overflow]>.layui-tab-title .layui-this:after{top:-1px}.layui-tab-card{border-width:1px;border-style:solid;border-radius:2px;box-shadow:0 2px 5px 0 rgba(0,0,0,.1)}.layui-tab-card>.layui-tab-title{background-color:#f2f2f2}.layui-tab-card>.layui-tab-title li{margin-right:-1px;margin-left:-1px}.layui-tab-card>.layui-tab-title .layui-this{background-color:#fff}.layui-tab-card>.layui-tab-title .layui-this:after{border-top:none;border-width:1px;border-bottom-color:#fff}.layui-tab-card>.layui-tab-title .layui-tab-bar{height:40px;line-height:40px;border-radius:0;border-top:none;border-right:none}.layui-tab-card>.layui-tab-more .layui-this{background:0 0;color:#5FB878}.layui-tab-card>.layui-tab-more .layui-this:after{border:none}.layui-timeline{padding-left:5px}.layui-timeline-item{position:relative;padding-bottom:20px}.layui-timeline-axis{position:absolute;left:-5px;top:0;z-index:10;width:20px;height:20px;line-height:20px;background-color:#fff;color:#5FB878;border-radius:50%;text-align:center;cursor:pointer}.layui-timeline-axis:hover{color:#FF5722}.layui-timeline-item:before{content:'';position:absolute;left:5px;top:0;z-index:0;width:1px;height:100%}.layui-timeline-item:last-child:before{display:none}.layui-timeline-item:first-child:before{display:block}.layui-timeline-content{padding-left:25px}.layui-timeline-title{position:relative;margin-bottom:10px}.layui-badge,.layui-badge-dot,.layui-badge-rim{position:relative;display:inline-block;padding:0 6px;font-size:12px;text-align:center;background-color:#FF5722;color:#fff;border-radius:2px}.layui-badge{height:18px;line-height:18px}.layui-badge-dot{width:8px;height:8px;padding:0;border-radius:50%}.layui-badge-rim{height:18px;line-height:18px;border-width:1px;border-style:solid;background-color:#fff;color:#666}.layui-btn .layui-badge,.layui-btn .layui-badge-dot{margin-left:5px}.layui-nav .layui-badge,.layui-nav .layui-badge-dot{position:absolute;top:50%;margin:-8px 6px 0}.layui-tab-title .layui-badge,.layui-tab-title .layui-badge-dot{left:5px;top:-2px}.layui-carousel{position:relative;left:0;top:0;background-color:#f8f8f8}.layui-carousel>[carousel-item]{position:relative;width:100%;height:100%;overflow:hidden}.layui-carousel>[carousel-item]:before{position:absolute;content:'\e63d';left:50%;top:50%;width:100px;line-height:20px;margin:-10px 0 0 -50px;text-align:center;color:#c2c2c2;font-family:layui-icon!important;font-size:30px;font-style:normal;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.layui-carousel>[carousel-item]>*{display:none;position:absolute;left:0;top:0;width:100%;height:100%;background-color:#f8f8f8;transition-duration:.3s;-webkit-transition-duration:.3s}.layui-carousel-updown>*{-webkit-transition:.3s ease-in-out up;transition:.3s ease-in-out up}.layui-carousel-arrow{display:none\9;opacity:0;position:absolute;left:10px;top:50%;margin-top:-18px;width:36px;height:36px;line-height:36px;text-align:center;font-size:20px;border:0;border-radius:50%;background-color:rgba(0,0,0,.2);color:#fff;-webkit-transition-duration:.3s;transition-duration:.3s;cursor:pointer}.layui-carousel-arrow[lay-type=add]{left:auto!important;right:10px}.layui-carousel:hover .layui-carousel-arrow[lay-type=add],.layui-carousel[lay-arrow=always] .layui-carousel-arrow[lay-type=add]{right:20px}.layui-carousel[lay-arrow=always] .layui-carousel-arrow{opacity:1;left:20px}.layui-carousel[lay-arrow=none] .layui-carousel-arrow{display:none}.layui-carousel-arrow:hover,.layui-carousel-ind ul:hover{background-color:rgba(0,0,0,.35)}.layui-carousel:hover .layui-carousel-arrow{display:block\9;opacity:1;left:20px}.layui-carousel-ind{position:relative;top:-35px;width:100%;line-height:0!important;text-align:center;font-size:0}.layui-carousel[lay-indicator=outside]{margin-bottom:30px}.layui-carousel[lay-indicator=outside] .layui-carousel-ind{top:10px}.layui-carousel[lay-indicator=outside] .layui-carousel-ind ul{background-color:rgba(0,0,0,.5)}.layui-carousel[lay-indicator=none] .layui-carousel-ind{display:none}.layui-carousel-ind ul{display:inline-block;padding:5px;background-color:rgba(0,0,0,.2);border-radius:10px;-webkit-transition-duration:.3s;transition-duration:.3s}.layui-carousel-ind li{display:inline-block;width:10px;height:10px;margin:0 3px;font-size:14px;background-color:#e2e2e2;background-color:rgba(255,255,255,.5);border-radius:50%;cursor:pointer;-webkit-transition-duration:.3s;transition-duration:.3s}.layui-carousel-ind li:hover{background-color:rgba(255,255,255,.7)}.layui-carousel-ind li.layui-this{background-color:#fff}.layui-carousel>[carousel-item]>.layui-carousel-next,.layui-carousel>[carousel-item]>.layui-carousel-prev,.layui-carousel>[carousel-item]>.layui-this{display:block}.layui-carousel>[carousel-item]>.layui-this{left:0}.layui-carousel>[carousel-item]>.layui-carousel-prev{left:-100%}.layui-carousel>[carousel-item]>.layui-carousel-next{left:100%}.layui-carousel>[carousel-item]>.layui-carousel-next.layui-carousel-left,.layui-carousel>[carousel-item]>.layui-carousel-prev.layui-carousel-right{left:0}.layui-carousel>[carousel-item]>.layui-this.layui-carousel-left{left:-100%}.layui-carousel>[carousel-item]>.layui-this.layui-carousel-right{left:100%}.layui-carousel[lay-anim=updown] .layui-carousel-arrow{left:50%!important;top:20px;margin:0 0 0 -18px}.layui-carousel[lay-anim=updown]>[carousel-item]>*,.layui-carousel[lay-anim=fade]>[carousel-item]>*{left:0!important}.layui-carousel[lay-anim=updown] .layui-carousel-arrow[lay-type=add]{top:auto!important;bottom:20px}.layui-carousel[lay-anim=updown] .layui-carousel-ind{position:absolute;top:50%;right:20px;width:auto;height:auto}.layui-carousel[lay-anim=updown] .layui-carousel-ind ul{padding:3px 5px}.layui-carousel[lay-anim=updown] .layui-carousel-ind li{display:block;margin:6px 0}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-this{top:0}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-carousel-prev{top:-100%}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-carousel-next{top:100%}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-carousel-next.layui-carousel-left,.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-carousel-prev.layui-carousel-right{top:0}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-this.layui-carousel-left{top:-100%}.layui-carousel[lay-anim=updown]>[carousel-item]>.layui-this.layui-carousel-right{top:100%}.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-carousel-next,.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-carousel-prev{opacity:0}.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-carousel-next.layui-carousel-left,.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-carousel-prev.layui-carousel-right{opacity:1}.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-this.layui-carousel-left,.layui-carousel[lay-anim=fade]>[carousel-item]>.layui-this.layui-carousel-right{opacity:0}.layui-fixbar{position:fixed;right:15px;bottom:15px;z-index:999999}.layui-fixbar li{width:50px;height:50px;line-height:50px;margin-bottom:1px;text-align:center;cursor:pointer;font-size:30px;background-color:#9F9F9F;color:#fff;border-radius:2px;opacity:.95}.layui-fixbar li:hover{opacity:.85}.layui-fixbar li:active{opacity:1}.layui-fixbar .layui-fixbar-top{display:none;font-size:40px}body .layui-util-face{border:none;background:0 0}body .layui-util-face .layui-layer-content{padding:0;background-color:#fff;color:#666;box-shadow:none}.layui-util-face .layui-layer-TipsG{display:none}.layui-util-face ul{position:relative;width:372px;padding:10px;border:1px solid #D9D9D9;background-color:#fff;box-shadow:0 0 20px rgba(0,0,0,.2)}.layui-util-face ul li{cursor:pointer;float:left;border:1px solid #e8e8e8;height:22px;width:26px;overflow:hidden;margin:-1px 0 0 -1px;padding:4px 2px;text-align:center}.layui-util-face ul li:hover{position:relative;z-index:2;border:1px solid #eb7350;background:#fff9ec}.layui-code{position:relative;margin:10px 0;padding:15px;line-height:20px;border:1px solid #ddd;border-left-width:6px;background-color:#F2F2F2;color:#333;font-family:Courier New;font-size:12px}.layui-rate,.layui-rate *{display:inline-block;vertical-align:middle}.layui-rate{padding:10px 5px 10px 0;font-size:0}.layui-rate li i.layui-icon{font-size:20px;color:#FFB800;margin-right:5px;transition:all .3s;-webkit-transition:all .3s}.layui-rate li i:hover{cursor:pointer;transform:scale(1.12);-webkit-transform:scale(1.12)}.layui-rate[readonly] li i:hover{cursor:default;transform:scale(1)}.layui-colorpicker{width:26px;height:26px;border:1px solid #e6e6e6;padding:5px;border-radius:2px;line-height:24px;display:inline-block;cursor:pointer;transition:all .3s;-webkit-transition:all .3s}.layui-colorpicker:hover{border-color:#d2d2d2}.layui-colorpicker.layui-colorpicker-lg{width:34px;height:34px;line-height:32px}.layui-colorpicker.layui-colorpicker-sm{width:24px;height:24px;line-height:22px}.layui-colorpicker.layui-colorpicker-xs{width:22px;height:22px;line-height:20px}.layui-colorpicker-trigger-bgcolor{display:block;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);border-radius:2px}.layui-colorpicker-trigger-span{display:block;height:100%;box-sizing:border-box;border:1px solid rgba(0,0,0,.15);border-radius:2px;text-align:center}.layui-colorpicker-trigger-i{display:inline-block;color:#FFF;font-size:12px}.layui-colorpicker-trigger-i.layui-icon-close{color:#999}.layui-colorpicker-main{position:absolute;z-index:66666666;width:280px;padding:7px;background:#FFF;border:1px solid #d2d2d2;border-radius:2px;box-shadow:0 2px 4px rgba(0,0,0,.12)}.layui-colorpicker-main-wrapper{height:180px;position:relative}.layui-colorpicker-basis{width:260px;height:100%;position:relative}.layui-colorpicker-basis-white{width:100%;height:100%;position:absolute;top:0;left:0;background:linear-gradient(90deg,#FFF,hsla(0,0%,100%,0))}.layui-colorpicker-basis-black{width:100%;height:100%;position:absolute;top:0;left:0;background:linear-gradient(0deg,#000,transparent)}.layui-colorpicker-basis-cursor{width:10px;height:10px;border:1px solid #FFF;border-radius:50%;position:absolute;top:-3px;right:-3px;cursor:pointer}.layui-colorpicker-side{position:absolute;top:0;right:0;width:12px;height:100%;background:linear-gradient(red,#FF0,#0F0,#0FF,#00F,#F0F,red)}.layui-colorpicker-side-slider{width:100%;height:5px;box-shadow:0 0 1px #888;box-sizing:border-box;background:#FFF;border-radius:1px;border:1px solid #f0f0f0;cursor:pointer;position:absolute;left:0}.layui-colorpicker-main-alpha{display:none;height:12px;margin-top:7px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.layui-colorpicker-alpha-bgcolor{height:100%;position:relative}.layui-colorpicker-alpha-slider{width:5px;height:100%;box-shadow:0 0 1px #888;box-sizing:border-box;background:#FFF;border-radius:1px;border:1px solid #f0f0f0;cursor:pointer;position:absolute;top:0}.layui-colorpicker-main-pre{padding-top:7px;font-size:0}.layui-colorpicker-pre{width:20px;height:20px;border-radius:2px;display:inline-block;margin-left:6px;margin-bottom:7px;cursor:pointer}.layui-colorpicker-pre:nth-child(11n+1){margin-left:0}.layui-colorpicker-pre-isalpha{background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.layui-colorpicker-pre.layui-this{box-shadow:0 0 3px 2px rgba(0,0,0,.15)}.layui-colorpicker-pre>div{height:100%;border-radius:2px}.layui-colorpicker-main-input{text-align:right;padding-top:7px}.layui-colorpicker-main-input .layui-btn-container .layui-btn{margin:0 0 0 10px}.layui-colorpicker-main-input div.layui-inline{float:left;margin-right:10px;font-size:14px}.layui-colorpicker-main-input input.layui-input{width:150px;height:30px;color:#666}.layui-slider{height:4px;background:#e2e2e2;border-radius:3px;position:relative;cursor:pointer}.layui-slider-bar{border-radius:3px;position:absolute;height:100%}.layui-slider-step{position:absolute;top:0;width:4px;height:4px;border-radius:50%;background:#FFF;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.layui-slider-wrap{width:36px;height:36px;position:absolute;top:-16px;-webkit-transform:translateX(-50%);transform:translateX(-50%);z-index:10;text-align:center}.layui-slider-wrap-btn{width:12px;height:12px;border-radius:50%;background:#FFF;display:inline-block;vertical-align:middle;cursor:pointer;transition:.3s}.layui-slider-wrap:after{content:"";height:100%;display:inline-block;vertical-align:middle}.layui-slider-wrap-btn.layui-slider-hover,.layui-slider-wrap-btn:hover{transform:scale(1.2)}.layui-slider-wrap-btn.layui-disabled:hover{transform:scale(1)!important}.layui-slider-tips{position:absolute;top:-42px;z-index:66666666;white-space:nowrap;display:none;-webkit-transform:translateX(-50%);transform:translateX(-50%);color:#FFF;background:#000;border-radius:3px;height:25px;line-height:25px;padding:0 10px}.layui-slider-tips:after{content:'';position:absolute;bottom:-12px;left:50%;margin-left:-6px;width:0;height:0;border-width:6px;border-style:solid;border-color:#000 transparent transparent}.layui-slider-input{width:70px;height:32px;border:1px solid #e6e6e6;border-radius:3px;font-size:16px;line-height:32px;position:absolute;right:0;top:-15px}.layui-slider-input-btn{display:none;position:absolute;top:0;right:0;width:20px;height:100%;border-left:1px solid #d2d2d2}.layui-slider-input-btn i{cursor:pointer;position:absolute;right:0;bottom:0;width:20px;height:50%;font-size:12px;line-height:16px;text-align:center;color:#999}.layui-slider-input-btn i:first-child{top:0;border-bottom:1px solid #d2d2d2}.layui-slider-input-txt{height:100%;font-size:14px}.layui-slider-input-txt input{height:100%;border:none}.layui-slider-input-btn i:hover{color:#009688}.layui-slider-vertical{width:4px;margin-left:34px}.layui-slider-vertical .layui-slider-bar{width:4px}.layui-slider-vertical .layui-slider-step{top:auto;left:0;-webkit-transform:translateY(50%);transform:translateY(50%)}.layui-slider-vertical .layui-slider-wrap{top:auto;left:-16px;-webkit-transform:translateY(50%);transform:translateY(50%)}.layui-slider-vertical .layui-slider-tips{top:auto;left:2px}@media \0screen{.layui-slider-wrap-btn{margin-left:-20px}.layui-slider-vertical .layui-slider-wrap-btn{margin-left:0;margin-bottom:-20px}.layui-slider-vertical .layui-slider-tips{margin-left:-8px}.layui-slider>span{margin-left:8px}}.layui-anim{-webkit-animation-duration:.3s;animation-duration:.3s;-webkit-animation-fill-mode:both;animation-fill-mode:both}.layui-anim.layui-icon{display:inline-block}.layui-anim-loop{-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite}.layui-trans,.layui-trans a{transition:all .3s;-webkit-transition:all .3s}@-webkit-keyframes layui-rotate{from{-webkit-transform:rotate(0)}to{-webkit-transform:rotate(360deg)}}@keyframes layui-rotate{from{transform:rotate(0)}to{transform:rotate(360deg)}}.layui-anim-rotate{-webkit-animation-name:layui-rotate;animation-name:layui-rotate;-webkit-animation-duration:1s;animation-duration:1s;-webkit-animation-timing-function:linear;animation-timing-function:linear}@-webkit-keyframes layui-up{from{-webkit-transform:translate3d(0,100%,0);opacity:.3}to{-webkit-transform:translate3d(0,0,0);opacity:1}}@keyframes layui-up{from{transform:translate3d(0,100%,0);opacity:.3}to{transform:translate3d(0,0,0);opacity:1}}.layui-anim-up{-webkit-animation-name:layui-up;animation-name:layui-up}@-webkit-keyframes layui-upbit{from{-webkit-transform:translate3d(0,30px,0);opacity:.3}to{-webkit-transform:translate3d(0,0,0);opacity:1}}@keyframes layui-upbit{from{transform:translate3d(0,30px,0);opacity:.3}to{transform:translate3d(0,0,0);opacity:1}}.layui-anim-upbit{-webkit-animation-name:layui-upbit;animation-name:layui-upbit}@-webkit-keyframes layui-scale{0%{opacity:.3;-webkit-transform:scale(.5)}100%{opacity:1;-webkit-transform:scale(1)}}@keyframes layui-scale{0%{opacity:.3;-ms-transform:scale(.5);transform:scale(.5)}100%{opacity:1;-ms-transform:scale(1);transform:scale(1)}}.layui-anim-scale{-webkit-animation-name:layui-scale;animation-name:layui-scale}@-webkit-keyframes layui-scale-spring{0%{opacity:.5;-webkit-transform:scale(.5)}80%{opacity:.8;-webkit-transform:scale(1.1)}100%{opacity:1;-webkit-transform:scale(1)}}@keyframes layui-scale-spring{0%{opacity:.5;transform:scale(.5)}80%{opacity:.8;transform:scale(1.1)}100%{opacity:1;transform:scale(1)}}.layui-anim-scaleSpring{-webkit-animation-name:layui-scale-spring;animation-name:layui-scale-spring}@-webkit-keyframes layui-fadein{0%{opacity:0}100%{opacity:1}}@keyframes layui-fadein{0%{opacity:0}100%{opacity:1}}.layui-anim-fadein{-webkit-animation-name:layui-fadein;animation-name:layui-fadein}@-webkit-keyframes layui-fadeout{0%{opacity:1}100%{opacity:0}}@keyframes layui-fadeout{0%{opacity:1}100%{opacity:0}}.layui-anim-fadeout{-webkit-animation-name:layui-fadeout;animation-name:layui-fadeout} ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/css/layui.mobile.css ================================================ /** layui-v2.4.5 MIT License By https://www.layui.com */ blockquote,body,button,dd,div,dl,dt,form,h1,h2,h3,h4,h5,h6,input,legend,li,ol,p,td,textarea,th,ul{margin:0;padding:0;-webkit-tap-highlight-color:rgba(0,0,0,0)}html{font:12px 'Helvetica Neue','PingFang SC',STHeitiSC-Light,Helvetica,Arial,sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}a,button,input{-webkit-tap-highlight-color:rgba(255,0,0,0)}a{text-decoration:none;background:0 0}a:active,a:hover{outline:0}table{border-collapse:collapse;border-spacing:0}li{list-style:none}b,strong{font-weight:700}h1,h2,h3,h4,h5,h6{font-weight:500}address,cite,dfn,em,var{font-style:normal}dfn{font-style:italic}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}img{border:0;vertical-align:bottom}.layui-inline,input,label{vertical-align:middle}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0;outline:0}button,select{text-transform:none}select{-webkit-appearance:none;border:none}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}@font-face{font-family:layui-icon;src:url(../font/iconfont.eot?v=1.0.7);src:url(../font/iconfont.eot?v=1.0.7#iefix) format('embedded-opentype'),url(../font/iconfont.woff?v=1.0.7) format('woff'),url(../font/iconfont.ttf?v=1.0.7) format('truetype'),url(../font/iconfont.svg?v=1.0.7#iconfont) format('svg')}.layui-icon{font-family:layui-icon!important;font-size:16px;font-style:normal;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.layui-box,.layui-box *{-webkit-box-sizing:content-box!important;-moz-box-sizing:content-box!important;box-sizing:content-box!important}.layui-border-box,.layui-border-box *{-webkit-box-sizing:border-box!important;-moz-box-sizing:border-box!important;box-sizing:border-box!important}.layui-inline{position:relative;display:inline-block;*display:inline;*zoom:1}.layui-edge,.layui-upload-iframe{position:absolute;width:0;height:0}.layui-edge{border-style:dashed;border-color:transparent;overflow:hidden}.layui-elip{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-unselect{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}.layui-disabled,.layui-disabled:active{background-color:#d2d2d2!important;color:#fff!important;cursor:not-allowed!important}.layui-circle{border-radius:100%}.layui-show{display:block!important}.layui-hide{display:none!important}.layui-upload-iframe{border:0;visibility:hidden}.layui-upload-enter{border:1px solid #009E94;background-color:#009E94;color:#fff;-webkit-transform:scale(1.1);transform:scale(1.1)}@-webkit-keyframes layui-m-anim-scale{0%{opacity:0;-webkit-transform:scale(.5);transform:scale(.5)}100%{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}@keyframes layui-m-anim-scale{0%{opacity:0;-webkit-transform:scale(.5);transform:scale(.5)}100%{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}.layui-m-anim-scale{animation-name:layui-m-anim-scale;-webkit-animation-name:layui-m-anim-scale}@-webkit-keyframes layui-m-anim-up{0%{opacity:0;-webkit-transform:translateY(800px);transform:translateY(800px)}100%{opacity:1;-webkit-transform:translateY(0);transform:translateY(0)}}@keyframes layui-m-anim-up{0%{opacity:0;-webkit-transform:translateY(800px);transform:translateY(800px)}100%{opacity:1;-webkit-transform:translateY(0);transform:translateY(0)}}.layui-m-anim-up{-webkit-animation-name:layui-m-anim-up;animation-name:layui-m-anim-up}@-webkit-keyframes layui-m-anim-left{0%{-webkit-transform:translateX(100%);transform:translateX(100%)}100%{-webkit-transform:translateX(0);transform:translateX(0)}}@keyframes layui-m-anim-left{0%{-webkit-transform:translateX(100%);transform:translateX(100%)}100%{-webkit-transform:translateX(0);transform:translateX(0)}}.layui-m-anim-left{-webkit-animation-name:layui-m-anim-left;animation-name:layui-m-anim-left}@-webkit-keyframes layui-m-anim-right{0%{-webkit-transform:translateX(-100%);transform:translateX(-100%)}100%{-webkit-transform:translateX(0);transform:translateX(0)}}@keyframes layui-m-anim-right{0%{-webkit-transform:translateX(-100%);transform:translateX(-100%)}100%{-webkit-transform:translateX(0);transform:translateX(0)}}.layui-m-anim-right{-webkit-animation-name:layui-m-anim-right;animation-name:layui-m-anim-right}@-webkit-keyframes layui-m-anim-lout{0%{-webkit-transform:translateX(0);transform:translateX(0)}100%{-webkit-transform:translateX(-100%);transform:translateX(-100%)}}@keyframes layui-m-anim-lout{0%{-webkit-transform:translateX(0);transform:translateX(0)}100%{-webkit-transform:translateX(-100%);transform:translateX(-100%)}}.layui-m-anim-lout{-webkit-animation-name:layui-m-anim-lout;animation-name:layui-m-anim-lout}@-webkit-keyframes layui-m-anim-rout{0%{-webkit-transform:translateX(0);transform:translateX(0)}100%{-webkit-transform:translateX(100%);transform:translateX(100%)}}@keyframes layui-m-anim-rout{0%{-webkit-transform:translateX(0);transform:translateX(0)}100%{-webkit-transform:translateX(100%);transform:translateX(100%)}}.layui-m-anim-rout{-webkit-animation-name:layui-m-anim-rout;animation-name:layui-m-anim-rout}.layui-m-layer{position:relative;z-index:19891014}.layui-m-layer *{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.layui-m-layermain,.layui-m-layershade{position:fixed;left:0;top:0;width:100%;height:100%}.layui-m-layershade{background-color:rgba(0,0,0,.7);pointer-events:auto}.layui-m-layermain{display:table;font-family:Helvetica,arial,sans-serif;pointer-events:none}.layui-m-layermain .layui-m-layersection{display:table-cell;vertical-align:middle;text-align:center}.layui-m-layerchild{position:relative;display:inline-block;text-align:left;background-color:#fff;font-size:14px;border-radius:5px;box-shadow:0 0 8px rgba(0,0,0,.1);pointer-events:auto;-webkit-overflow-scrolling:touch;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:.2s;animation-duration:.2s}.layui-m-layer0 .layui-m-layerchild{width:90%;max-width:640px}.layui-m-layer1 .layui-m-layerchild{border:none;border-radius:0}.layui-m-layer2 .layui-m-layerchild{width:auto;max-width:260px;min-width:40px;border:none;background:0 0;box-shadow:none;color:#fff}.layui-m-layerchild h3{padding:0 10px;height:60px;line-height:60px;font-size:16px;font-weight:400;border-radius:5px 5px 0 0;text-align:center}.layui-m-layerbtn span,.layui-m-layerchild h3{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-m-layercont{padding:50px 30px;line-height:22px;text-align:center}.layui-m-layer1 .layui-m-layercont{padding:0;text-align:left}.layui-m-layer2 .layui-m-layercont{text-align:center;padding:0;line-height:0}.layui-m-layer2 .layui-m-layercont i{width:25px;height:25px;margin-left:8px;display:inline-block;background-color:#fff;border-radius:100%;-webkit-animation:layui-m-anim-loading 1.4s infinite ease-in-out;animation:layui-m-anim-loading 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;animation-fill-mode:both}.layui-m-layerbtn,.layui-m-layerbtn span{position:relative;text-align:center;border-radius:0 0 5px 5px}.layui-m-layer2 .layui-m-layercont p{margin-top:20px}@-webkit-keyframes layui-m-anim-loading{0%,100%,80%{transform:scale(0);-webkit-transform:scale(0)}40%{transform:scale(1);-webkit-transform:scale(1)}}@keyframes layui-m-anim-loading{0%,100%,80%{transform:scale(0);-webkit-transform:scale(0)}40%{transform:scale(1);-webkit-transform:scale(1)}}.layui-m-layer2 .layui-m-layercont i:first-child{margin-left:0;-webkit-animation-delay:-.32s;animation-delay:-.32s}.layui-m-layer2 .layui-m-layercont i.layui-m-layerload{-webkit-animation-delay:-.16s;animation-delay:-.16s}.layui-m-layer2 .layui-m-layercont>div{line-height:22px;padding-top:7px;margin-bottom:20px;font-size:14px}.layui-m-layerbtn{display:box;display:-moz-box;display:-webkit-box;width:100%;height:50px;line-height:50px;font-size:0;border-top:1px solid #D0D0D0;background-color:#F2F2F2}.layui-m-layerbtn span{display:block;-moz-box-flex:1;box-flex:1;-webkit-box-flex:1;font-size:14px;cursor:pointer}.layui-m-layerbtn span[yes]{color:#40AFFE}.layui-m-layerbtn span[no]{border-right:1px solid #D0D0D0;border-radius:0 0 0 5px}.layui-m-layerbtn span:active{background-color:#F6F6F6}.layui-m-layerend{position:absolute;right:7px;top:10px;width:30px;height:30px;border:0;font-weight:400;background:0 0;cursor:pointer;-webkit-appearance:none;font-size:30px}.layui-m-layerend::after,.layui-m-layerend::before{position:absolute;left:5px;top:15px;content:'';width:18px;height:1px;background-color:#999;transform:rotate(45deg);-webkit-transform:rotate(45deg);border-radius:3px}.layui-m-layerend::after{transform:rotate(-45deg);-webkit-transform:rotate(-45deg)}body .layui-m-layer .layui-m-layer-footer{position:fixed;width:95%;max-width:100%;margin:0 auto;left:0;right:0;bottom:10px;background:0 0}.layui-m-layer-footer .layui-m-layercont{padding:20px;border-radius:5px 5px 0 0;background-color:rgba(255,255,255,.8)}.layui-m-layer-footer .layui-m-layerbtn{display:block;height:auto;background:0 0;border-top:none}.layui-m-layer-footer .layui-m-layerbtn span{background-color:rgba(255,255,255,.8)}.layui-m-layer-footer .layui-m-layerbtn span[no]{color:#FD482C;border-top:1px solid #c2c2c2;border-radius:0 0 5px 5px}.layui-m-layer-footer .layui-m-layerbtn span[yes]{margin-top:10px;border-radius:5px}body .layui-m-layer .layui-m-layer-msg{width:auto;max-width:90%;margin:0 auto;bottom:-150px;background-color:rgba(0,0,0,.7);color:#fff}.layui-m-layer-msg .layui-m-layercont{padding:10px 20px} ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/css/modules/code.css ================================================ /** layui-v2.4.5 MIT License By https://www.layui.com */ html #layuicss-skincodecss{display:none;position:absolute;width:1989px}.layui-code-h3,.layui-code-view{position:relative;font-size:12px}.layui-code-view{display:block;margin:10px 0;padding:0;border:1px solid #e2e2e2;border-left-width:6px;background-color:#F2F2F2;color:#333;font-family:Courier New}.layui-code-h3{padding:0 10px;height:32px;line-height:32px;border-bottom:1px solid #e2e2e2}.layui-code-h3 a{position:absolute;right:10px;top:0;color:#999}.layui-code-view .layui-code-ol{position:relative;overflow:auto}.layui-code-view .layui-code-ol li{position:relative;margin-left:45px;line-height:20px;padding:0 5px;border-left:1px solid #e2e2e2;list-style-type:decimal-leading-zero;*list-style-type:decimal;background-color:#fff}.layui-code-view pre{margin:0}.layui-code-notepad{border:1px solid #0C0C0C;border-left-color:#3F3F3F;background-color:#0C0C0C;color:#C2BE9E}.layui-code-notepad .layui-code-h3{border-bottom:none}.layui-code-notepad .layui-code-ol li{background-color:#3F3F3F;border-left:none} ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/css/modules/laydate/default/laydate.css ================================================ /** layui-v2.4.5 MIT License By https://www.layui.com */ .laydate-set-ym,.layui-laydate,.layui-laydate *,.layui-laydate-list{box-sizing:border-box}html #layuicss-laydate{display:none;position:absolute;width:1989px}.layui-laydate *{margin:0;padding:0}.layui-laydate{position:absolute;z-index:66666666;margin:5px 0;border-radius:2px;font-size:14px;-webkit-animation-duration:.3s;animation-duration:.3s;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-name:laydate-upbit;animation-name:laydate-upbit}.layui-laydate-main{width:272px}.layui-laydate-content td,.layui-laydate-header *,.layui-laydate-list li{transition-duration:.3s;-webkit-transition-duration:.3s}@-webkit-keyframes laydate-upbit{from{-webkit-transform:translate3d(0,20px,0);opacity:.3}to{-webkit-transform:translate3d(0,0,0);opacity:1}}@keyframes laydate-upbit{from{transform:translate3d(0,20px,0);opacity:.3}to{transform:translate3d(0,0,0);opacity:1}}.layui-laydate-static{position:relative;z-index:0;display:inline-block;margin:0;-webkit-animation:none;animation:none}.laydate-ym-show .laydate-next-m,.laydate-ym-show .laydate-prev-m{display:none!important}.laydate-ym-show .laydate-next-y,.laydate-ym-show .laydate-prev-y{display:inline-block!important}.laydate-time-show .laydate-set-ym span[lay-type=month],.laydate-time-show .laydate-set-ym span[lay-type=year],.laydate-time-show .layui-laydate-header .layui-icon,.laydate-ym-show .laydate-set-ym span[lay-type=month]{display:none!important}.layui-laydate-header{position:relative;line-height:30px;padding:10px 70px 5px}.laydate-set-ym span,.layui-laydate-header i{padding:0 5px;cursor:pointer}.layui-laydate-header *{display:inline-block;vertical-align:bottom}.layui-laydate-header i{position:absolute;top:10px;color:#999;font-size:18px}.layui-laydate-header i.laydate-prev-y{left:15px}.layui-laydate-header i.laydate-prev-m{left:45px}.layui-laydate-header i.laydate-next-y{right:15px}.layui-laydate-header i.laydate-next-m{right:45px}.laydate-set-ym{width:100%;text-align:center;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.laydate-time-text{cursor:default!important}.layui-laydate-content{position:relative;padding:10px;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}.layui-laydate-content table{border-collapse:collapse;border-spacing:0}.layui-laydate-content td,.layui-laydate-content th{width:36px;height:30px;padding:5px;text-align:center}.layui-laydate-content td{position:relative;cursor:pointer}.laydate-day-mark{position:absolute;left:0;top:0;width:100%;height:100%;line-height:30px;font-size:12px;overflow:hidden}.laydate-day-mark::after{position:absolute;content:'';right:2px;top:2px;width:5px;height:5px;border-radius:50%}.layui-laydate-footer{position:relative;height:46px;line-height:26px;padding:10px 20px}.layui-laydate-footer span{margin-right:15px;display:inline-block;cursor:pointer;font-size:12px}.layui-laydate-footer span:hover{color:#5FB878}.laydate-footer-btns{position:absolute;right:10px;top:10px}.laydate-footer-btns span{height:26px;line-height:26px;margin:0 0 0 -1px;padding:0 10px;border:1px solid #C9C9C9;background-color:#fff;white-space:nowrap;vertical-align:top;border-radius:2px}.layui-laydate-list>li,.layui-laydate-range .layui-laydate-main{display:inline-block;vertical-align:middle}.layui-laydate-list{position:absolute;left:0;top:0;width:100%;height:100%;padding:10px;background-color:#fff}.layui-laydate-list>li{position:relative;width:33.3%;height:36px;line-height:36px;margin:3px 0;text-align:center;cursor:pointer}.laydate-month-list>li{width:25%;margin:17px 0}.laydate-time-list>li{height:100%;margin:0;line-height:normal;cursor:default}.laydate-time-list p{position:relative;top:-4px;line-height:29px}.laydate-time-list ol{height:181px;overflow:hidden}.laydate-time-list>li:hover ol{overflow-y:auto}.laydate-time-list ol li{width:130%;padding-left:33px;line-height:30px;text-align:left;cursor:pointer}.layui-laydate-hint{position:absolute;top:115px;left:50%;width:250px;margin-left:-125px;line-height:20px;padding:15px;text-align:center;font-size:12px}.layui-laydate-range{width:546px}.layui-laydate-range .laydate-main-list-0 .laydate-next-m,.layui-laydate-range .laydate-main-list-0 .laydate-next-y,.layui-laydate-range .laydate-main-list-1 .laydate-prev-m,.layui-laydate-range .laydate-main-list-1 .laydate-prev-y{display:none}.layui-laydate-range .laydate-main-list-1 .layui-laydate-content{border-left:1px solid #e2e2e2}.layui-laydate,.layui-laydate-hint{border:1px solid #d2d2d2;box-shadow:0 2px 4px rgba(0,0,0,.12);background-color:#fff;color:#666}.layui-laydate-header{border-bottom:1px solid #e2e2e2}.layui-laydate-header i:hover,.layui-laydate-header span:hover{color:#5FB878}.layui-laydate-content{border-top:none 0;border-bottom:none 0}.layui-laydate-content th{font-weight:400;color:#333}.layui-laydate-content td{color:#666}.layui-laydate-content td.laydate-selected{background-color:#00F7DE}.laydate-selected:hover{background-color:#00F7DE!important}.layui-laydate-content td:hover,.layui-laydate-list li:hover{background-color:#eaeaea;color:#333}.laydate-time-list li ol{margin:0;padding:0;border:1px solid #e2e2e2;border-left-width:0}.laydate-time-list li:first-child ol{border-left-width:1px}.laydate-time-list>li:hover{background:0 0}.layui-laydate-content .laydate-day-next,.layui-laydate-content .laydate-day-prev{color:#d2d2d2}.laydate-selected.laydate-day-next,.laydate-selected.laydate-day-prev{background-color:#f8f8f8!important}.layui-laydate-footer{border-top:1px solid #e2e2e2}.layui-laydate-hint{color:#FF5722}.laydate-day-mark::after{background-color:#5FB878}.layui-laydate-content td.layui-this .laydate-day-mark::after{display:none}.layui-laydate-footer span[lay-type=date]{color:#5FB878}.layui-laydate .layui-this{background-color:#009688!important;color:#fff!important}.layui-laydate .laydate-disabled,.layui-laydate .laydate-disabled:hover{background:0 0!important;color:#d2d2d2!important;cursor:not-allowed!important;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}.laydate-theme-molv{border:none}.laydate-theme-molv.layui-laydate-range{width:548px}.laydate-theme-molv .layui-laydate-main{width:274px}.laydate-theme-molv .layui-laydate-header{border:none;background-color:#009688}.laydate-theme-molv .layui-laydate-header i,.laydate-theme-molv .layui-laydate-header span{color:#f6f6f6}.laydate-theme-molv .layui-laydate-header i:hover,.laydate-theme-molv .layui-laydate-header span:hover{color:#fff}.laydate-theme-molv .layui-laydate-content{border:1px solid #e2e2e2;border-top:none;border-bottom:none}.laydate-theme-molv .laydate-main-list-1 .layui-laydate-content{border-left:none}.laydate-theme-grid .laydate-month-list>li,.laydate-theme-grid .laydate-year-list>li,.laydate-theme-grid .layui-laydate-content td,.laydate-theme-grid .layui-laydate-content thead,.laydate-theme-molv .layui-laydate-footer{border:1px solid #e2e2e2}.laydate-theme-grid .laydate-selected,.laydate-theme-grid .laydate-selected:hover{background-color:#f2f2f2!important;color:#009688!important}.laydate-theme-grid .laydate-selected.laydate-day-next,.laydate-theme-grid .laydate-selected.laydate-day-prev{color:#d2d2d2!important}.laydate-theme-grid .laydate-month-list,.laydate-theme-grid .laydate-year-list{margin:1px 0 0 1px}.laydate-theme-grid .laydate-month-list>li,.laydate-theme-grid .laydate-year-list>li{margin:0 -1px -1px 0}.laydate-theme-grid .laydate-year-list>li{height:43px;line-height:43px}.laydate-theme-grid .laydate-month-list>li{height:71px;line-height:71px} ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/css/modules/layer/default/layer.css ================================================ /** layui-v2.4.5 MIT License By https://www.layui.com */ .layui-layer-imgbar,.layui-layer-imgtit a,.layui-layer-tab .layui-layer-title span,.layui-layer-title{text-overflow:ellipsis;white-space:nowrap}html #layuicss-layer{display:none;position:absolute;width:1989px}.layui-layer,.layui-layer-shade{position:fixed;_position:absolute;pointer-events:auto}.layui-layer-shade{top:0;left:0;width:100%;height:100%;_height:expression(document.body.offsetHeight+"px")}.layui-layer{-webkit-overflow-scrolling:touch;top:150px;left:0;margin:0;padding:0;background-color:#fff;-webkit-background-clip:content;border-radius:2px;box-shadow:1px 1px 50px rgba(0,0,0,.3)}.layui-layer-close{position:absolute}.layui-layer-content{position:relative}.layui-layer-border{border:1px solid #B2B2B2;border:1px solid rgba(0,0,0,.1);box-shadow:1px 1px 5px rgba(0,0,0,.2)}.layui-layer-load{background:url(loading-1.gif) center center no-repeat #eee}.layui-layer-ico{background:url(icon.png) no-repeat}.layui-layer-btn a,.layui-layer-dialog .layui-layer-ico,.layui-layer-setwin a{display:inline-block;*display:inline;*zoom:1;vertical-align:top}.layui-layer-move{display:none;position:fixed;*position:absolute;left:0;top:0;width:100%;height:100%;cursor:move;opacity:0;filter:alpha(opacity=0);background-color:#fff;z-index:2147483647}.layui-layer-resize{position:absolute;width:15px;height:15px;right:0;bottom:0;cursor:se-resize}.layer-anim{-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:.3s;animation-duration:.3s}@-webkit-keyframes layer-bounceIn{0%{opacity:0;-webkit-transform:scale(.5);transform:scale(.5)}100%{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}@keyframes layer-bounceIn{0%{opacity:0;-webkit-transform:scale(.5);-ms-transform:scale(.5);transform:scale(.5)}100%{opacity:1;-webkit-transform:scale(1);-ms-transform:scale(1);transform:scale(1)}}.layer-anim-00{-webkit-animation-name:layer-bounceIn;animation-name:layer-bounceIn}@-webkit-keyframes layer-zoomInDown{0%{opacity:0;-webkit-transform:scale(.1) translateY(-2000px);transform:scale(.1) translateY(-2000px);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}60%{opacity:1;-webkit-transform:scale(.475) translateY(60px);transform:scale(.475) translateY(60px);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}}@keyframes layer-zoomInDown{0%{opacity:0;-webkit-transform:scale(.1) translateY(-2000px);-ms-transform:scale(.1) translateY(-2000px);transform:scale(.1) translateY(-2000px);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}60%{opacity:1;-webkit-transform:scale(.475) translateY(60px);-ms-transform:scale(.475) translateY(60px);transform:scale(.475) translateY(60px);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}}.layer-anim-01{-webkit-animation-name:layer-zoomInDown;animation-name:layer-zoomInDown}@-webkit-keyframes layer-fadeInUpBig{0%{opacity:0;-webkit-transform:translateY(2000px);transform:translateY(2000px)}100%{opacity:1;-webkit-transform:translateY(0);transform:translateY(0)}}@keyframes layer-fadeInUpBig{0%{opacity:0;-webkit-transform:translateY(2000px);-ms-transform:translateY(2000px);transform:translateY(2000px)}100%{opacity:1;-webkit-transform:translateY(0);-ms-transform:translateY(0);transform:translateY(0)}}.layer-anim-02{-webkit-animation-name:layer-fadeInUpBig;animation-name:layer-fadeInUpBig}@-webkit-keyframes layer-zoomInLeft{0%{opacity:0;-webkit-transform:scale(.1) translateX(-2000px);transform:scale(.1) translateX(-2000px);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}60%{opacity:1;-webkit-transform:scale(.475) translateX(48px);transform:scale(.475) translateX(48px);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}}@keyframes layer-zoomInLeft{0%{opacity:0;-webkit-transform:scale(.1) translateX(-2000px);-ms-transform:scale(.1) translateX(-2000px);transform:scale(.1) translateX(-2000px);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}60%{opacity:1;-webkit-transform:scale(.475) translateX(48px);-ms-transform:scale(.475) translateX(48px);transform:scale(.475) translateX(48px);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}}.layer-anim-03{-webkit-animation-name:layer-zoomInLeft;animation-name:layer-zoomInLeft}@-webkit-keyframes layer-rollIn{0%{opacity:0;-webkit-transform:translateX(-100%) rotate(-120deg);transform:translateX(-100%) rotate(-120deg)}100%{opacity:1;-webkit-transform:translateX(0) rotate(0);transform:translateX(0) rotate(0)}}@keyframes layer-rollIn{0%{opacity:0;-webkit-transform:translateX(-100%) rotate(-120deg);-ms-transform:translateX(-100%) rotate(-120deg);transform:translateX(-100%) rotate(-120deg)}100%{opacity:1;-webkit-transform:translateX(0) rotate(0);-ms-transform:translateX(0) rotate(0);transform:translateX(0) rotate(0)}}.layer-anim-04{-webkit-animation-name:layer-rollIn;animation-name:layer-rollIn}@keyframes layer-fadeIn{0%{opacity:0}100%{opacity:1}}.layer-anim-05{-webkit-animation-name:layer-fadeIn;animation-name:layer-fadeIn}@-webkit-keyframes layer-shake{0%,100%{-webkit-transform:translateX(0);transform:translateX(0)}10%,30%,50%,70%,90%{-webkit-transform:translateX(-10px);transform:translateX(-10px)}20%,40%,60%,80%{-webkit-transform:translateX(10px);transform:translateX(10px)}}@keyframes layer-shake{0%,100%{-webkit-transform:translateX(0);-ms-transform:translateX(0);transform:translateX(0)}10%,30%,50%,70%,90%{-webkit-transform:translateX(-10px);-ms-transform:translateX(-10px);transform:translateX(-10px)}20%,40%,60%,80%{-webkit-transform:translateX(10px);-ms-transform:translateX(10px);transform:translateX(10px)}}.layer-anim-06{-webkit-animation-name:layer-shake;animation-name:layer-shake}@-webkit-keyframes fadeIn{0%{opacity:0}100%{opacity:1}}.layui-layer-title{padding:0 80px 0 20px;height:42px;line-height:42px;border-bottom:1px solid #eee;font-size:14px;color:#333;overflow:hidden;background-color:#F8F8F8;border-radius:2px 2px 0 0}.layui-layer-setwin{position:absolute;right:15px;*right:0;top:15px;font-size:0;line-height:initial}.layui-layer-setwin a{position:relative;width:16px;height:16px;margin-left:10px;font-size:12px;_overflow:hidden}.layui-layer-setwin .layui-layer-min cite{position:absolute;width:14px;height:2px;left:0;top:50%;margin-top:-1px;background-color:#2E2D3C;cursor:pointer;_overflow:hidden}.layui-layer-setwin .layui-layer-min:hover cite{background-color:#2D93CA}.layui-layer-setwin .layui-layer-max{background-position:-32px -40px}.layui-layer-setwin .layui-layer-max:hover{background-position:-16px -40px}.layui-layer-setwin .layui-layer-maxmin{background-position:-65px -40px}.layui-layer-setwin .layui-layer-maxmin:hover{background-position:-49px -40px}.layui-layer-setwin .layui-layer-close1{background-position:1px -40px;cursor:pointer}.layui-layer-setwin .layui-layer-close1:hover{opacity:.7}.layui-layer-setwin .layui-layer-close2{position:absolute;right:-28px;top:-28px;width:30px;height:30px;margin-left:0;background-position:-149px -31px;*right:-18px;_display:none}.layui-layer-setwin .layui-layer-close2:hover{background-position:-180px -31px}.layui-layer-btn{text-align:right;padding:0 15px 12px;pointer-events:auto;user-select:none;-webkit-user-select:none}.layui-layer-btn a{height:28px;line-height:28px;margin:5px 5px 0;padding:0 15px;border:1px solid #dedede;background-color:#fff;color:#333;border-radius:2px;font-weight:400;cursor:pointer;text-decoration:none}.layui-layer-btn a:hover{opacity:.9;text-decoration:none}.layui-layer-btn a:active{opacity:.8}.layui-layer-btn .layui-layer-btn0{border-color:#1E9FFF;background-color:#1E9FFF;color:#fff}.layui-layer-btn-l{text-align:left}.layui-layer-btn-c{text-align:center}.layui-layer-dialog{min-width:260px}.layui-layer-dialog .layui-layer-content{position:relative;padding:20px;line-height:24px;word-break:break-all;overflow:hidden;font-size:14px;overflow-x:hidden;overflow-y:auto}.layui-layer-dialog .layui-layer-content .layui-layer-ico{position:absolute;top:16px;left:15px;_left:-40px;width:30px;height:30px}.layui-layer-ico1{background-position:-30px 0}.layui-layer-ico2{background-position:-60px 0}.layui-layer-ico3{background-position:-90px 0}.layui-layer-ico4{background-position:-120px 0}.layui-layer-ico5{background-position:-150px 0}.layui-layer-ico6{background-position:-180px 0}.layui-layer-rim{border:6px solid #8D8D8D;border:6px solid rgba(0,0,0,.3);border-radius:5px;box-shadow:none}.layui-layer-msg{min-width:180px;border:1px solid #D3D4D3;box-shadow:none}.layui-layer-hui{min-width:100px;background-color:#000;filter:alpha(opacity=60);background-color:rgba(0,0,0,.6);color:#fff;border:none}.layui-layer-hui .layui-layer-content{padding:12px 25px;text-align:center}.layui-layer-dialog .layui-layer-padding{padding:20px 20px 20px 55px;text-align:left}.layui-layer-page .layui-layer-content{position:relative;overflow:auto}.layui-layer-iframe .layui-layer-btn,.layui-layer-page .layui-layer-btn{padding-top:10px}.layui-layer-nobg{background:0 0}.layui-layer-iframe iframe{display:block;width:100%}.layui-layer-loading{border-radius:100%;background:0 0;box-shadow:none;border:none}.layui-layer-loading .layui-layer-content{width:60px;height:24px;background:url(loading-0.gif) no-repeat}.layui-layer-loading .layui-layer-loading1{width:37px;height:37px;background:url(loading-1.gif) no-repeat}.layui-layer-ico16,.layui-layer-loading .layui-layer-loading2{width:32px;height:32px;background:url(loading-2.gif) no-repeat}.layui-layer-tips{background:0 0;box-shadow:none;border:none}.layui-layer-tips .layui-layer-content{position:relative;line-height:22px;min-width:12px;padding:8px 15px;font-size:12px;_float:left;border-radius:2px;box-shadow:1px 1px 3px rgba(0,0,0,.2);background-color:#000;color:#fff}.layui-layer-tips .layui-layer-close{right:-2px;top:-1px}.layui-layer-tips i.layui-layer-TipsG{position:absolute;width:0;height:0;border-width:8px;border-color:transparent;border-style:dashed;*overflow:hidden}.layui-layer-tips i.layui-layer-TipsB,.layui-layer-tips i.layui-layer-TipsT{left:5px;border-right-style:solid;border-right-color:#000}.layui-layer-tips i.layui-layer-TipsT{bottom:-8px}.layui-layer-tips i.layui-layer-TipsB{top:-8px}.layui-layer-tips i.layui-layer-TipsL,.layui-layer-tips i.layui-layer-TipsR{top:5px;border-bottom-style:solid;border-bottom-color:#000}.layui-layer-tips i.layui-layer-TipsR{left:-8px}.layui-layer-tips i.layui-layer-TipsL{right:-8px}.layui-layer-lan[type=dialog]{min-width:280px}.layui-layer-lan .layui-layer-title{background:#4476A7;color:#fff;border:none}.layui-layer-lan .layui-layer-btn{padding:5px 10px 10px;text-align:right;border-top:1px solid #E9E7E7}.layui-layer-lan .layui-layer-btn a{background:#fff;border-color:#E9E7E7;color:#333}.layui-layer-lan .layui-layer-btn .layui-layer-btn1{background:#C9C5C5}.layui-layer-molv .layui-layer-title{background:#009f95;color:#fff;border:none}.layui-layer-molv .layui-layer-btn a{background:#009f95;border-color:#009f95}.layui-layer-molv .layui-layer-btn .layui-layer-btn1{background:#92B8B1}.layui-layer-iconext{background:url(icon-ext.png) no-repeat}.layui-layer-prompt .layui-layer-input{display:block;width:230px;height:36px;margin:0 auto;line-height:30px;padding-left:10px;border:1px solid #e6e6e6;color:#333}.layui-layer-prompt textarea.layui-layer-input{width:300px;height:100px;line-height:20px;padding:6px 10px}.layui-layer-prompt .layui-layer-content{padding:20px}.layui-layer-prompt .layui-layer-btn{padding-top:0}.layui-layer-tab{box-shadow:1px 1px 50px rgba(0,0,0,.4)}.layui-layer-tab .layui-layer-title{padding-left:0;overflow:visible}.layui-layer-tab .layui-layer-title span{position:relative;float:left;min-width:80px;max-width:260px;padding:0 20px;text-align:center;overflow:hidden;cursor:pointer}.layui-layer-tab .layui-layer-title span.layui-this{height:43px;border-left:1px solid #eee;border-right:1px solid #eee;background-color:#fff;z-index:10}.layui-layer-tab .layui-layer-title span:first-child{border-left:none}.layui-layer-tabmain{line-height:24px;clear:both}.layui-layer-tabmain .layui-layer-tabli{display:none}.layui-layer-tabmain .layui-layer-tabli.layui-this{display:block}.layui-layer-photos{-webkit-animation-duration:.8s;animation-duration:.8s}.layui-layer-photos .layui-layer-content{overflow:hidden;text-align:center}.layui-layer-photos .layui-layer-phimg img{position:relative;width:100%;display:inline-block;*display:inline;*zoom:1;vertical-align:top}.layui-layer-imgbar,.layui-layer-imguide{display:none}.layui-layer-imgnext,.layui-layer-imgprev{position:absolute;top:50%;width:27px;_width:44px;height:44px;margin-top:-22px;outline:0;blr:expression(this.onFocus=this.blur())}.layui-layer-imgprev{left:10px;background-position:-5px -5px;_background-position:-70px -5px}.layui-layer-imgprev:hover{background-position:-33px -5px;_background-position:-120px -5px}.layui-layer-imgnext{right:10px;_right:8px;background-position:-5px -50px;_background-position:-70px -50px}.layui-layer-imgnext:hover{background-position:-33px -50px;_background-position:-120px -50px}.layui-layer-imgbar{position:absolute;left:0;bottom:0;width:100%;height:32px;line-height:32px;background-color:rgba(0,0,0,.8);background-color:#000\9;filter:Alpha(opacity=80);color:#fff;overflow:hidden;font-size:0}.layui-layer-imgtit *{display:inline-block;*display:inline;*zoom:1;vertical-align:top;font-size:12px}.layui-layer-imgtit a{max-width:65%;overflow:hidden;color:#fff}.layui-layer-imgtit a:hover{color:#fff;text-decoration:underline}.layui-layer-imgtit em{padding-left:10px;font-style:normal}@-webkit-keyframes layer-bounceOut{100%{opacity:0;-webkit-transform:scale(.7);transform:scale(.7)}30%{-webkit-transform:scale(1.05);transform:scale(1.05)}0%{-webkit-transform:scale(1);transform:scale(1)}}@keyframes layer-bounceOut{100%{opacity:0;-webkit-transform:scale(.7);-ms-transform:scale(.7);transform:scale(.7)}30%{-webkit-transform:scale(1.05);-ms-transform:scale(1.05);transform:scale(1.05)}0%{-webkit-transform:scale(1);-ms-transform:scale(1);transform:scale(1)}}.layer-anim-close{-webkit-animation-name:layer-bounceOut;animation-name:layer-bounceOut;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:.2s;animation-duration:.2s}@media screen and (max-width:1100px){.layui-layer-iframe{overflow-y:auto;-webkit-overflow-scrolling:touch}} ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/ext/eleTree/eleTree.css ================================================ /* #region tree */ .eleTree{ position: relative; } .eleTree-hide{ display: none; } .eleTree-loadData{ width: 100%; height: 100%; position: absolute; z-index: 1; top: 0px; } .eleTree-loadData .layui-icon{ position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); } .eleTree-node-content{ cursor: pointer; height: 26px; line-height: 1.3; white-space: nowrap; } .eleTree-node-content:hover, .eleTree-node-content.eleTree-node-content-active{ background-color: #eee; } .eleTree-node-content-icon .layui-icon{ padding: 6px 3px; color: #c0c4cc; font-size: 12px; display: inline-block; transform: rotate(0deg); transition: transform .3s ease-in-out; } .eleTree-node-content-icon .layui-icon.icon-rotate{ transform: rotate(90deg); } .eleTree-node-content .layui-form-checkbox[lay-skin=primary] i{ width: 13px; height: 14px; line-height: 1.3; } .eleTree-node-content-label{ padding-left: 5px; } .eleTree-node-content-input{ width: 80px; border: 1px solid #e6e6e6; outline: 0; padding: 3px 5px; font-size: 12px; } /* checkbox第三种状态 */ input.eleTree-hideen[type=checkbox]{ display: none; } .eleTree-checkbox { height: auto!important; line-height: normal!important; min-height: 12px; border: none!important; margin-right: 0; padding-left: 18px; position: relative; display: inline-block; } .eleTree-checkbox i { left: 0; border: 1px solid #d2d2d2; font-size: 12px; border-radius: 2px; background-color: #fff; -webkit-transition: .1s linear; transition: .1s linear; position: absolute; top: 0; color: #fff; cursor: pointer; text-align: center; width: 13px; height: 14px; line-height: 1.3; } .eleTree-checkbox i:hover { border-color: #5FB878; } .eleTree-checkbox-checked i { border-color: #5FB878; background-color: #5FB878; color: #fff; } .eleTree-checkbox-line:after{ content: ""; position: relative; width: 8px; height: 1px; background-color: #fff; display: inline-block; top: -4px; } .eleTree-checkbox.eleTree-checkbox-disabled i{ cursor: not-allowed; background-color: #f2f6fc; border-color: #dcdfe6; color: #c2c2c2; } .eleTree-checkbox.eleTree-checkbox-disabled i.eleTree-checkbox-line:after{ background-color: #c2c2c2; } .eleTree-checkbox.eleTree-checkbox-disabled i:hover{ border-color: #dcdfe6; } #tree-menu{ margin: 0; padding: 2px; position: absolute; background: #f5f5f5; border: 1px solid #979797; box-shadow: 2px 2px 2px #999; display: none; z-index: 20181205; } #tree-menu li>a{ display: block; padding: 0 1em; text-decoration: none; width: auto; color: #000; white-space: nowrap; line-height: 2.4em; text-shadow: 1px 1px 0 #fff; border-radius: 1px; } #tree-menu li>a:hover{ background-color: #e8eff7; box-shadow: 0 0 2px #0a6aa1; } .tree-menu-bg{ background-color: #ccc; } /* #endregion */ ================================================ FILE: spider-flow-web/src/main/resources/static/js/layui/ext/eleTree/eleTree.js ================================================ /** * 基于layui的tree重写 * author: hsianglee * 最近修改时间: 2019/01/07 */ layui.define(["jquery","laytpl"], function (exports) { var $ = layui.jquery; var laytpl = layui.laytpl; var hint = layui.hint(); var MOD_NAME="eleTree"; //外部接口 var eleTree={ //事件监听 on: function(events, callback){ return layui.onevent.call(this, MOD_NAME, events, callback); }, render: function(options) { var inst = new Class(options); return thisTree.call(inst); } } var thisTree=function() { var _self=this; var options = _self.config; // 暴漏外面的方法 return { // 接收两个参数,1. 节点 key 2. 节点数据的数组 updateKeyChildren: function(key,data) { if(options.data.length===0) return; return _self.updateKeyChildren.call(_self,key,data); }, updateKeySelf: function(key,data) { if(options.data.length===0) return; return _self.updateKeySelf.call(_self,key,data); }, remove: function(key) { if(options.data.length===0) return; return _self.remove.call(_self,key); }, append: function(key,data) { if(options.data.length===0) return; return _self.append.call(_self,key,data); }, insertBefore: function(key,data) { if(options.data.length===0) return; return _self.insertBefore.call(_self,key,data); }, insertAfter: function(key,data) { if(options.data.length===0) return; return _self.insertAfter.call(_self,key,data); }, // 接收两个 boolean 类型的参数,1. 是否只是叶子节点,默认值为 false 2. 是否包含半选节点,默认值为 false getChecked: function(leafOnly, includeHalfChecked) { if(options.data.length===0) return; return _self.getChecked.call(_self,leafOnly, includeHalfChecked); }, // 接收勾选节点数据的数组 setChecked: function(data) { if(options.data.length===0) return; return _self.setChecked.call(_self,data); }, // 取消选中 unCheckNodes: function() { if(options.data.length===0) return; return _self.unCheckNodes.call(_self); }, expandAll: function() { options.elem.children(".eleTree-node").children(".eleTree-node-group").empty(); _self.expandAll.call(_self,options.data,[],1,true); _self.unCheckNodes(); _self.defaultChecked(); }, unExpandAll: function() { return _self.unExpandAll.call(_self); }, reload: function(options) { return _self.reload.call(_self,options); }, search: function(value) { return _self.search.call(_self,value); } } } // 模板渲染 var TPL_ELEM=function(options,floor,parentStatus) { return [ '{{# for(var i=0;i