diff --git a/.gitignore b/.gitignore index b4ad56f5..665a9e77 100644 --- a/.gitignore +++ b/.gitignore @@ -10,12 +10,6 @@ min #node modules folder node_modules -#moving out minify from cloudcmd submodules -#minify module -#!node_modules/ -#node_modules/* -#!node_modules/minify - #temporary files folder tmp @@ -28,5 +22,5 @@ apache-status #log file log.txt -#hashes file -hashes.json \ No newline at end of file +#cloudfoundry file +manifest.yml \ No newline at end of file diff --git a/ChangeLog b/ChangeLog index 605c4426..cf2cbab1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,197 @@ +2012.03.01, Version 0.1.9 + +* Changed the way of getting github application id +(now it's just from config, rest api removed). + +* Added ability to upload files to GDrive. + +* Added functions DOM.getCurrentFileContent(pCallBack [, pCurrentFile]) +and Util.setTimeout(pFunction [, pCallBack, pTime]) + +* Added functions in win.js for parsing diskpart output. + +* Added function getCurrentDir to DOM module. + +* Fixed bug with terminal load. + +* From now api url on client readed from config.json. + +* If choosen upload to -> Gist, and file in json have +not '.json' extension, it's added to the and of filename. + +* Fixed bug in not fully functional browsers, +jquery loaded after ie.js, should be before. + +* Fixed bug with closing terminal and opening viewer: +inside event function varible called event do not exist +(everithing ok on webkit). + +* Added ability to upload files to dropbox. + +* Added ability to authorize on github thru new window, +changed redirecting url to /auth and added rout function +to cloudcmd.js + +* DropBox, GDrive and GitHub modules now look the same. + +* Fixed bug with pressing Esc when menu showed. +We could not to now, when key was pressed becaouse of +stopPropogation function in jquery.contextMenu module. +Commented stopPropogration. +``` +keyStop: function(e, opt) { + if (!opt.isInput) { + e.preventDefault(); + } + + //e.stopPropagation(); +} +``` +* Updated socket.io to v0.9.13. + +* Updated jquery-terminal to v0.4.22. + +* Refactore viewer module. + +* Removed loading spinner by commenting jquery.fancybox.css block +#fancybox-loading div { + width: 44px; + height: 44px; + background: url('fancybox_loading.gif') center center no-repeat; +} + +* Updated CodeMirror to v2.37.01. + +* Updated jquery to v.1.8.3. + +* Improved optimizing size of menu.js from 2539 to 2444. + +* Fixed bug with height of terminal. + +* Added ability to read gdrive key from config. + +* Fixed bug with setting curent cursor when +clicked on menu item. + +* Updated dropbox library to v.0.8.1. + +* Added ability to authorize on dropbox thru popup. + +* Added ability to authorize in vk.com. + +* Added vk to menu. + +* Updated funcyBox to v2.1.4. + +* Updated jquery to v1.9.0. + +* Improved modules.json format and parsing. + +* Added ability to read storage modules information from menu module. + +* Added easy template renderrer system Util.render. + +* Added functions DOM.parseJSON and DOM.stringifyJSON + +* Improved modules.json. + +* Added migrate plugin for jquery. + +* Removed getting data from Minify cache. + +* Moved jsons to json folder. + +* Fixed bug with working links in path panel and +with clicks on files. + +* Changed icons font from octicons to foundicons + +* Changed icons font from foundicons to fonteollo + +* Removed Octicons font. + +* Removed allowed from cache property in config. + +* Added ability to hide "Upload To" menu item if +no storage modules setted up in modules.json. + +* From now any file minifying only if last modified +time was changed. + +* Removed ability to cache files in memory. + +* Moved extensions from main.js to json/ext.json. + +* Commander functions moved out to commander.js from server.js + +* Fixed bug with old browsers support. + +* Fixed bug with scrolling in opera and firefox. + +* Fixed bug with (fake) deleting file. + +* Added ability show context menu on right click +while menu is showing now. + +* Added ability to remove /fs/no-js when go up to root +directory. + +* Removed reflows maded by js. + +* Fixed bug with setting current file +after refresh and refreshing dir content. + +* Removed part of url thet says that js is disabled, from +now json data of file structure would be getted from +click event with ?json flag. "no-js" part of url +would not be supported anymore. + +* Added ability to add ?json flag only if we work with dir. + +* Added ability not to change url if we have no rights +for reading. + +* Fixed bug with pressing enter on file. + +* Updated jquery jQuery-contextMenu to v1.6.5. + +* Fixed bug with getting showed menu in firefox. + +* Added temporary redirection for old no-js urls. + +* Changed the way clickProcessing of menu works, +for now it's much simplier. + +* Fixed dblclick selection in firefox. + +* Fixed the first show of menu in firefox. + +* Added ability to change configs without restart +(works for js minification only). + +* Added ability to disable browser cache from config.json. + +* Totaly refactored and leave in commander.js just +generation of json of directory listing. + +* Added ability to upload files. + +* Added ability save files on Ctrl+S in CodeMirror. + +* Added ability to delete files. + +* Added rename menu item. + +* Added to html templating. + +* Added ability to rename files. + +* Added RESTfull object to DOM for easy work with +CloudCmd REST API. + +* Added help screen (on F1 after viewer loads). + + 2012.12.12, Version 0.1.8 * Added ability to shutdown Cloud Commander diff --git a/ChangeLog.rus.md b/ChangeLog.rus.md new file mode 100644 index 00000000..8541d4f5 --- /dev/null +++ b/ChangeLog.rus.md @@ -0,0 +1,94 @@ +**2012.03.01** + +Сегодня, в первый день весны, вышла новая версия облачного менеджера файлов: 0.1.9. +В связи с этим, есть двойной повод порадоватся: наконец, пришла весна, +с полной готовностью согревать серца жителей, после зимних холодов, +а так же новая порция положительных изминений и исправленных ошибок в +Облачном Командире. + +Теперь Cloud Commander гораздо стабильнее, +продуманее, внего гораздо проще вносить изминения и добавлять новые функции. +Скоро будет много всего интересного. + +С прошлой версии произошло очень много перемен и для пользователей и +для программистов, некоторые части были полностью переписаны, и теперь программа +более стабильна, а исходный код более простой и логичный. +К примеру раньше был один баг, из-за которого при нескольких одновременных +соединениях людям могли не приходить запрошенные файлы. Сейчас подобные просчёты +позади. Рассмотрим подробнее, чем нас порадует новая версия Cloud Commaner’а. + +**Добавленна внешняя возможность:** +- загрузки файлов на Google Drive и DropBox; +- пункт VK в меню; +- прятать пункт меню Upload To, если ниодного storage модуля не задано в modules.json. +- показывать контекстное меню, правкой кнопкой мыши, даже если оно уже открыто +- не менять путь, если у нас нет прав на чтение папки. +- времнный редирект для старых no-js урлов. +- отключения кеширования файлов браузером в config.json +- загрузка файлов; +- сохранение файлов по + в CodeMirror; +- удаление файлов; +- пункт меню и возможность переименовать; +- экран помощи (, когда Viewer загружен); + +**Убрана внешняя возможность:** +- Удалена часть URL, которая говорит о том, что JavaScript отключен. Теперь json-данные о структуре файлов будут получатся в собитии click с флагом ?json. Часть URL /no-js больше не будет поддерживатся; + +**Исправленные ошибки:** +- загрузка терминала; +- в браузерах, которые поддерживают не все функции: jquery загружался после ie.js, должен загружатся — до; +- закрытием терминала и откритием Вьюера, внутри функции, которая возникает во-время возникновения события переменной event не существует (всё хорошо работало на вебките); +- высотой терминала; +- установка текущего курсора, когда выбрали пункт меню; +- ссылки в панели пути и с кликами на файлы.; +- поддержка старых браузеров; +- скроллинг в опере и Фаерфоксе; +- (ненастоящее) удаление файлов; +- установка текущего файла после обновления содержимого директории; +- нажатие на файле; +- первый и последующие показы меню, а так же выделение даблкликом в Firefox + +**Обновлены:** +- jquery до версии v1.9.0 +- jquery-terminal до версии v0.4.22. +- jQuery-contextMenu до версии v1.6.5. +- socket.io до версии 0.9.13. +- CodeMirror до версии 2.37.01. +- dropbox до версии v.0.8.1. +- funcyBox до версии v2.1.4. + +**Внутренние изминения:** +- Изменен способ получения github id (теперь это делается через config.json, rest api были удалены). +- Добавлены функции DOM.getCurrentFileContent(pCallBack [, pCurrentFile]) для получения содержимого файла в ФС, а так же обёртка Util.setTimeout(pFunction [, pCallBack, pTime]). +- Добавлена функция в win.js для парсинга вывода команды diskpart (которая используется для опредиления локальных дисков). +- Добавлена функция DOM.getCurrentDir() +- API url на клиенте читается с файла config.json +- Если выбрана загрузка на Gist (GitHub) и у файла в формате json нет расширения — оно добавляется +- Добавлена возможность авторизовыватся на Гитхабе через новое окно. Изминен редирект на /auth и добавлена фнукция rout в cloudcmd.js +- DropBox, GDrive и GitHub модули теперь выглядят одинаково +- Рефакторинг в модуле Viewer +- Улучшена оптимизация файла menu.js с 2539 до 2444 байт +- Добавлена возможность читать GDrive key из конфига +- Добавлена возможность авторизовыватся на дропбоксе через popup +- Добавлена возможность авторизовыватся на vk.com. +- Улучшен формат и парсинг файла modules.json +- Добавлена возможность читать информацию о модулях сохранения из модуля меню +- Добавлена простая система рендеринга шаблонов Util.render +- Добавлены функции DOM.parseJSON и DOM.stringifyJSON, как обёртки над системными функциями +- Добавлен плагин для миграции к новой версии jquery +- Убрано получения данных из кеша Minify +- JSON-файлы перемещены в папки json +- Изминен шрифт с Octicons на Fonteollo +- Полностью удален шрифт Octicons. +- Удалено свойство allowed из свойства cache в конфиге. +- С этого момента оптимизироватся будут лишь те файлы, дата последнего изминения которых была изменена +- Убрана возможность кешировать файлы в памяти +- Перемещены расширения из main.js в json/ext.json +- Основная функциональность CloudCmd перемещена в commander.js из server.js +- Добавлена возможность удалять приставку к URL /fs когда мы в корневом каталоге +- Убраны перересовки создаваемые js +- Добавлена возможность добавлять флаг ?json только если мы работаем с папкой +- Изминен принцип работы функции clickProcessing в меню, теперь он гораздо проще +- Произведен тотальный рефакторинг в файле commander.js, теперь там только генерация +структуры каталогов в формате json +- добавлен обьект RESTfull в DOM модуль для упрощения работы с CloudCmd REST API. diff --git a/README.md b/README.md index e2325caa..9a73f3a6 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ Cloud Commander [![Build Status](https://secure.travis-ci.org/coderaiser/cloudcmd.png?branch=master)](http://travis-ci.org/coderaiser/cloudcmd) -=============== +=============== **Cloud Commander** - user friendly cloud file manager. DEMO: [cloudfoundry] (http://cloudcmd.cloudfoundry.com "cloudfoundry"), [appfog] (http://cloudcmd.aws.af.cm "appfog"). -Google PageSpeed Score : [100](https://developers.google.com/speed/pagespeed/insights#url=http_3A_2F_2Fcloudcmd.cloudfoundry.com_2F&mobile=false "score") (out of 100) +Google PageSpeed Score : [100](http://developers.google.com/speed/pagespeed/insights#url=http_3A_2F_2Fcloudcmd.cloudfoundry.com_2F&mobile=false "score") (out of 100) (or 96 if js or css minification disabled in config.json). -![Cloud Commander](https://raw.github.com/coderaiser/cloudcmd/dev/img/logo/cloudcmd.png) +![Cloud Commander](img/logo/cloudcmd.png "Cloud Commander") Benefits --------------- @@ -41,19 +41,38 @@ There is a short list: - **Alt + q** - disable key bindings - **Alt + s** - get all key bindings back - **up, down, enter** - filesystem navigation -- **Alt + g** - authorization +- **Tab** - move thru panels +- **Page Up** - up on one page +- **Page Down** - down on one page +- **Home** - to begin of list +- **End** - to end of list +- **Shift + F10** - show context menu +- **F2** - rename current file +- **Alt + g** - authorization in GitHub Viewer's hot keys --------------- -- **Shift + F3** - open viewer window +- **Shift + F3** - open viewer window - **Esc** - close viewer window Editor's hot keys --------------- - **F3** - open CodeMirror editor in read only mode - **F4** - open CodeMirror editor +- **Ctrl + s** - save file - **Esc** - close CodeMirror editor +Menu +--------------- +Right mouse click button show context menu with items: +- View +- Edit +- Rename +- Delete +- Upload to (Dropbox, Github, GDrive) +- Downloud + + Documentation --------------- JS Doc documentation could be found in [http://jsdoc.info/coderaiser/cloudcmd/](http://jsdoc.info/coderaiser/cloudcmd/) @@ -76,19 +95,15 @@ All main configuration could be done thrue config.json. ```js { "api_url" :"/api/v1", - "appcache" : false, /* html5 feature appcache */ - "cache" : {"allowed" : true}, /* cashing of js and css files in memory */ + "appcache" : false, /* html5 feature appcache */ + "cache" : true, /* cashing on a client */ "minification" : { /* minification of js,css,html and img */ "js" : false, /* minify module neaded */ "css" : false, /* npm i minify */ "html" : true, "img" : false }, - "github_key" : "891c251b925e4e967fa9", - "github_secret" : "afe9bed1e810c5dc44c4c2a953fc6efb1e5b0545", - "dropbox_key" : "0nd3ssnp5fp7tqs", - "dropbox_chooser_key" : "o7d6llji052vijk" - "show_keys_panel" : true, /* show classic panel with buttons of keys */ + "show_keys_panel" : true, /* show classic panel with buttons of keys */ "server" : true, /* server mode or testing mode */ "logs" : false, /* logs or console ouput */ "socket" : true /* enable web sockets */ @@ -169,11 +184,15 @@ For extend main functionality Cloud Commander use next modules: - [FancyBox] [FancyBoxURL] - [jQuery-contextMenu] [jQuery-contextMenuURL] - [jquery.terminal] [jquery.terminalURL] +- [github] [githubURL] +- [dropbox-js] [dropbox-jsURL] -[CodeMirrorURL]: https://github.com/marijnh/CodeMirror "CodeMirror" -[FancyBoxURL]: https://github.com/fancyapps/fancyBox "FancyBox" -[jQuery-contextMenuURL]: https://github.com/medialize/jQuery-contextMenu "jQuery-contextMenu" -[jquery.terminalURL]: https://github.com/jcubic/jquery.terminal "jquery.terminal" +[CodeMirrorURL]: //github.com/marijnh/CodeMirror "CodeMirror" +[FancyBoxURL]: //github.com/fancyapps/fancyBox "FancyBox" +[jQuery-contextMenuURL]: //github.com/medialize/jQuery-contextMenu "jQuery-contextMenu" +[jquery.terminalURL]: //github.com/jcubic/jquery.terminal "jquery.terminal" +[githubURL]: //github.com/michael/github +[dropbox-jsURL]: //github.com/dropbox/dropbox-js Contributing --------------- diff --git a/cloudcmd.js b/cloudcmd.js index 596e188a..37ce4d7d 100644 --- a/cloudcmd.js +++ b/cloudcmd.js @@ -1,147 +1,318 @@ -(function(){ - "use strict"; - - var DIR = __dirname + '/', - main = require(DIR + 'lib/server/main'), - - LIBDIR = main.LIBDIR, - SRVDIR = main.SRVDIR, - - path = main.path, - fs = main.fs, - CloudFunc = main.cloudfunc, - Util = main.util, - update = main.update, - - Server = main.require(LIBDIR + 'server'), - srv = Server.CloudServer, - Config = main.config; - - /* reinit main dir os if we on - * Win32 should be backslashes */ - DIR = main.DIR; - - readConfig(); - Server.start(Config, { - index : indexProcessing, - appcache : appCacheProcessing, - rest : rest - }); - - if(update) - update.get(); - - /** - * additional processing of index file - */ - function indexProcessing(pData){ - var lReplace_s, - lData = pData.data, - lAdditional = pData.additional; - - /* - * если выбрана опция минимизировать скрипты - * меняем в index.html обычные css на - * минифицированый - */ - if(srv.Minify._allowed.css){ - var lPath = '/' + srv.Minify.MinFolder.replace(DIR, ''); - - lReplace_s = ''; - - lData = Util.removeStr(lData, lReplace_s) - .replace('/css/style.css', lPath + 'all.min.css'); - } - - lReplace_s = '
'; - - /* меняем title */ - lData = lData.replace(lReplace_s, lReplace_s + lAdditional) - .replace('Cloud Commander', - '' + CloudFunc.getTitle() + ''); - - if(!srv.Config.appcache) - lData = Util.removeStr(lData, ' manifest="/cloudcmd.appcache"'); - - if(!srv.Config.show_keys_panel){ - var lKeysPanel = '
' + p.name); + pParams.name = main.HTMLDIR + p.name + '.html'; + lRet = main.sendFile( pParams ); + } + else if( Util.isContainStr(p.name, FS) || Util.strCmp( p.name, '/') ){ + if( Util.isContainStr(p.name, 'no-js/') ) + return noJSTMPRedirection(pParams); + + lRet = sendCommanderContent(p); + } + /* termporary redirect for old urls */ + else + lRet = false; + } + + return lRet; + } + + function sendCommanderContent(pParams){ + var lRet = main.checkParams(pParams); + if(lRet){ + var p = pParams; + p.name = Util.removeStr(p.name, CloudFunc.FS) || main.SLASH; + + fs.stat(p.name, function(pError, pStat){ + if(!pError) + if( pStat.isDirectory() ) + processCommanderContent(pParams); + else + main.sendFile(p); + else + main.sendError(pParams, pError); + + }); + } + + return lRet; + } + + function processCommanderContent(pParams){ + var lRet = main.checkParams(pParams); + if(lRet){ + var p = pParams; + main.commander.getDirContent(p.name, function(pError, pJSON){ + if(!pError){ + var lQuery = main.getQuery(p.request); + if( Util.isContainStr(lQuery, 'json') ){ + p.data = Util.stringifyJSON(pJSON); + p.name +='.json'; + main.sendResponse(p); + } + else if(!lQuery){ /* get back html*/ + p.name = Minify.allowed.html ? Minify.getName(INDEX) : INDEX; + fs.readFile(p.name, function(pError, pData){ + if(!pError){ + var lPanel = CloudFunc.buildFromJSON(pJSON), + lList = '
    ' + lPanel + '
' + + ''; + + main.sendResponse(p, indexProcessing({ + additional : lList, + data : pData.toString(), + })); + } + else + main.sendError(pParams, pError); + }); + } + } + else + main.sendError(pParams, pError); + }); + } + } + + function noJSTMPRedirection(pParams){ + var MOVED_PERMANENTLY = 301, + lPath = Util.removeStr(pParams.name, 'no-js/'); + + pParams.response.writeHead(MOVED_PERMANENTLY, {'Location': lPath}); + pParams.response.end(); + + return true; + } + + + /* function sets stdout to file log.txt */ + function writeLogsToFile(){ + var stdo = fs.createWriteStream('./log.txt'); + + process.stdout.write = (function(write) { + return function(string, encoding, fd) { + stdo.write(string); + }; + })(process.stdout.write); + } })(); \ No newline at end of file diff --git a/css/reset.css b/css/reset.css index 199fee29..cd411656 100644 --- a/css/reset.css +++ b/css/reset.css @@ -25,9 +25,9 @@ body { margin: 0; font-size: 1em; line-height: 1.4; } ::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; } ::selection { background: #fe57a1; color: #fff; text-shadow: none; } */ +::-moz-selection{ text-shadow: none; opacity: 0;} ::selection { text-shadow: none; opacity: 0;} - /* ============================================================================= Links ========================================================================== */ diff --git a/css/style.css b/css/style.css index d930bd50..ec1a380d 100644 --- a/css/style.css +++ b/css/style.css @@ -2,30 +2,21 @@ @import url(//fonts.googleapis.com/css?family=Droid+Sans+Mono); */ -/* Foundation Icons General Enclosed */ -/* -@font-face { - font-family: 'FoundationIconsGeneralEnclosed'; - src: url('//dl.dropbox.com/u/78163899/mnemonia/fonts/foundation-icons-general-enclosed.woff') format('woff'); - font-weight: normal; - font-style: normal; - -} -*/ /* символьный шрифт от гитхаба*/ - @font-face { - font-family: 'Fontello'; - font-style: normal; + font-family: "GeneralFoundicons"; + src: url('/font/general_foundicons.woff') format('woff'); font-weight: normal; - src: url('/font/fontello.woff') format('woff'); + font-style: normal; } +/* http://fontello.com/ */ @font-face { - font-family: 'Octicons Regular'; - font-style: normal; + font-family: 'Fontello'; + src: url("/font/fontello.eot"); + src: url("/font/fontello.eot?#iefix") format('embedded-opentype'), url("/font/fontello.woff") format('woff'), url("/font/fontello.ttf") format('truetype'), url("/font/fontello.svg#cloudcmd") format('svg'); font-weight: normal; - src: local('Octicons Regular'), url('/font/Octicons.woff') format('woff'); + font-style: normal; } @font-face { @@ -40,11 +31,6 @@ body{ background-color:white; } -.menu{ - margin-bottom: 0; - font: 16px 'Octicons Regular'; -} - .path-icon{ position: relative; top: 3px; @@ -59,9 +45,6 @@ body{ text-shadow:black 0 2px 1px; } .path-icon:hover{ - /* - color:#45D827; - */ cursor:pointer; } .path-icon:active{ @@ -74,15 +57,15 @@ body{ width:16px; height:16px; margin-left:0.5%; - font-family: 'Octicons Regular'; - font-size:16px; + /* font-family: 'GeneralFoundicons'; */ + font-family: 'Fontello'; } .error::before{ position: relative; - bottom : 4px; - color:rgb(222, 41, 41); - cursor:default; - content:'\f026'; + font-size: 14px; + color: rgb(222, 41, 41); + cursor :default; + content: '\2757'; } .loading{ position:relative; @@ -111,13 +94,14 @@ body{ background-color: white; border: 1.5px solid rgba(49,123,249,.40); } + .cmd-button:hover{ border: 1.5px solid rgb(0,0,0); } .cmd-button:active{ color: white; - background-color: rgb(49,123,249); + background-color: rgb(49,123,249); } .clear-cache{ @@ -126,19 +110,13 @@ body{ background:url(/img/console_clear.png) -4px -4px no-repeat; } .clear-cache:active{ - /* - background-position-y: -25px; - */ - top:5px; -} - -.settings:before{ - content:'k'; -} + top:5px; +} + .links{ color:red; } - + .mini-icon { position: relative; top: 2px; @@ -158,7 +136,7 @@ body{ * установления курсора */ .current-file > .mini-icon{ - left: -6px; + left: -6px; } /* freeupex */ .directory{ @@ -177,7 +155,7 @@ body{ height: 90%; margin: 26px 26px 0 26px; } -.fm_header{ +.fm-header{ font-weight: bold; } #path{ @@ -233,8 +211,6 @@ body{ */ text-align: right; } -.owner{ -} .mode{ float: right; width: 25%; @@ -252,14 +228,12 @@ button{ width:10%; } a{ - text-decoration:none; + text-decoration:none; } a:hover, a:active { color: #06e; cursor:pointer; - outline: 0; } -a:focus { outline: thin dotted; } /* Если размер окна очень маленький * располагаем имя и атрибуты файла @@ -276,6 +250,7 @@ a:focus { outline: thin dotted; } } /* текущий файл под курсором */ .current-file{ + background-color: rgb(49, 123, 249); background-color: rgba(49, 123, 249, .40); color:white; } @@ -287,24 +262,29 @@ a:focus { outline: thin dotted; } color:white; } -/* меняем иконки на шрифтовые*/ + .fm-header{ + display:none; + } + + /* меняем иконки на шрифтовые*/ .mini-icon { - font: 60px 'Octicons Regular'; + color: rgb(246, 224, 124); + color: rgba(246, 224, 124, 0.56); + font: 60px 'Fontello'; width: 40%; height: 0; margin-left: 0; float: right; position: relative; - top: -17px; - - color: rgba(246, 224, 124, 0.56); + top: 10px } .directory::before{ - content: '\f216'; + content: '\1f4c1'; } .text-file::before{ + color: rgb(26, 224, 124); color: rgba(26, 224, 124, 0.56); - content: '\f211'; + content: '\1f4c4'; } .text-file{ background-image:none; @@ -353,7 +333,7 @@ a:focus { outline: thin dotted; } } } @media only screen and (min-width: 601px) and (max-width: 785px){ - .panel{ + .panel{ width:94% !important; } #right{ @@ -362,7 +342,7 @@ a:focus { outline: thin dotted; } } @media only screen and (min-width:786px) and (max-width: 1155px){ - .panel{ + .panel{ width:94% !important; } /* если правая панель не помещаеться - прячем её */ diff --git a/font/Octicons.woff b/font/Octicons.woff deleted file mode 100644 index 79989eba..00000000 Binary files a/font/Octicons.woff and /dev/null differ diff --git a/font/fontello.eot b/font/fontello.eot new file mode 100644 index 00000000..9ae403f0 Binary files /dev/null and b/font/fontello.eot differ diff --git a/font/fontello.svg b/font/fontello.svg new file mode 100644 index 00000000..0eb33d8e --- /dev/null +++ b/font/fontello.svg @@ -0,0 +1,40 @@ + + + + +Created by FontForge 20100429 at Thu Jan 24 11:50:44 2013 + By root +Copyright (C) 2012 by original authors @ fontello.com + + + + + + + + + + + + + diff --git a/font/fontello.ttf b/font/fontello.ttf new file mode 100644 index 00000000..2868965d Binary files /dev/null and b/font/fontello.ttf differ diff --git a/font/fontello.woff b/font/fontello.woff new file mode 100644 index 00000000..5cf2f300 Binary files /dev/null and b/font/fontello.woff differ diff --git a/font/general_foundicons.woff b/font/general_foundicons.woff new file mode 100644 index 00000000..daab6314 Binary files /dev/null and b/font/general_foundicons.woff differ diff --git a/html/auth.html b/html/auth.html new file mode 100644 index 00000000..b1bc2445 --- /dev/null +++ b/html/auth.html @@ -0,0 +1,18 @@ + + + + + + + \ No newline at end of file diff --git a/html/auth/dropbox.html b/html/auth/dropbox.html new file mode 100644 index 00000000..cc702b56 --- /dev/null +++ b/html/auth/dropbox.html @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/html/auth/github.html b/html/auth/github.html new file mode 100644 index 00000000..e95eb1fd --- /dev/null +++ b/html/auth/github.html @@ -0,0 +1,27 @@ + + + + + + + \ No newline at end of file diff --git a/index.html b/html/index.html similarity index 55% rename from index.html rename to html/index.html index 85d13d8c..92e0e0dc 100644 --- a/index.html +++ b/html/index.html @@ -4,26 +4,14 @@ - Cloud Commander + {title} - - -
-
+ +
{fm}
@@ -32,15 +20,16 @@ - +
- - + \ No newline at end of file diff --git a/config.json b/json/config.json similarity index 61% rename from config.json rename to json/config.json index 3c8d7ff1..0298176d 100644 --- a/config.json +++ b/json/config.json @@ -1,22 +1,18 @@ -{ - "api_url" : "/api/v1", - "appcache" : false, - "cache" : {"allowed" : false}, - "minification" : { - "js" : true, - "css" : true, - "html" : true, - "img" : true - }, - "github_key" : "891c251b925e4e967fa9", - "github_secret" : "afe9bed1e810c5dc44c4c2a953fc6efb1e5b0545", - "dropbox_key" : "0nd3ssnp5fp7tqs", - "dropbox_chooser_key" : "o7d6llji052vijk", - "logs" : false, - "show_keys_panel" : true, - "server" : true, - "socket" : true, - "port" : 80, - "ip" : null, - "rest" : true +{ + "api_url" : "/api/v1", + "appcache" : false, + "minification" : { + "js" : true, + "css" : true, + "html" : true, + "img" : true + }, + "cache" : true, + "logs" : false, + "show_keys_panel" : true, + "server" : true, + "socket" : true, + "port" : 80, + "ip" : null, + "rest" : true } \ No newline at end of file diff --git a/json/ext.json b/json/ext.json new file mode 100644 index 00000000..b22e0d20 --- /dev/null +++ b/json/ext.json @@ -0,0 +1,169 @@ +{ + ".3gp": "video/3gpp", + ".a": "application/octet-stream", + ".ai": "application/postscript", + ".aif": "audio/x-aiff", + ".aiff": "audio/x-aiff", + ".appcache": "text/cache-manifest", + ".asc": "application/pgp-signature", + ".asf": "video/x-ms-asf", + ".asm": "text/x-asm", + ".asx": "video/x-ms-asf", + ".atom": "application/atom+xml", + ".au": "audio/basic", + ".avi": "video/x-msvideo", + ".bat": "application/x-msdownload", + ".bin": "application/octet-stream", + ".bmp": "image/bmp", + ".bz2": "application/x-bzip2", + ".c": "text/x-c", + ".cab": "application/vnd.ms-cab-compressed", + ".cc": "text/x-c", + ".chm": "application/vnd.ms-htmlhelp", + ".class": "application/octet-stream", + ".com": "application/x-msdownload", + ".conf": "text/plain", + ".cpp": "text/x-c", + ".crt": "application/x-x509-ca-cert", + ".css": "text/css", + ".csv": "text/csv", + ".cxx": "text/x-c", + ".deb": "application/x-debian-package", + ".der": "application/x-x509-ca-cert", + ".diff": "text/x-diff", + ".djv": "image/vnd.djvu", + ".djvu": "image/vnd.djvu", + ".dll": "application/x-msdownload", + ".dmg": "application/octet-stream", + ".doc": "application/msword", + ".dot": "application/msword", + ".dtd": "application/xml-dtd", + ".dvi": "application/x-dvi", + ".ear": "application/java-archive", + ".eml": "message/rfc822", + ".eps": "application/postscript", + ".exe": "application/x-msdownload", + ".f": "text/x-fortran", + ".f77": "text/x-fortran", + ".f90": "text/x-fortran", + ".flv": "video/x-flv", + ".for": "text/x-fortran", + ".gem": "application/octet-stream", + ".gemspec": "text/x-script.ruby", + ".gif": "image/gif", + ".gz": "application/x-gzip", + ".h": "text/x-c", + ".hh": "text/x-c", + ".htm": "text/html", + ".html": "text/html", + ".ico": "image/vnd.microsoft.icon", + ".ics": "text/calendar", + ".ifb": "text/calendar", + ".iso": "application/octet-stream", + ".jar": "application/java-archive", + ".java": "text/x-java-source", + ".jnlp": "application/x-java-jnlp-file", + ".jpeg": "image/jpeg", + ".jpg": "image/jpeg", + ".js": "application/javascript", + ".json": "application/json", + ".log": "text/plain", + ".m3u": "audio/x-mpegurl", + ".m4v": "video/mp4", + ".man": "text/troff", + ".mathml": "application/mathml+xml", + ".mbox": "application/mbox", + ".mdoc": "text/troff", + ".me": "text/troff", + ".mid": "audio/midi", + ".midi": "audio/midi", + ".mime": "message/rfc822", + ".mml": "application/mathml+xml", + ".mng": "video/x-mng", + ".mov": "video/quicktime", + ".mp3": "audio/mpeg", + ".mp4": "video/mp4", + ".mp4v": "video/mp4", + ".mpeg": "video/mpeg", + ".mpg": "video/mpeg", + ".ms": "text/troff", + ".msi": "application/x-msdownload", + ".odp": "application/vnd.oasis.opendocument.presentation", + ".ods": "application/vnd.oasis.opendocument.spreadsheet", + ".odt": "application/vnd.oasis.opendocument.text", + ".ogg": "application/ogg", + ".p": "text/x-pascal", + ".pas": "text/x-pascal", + ".pbm": "image/x-portable-bitmap", + ".pdf": "application/pdf", + ".pem": "application/x-x509-ca-cert", + ".pgm": "image/x-portable-graymap", + ".pgp": "application/pgp-encrypted", + ".pkg": "application/octet-stream", + ".pl": "text/x-script.perl", + ".pm": "text/x-script.perl-module", + ".png": "image/png", + ".pnm": "image/x-portable-anymap", + ".ppm": "image/x-portable-pixmap", + ".pps": "application/vnd.ms-powerpoint", + ".ppt": "application/vnd.ms-powerpoint", + ".ps": "application/postscript", + ".psd": "image/vnd.adobe.photoshop", + ".py": "text/x-script.python", + ".qt": "video/quicktime", + ".ra": "audio/x-pn-realaudio", + ".rake": "text/x-script.ruby", + ".ram": "audio/x-pn-realaudio", + ".rar": "application/x-rar-compressed", + ".rb": "text/x-script.ruby", + ".rdf": "application/rdf+xml", + ".roff": "text/troff", + ".rpm": "application/x-redhat-package-manager", + ".rss": "application/rss+xml", + ".rtf": "application/rtf", + ".ru": "text/x-script.ruby", + ".s": "text/x-asm", + ".sgm": "text/sgml", + ".sgml": "text/sgml", + ".sh": "application/x-sh", + ".sig": "application/pgp-signature", + ".snd": "audio/basic", + ".so": "application/octet-stream", + ".svg": "image/svg+xml", + ".svgz": "image/svg+xml", + ".swf": "application/x-shockwave-flash", + ".t": "text/troff", + ".tar": "application/x-tar", + ".tbz": "application/x-bzip-compressed-tar", + ".tcl": "application/x-tcl", + ".tex": "application/x-tex", + ".texi": "application/x-texinfo", + ".texinfo": "application/x-texinfo", + ".text": "text/plain", + ".tif": "image/tiff", + ".tiff": "image/tiff", + ".torrent": "application/x-bittorrent", + ".tr": "text/troff", + ".txt": "text/plain", + ".vcf": "text/x-vcard", + ".vcs": "text/x-vcalendar", + ".vrml": "model/vrml", + ".war": "application/java-archive", + ".wav": "audio/x-wav", + ".wma": "audio/x-ms-wma", + ".wmv": "video/x-ms-wmv", + ".wmx": "video/x-ms-wmx", + ".woff": "font/woff", + ".wrl": "model/vrml", + ".wsdl": "application/wsdl+xml", + ".xbm": "image/x-xbitmap", + ".xhtml": "application/xhtml+xml", + ".xls": "application/vnd.ms-excel", + ".xml": "application/xml", + ".xpm": "image/x-xpixmap", + ".xsl": "application/xml", + ".xslt": "application/xslt+xml", + ".yaml": "text/yaml", + ".yml": "text/yaml", + ".zip": "application/zip" +} \ No newline at end of file diff --git a/json/modules.json b/json/modules.json new file mode 100644 index 00000000..3ea504f4 --- /dev/null +++ b/json/modules.json @@ -0,0 +1,40 @@ +[ + "editor/_codemirror", + "menu", + "viewer", + "terminal", { + "name": "storage", + "data": [{ + "name": "DropBox", + "data":{ + "key" : "0nd3ssnp5fp7tqs", + "secret" : "r61lxpchmk8l06o", + "encodedKey": "DkMz4FYHQTA=|GW6pf2dONkrGvckMwBsl1V1vysrCPktPiUWN7UpDjw==", + "chooserKey": "o7d6llji052vijk" + } + }, { + "name": "GitHub", + "data": { + "key" : "891c251b925e4e967fa9", + "secret" : "afe9bed1e810c5dc44c4c2a953fc6efb1e5b0545" + } + }, { + "name": "GDrive", + "data": { + "id" : "255175681917" + } + }, { + "name": "VK", + "data": { + "id" : "3336188" + } + }, + { + "name": "SkyDrive", + "data": { + "id" : "00000000440E696F" + } + } + ] + } +] \ No newline at end of file diff --git a/lib/client.js b/lib/client.js index ae3e3767..36ae8b58 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,862 +1,680 @@ -/* Функция которая возвратит обьект CloudCommander - * @CloudFunc - обьект содержащий общий функционал - * клиентский и серверный - */ - -var Util, DOM, CloudFunc, CloudCommander = (function(){ -"use strict"; - -/* Клиентский обьект, содержащий функциональную часть*/ -var CloudClient = { - /* Конструктор CloudClient, который выполняет - * весь функционал по инициализации - */ - init : null, /* start initialization */ - - KeyBinding : null, /* обьект обработки нажатий клавишь */ - KeysPanel : null, /* panel with key buttons f1-f8 */ - Config : null, /* function loads and shows config */ - Editor : null, /* function loads and shows editor */ - Storage : null, /* function loads storage */ - Viewer : null, /* function loads and shows viewer */ - Terminal : null, /* function loads and shows terminal*/ - Menu : null, /* function loads and shows menu */ - GoogleAnalytics : null, - - _loadDir : null, /* Функция привязываеться ко всем - * ссылкам и - * загружает содержимое каталогов */ - - /* ОБЬЕКТЫ */ - - /* ПРИВАТНЫЕ ФУНКЦИИ */ - /* функция загружает json-данные о файловой системе */ - _ajaxLoad : null, - - /* Функция генерирует JSON из html-таблицы файлов */ - _getJSONfromFileTable : null, - - /* функция меняет ссыки на ajax-овые */ - _changeLinks : null, - - /* КОНСТАНТЫ*/ - /* название css-класа текущего файла*/ - CURRENT_FILE : 'current-file', - LIBDIR : '/lib/', - LIBDIRCLIENT : '/lib/client/', - /* height of Cloud Commander - * seting up in init() - */ - HEIGHT : 0, - MIN_ONE_PANEL_WIDTH : 1155, - OLD_BROWSER : false, - - HOST : (function(){ - var lLocation = document.location; - return lLocation.protocol + '//' + lLocation.host; - })() -}; - - - -var cloudcmd = CloudClient, - -/* глобальные переменные */ - $, KeyBinding, - -/* short names used all the time functions */ - getByClass, getById; - - -/** - * function load modules - * @pParams = {name, path, func, dobefore, arg} - */ -var loadModule = function(pParams){ - if(!pParams) return; - - var lName = pParams.name, - lPath = pParams.path, - lFunc = pParams.func, - lDoBefore = pParams.dobefore; - - if( Util.isString(pParams) ) - lPath = pParams; - - if(lPath && !lName){ - lName = lPath[0].toUpperCase() + lPath.substring(1); - lName = Util.removeStr(lName, '.js'); - - var lSlash = lName.indexOf('/'); - if(lSlash > 0){ - var lAfterSlash = lName.substr(lSlash); - lName = Util.removeStr(lName, lAfterSlash); - } - } - - if( !Util.isContainStr(lPath, '.js') ) - lPath += '.js'; - - if(!cloudcmd[lName]) - cloudcmd[lName] = function(pArg){ - Util.exec(lDoBefore); - - return DOM.jsload(cloudcmd.LIBDIRCLIENT + lPath, lFunc || - function(){ - Util.exec(cloudcmd[lName].init, pArg); - }); - }; -}; - -CloudClient.GoogleAnalytics = function(){ - /* google analytics */ - var lFunc = document.onmousemove; - - document.onmousemove = function(){ - setTimeout(function(){ - DOM.jsload(cloudcmd.LIBDIRCLIENT + 'google_analytics.js'); - },5000); - - Util.exec(lFunc); - - document.onmousemove = lFunc; - }; -}; - -/** - * Функция привязываеться ко всем ссылкам и - * загружает содержимое каталогов - */ -CloudClient._loadDir = function(pLink,pNeedRefresh){ - /* @pElem - элемент, - * для которого нужно - * выполнить загрузку - */ - return function(pEvent){ - var lRet = true; - /* показываем гиф загрузки возле пути папки сверху*/ - /* ctrl+r нажата? */ - - DOM.Images.showLoad(pNeedRefresh ? {top:true} : null); - - var lPanel = DOM.getPanel(), - /* получаем имя каталога в котором находимся*/ - lHref = DOM.getByClass('path', lPanel); - - lHref = lHref[0].textContent; - - lHref = CloudFunc.removeLastSlash(lHref); - var lSubstr = lHref.substr(lHref,lHref.lastIndexOf('/')); - lHref = lHref.replace(lSubstr+'/',''); - - /* загружаем содержимое каталога */ - CloudClient._ajaxLoad(pLink, { refresh: pNeedRefresh }); - - /* получаем все элементы выделенной папки*/ - /* при этом, если мы нажали обновить - * или +R - ссылок мы ненайдём - * и заходить не будем - */ - var lA = DOM.getCurrentLink(this); - - /* если нажали на ссылку на верхний каталог*/ - if(lA && lA.textContent==='..' && lHref!=='/'){ - - /* функция устанавливает курсор на каталог - * с которого мы пришли, если мы поднялись - * в верх по файловой структуре - */ - CloudClient._currentToParent(lHref); - } - - /* что бы не переходить по ссылкам - * а грузить всё ajax'ом, - * возвращаем false на событие - * onclick - */ - - Util.setValue({ - object : pEvent, - property: 'returnValue', - value : false - }); - - return lRet; - }; - }; - - -/** - * Function edits file name - * - * @param pParent - parent element - * @param pEvent - */ -CloudClient._editFileName = function(pParent){ - var lA = DOM.getCurrentLink(pParent); - - if (lA && lA.textContent !== '..'){ - - lA.contentEditable = true; - KeyBinding.unSet(); - - var lDocumentOnclick = document.onclick; - - /* setting event handler onclick - * if user clicks somewhere keyBinded - * backs - */ - document.onclick = (function(){ - var lA = DOM.getCurrentLink(pParent); - if (lA && lA.textContent !== '..') - lA.contentEditable = false; - - KeyBinding.set(); - - /* backs old document.onclick - * and call it if it was - * setted up earlier - */ - document.onclick = lDocumentOnclick; - - Util.exec(lDocumentOnclick); - - }); - } -}; - -/** - * Функция устанавливает текущим файлом, тот - * на который кликнули единожды - */ -CloudClient._setCurrent = function(){ - /* - * @pFromEnter - если мы сюда попали - * из события нажатия на энтер - - * вызоветься _loadDir - */ - return function(pFromEnter){ - var lCurrentFile = DOM.getCurrentFile(); - if(lCurrentFile){/* устанавливаем курсор на файл, на который нажали */ - DOM.setCurrentFile(this); - //if (DOM.isCurrentFile(this) && - // !Util.isBoolean(pFromEnter)){ - //var lParent = this; - - //setTimeout(function(){ - /* waiting a few seconds - * and if classes still equal - * make file name editable - * in other case - * double click event happend - */ - // if(DOM.getCurrentFile() === lParent) - // CloudClient._editFileName(lParent); - // },1000); - //} - } - /* если мы попали сюда с энтера */ - if(pFromEnter===true){ - var lResult = Util.exec( Util.bind(this.ondblclick, this) ); - /* enter pressed on file */ - if(!lResult){ - var lA = DOM.getCurrentLink(this); - Util.exec( Util.bind(lA.ondblclick, this) ); - } - }/* если мы попали сюда от клика мышки */ - else - pFromEnter.returnValue = false; - - /* что бы не переходить по ссылкам - * а грузить всё ajax'ом, - * возвращаем false на событие - * onclick - */ - return true; - }; - }; - -/** функция устанавливает курсор на каталог - * с которого мы пришли, если мы поднялись - * в верх по файловой структуре - * @param pDirName - имя каталога с которого мы пришли - */ -CloudClient._currentToParent = function(pDirName){ - /* опредиляем в какой мы панели: - * правой или левой - */ - var lPanel = DOM.getPanel(); - - /* убираем слэш с имени каталога*/ - pDirName = pDirName.replace('/',''); - - var lRootDir = getById(pDirName + '(' + lPanel.id + ')'); - - /* if found li element with ID directory name - * set it to current file - */ - if(lRootDir){ - DOM.setCurrentFile(lRootDir); - DOM.scrollIntoViewIfNeeded(lRootDir, true); - } -}; - -/** Конструктор CloudClient, который - * выполняет весь функционал по - * инициализации - */ -CloudClient.init = function(){ - var lFunc = function(){ - Util.loadOnLoad([ - initKeysPanel, - initModules, - baseInit - ]); - }; - - getByClass = DOM.getByClass; - getById = DOM.getById; - - - //Util.socketLoad(); - - if(!document.body.scrollIntoViewIfNeeded){ - this.OLD_BROWSER = true; - DOM.jsload(CloudClient.LIBDIRCLIENT + 'ie.js', - function(){ - DOM.jqueryLoad( lFunc ); - }); - }else - lFunc(); -}; - -function initModules(pCallBack){ - loadModule({ - /* привязываем клавиши к функциям */ - path : 'keyBinding.js', - func : function(){ - KeyBinding = cloudcmd.KeyBinding; - KeyBinding.init(); - } - }); - - DOM.ajax({ - url:'/modules.json', - success: function(pModules){ - var lStorage = 'storage/', - lShowLoadFunc = Util.retFunc( DOM.Images.showLoad ), - lDisableMenuFunc = function(){ - var lFunc = document.oncontextmenu; - document.oncontextmenu = function(){ - Util.exec(lFunc); - return cloudcmd.Menu.ENABLED || false; - }; - }, - - lDoBefore = { - 'editor/_codemirror' : lShowLoadFunc, - 'menu' : lDisableMenuFunc, - 'viewer' : lShowLoadFunc - }, - - lNames = {}; - lNames[lStorage + '_dropbox'] = 'DropBox', - lNames[lStorage + '_github' ] = 'GitHub', - - lDisableMenuFunc(); - - if( Util.isArray(pModules) ) - for(var i = 0, n = pModules.length; i < n ; i++){ - var lModule = pModules[i]; - - loadModule({ - path : lModule, - dobefore : lDoBefore[lModule], - name : lNames[lModule] - }); - } - - Util.exec(pCallBack); - } - }); -} - -function initKeysPanel(pCallBack){ - var lKeysPanel = {}, - - lFuncs =[ - null, - null, /* f1 */ - null, /* f2 */ - cloudcmd.Viewer, /* f3 */ - cloudcmd.Editor, /* f4 */ - null, /* f5 */ - null, /* f6 */ - null, /* f7 */ - DOM.promptRemoveCurrent,/* f8 */ - ]; - - for(var i = 1; i <= 8; i++){ - var lButton = 'f' + i, - lEl = getById('f' + i); - - lEl.onclick = lFuncs[i]; - lKeysPanel[lButton] = lEl; - } - - cloudcmd.KeysPanel = lKeysPanel; - Util.exec(pCallBack); -} - -function baseInit(pCallBack){ - if(applicationCache){ - var lFunc = applicationCache.onupdateready; - - applicationCache.onupdateready = function(){ - console.log('app cacheed'); - location.reload(); - - Util.exec(lFunc); - }; - } - - /* загружаем общие функции для клиента и сервера */ - DOM.jsload(cloudcmd.LIBDIR + 'cloudfunc.js',function(){ - DOM.addListener("popstate", function(pEvent) { - var lPath = pEvent.state; - - if(lPath) - cloudcmd._ajaxLoad(lPath, {nohistory: true}); - - return true; - }); - - /* берём из обьекта window общий с сервером функционал */ - CloudFunc = window.CloudFunc; - - /* меняем ссылки на ajax'овые */ - cloudcmd._changeLinks(CloudFunc.LEFTPANEL); - cloudcmd._changeLinks(CloudFunc.RIGHTPANEL); - - /* устанавливаем переменную доступности кэша */ - DOM.Cache.isAllowed(); - /* Устанавливаем кэш корневого каталога */ - if( !DOM.Cache.get('/') ) - DOM.Cache.set('/', cloudcmd._getJSONfromFileTable()); - }); - - /* устанавливаем размер высоты таблицы файлов - * исходя из размеров разрешения экрана - */ - - /* выделяем строку с первым файлом */ - var lFmHeader = getByClass('fm_header'); - if(lFmHeader && lFmHeader[0].nextSibling) - DOM.setCurrentFile(lFmHeader[0].nextSibling); - - /* показываем элементы, которые будут работать только, если есть js */ - var lFM = getById('fm'); - if(lFM) - lFM.className='localstorage'; - - /* формируем и округляем высоту экрана - * при разрешениии 1024x1280: - * 658 -> 700 - */ - - var lHeight = window.screen.height; - lHeight = lHeight - (lHeight/3).toFixed(); - - lHeight = (lHeight / 100).toFixed() * 100; - - cloudcmd.HEIGHT = lHeight; - - DOM.cssSet({id:'cloudcmd', - inner: - '.panel{' + - 'height:' + lHeight +'px;' + - '}' - }); - - Util.exec(pCallBack); - cloudcmd.KeyBinding(); -} - -CloudClient.getConfig = function(pCallBack){ - if(!cloudcmd.Config) - return DOM.ajax({ - url:'/config.json', - success: function(pConfig){ - cloudcmd.Config = pConfig; - - Util.exec(pCallBack, pConfig); - } - }); - else - Util.exec(pCallBack, cloudcmd.Config); -}; - - -/* функция меняет ссыки на ajax-овые */ -CloudClient._changeLinks = function(pPanelID){ - /* назначаем кнопку очистить кэш и показываем её */ - var lClearcache = getById('clear-cache'); - if(lClearcache) - lClearcache.onclick = DOM.Cache.clear; - - /* меняем ссылки на ajax-запросы */ - var lPanel = getById(pPanelID), - a = lPanel.getElementsByTagName('a'), - - /* номер ссылки иконки обновления страницы */ - lREFRESHICON = 0, - - /* путь в ссылке, который говорит - * что js отключен - */ - lNoJS_s = CloudFunc.NOJS, - - /* right mouse click function varible */ - lOnContextMenu_f = function(pEvent){ - var lReturn_b = true; - - KeyBinding.unSet(); - - /* getting html element - * currentTarget - DOM event - * target - jquery event - */ - var lTarget = pEvent.currentTarget || pEvent.target; - DOM.setCurrentFile(lTarget); - - if(Util.isFunction(cloudcmd.Menu) ){ - cloudcmd.Menu({ - x: pEvent.x, - y: pEvent.y - }); - - /* disabling browsers menu*/ - lReturn_b = false; - DOM.Images.showLoad(); - } - - return lReturn_b; - }, - - /* drag and drop function varible - * download file from browser to descktop - * in Chrome (HTML5) - */ - lOnDragStart_f = function(pEvent){ - var lElement = pEvent.target, - lLink = lElement.href, - lName = lElement.textContent, - /* if it's directory - adding json extension */ - lType = lElement.parentElement.nextSibling; - - if(lType && lType.textContent === ''){ - lLink = lLink.replace(lNoJS_s,''); - lName += '.json'; - } - - pEvent.dataTransfer.setData("DownloadURL", - 'application/octet-stream' + ':' + - lName + ':' + - lLink); - }, - - lSetCurrentFile_f = function(pEvent){ - var pElement = pEvent.target, - lTag = pElement.tagName; - - if(lTag !== 'LI') - do{ - pElement = pElement.parentElement; - lTag = pElement.tagName; - }while(lTag !== 'LI'); - - DOM.setCurrentFile(pElement); - }, - - lUrl = cloudcmd.HOST; - - for(var i = 0, n = a.length; i < n ; i++) - { - /* убираем адрес хоста*/ - var link = a[i].href.replace(lUrl,''); - - /* ставим загрузку гифа на клик*/ - if(i === lREFRESHICON){ - a[i].onclick = CloudClient._loadDir(link, true); - - a[i].parentElement.onclick = a[i].onclick; - } - - /* устанавливаем обработчики на строку на одинарное и * - * двойное нажатие на левую кнопку мышки */ - else{ - var lLi = a[i].parentElement.parentElement; - - /* if we in path changing onclick events */ - if (lLi.className === 'path') { - a[i].onclick = CloudClient._loadDir(link); - } - else { - lLi.onclick = CloudClient._setCurrent(); - lLi.onmousedown = lSetCurrentFile_f; - a[i].ondragstart = lOnDragStart_f; - - /* if right button clicked menu will - * loads and shows - */ - lLi.oncontextmenu = lOnContextMenu_f; - - /* если ссылка на папку, а не файл */ - if(a[i].target !== '_blank'){ - lLi.ondblclick = CloudClient._loadDir(link); - - DOM.addListener('touchend', - CloudClient._loadDir(link), - false, - lLi - ); - } - - lLi.id = (a[i].title ? a[i].title : a[i].textContent) + - '(' + pPanelID + ')'; - } - } - } -}; - -/** - * Функция загружает json-данные о Файловой Системе - * через ajax-запрос. - * @param path - каталог для чтения - * @param pOptions - * { refresh, nohistory } - необходимость обновить данные о каталоге - */ -CloudClient._ajaxLoad = function(pFullPath, pOptions){ - if(!pOptions) - pOptions = {}; - /* Отображаем красивые пути */ - /* added supporting of russian language */ - pFullPath = decodeURI(pFullPath); - - var lPath = pFullPath, - lFSPath = pFullPath, - - lFS_s = CloudFunc.FS, - lNoJS_s = CloudFunc.NOJS; - /* - * убираем значения, которые, - * говорят об отсутствии js - */ - if(lPath.indexOf(lNoJS_s) === lFS_s.length){ - lPath = lFSPath = Util.removeStr(lPath, lNoJS_s); - } - - if(lPath.indexOf(lFS_s) === 0){ - lPath = lPath.replace(lFS_s,''); - - if(lPath === '/') - pFullPath = '/'; - } - - console.log ('reading dir: "' + lPath + '";'); - - - if(!pOptions.nohistory) - DOM.setHistory(pFullPath, null, pFullPath); - - DOM.setTitle( CloudFunc.getTitle(lPath) ); - - /* если доступен localStorage и - * в нём есть нужная нам директория - - * читаем данные с него и - * выходим - * если стоит поле обязательной перезагрузки - - * перезагружаемся - */ - - /* опредиляем в какой мы панели: - * правой или левой - */ - var lPanel = DOM.getPanel().id, - lError; - - if(!pOptions.refresh && lPanel){ - var lJSON = DOM.Cache.get(lPath); - - if (lJSON){ - /* переводим из текста в JSON */ - if(window && !window.JSON){ - lError = Util.tryCatchLog(function(){ - lJSON = eval('('+lJSON+')'); - }); - - }else - lJSON = JSON.parse(lJSON); - - CloudClient._createFileTable(lPanel, lJSON); - CloudClient._changeLinks(lPanel); - - - return; - } - } - - DOM.ajax({ - url: lFSPath, - error: DOM.Images.showError, - - success:function(data, textStatus, jqXHR){ - /* если такой папки (или файла) нет - * прячем загрузку и показываем ошибку - */ - if(!jqXHR.responseText.indexOf('Error:')) - return DOM.showError(jqXHR); - - CloudClient._createFileTable(lPanel, data); - CloudClient._changeLinks(lPanel); - - /* Сохраняем структуру каталогов в localStorage, - * если он поддерживаеться браузером - */ - /* переводим таблицу файлов в строку, для - * сохранения в localStorage - */ - var lJSON_s = JSON.stringify(data); - console.log(lJSON_s.length); - - /* если размер данных не очень бошьой - * сохраняем их в кэше - */ - if(lJSON_s.length < 50000 ) - DOM.Cache.set(lPath, lJSON_s); - } - }); -}; - -/** - * Функция строит файловую таблицу - * @param pEleme - родительский элемент - * @param pJSON - данные о файлах - */ -CloudClient._createFileTable = function(pElem, pJSON){ - var lElem = getById(pElem); - - /* getting current element if was refresh */ - var lPath = getByClass('path', lElem); - var lWasRefresh_b = lPath[0].textContent === pJSON[0].path; - var lCurrent; - if(lWasRefresh_b) - lCurrent = DOM.getCurrentFile(); - - /* говорим построителю, - * что бы он в нужный момент - * выделил строку с первым файлом - */ - - /* очищаем панель */ - var i = lElem.childNodes.length; - while(i--) - lElem.removeChild(lElem.lastChild); - - /* заполняем панель новыми элементами */ - lElem.innerHTML = CloudFunc.buildFromJSON(pJSON,true); - - /* searching current file */ - if(lWasRefresh_b && lCurrent){ - for(i = 0; i < lElem.childNodes.length; i++) - if(lElem.childNodes[i].textContent === lCurrent.textContent){ - lCurrent = lElem.childNodes[i]; - break; - } - DOM.setCurrentFile(lCurrent); - //lCurrent.parentElement.focus(); - } -}; - -/** - * Функция генерирует JSON из html-таблицы файлов и - * используеться при первом заходе в корень - */ -CloudClient._getJSONfromFileTable = function(){ - var lLeft = getById('left'), - lPath = getByClass('path')[0].textContent, - - lFileTable = [{ - path:lPath, - size:'dir' - }], - - lLI = lLeft.getElementsByTagName('li'), - - j = 1; /* счётчик реальных файлов */ - - /* счётчик элементов файлов в DOM */ - /* Если путь отличный от корневного - * второй элемент li - это ссылка на верхний - * каталог '..' - */ - - /* пропускам Path и Header*/ - for(var i = 2, n = lLI.length; i < n; i++){ - var lChildren = lLI[i].children, - /* file attributes */ - lAttr = {}; - - /* getting all elements to lAttr object */ - for(var l = 0; l < lChildren.length; l++) - lAttr[lChildren[l].className] = lChildren[l]; - - /* mini-icon */ - var lIsDir = lAttr['mini-icon directory'] ? true : false, - - lName = lAttr.name; - if(lName) - lName = DOM.getByTag('a', lName); - - /* if found link to folder - * cheking is it a full name - * or short - */ - /* if short we got title - * if full - getting textConent - */ - if(lName.length) - lName = lName[0]; - - lName = lName.title || lName.textContent; - - /* если это папка - выводим слово dir вместо размера*/ - var lSize = lIsDir ? 'dir' : lAttr.size.textContent, - lMode = lAttr.mode.textContent; - - /* переводим права доступа в цыфровой вид - * для хранения в localStorage - */ - lMode = CloudFunc.convertPermissionsToNumberic(lMode); - - lFileTable[ j++ ]={ - name: lName, - size: lSize, - mode: lMode - }; - } - return JSON.stringify(lFileTable); -}; - -return CloudClient; -})(); - -window.onload = function(){ - 'use strict'; - - /* базовая инициализация*/ - CloudCommander.init(); - - /* загружаем Google Analytics */ - CloudCommander.GoogleAnalytics(); -}; +/* Функция которая возвратит обьект CloudCommander + * @CloudFunc - обьект содержащий общий функционал + * клиентский и серверный + */ + +var Util, DOM, CloudFunc, $, KeyBinding, CloudCommander = (function(Util, DOM){ +'use strict'; + +var Config, Modules; + +/* Клиентский обьект, содержащий функциональную часть*/ +var CloudCmd = { + /* Конструктор CloudClient, который выполняет + * весь функционал по инициализации + */ + init : null, /* start initialization */ + + KeyBinding : null, /* обьект обработки нажатий клавишь */ + KeysPanel : null, /* panel with key buttons f1-f8 */ + Editor : null, /* function loads and shows editor */ + Storage : null, /* function loads storage */ + Viewer : null, /* function loads and shows viewer */ + Terminal : null, /* function loads and shows terminal*/ + Menu : null, /* function loads and shows menu */ + GoogleAnalytics : null, + + _loadDir : null, /* Функция привязываеться ко всем + * ссылкам и + * загружает содержимое каталогов */ + + /* ОБЬЕКТЫ */ + + /* ПРИВАТНЫЕ ФУНКЦИИ */ + /* функция загружает json-данные о файловой системе */ + _ajaxLoad : null, + + /* Функция генерирует JSON из html-таблицы файлов */ + _getJSONfromFileTable : null, + + /* функция меняет ссыки на ajax-овые */ + _changeLinks : null, + + /* КОНСТАНТЫ*/ + LIBDIR : '/lib/', + LIBDIRCLIENT : '/lib/client/', + JSONDIR : '/json/', + /* height of Cloud Commander + * seting up in init() + */ + HEIGHT : 0, + MIN_ONE_PANEL_WIDTH : 1155, + OLD_BROWSER : false, + + HOST : (function(){ + var lLocation = document.location; + return lLocation.protocol + '//' + lLocation.host; + })() +}; + +CloudCmd.GoogleAnalytics = function(){ + DOM.addOneTimeListener('mousemove', function(){ + var lUrl = CloudCmd.LIBDIRCLIENT + 'google_analytics.js'; + + setTimeout(function(){ + DOM.jsload(lUrl); + }, 5000); + }); +}; + +/** + * Функция привязываеться ко всем ссылкам и + * загружает содержимое каталогов + * + * @param pLink - ссылка + * @param pNeedRefresh - необходимость обязательной загрузки данных с сервера + */ +CloudCmd._loadDir = function(pLink, pNeedRefresh){ + return function(pEvent){ + /* показываем гиф загрузки возле пути папки сверху + * ctrl+r нажата? */ + + var lCurrentLink = DOM.getCurrentLink(), + lHref = lCurrentLink.href, + lParent = lCurrentLink.textContent, + lLink = pLink || Util.removeStr(lHref, CloudCmd.HOST), + lDir = DOM.getCurrentDirName(); + + lLink += '?json'; + + if(lLink || lCurrentLink.target !== '_blank'){ + DOM.Images.showLoad(pNeedRefresh ? {top:true} : null); + + /* загружаем содержимое каталога */ + CloudCmd._ajaxLoad(lLink, { refresh: pNeedRefresh }); + + /* если нажали на ссылку на верхний каталог*/ + if(lParent === '..' && lDir !== '/') + CloudCmd._currentToParent(lDir); + } + + DOM.preventDefault(pEvent); + }; +}; + + +/** + * Function edits file name + * + * @param pParent - parent element + * @param pEvent + */ +CloudCmd._editFileName = function(pParent){ + var lA = DOM.getCurrentLink(pParent); + + if (lA && lA.textContent !== '..'){ + + lA.contentEditable = true; + KeyBinding && KeyBinding.unSet(); + + /* setting event handler onclick + * if user clicks somewhere keyBinded + * backs + */ + DOM.addOneTimeListener('click', function(){ + var lA = DOM.getCurrentLink(pParent); + if (lA && lA.textContent !== '..') + lA.contentEditable = false; + + KeyBinding && KeyBinding.set(); + }); + } +}; + + +/** функция устанавливает курсор на каталог + * с которого мы пришли, если мы поднялись + * в верх по файловой структуре + * @param pDirName - имя каталога с которого мы пришли + */ +CloudCmd._currentToParent = function(pDirName){ + /* убираем слэш с имени каталога */ + pDirName = Util.removeStr(pDirName, '/'); + + /* опредиляем в какой мы панели: * + * правой или левой */ + var lPanel = DOM.getPanel(), + lRootDir = DOM.getById(pDirName + '(' + lPanel.id + ')'); + + /* if found li element with ID directory name * + * set it to current file */ + if(lRootDir){ + DOM.setCurrentFile(lRootDir); + DOM.scrollIntoViewIfNeeded(lRootDir, true); + } +}; + +/** + * function load modules + * @pParams = {name, path, func, dobefore, arg} + */ +function loadModule(pParams){ + if(!pParams) return; + + var lName = pParams.name, + lPath = pParams.path, + lFunc = pParams.func, + lDoBefore = pParams.dobefore; + + if( Util.isString(pParams) ) + lPath = pParams; + + if(lPath && !lName){ + lName = lPath[0].toUpperCase() + lPath.substring(1); + lName = Util.removeStr(lName, '.js'); + + var lSlash = lName.indexOf('/'); + if(lSlash > 0){ + var lAfterSlash = lName.substr(lSlash); + lName = Util.removeStr(lName, lAfterSlash); + } + } + + if( !Util.isContainStr(lPath, '.js') ) + lPath += '.js'; + + if(!CloudCmd[lName]) + CloudCmd[lName] = function(pArg){ + Util.exec(lDoBefore); + + return DOM.jsload(CloudCmd.LIBDIRCLIENT + lPath, lFunc || + function(){ + Util.exec(CloudCmd[lName].init, pArg); + }); + }; +} +/** Конструктор CloudClient, который + * выполняет весь функционал по + * инициализации + */ +CloudCmd.init = function(){ + var lCallBack = function(){ + Util.loadOnLoad([ + initKeysPanel, + initModules, + baseInit + ]); + }, + lFunc = function(pCallBack){ + CloudCmd.OLD_BROWSER = true; + var lSrc = CloudCmd.LIBDIRCLIENT + 'ie.js'; + + DOM.jqueryLoad( + DOM.retJSLoad(lSrc, pCallBack) + ); + }; + + //Util.socketLoad(); + + Util.ifExec(document.body.scrollIntoViewIfNeeded, lCallBack, lFunc); +}; + +function initModules(pCallBack){ + loadModule({ + /* привязываем клавиши к функциям */ + path : 'keyBinding.js', + func : function(){ + KeyBinding = CloudCmd.KeyBinding; + KeyBinding.init(); + } + }); + + CloudCmd.getModules(function(pModules){ + pModules = pModules || []; + + DOM.addContextMenuListener(function(pEvent){ + CloudCmd.Menu.ENABLED || DOM.preventDefault(pEvent); + }, document); + + var lStorage = 'storage', + lShowLoadFunc = Util.retFunc( DOM.Images.showLoad ), + + lDoBefore = { + 'editor/_codemirror' : lShowLoadFunc, + 'viewer' : lShowLoadFunc + }, + + lLoad = function(pName, pPath, pDoBefore){ + loadModule({ + path : pPath, + name : pName, + dobefore : pDoBefore + }); + }; + + for(var i = 0, n = pModules.length; i < n ; i++){ + var lModule = pModules[i]; + + if(Util.isString(lModule)) + lLoad(null, lModule, lDoBefore[lModule]); + } + + var lStorageObj = Util.findObjByNameInArr( pModules, lStorage ), + lMod = Util.getNamesFromObjArray( lStorageObj ); + + for(i = 0, n = lMod.length; i < n; i++){ + var lName = lMod[i], + lPath = lStorage + '/_' + lName.toLowerCase(); + + lLoad(lName, lPath); + } + + + Util.exec(pCallBack); + + }); +} + +function initKeysPanel(pCallBack){ + var lKeysPanel = {}, + + lFuncs =[ + null, + null, /* f1 */ + DOM.renameCurrentFile, /* f2 */ + CloudCmd.Viewer, /* f3 */ + CloudCmd.Editor, /* f4 */ + null, /* f5 */ + null, /* f6 */ + null, /* f7 */ + DOM.promptDeleteCurrent,/* f8 */ + ]; + + for(var i = 1; i <= 8; i++){ + var lButton = 'f' + i, + lEl = DOM.getById('f' + i); + + DOM.addClickListener(lFuncs[i], lEl); + lKeysPanel[lButton] = lEl; + } + + CloudCmd.KeysPanel = lKeysPanel; + Util.exec(pCallBack); +} + +function baseInit(pCallBack){ + if(window.applicationCache){ + var lFunc = applicationCache.onupdateready; + + applicationCache.onupdateready = function(){ + Util.log('app cacheed'); + location.reload(); + + Util.exec(lFunc); + }; + } + + /* загружаем общие функции для клиента и сервера */ + DOM.jsload(CloudCmd.LIBDIR + 'cloudfunc.js',function(){ + DOM.addListener("popstate", function(pEvent) { + var lPath = pEvent.state + '?json'; + + if(lPath) + CloudCmd._ajaxLoad(lPath, {nohistory: true}); + + return true; + }); + + /* берём из обьекта window общий с сервером функционал */ + CloudFunc = window.CloudFunc; + + /* меняем ссылки на ajax'овые */ + CloudCmd._changeLinks(CloudFunc.LEFTPANEL); + CloudCmd._changeLinks(CloudFunc.RIGHTPANEL); + + /* устанавливаем переменную доступности кэша */ + DOM.Cache.isAllowed(); + /* Устанавливаем кэш корневого каталога */ + if( !DOM.Cache.get('/') ) + DOM.Cache.set('/', CloudCmd._getJSONfromFileTable()); + }); + + /* выделяем строку с первым файлом */ + var lFmHeader = DOM.getByClass('fm-header'); + if(lFmHeader && lFmHeader[0]){ + var lCurrent = lFmHeader[0].nextSibling; + DOM.setCurrentFile(lCurrent); + } + + /* показываем элементы, которые будут работать только, если есть js */ + var lFM = DOM.getById('fm'); + lFM.className='localstorage'; + + /* устанавливаем размер высоты таблицы файлов + * исходя из размеров разрешения экрана + * + * формируем и округляем высоту экрана + * при разрешениии 1024x1280: + * 658 -> 700 + */ + + var lHeight = window.screen.height; + lHeight = lHeight - (lHeight/3).toFixed(); + + lHeight = (lHeight / 100).toFixed() * 100; + + CloudCmd.HEIGHT = lHeight; + + DOM.cssSet({ + id:'cloudcmd', + inner: + '.panel{' + + 'height:' + lHeight +'px;' + + '}' + }); + + Util.exec(pCallBack); + CloudCmd.KeyBinding(); +} + +CloudCmd.getConfig = function(pCallBack){ + Util.ifExec(Config, pCallBack, function(pCallBack){ + DOM.ajax({ + url : CloudCmd.JSONDIR + 'config.json', + success : function(pConfig){ + Config = pConfig; + Util.exec(pCallBack, pConfig); + } + }); + }); +}; + +CloudCmd.getModules = function(pCallBack){ + Util.ifExec(Modules, pCallBack, function(pCallBack){ + DOM.ajax({ + url : CloudCmd.JSONDIR + 'modules.json', + success : Util.retExec(pCallBack) + }); + }); +}; + + +/* функция меняет ссыки на ajax-овые */ +CloudCmd._changeLinks = function(pPanelID){ + /* назначаем кнопку очистить кэш и показываем её */ + var lClearcache = DOM.getById('clear-cache'); + DOM.addClickListener(DOM.Cache.clear, lClearcache); + + /* меняем ссылки на ajax-запросы */ + var lPanel = DOM.getById(pPanelID), + a = lPanel.getElementsByTagName('a'), + + /* right mouse click function varible */ + lOnContextMenu_f = function(pEvent){ + var lReturn_b = true; + + KeyBinding.unSet(); + + /* getting html element + * currentTarget - DOM event + * target - jquery event + */ + var lTarget = pEvent.currentTarget || pEvent.target; + DOM.setCurrentFile(lTarget); + + if(Util.isFunction(CloudCmd.Menu) ){ + CloudCmd.Menu({ + x: pEvent.clientX, + y: pEvent.clientY + }); + + /* disabling browsers menu*/ + lReturn_b = false; + DOM.Images.showLoad(); + } + + return lReturn_b; + }, + + /* drag and drop function varible + * download file from browser to descktop + * in Chrome (HTML5) + */ + lOnDragStart_f = function(pEvent){ + var lElement = pEvent.target, + lLink = lElement.href, + lName = lElement.textContent; + + /* if it's directory - adding json extension */ + if( DOM.isCurrentIsDir() ){ + lName += '.json'; + lLink += '?json'; + } + + pEvent.dataTransfer.setData("DownloadURL", + 'application/octet-stream' + ':' + + lName + ':' + + lLink); + }, + + lSetCurrentFile_f = function(pEvent){ + var pElement = pEvent.target, + lTag = pElement.tagName; + + if(lTag !== 'LI') + do{ + pElement = pElement.parentElement; + lTag = pElement.tagName; + }while(lTag !== 'LI'); + + DOM.setCurrentFile(pElement); + }, + + lUrl = CloudCmd.HOST; + + var lLoadDirOnce = CloudCmd._loadDir(), + /* номер ссылки иконки обновления страницы */ + lREFRESHICON = 0; + for(var i = 0, n = a.length; i < n ; i++){ + /* убираем адрес хоста*/ + var ai = a[i], + link = ai.href.replace(lUrl, ''), + lNEADREFRESH = i === lREFRESHICON, + lLoadDir = CloudCmd._loadDir(link, lNEADREFRESH); + + /* ставим загрузку гифа на клик*/ + if(lNEADREFRESH) + DOM.addClickListener( lLoadDir, ai.parentElement ); + + /* устанавливаем обработчики на строку + * на двойное нажатие на левую кнопку мышки */ + else{ + var lLi = ai.parentElement.parentElement; + + /* if we in path changing onclick events */ + if (lLi.className === 'path') + DOM.addClickListener( lLoadDir, ai ); + else { + DOM.addClickListener( DOM.preventDefault, lLi); + DOM.addListener('mousedown', lSetCurrentFile_f, lLi); + DOM.addListener('dragstart', lOnDragStart_f, ai); + /* if right button clicked menu will + * loads and shows + */ + DOM.addListener('contextmenu', lOnContextMenu_f, lLi); + + /* если ссылка на папку, а не файл */ + if(ai.target !== '_blank'){ + DOM.addListener('dblclick', lLoadDirOnce, lLi); + DOM.addListener('touchend', lLoadDirOnce, lLi); + } + + lLi.id = (ai.title ? ai.title : ai.textContent) + + '(' + pPanelID + ')'; + } + } + } +}; + +/** + * Функция загружает json-данные о Файловой Системе + * через ajax-запрос. + * @param path - каталог для чтения + * @param pOptions + * { refresh, nohistory } - необходимость обновить данные о каталоге + */ +CloudCmd._ajaxLoad = function(pPath, pOptions){ + if(!pOptions) + pOptions = {}; + + /* Отображаем красивые пути */ + var lFSPath = decodeURI(pPath), + lNOJSPath = Util.removeStr( lFSPath, '?json' ), + lCleanPath = Util.removeStr( lNOJSPath, CloudFunc.FS ) || '/', + + lOldURL = window.location.pathname; + + Util.log ('reading dir: "' + lCleanPath + '";'); + + if(!pOptions.nohistory){ + lNOJSPath = lCleanPath === '/' ? '/' : lNOJSPath; + DOM.setHistory(lNOJSPath, null, lNOJSPath); + } + + DOM.setTitle( CloudFunc.getTitle(lCleanPath) ); + + var lPanel = DOM.getPanel().id; + /* если доступен localStorage и + * в нём есть нужная нам директория - + * читаем данные с него и + * выходим + * если стоит поле обязательной перезагрузки - + * перезагружаемся + */ + var lRet = pOptions.refresh; + if(!lRet){ + var lJSON = DOM.Cache.get(lCleanPath); + + if (lJSON){ + /* переводим из текста в JSON */ + lJSON = Util.parseJSON(lJSON); + CloudCmd._createFileTable(lPanel, lJSON, true); + CloudCmd._changeLinks(lPanel); + } + else + lRet = true; + } + + if(lRet) + DOM.getCurrentFileContent({ + url : lFSPath, + + error : function(){ + DOM.setHistory(lOldURL, null, lOldURL); + }, + + success : function(pData){ + CloudCmd._createFileTable(lPanel, pData, true); + CloudCmd._changeLinks(lPanel); + + /* переводим таблицу файлов в строку, для * + * сохранения в localStorage */ + var lJSON_s = Util.stringifyJSON(pData); + Util.log(lJSON_s.length); + + /* если размер данных не очень бошьой * + * сохраняем их в кэше */ + if(lJSON_s.length < 50000 ) + DOM.Cache.set(lCleanPath, lJSON_s); + } + }); +}; + +/** + * Функция строит файловую таблицу + * @param pEleme - родительский элемент + * @param pJSON - данные о файлах + */ +CloudCmd._createFileTable = function(pElem, pJSON, pSetCurrent){ + var lElem = DOM.getById(pElem), + /* getting current element if was refresh */ + lPath = DOM.getByClass('path', lElem), + lCurrent = DOM.getCurrentFile(), + lWasRefresh_b = lPath[0].textContent === pJSON[0].path; + + /* говорим построителю, + * что бы он в нужный момент + * выделил строку с первым файлом + */ + + /* очищаем панель */ + var i = lElem.childNodes.length; + while(i--) + lElem.removeChild(lElem.lastChild); + + /* заполняем панель новыми элементами */ + lElem.innerHTML = CloudFunc.buildFromJSON(pJSON, pSetCurrent); + + /* searching current file */ + if(lWasRefresh_b){ + for(i = 0; i < lElem.childNodes.length; i++) + if(lElem.childNodes[i].textContent === lCurrent.textContent){ + lCurrent = lElem.childNodes[i]; + break; + } + DOM.setCurrentFile(lCurrent); + } +}; + +/** + * Функция генерирует JSON из html-таблицы файлов и + * используеться при первом заходе в корень + */ +CloudCmd._getJSONfromFileTable = function(){ + var lLeft = DOM.getById('left'), + lPath = DOM.getByClass('path')[0].textContent, + + lFileTable = [{ + path:lPath, + size:'dir' + }], + + lLI = lLeft.getElementsByTagName('li'), + i, n, j = 1; /* счётчик реальных файлов */ + + /* счётчик элементов файлов в DOM */ + /* Если путь отличный от корневного + * второй элемент li - это ссылка на верхний + * каталог '..' + */ + + /* пропускам Path и Header*/ + for(i = 2, n = lLI.length; i < n; i++){ + var lCurrent = lLI[i], + + /* переводим права доступа в цыфровой вид + * для хранения в localStorage + */ + lMode = DOM.getCurrentMode(lCurrent); + lMode = CloudFunc.convertPermissionsToNumberic(lMode); + + lFileTable[ j++ ] = { + name: DOM.getCurrentName(lCurrent), + size: DOM.getCurrentSize(lCurrent), + mode: lMode + }; + } + return Util.stringifyJSON(lFileTable); +}; + +return CloudCmd; +})(Util, DOM); + + +DOM.addOneTimeListener('load', function(){ + /* базовая инициализация*/ + CloudCommander.init(); + + /* загружаем Google Analytics */ + CloudCommander.GoogleAnalytics(); +}); diff --git a/lib/client/dom.js b/lib/client/dom.js index 13272b85..c79407de 100644 --- a/lib/client/dom.js +++ b/lib/client/dom.js @@ -1,1115 +1,1477 @@ -var CloudCommander, Util, DOM, CloudFunc; - -(function(){ - "use strict"; - - DOM = {}; - - /* PRIVATE */ - - function getCurrentFile(){ - return CloudCommander.CURRENT_FILE; - } - - /** - * private function thet unset currentfile - */ - function UnSetCurrentFile(pCurrentFile){ - var lRet_b = DOM.isCurrentFile(pCurrentFile); - - if(!pCurrentFile) - DOM.addCloudStatus({ - code : -1, - msg : 'Error pCurrentFile in' + - 'unSetCurrentFile' + - 'could not be none' - }); - - if(lRet_b) - DOM.removeClass(pCurrentFile, getCurrentFile()); - - return lRet_b; - } - - /* private members */ - var XMLHTTP, - Title, - LoadingImage, - ErrorImage, - - /* Обьект, который содержит - * функции для отображения - * картинок - */ - Images_o = { - /* Функция создаёт картинку загрузки*/ - loading : function(){ - var lE = DOM.getById('loading-image'); - if (!lE) - lE = DOM.anyload({ - name : 'span', - className : 'icon loading', - id : 'loading-image', - not_append : true - }); - - LoadingImage = lE; - - return lE; - }, - - /* Функция создаёт картинку ошибки загрузки*/ - error : function(){ - var lE = DOM.getById('error-image'); - if (!lE) - lE = DOM.anyload({ - name : 'span', - className : 'icon error', - id : 'error-image', - not_append : true - }); - - return lE; - } - }; - - /** - * add class to current element - * @param pElement - * @param pClass - */ - DOM.addClass = function(pElement, pClass){ - var lRet_b = true; - - var lClassList = pElement.classList; - if(lClassList){ - if( !lClassList.contains(pClass) ) - lClassList.add(pClass); - else - lRet_b = false; - } - - return lRet_b; - }; - - /** - * safe add event listener - * @param pType - * @param pListener - * @param pUseCapture - * @param pElement {document by default} - */ - DOM.addListener = function(pType, pListener, pUseCapture, pElement){ - var lRet = this; - - (pElement || window).addEventListener( - pType, - pListener, - pUseCapture || false - ); - - return lRet; - }; - - /** - * safe add event keydown listener - * @param pListener - * @param pUseCapture - */ - DOM.addKeyListener = function(pListener, pUseCapture){ - return DOM.addListener('keydown', pListener, pUseCapture); - }; - - /** - * load file countent thrue ajax - */ - DOM.ajax = function(pParams){ - var lType = pParams.type || 'GET', - lData = pParams.data, - lSuccess_f = pParams.success; - - if(!XMLHTTP) - XMLHTTP = new XMLHttpRequest(); - - XMLHTTP.open(lType, pParams.url, true); - XMLHTTP.send(lData); - - if( !Util.isFunction(lSuccess_f) ){ - console.log('error in DOM.ajax onSuccess:', pParams); - console.log(pParams); - } - - XMLHTTP.onreadystatechange = function(pEvent){ - if (XMLHTTP.readyState === 4 /* Complete */){ - var lJqXHR = pEvent.target, - lType = XMLHTTP.getResponseHeader('content-type'); - - if (XMLHTTP.status === 200 /* OK */){ - var lData = lJqXHR.response; - - /* If it's json - parse it as json */ - if(lType && Util.isContainStr(lType, 'application/json') ){ - var lResult = Util.tryCatch(function(){ - lData = JSON.parse(lJqXHR.response); - }); - - if( Util.log(lResult) ) - lData = lJqXHR.response; - } - - lSuccess_f(lData, lJqXHR.statusText, lJqXHR); - } - else/* file not found or connection lost */{ - /* if html given or something like it - * getBack just status of result - */ - if(lType && - lType.indexOf('text/plain') !== 0){ - lJqXHR.responseText = lJqXHR.statusText; - } - Util.exec(pParams.error, lJqXHR); - } - } - }; - }; - - /** - * Обьект для работы с кэшем - * в него будут включены функции для - * работы с LocalStorage, webdb, - * indexed db etc. - */ - DOM.Cache = function(){ - /* приватный переключатель возможности работы с кэшем */ - var CacheAllowed; - - /* функция проверяет возможно ли работать с кэшем каким-либо образом */ - this.isAllowed = function(){ - return ( CacheAllowed = Util.isObject( window.localStorage ) ); - }; - - - /** - * allow cache usage - */ - this.setAllowed = function(){ - var lRet = this; - CacheAllowed = true; - - return lRet; - }; - - /** - * dissalow cache usage - */ - this.UnSetAllowed = function(){ - var lRet = this; - CacheAllowed = false; - - return lRet; - }; - - /** remove element */ - this.remove = function(pItem){ - var lRet = this; - - if(CacheAllowed) - localStorage.removeItem(pItem); - - return lRet; - }; - - /** если доступен localStorage и - * в нём есть нужная нам директория - - * записываем данные в него - */ - this.set = function(pName, pData){ - var lRet = this; - - if(CacheAllowed && pName && pData) - localStorage.setItem(pName,pData); - - return lRet; - }, - - /** Если доступен Cache принимаем из него данные*/ - this.get = function(pName){ - var lRet = this; - - if(CacheAllowed) - lRet = localStorage.getItem(pName); - - return lRet; - }, - - /* get all cache from local storage */ - this.getAll = function(){ - var lRet = null; - - if(CacheAllowed) - lRet = localStorage; - - return lRet; - }; - - /** функция чистит весь кэш для всех каталогов*/ - this.clear = function(){ - var lRet = this; - - if(CacheAllowed) - localStorage.clear(); - - return lRet; - }; - }; - - DOM.Cache = new DOM.Cache(); - - /** - * delete currentfile, prompt before it - * - * @pCurrentFile - */ - DOM.promptRemoveCurrent = function(pCurrentFile){ - var lRet, - lCurrent, - lName, - lMsg = 'Are you sure thet you wont delete '; - - /* dom element passed and it is not event */ - if(pCurrentFile && !pCurrentFile.type) - lCurrent = pCurrentFile; - - lName = DOM.getCurrentName(lCurrent); - - lRet = confirm(lMsg + lName + '?'); - - if(lRet) - DOM.removeCurrent(lCurrent); - - return lRet; - }; - - /** - * Function gets id by src - * @param pSrc - * - * Example: http://domain.com/1.js -> 1_js - */ - DOM.getIdBySrc = function(pSrc){ - var lID = pSrc.replace(pSrc.substr(pSrc, - pSrc.lastIndexOf('/')+1), - ''); - - /* убираем точки */ - while(lID.indexOf('.') > 0) - lID = lID.replace('.','_'); - - return lID; - }, - - - /** - * create elements and load them to DOM-tree - * one-by-one - * - * @param pParams_a - * @param pFunc - onload function - */ - DOM.anyLoadOnLoad = function(pParams_a, pFunc){ - var lRet = this; - - if( Util.isArray(pParams_a) ) { - var lParam = pParams_a.pop(), - lFunc = function(){ - DOM.anyLoadOnLoad(pParams_a, pFunc); - }; - - if( Util.isString(lParam) ) - lParam = { src : lParam }; - else if( Util.isArray(lParam) ){ - - DOM.anyLoadInParallel(lParam, lFunc); - } - - if(lParam && !lParam.func){ - lParam.func = lFunc; - - DOM.anyload(lParam); - - }else - Util.exec(pFunc); - } - - return lRet; - }; - - /** - * improve callback of funcs so - * we pop number of function and - * if it's last we call pCallBack - * - * @param pParams_a - * @param pFunc - onload function - */ - DOM.anyLoadInParallel = function(pParams_a, pFunc){ - var lRet = this, - done = [], - - doneFunc = function (pCallBack){ - Util.exec(pCallBack); - - if( !done.pop() ) - Util.exec(pFunc); - }; - - if( !Util.isArray(pParams_a) ){ - pParams_a = [pParams_a]; - } - - for(var i = 0, n = pParams_a.length; i < n; i++){ - var lParam = pParams_a.pop(); - - if(lParam){ - done.push(i); - - if(Util.isString(lParam) ) - lParam = { src : lParam }; - - var lFunc = lParam.func; - lParam.func = Util.retExec(doneFunc, lFunc); - - DOM.anyload(lParam); - } - } - - return lRet; - }; - - /** - * Функция создаёт элемент и загружает файл с src. - * - * @param pParams_o = { - * name, - название тэга - * src', - путь к файлу - * func, - обьект, содержаий одну из функций - * или сразу две onload и onerror - * {onload: function(){}, onerror: function();} - * style, - * id, - * element, - * async, - true by default - * inner: 'id{color:red, }, - * class, - * not_append - false by default - * } - */ - DOM.anyload = function(pParams_o){ - - if( !pParams_o ) return; - - /* if a couple of params was - * processing every of params - * and quit - */ - if( Util.isArray(pParams_o) ){ - var lElements_a = []; - for(var i = 0, n = pParams_o.length; i < n ; i++) - lElements_a[i] = DOM.anyload(pParams_o[i]); - - return lElements_a; - } - - var lName = pParams_o.name, - lID = pParams_o.id, - lClass = pParams_o.className, - lSrc = pParams_o.src, - lFunc = pParams_o.func, - lOnError, - lAsync = pParams_o.async, - lParent = pParams_o.parent, - lInner = pParams_o.inner, - lNotAppend = pParams_o.not_append; - - if ( Util.isObject(lFunc) ){ - lOnError = lFunc.onerror; - lFunc = lFunc.onload; - } - /* убираем путь к файлу, оставляя только название файла */ - if(!lID && lSrc) - lID = DOM.getIdBySrc(lSrc); - - var element = DOM.getById(lID); - - /* если скрипт еще не загружен */ - if(!element){ - if(!lName && lSrc){ - - var lDot = lSrc.lastIndexOf('.'), - lExt = lSrc.substr(lDot); - switch(lExt){ - case '.js': - lName = 'script'; - break; - case '.css': - lName = 'link'; - lParent = document.head; - break; - default: - return {code: -1, text: 'name can not be empty'}; - } - } - element = document.createElement(lName); - - if(lID) - element.id = lID; - - if(lClass) - element.className = lClass; - - /* if working with external css - * using href in any other case - * using src - */ - if(lName === 'link'){ - element.href = lSrc; - element.rel = 'stylesheet'; - }else - element.src = lSrc; - - /* - * if passed arguments function - * then it's onload by default - * - * if object - then onload and onerror - */ - - if( Util.isFunction(lFunc) ) - element.onload = lFunc; - - /* if element (js/css) will not loaded - * it would be removed from DOM tree - * and error image would be shown - */ - element.onerror = (function(){ - (pParams_o.parent || document.body) - .removeChild(element); - - DOM.Images.showError({ - responseText: 'file ' + - lSrc + - ' could not be loaded', - status : 404 - }); - - Util.exec(lOnError); - }); - - if(pParams_o.style){ - element.style.cssText = pParams_o.style; - } - - if(lAsync || lAsync === undefined) - element.async = true; - - if(!lNotAppend) - (lParent || document.body).appendChild(element); - - if(lInner){ - element.innerHTML = lInner; - } - } - /* если js-файл уже загружен - * запускаем функцию onload - */ - else - Util.exec(lFunc); - - return element; - }, - - /** - * Функция загружает js-файл - * - * @param pSrc - * @param pFunc - */ - DOM.jsload = function(pSrc, pFunc){ - if(pSrc instanceof Array){ - for(var i=0; i < pSrc.length; i++) - pSrc[i].name = 'script'; - - return DOM.anyload(pSrc); - } - - return DOM.anyload({ - name : 'script', - src : pSrc, - func : pFunc - }); - }, - - /** - * Функция создаёт елемент style и записывает туда стили - * @param pParams_o - структура параметров, заполняеться таким - * образом: {src: ' ',func: '', id: '', element: '', inner: ''} - * все параметры опциональны - */ - DOM.cssSet = function(pParams_o){ - pParams_o.name = 'style'; - pParams_o.parent = pParams_o.parent || document.head; - - return DOM.anyload(pParams_o); - }, - - /** - * Function loads external css files - * @pParams_o - структура параметров, заполняеться таким - * образом: {src: ' ',func: '', id: '', element: '', inner: ''} - * все параметры опциональны - */ - DOM.cssLoad = function(pParams_o){ - if( Util.isArray(pParams_o) ){ - for(var i = 0, n = pParams_o.length; i < n; i++){ - pParams_o[i].name = 'link'; - pParams_o[i].parent = pParams_o.parent || document.head; - } - - return DOM.anyload(pParams_o); - } - - else if( Util.isString(pParams_o) ) - pParams_o = { src: pParams_o }; - - pParams_o.name = 'link'; - pParams_o.parent = pParams_o.parent || document.head; - - return DOM.anyload(pParams_o); - }; - - /** - * load jquery from google cdn or local copy - * @param pCallBack - */ - DOM.jqueryLoad = function(pCallBack){ - /* загружаем jquery: */ - DOM.jsload('//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js',{ - onload: Util.retExec(pCallBack), - - onerror: function(){ - DOM.jsload('lib/client/jquery.js'); - - /* - * if could not load jquery from google server - * maybe we offline, load font from local - * directory - */ - DOM.cssSet({id:'local-droids-font', - element : document.head, - inner : '@font-face {font-family: "Droid Sans Mono";' + - 'font-style: normal;font-weight: normal;' + - 'src: local("Droid Sans Mono"), local("DroidSansMono"),'+ - ' url("font/DroidSansMono.woff") format("woff");}' - }); - } - }); - }; - - /** - * load socket.io - * @param pCallBack - */ - DOM.socketLoad = function(pCallBack){ - DOM.jsload('lib/client/socket.js', pCallBack); - }; - - /* DOM */ - - /** - * Function search element by tag - * @param pTag - className - * @param pElement - element - */ - DOM.getByTag = function(pTag, pElement){ - return (pElement || document).getElementsByTagName(pTag); - }; - - /** - * Function search element by id - * @param Id - className - * @param pElement - element - */ - DOM.getById = function(pId, pElement){ - return (pElement || document).getElementById(pId); - }; - - /** - * Function search element by class name - * @param pClass - className - * @param pElement - element - */ - DOM.getByClass = function(pClass, pElement){ - return (pElement || document).getElementsByClassName(pClass); - }; - - - DOM.Images = { - /** - * Function shows loading spinner - * pPosition = {top: true}; - */ - showLoad : function(pPosition){ - var lRet_b = true; - - LoadingImage = Images_o.loading(); - ErrorImage = Images_o.error(); - - DOM.hide(ErrorImage); - - var lCurrent; - if(pPosition){ - if(pPosition.top){ - lCurrent = DOM.getRefreshButton(); - if(lCurrent) - lCurrent = lCurrent.parentElement; - else - lRet_b = false; - } - } - else{ - lCurrent = DOM.getCurrentFile(); - lCurrent = lCurrent.firstChild.nextSibling; - } - - /* show loading icon - * if it not showed - * and if error was not - * heppen - */ - if(lRet_b){ - var lParent = LoadingImage.parentElement; - if(!lParent || - (lParent && lParent !== lCurrent)) - lCurrent.appendChild(LoadingImage); - - DOM.show(LoadingImage); /* показываем загрузку*/ - } - - return lRet_b; - }, - - /** - * hide load image - */ - hideLoad : function(){ - LoadingImage = Images_o.loading(); - DOM.hide(LoadingImage); - }, - - /** - * show error image (usualy after error on ajax request) - */ - showError : function(jqXHR, textStatus, errorThrown){ - LoadingImage = Images_o.loading(); - - ErrorImage = Images_o.error(); - - var lText; - if(jqXHR.status === 404) - lText = jqXHR.responseText; - else - lText = jqXHR.statusText; - - /* если файла не существует*/ - if(!lText.indexOf('Error: ENOENT, ')) - lText = lText.replace('Error: ENOENT, n','N'); - - /* если не хватает прав для чтения файла*/ - else if(!lText.indexOf('Error: EACCES,')) - lText = lText.replace('Error: EACCES, p','P'); - - DOM.show(ErrorImage); - ErrorImage.title = lText; - - var lParent = LoadingImage.parentElement; - if(lParent) - lParent.appendChild(ErrorImage); - - DOM.hide(LoadingImage); - - console.log(lText); - } - }; - - /** - * unified way to get current file - * - * @pCurrentFile - */ - DOM.getCurrentFile = function(pCurrentFile){ - var lCurrent = DOM.getByClass( pCurrentFile || getCurrentFile() )[0]; - if(!lCurrent){ - DOM.addCloudStatus({ - code : -1, - msg : 'Error: can not find ' + - 'CurrentFile ' + - 'in getCurrentFile' - }); - } - return lCurrent; - }; - - - /** - * unified way to get RefreshButton - */ - DOM.getRefreshButton = function(){ - var lPanel = DOM.getPanel(), - lRefresh = DOM.getByClass(CloudFunc.REFRESHICON, lPanel); - - if (lRefresh.length) - lRefresh = lRefresh[0]; - else { - DOM.addCloudStatus({ - code : -3, - msg : 'Error Refresh icon not found' - }); - lRefresh = false; - } - - return lRefresh; - }; - - /** - * unified way to set current file - */ - DOM.setCurrentFile = function(pCurrentFile){ - var lRet_b = true; - - if(!pCurrentFile){ - DOM.addCloudStatus({ - code : -1, - msg : 'Error pCurrentFile in' + - 'setCurrentFile' + - 'could not be none' - }); - - lRet_b = false; - } - var lCurrentFileWas = DOM.getCurrentFile(); - - if (pCurrentFile.className === 'path') - pCurrentFile = pCurrentFile.nextSibling; - - if (pCurrentFile.className === 'fm_header') - pCurrentFile = pCurrentFile.nextSibling; - - if(lCurrentFileWas) - UnSetCurrentFile(lCurrentFileWas); - - DOM.addClass(pCurrentFile, getCurrentFile()); - - /* scrolling to current file */ - DOM.scrollIntoViewIfNeeded(pCurrentFile); - - return lRet_b; - }; - - /** - * setting history wrapper - */ - DOM.setHistory = function(pData, pTitle, pUrl){ - var lRet = true; - - if(window.history) - history.pushState(pData, pTitle, pUrl); - else - lRet = false; - - return lRet; - }; - - /** - * set onclick handler on buttons f1-f10 - * @param pKey - 'f1'-'f10' - */ - DOM.setButtonKey = function(pKey, pFunc){ - return CloudCommander.KeysPanel[pKey].onclick = pFunc; - }; - - /** - * set title with pName - * create title element - * if it absent - * @param pName - */ - - DOM.setTitle = function(pName){ - if(!Title) - Title = DOM.getByTag('title')[0] || - DOM.anyload({ - name:'title', - parentElement: document.head, - innerHTML: pName - }); - if(Title) - Title.textContent = pName; - - return Title; - }; - - /** - * current file check - * - * @param pCurrentFile - */ - DOM.isCurrentFile = function(pCurrentFile){ - if(!pCurrentFile) - DOM.addCloudStatus({ - code : -1, - msg : 'Error pCurrentFile in' + - 'isCurrentFile' + - 'could not be none' - }); - - var lCurrentFileClass = pCurrentFile.className, - lIsCurrent = lCurrentFileClass.indexOf(getCurrentFile()) >= 0; - - return lIsCurrent; - }; - - - /** - * get link from current (or param) file - * - * @param pCurrentFile - current file by default - */ - DOM.getCurrentLink = function(pCurrentFile){ - var lLink = DOM.getByTag('a', - pCurrentFile || DOM.getCurrentFile()), - - lRet = lLink.length > 0 ? lLink[0] : -1; - - if(!lRet) - DOM.addCloudStatus({ - code : -1, - msg : 'Error current element do not contain links' - }); - - return lRet; - }; - - /** - * get link from current (or param) file - * - * @param pCurrentFile - current file by default - */ - DOM.getCurrentPath = function(pCurrentFile){ - var lCurrent = pCurrentFile || DOM.getCurrentFile(), - lPath = DOM.getCurrentLink(lCurrent).href; - /* убираем адрес хоста*/ - lPath = Util.removeStr(lPath, CloudCommander.HOST); - lPath = Util.removeStr(lPath, CloudFunc.NOJS); - - return lPath; - }; - - /** - * get name from current (or param) file - * - * @param pCurrentFile - */ - DOM.getCurrentName = function(pCurrentFile){ - var lLink = DOM.getCurrentLink( - pCurrentFile || DOM.getCurrentFile()); - - if(!lLink) - DOM.addCloudStatus({ - code : -1, - msg : 'Error current element do not contain links' - }); - else lLink = lLink.textContent; - - return lLink; - }; - - /** function getting FM - * @param pPanel_o = {active: true} - */ - DOM.getFM = function(){ - return DOM.getPanel().parentElement; - }; - - /** function getting panel active, or passive - * @param pPanel_o = {active: true} - */ - DOM.getPanel = function(pActive){ - var lPanel = DOM.getCurrentFile().parentElement; - - /* if {active : false} getting passive panel */ - if(pActive && !pActive.active){ - var lId = lPanel.id === 'left' ? 'right' : 'left'; - lPanel = DOM.getById(lId); - } - - /* if two panels showed - * then always work with passive - * panel - */ - if(window.innerWidth < CloudCommander.MIN_ONE_PANEL_WIDTH) - lPanel = DOM.getById('left'); - - - if(!lPanel) - console.log('Error can not find Active Panel'); - - return lPanel; - }; - - DOM.show = function(pElement){ - DOM.removeClass(pElement, 'hidden'); - }; - - /** - * shows panel right or left (or active) - */ - DOM.showPanel = function(pActive){ - var lRet = true, - lPanel = DOM.getPanel(pActive); - - if(lPanel) - DOM.show(lPanel); - else - lRet = false; - - return lRet; - }; - - /** - * hides panel right or left (or active) - */ - DOM.hidePanel = function(pActive){ - var lRet = false, - lPanel = DOM.getPanel(pActive); - - if(lPanel) - lRet = DOM.hide(lPanel); - - return lRet; - }; - - /** - * add class=hidden to element - * - * @param pElement - */ - DOM.hide = function(pElement){ - return DOM.addClass(pElement, 'hidden'); - }; - - /** - * remove child of element - * @param pChild - * @param pElement - */ - DOM.remove = function(pChild, pElement){ - return (pElement || document.body).removeChild(pChild); - }; - - /** - * remove class pClass from element pElement - * @param pElement - * @param pClass - */ - DOM.removeClass = function(pElement, pClass){ - var lRet_b = true, - lClassList = pElement.classList; - - if(pElement && lClassList) - lClassList.remove(pClass); - - else - lRet_b = false; - - return lRet_b; - }; - - /** - * remove current file from file table - * @pCurrent - */ - DOM.removeCurrent = function(pCurrent){ - var lCurrent = pCurrent || DOM.getCurrentFile(), - lParent = lCurrent.parentElement, - lName = DOM.getCurrentName(lCurrent); - - if(lCurrent && lParent){ - if(lName !== '..'){ - var lNext = lCurrent.nextSibling; - var lPrevious = lCurrent.previousSibling; - if(lNext) - DOM.setCurrentFile(lNext); - else if(lPrevious) - DOM.setCurrentFile(lPrevious); - - lParent.removeChild(lCurrent); - } - else - DOM.addCloudStatus({ - code : -1, - msg : 'Could not remove parrent dir' - }); - } - else - DOM.addCloudStatus({ - code : -1, - msg : 'Current file (or parent of current) could not be empty' - }); - - return lCurrent; - }; - - /** - * unified way to scrollIntoViewIfNeeded - * (native suporte by webkit only) - * @param pElement - */ - DOM.scrollIntoViewIfNeeded = function(pElement){ - var lRet = true; - - if(pElement && pElement.scrollIntoViewIfNeeded) - pElement.scrollIntoViewIfNeeded(); - else - lRet = false; - - return lRet; - }; - - /** - * function gets time - */ - DOM.getTime = function(){ - var date = new Date(), - hours = date.getHours(), - minutes = date.getMinutes(), - seconds = date.getSeconds(); - - minutes = minutes < 10 ? '0' + minutes : minutes; - seconds = seconds < 10 ? '0' + seconds : seconds; - - return hours + ":" + minutes + ":" + seconds; - }; - - /** - * array of all statuses of opertattions - */ - DOM.CloudStatus = []; - - /** - * adds status of operation - * @param pStatus - */ - DOM.addCloudStatus = function(pStatus){ - DOM.CloudStatus[DOM.CloudStatus.length] = pStatus; - }; -})(); \ No newline at end of file +var CloudCommander, Util, + DOM = {}, + CloudFunc; + +(function(Util, DOM){ + 'use strict'; + + /* PRIVATE */ + + /* private members */ + var /* название css-класа текущего файла*/ + CURRENT_FILE = 'current-file', + Listeners = [], + XMLHTTP, + Title, + + /* Обьект содержит функции для отображения картинок */ + Images = function (){ + var getImage = function(pName){ + var lId = pName + '-image', + lE = DOM.getById(lId); + if (!lE) + lE = DOM.anyload({ + name : 'span', + className : 'icon ' + pName, + id : lId, + not_append : true + }); + + return lE; + }; + /* Функция создаёт картинку загрузки*/ + this.loading = function(){ + return getImage('loading'); + }; + + /* Функция создаёт картинку ошибки загрузки*/ + this.error = function(){ + return getImage('error'); + }; + }, + + /* Обьект содержит функции для работы с CloudCmd API */ + RESTfull = function(){ + this.delete = function(pUrl, pCallBack){ + DOM.Images.showLoad(); + sendRequest({ + method : 'DELETE', + url : CloudFunc.FS + pUrl, + callback : pCallBack + }); + }; + + this.save = function(pUrl, pData, pCallBack){ + sendRequest({ + method : 'PUT', + url : CloudFunc.FS + pUrl, + data : pData, + callback : pCallBack + }); + }; + + this.read = function(pUrl, pCallBack){ + sendRequest({ + method : 'GET', + url : CloudFunc.FS + pUrl, + callback : pCallBack + }); + }; + + this.mv = function(pData, pCallBack){ + sendRequest({ + method : 'PUT', + url : '/mv', + data : pData, + callback : pCallBack + }); + }; + + function sendRequest(pParams){ + var lRet = Util.checkObjTrue(pParams, ['method']); + if(lRet){ + DOM.Images.showLoad(); + CloudCommander.getConfig(function(pConfig){ + var p = pParams, lData; + + if( Util.isString(p.url) ) + p.url = decodeURI(p.url); + + if( p.data && !Util.isString(p.data)) + lData = Util.stringifyJSON(p.data); + else + lData = p.data; + + p.url = pConfig && pConfig.api_url + p.url, + DOM.ajax({ + method : p.method, + url : p.url, + data : lData, + error : DOM.Images.showError, + success : function(pData){ + DOM.Images.hideLoad(); + Util.log(pData); + Util.exec(p.callback, pData); + } + }); + }); + } + + return lRet; + } + }; + + Images = new Images(); + + DOM.RESTfull = new RESTfull(); + + function removeListenerFromList(pElement){ + var lRet; + + for(var i = 0, n = Listeners.length; i < n; i++){ + if(Listeners[i].element === pElement){ + Listeners[i] = null; + break; + } + } + + return lRet; + } + + /** + * private function thet unset currentfile + * + * @pCurrentFile + */ + function unSetCurrentFile(pCurrentFile){ + var lRet_b = DOM.isCurrentFile(pCurrentFile); + + if(!pCurrentFile) + DOM.addCloudStatus({ + code : -1, + msg : 'Error pCurrentFile in' + + 'unSetCurrentFile' + + 'could not be none' + }); + + if(lRet_b) + DOM.removeClass(pCurrentFile, CURRENT_FILE); + + return lRet_b; + } + + /** + * add class to current element + * + * @param pElement + * @param pClass + */ + DOM.addClass = function(pElement, pClass){ + var lRet; + + if(pElement){ + var lClassList = pElement.classList; + + if(lClassList){ + if( !lClassList.contains(pClass) ) + lClassList.add(pClass); + lRet = true; + } + } + + return lRet; + }; + + /** + * safe add event listener + * + * @param pType + * @param pListener + * @param pUseCapture + * @param pElement {document by default} + */ + DOM.addListener = function(pType, pListener, pElement, pUseCapture){ + var lRet = this, + lElement = (pElement || window); + + if( lElement.addEventListener){ + lElement.addEventListener( + pType, + pListener, + pUseCapture + ); + + Listeners.push({ + element : lElement, + callback: pListener + }); + } + + return lRet; + }; + + /** + * safe add event listener + * + * @param pType + * @param pListener + * @param pUseCapture + * @param pElement {document by default} + */ + DOM.addOneTimeListener = function(pType, pListener, pElement, pUseCapture){ + var lRet = this, + lOneTime = function (pEvent){ + DOM.removeListener(pType, lOneTime, pElement, pUseCapture); + pListener(pEvent); + }; + + DOM.addListener(pType, lOneTime, pElement, pUseCapture); + + return lRet; + }; + + /** + * safe remove event listener + * + * @param pType + * @param pListener + * @param pUseCapture + * @param pElement {document by default} + */ + DOM.removeListener = function(pType, pListener, pElement, pUseCapture){ + var lRet = this; + + (pElement || window).removeEventListener( + pType, + pListener, + pUseCapture + ); + + return lRet; + }; + + + /** + * safe add event keydown listener + * + * @param pListener + * @param pUseCapture + */ + DOM.addKeyListener = function(pListener, pElement, pUseCapture){ + return DOM.addListener('keydown', pListener, pElement, pUseCapture); + }; + + /** + * safe add event click listener + * + * @param pListener + * @param pUseCapture + */ + DOM.addClickListener = function(pListener, pElement, pUseCapture){ + return DOM.addListener('click', pListener, pElement, pUseCapture); + }; + + DOM.addContextMenuListener = function(pListener, pElement, pUseCapture){ + return DOM.addListener('contextmenu', pListener, pElement, pUseCapture); + }; + + /** + * safe add event click listener + * + * @param pListener + * @param pUseCapture + */ + DOM.addErrorListener = function(pListener, pElement, pUseCapture){ + return DOM.addListener('error', pListener, pElement, pUseCapture); + }; + + /** + * getListener for element + * + * @param pElement + */ + DOM.getListener = function(pElement){ + var lRet; + + for(var i = 0, n = Listeners.length; i < n; i++){ + if(Listeners[i].element === pElement){ + lRet = Listeners[i].callback; + break; + } + } + + return lRet; + }; + + /** + * load file countent thrue ajax + * + * @param pParams + */ + DOM.ajax = function(pParams){ + var lRet = Util.checkObjTrue(pParams, ['url', 'success']); + if(lRet){ + var p = pParams, + lType = p.type || p.method || 'GET'; + + if(!XMLHTTP) + XMLHTTP = new XMLHttpRequest(); + + XMLHTTP.open(lType, pParams.url, true); + XMLHTTP.send(p.data); + + XMLHTTP.onreadystatechange = function(pEvent){ + if (XMLHTTP.readyState === 4 /* Complete */){ + var lJqXHR = pEvent.target, + lType = XMLHTTP.getResponseHeader('content-type'); + + if (XMLHTTP.status === 200 /* OK */){ + var lData = lJqXHR.response; + + /* If it's json - parse it as json */ + if(lType && Util.isContainStr(lType, 'application/json') ){ + var lResult = Util.tryCatch(function(){ + lData = Util.parseJSON(lJqXHR.response); + }); + + if( Util.log(lResult) ) + lData = lJqXHR.response; + } + if( Util.isFunction(p.success) ) + p.success(lData, lJqXHR.statusText, lJqXHR); + } + /* file not found or connection lost */ + else{ + /* if html given or something like thet + * getBack just status of result + */ + if(lType && lType.indexOf('text/plain') !== 0) + lJqXHR.responseText = lJqXHR.statusText; + + Util.exec(p.error, lJqXHR); + } + } + }; + } + return lRet; + }; + + /** + * Обьект для работы с кэшем + * в него будут включены функции для + * работы с LocalStorage, webdb, + * indexed db etc. + */ + DOM.Cache = function(){ + /* приватный переключатель возможности работы с кэшем */ + var CacheAllowed; + + /* функция проверяет возможно ли работать с кэшем каким-либо образом */ + this.isAllowed = function(){ + return ( CacheAllowed = Util.isObject( window.localStorage ) ); + }; + + + /** + * allow cache usage + */ + this.setAllowed = function(){ + var lRet = this; + CacheAllowed = true; + + return lRet; + }; + + /** + * dissalow cache usage + */ + this.UnSetAllowed = function(){ + var lRet = this; + CacheAllowed = false; + + return lRet; + }; + + /** remove element */ + this.remove = function(pItem){ + var lRet = this; + + if(CacheAllowed) + localStorage.removeItem(pItem); + + return lRet; + }; + + /** если доступен localStorage и + * в нём есть нужная нам директория - + * записываем данные в него + */ + this.set = function(pName, pData){ + var lRet = this; + + if(CacheAllowed && pName && pData) + localStorage.setItem(pName,pData); + + return lRet; + }, + + /** Если доступен Cache принимаем из него данные*/ + this.get = function(pName){ + var lRet = this; + + if(CacheAllowed) + lRet = localStorage.getItem(pName); + + return lRet; + }, + + /* get all cache from local storage */ + this.getAll = function(){ + var lRet = null; + + if(CacheAllowed) + lRet = localStorage; + + return lRet; + }; + + /** функция чистит весь кэш для всех каталогов*/ + this.clear = function(){ + var lRet = this; + + if(CacheAllowed) + localStorage.clear(); + + return lRet; + }; + }; + + DOM.Cache = new DOM.Cache(); + + /** + * delete currentfile, prompt before it + * + * @pCurrentFile + */ + DOM.promptDeleteCurrent = function(pCurrentFile){ + var lRet, + lCurrent, + lName, + lMsg = 'Are you sure thet you wont delete '; + + /* dom element passed and it is not event */ + if( Util.isObject(pCurrentFile) && !pCurrentFile.type) + lCurrent = pCurrentFile; + + lName = DOM.getCurrentName(lCurrent); + + lRet = confirm(lMsg + lName + '?'); + + if(lRet) + DOM.deleteCurrent(lCurrent); + + return lRet; + }; + + /** + * Function gets id by src + * @param pSrc + * + * Example: http://domain.com/1.js -> 1_js + */ + DOM.getIdBySrc = function(pSrc){ + var lRet = Util.isString(pSrc); + + if(lRet){ + var lNum = pSrc.lastIndexOf('/') + 1, + lSub = pSrc.substr(pSrc, lNum), + lID = Util.removeStr(pSrc, lSub ); + + /* убираем точки */ + while(lID.indexOf('.') > 0) + lID = lID.replace('.', '_'); + + lRet = lID; + } + + return lRet; + }, + + /** + * create elements and load them to DOM-tree + * one-by-one + * + * @param pParams_a + * @param pFunc - onload function + */ + DOM.anyLoadOnLoad = function(pParams_a, pFunc){ + var lRet = this; + + if( Util.isArray(pParams_a) ) { + var lParam = pParams_a.pop(), + lFunc = function(){ + DOM.anyLoadOnLoad(pParams_a, pFunc); + }; + + if( Util.isString(lParam) ) + lParam = { src : lParam }; + else if( Util.isArray(lParam) ){ + + DOM.anyLoadInParallel(lParam, lFunc); + } + + if(lParam && !lParam.func){ + lParam.func = lFunc; + + DOM.anyload(lParam); + + }else + Util.exec(pFunc); + } + + return lRet; + }; + + /** + * improve callback of funcs so + * we pop number of function and + * if it's last we call pCallBack + * + * @param pParams_a + * @param pFunc - onload function + */ + DOM.anyLoadInParallel = function(pParams_a, pFunc){ + var lRet = this, + done = [], + + doneFunc = function (pCallBack){ + Util.exec(pCallBack); + + if( !done.pop() ) + Util.exec(pFunc); + }; + + if( !Util.isArray(pParams_a) ){ + pParams_a = [pParams_a]; + } + + for(var i = 0, n = pParams_a.length; i < n; i++){ + var lParam = pParams_a.pop(); + + if(lParam){ + done.push(i); + + if(Util.isString(lParam) ) + lParam = { src : lParam }; + + var lFunc = lParam.func; + lParam.func = Util.retExec(doneFunc, lFunc); + + DOM.anyload(lParam); + } + } + + return lRet; + }; + + /** + * Функция создаёт элемент и загружает файл с src. + * + * @param pParams_o = { + * name, - название тэга + * src', - путь к файлу + * func, - обьект, содержаий одну из функций + * или сразу две onload и onerror + * {onload: function(){}, onerror: function();} + * style, + * id, + * element, + * async, - true by default + * inner: 'id{color:red, }, + * class, + * not_append - false by default + * } + */ + DOM.anyload = function(pParams_o){ + + if( !pParams_o ) return; + + /* if a couple of params was + * processing every of params + * and quit + */ + if( Util.isArray(pParams_o) ){ + var lElements_a = []; + for(var i = 0, n = pParams_o.length; i < n ; i++) + lElements_a[i] = DOM.anyload(pParams_o[i]); + + return lElements_a; + } + + var lName = pParams_o.name, + lID = pParams_o.id, + lClass = pParams_o.className, + lSrc = pParams_o.src, + lFunc = pParams_o.func, + lOnError, + lAsync = pParams_o.async, + lParent = pParams_o.parent || document.body, + lInner = pParams_o.inner, + lStyle = pParams_o.style, + lNotAppend = pParams_o.not_append; + + if ( Util.isObject(lFunc) ){ + lOnError = lFunc.onerror; + lFunc = lFunc.onload; + } + /* убираем путь к файлу, оставляя только название файла */ + if(!lID && lSrc) + lID = DOM.getIdBySrc(lSrc); + + var lElement = DOM.getById(lID); + + /* если скрипт еще не загружен */ + if(!lElement){ + if(!lName && lSrc){ + + var lDot = lSrc.lastIndexOf('.'), + lExt = lSrc.substr(lDot); + switch(lExt){ + case '.js': + lName = 'script'; + break; + case '.css': + lName = 'link'; + lParent = document.head; + break; + default: + return {code: -1, text: 'name can not be empty'}; + } + } + lElement = document.createElement(lName); + + if(lID) + lElement.id = lID; + + if(lClass) + lElement.className = lClass; + + /* if working with external css + * using href in any other case + * using src + */ + if(lName === 'link'){ + lElement.href = lSrc; + lElement.rel = 'stylesheet'; + }else + lElement.src = lSrc; + + /* + * if passed arguments function + * then it's onload by default + * + * if object - then onload and onerror + */ + + var lLoad = function(pEvent){ + DOM.removeListener('load', lLoad, lElement); + DOM.removeListener('error', lError, lElement); + + Util.exec(lFunc, pEvent); + }, + + lError = function(){ + lParent.removeChild(lElement); + + DOM.Images.showError({ + responseText: 'file ' + + lSrc + + ' could not be loaded', + status : 404 + }); + + Util.exec(lOnError); + }; + + DOM.addListener('load', lLoad, lElement); + DOM.addErrorListener(lError, lElement); + + if(lStyle) + lElement.style.cssText = lStyle; + + if(lAsync || lAsync === undefined) + lElement.async = true; + + if(!lNotAppend) + lParent.appendChild(lElement); + + if(lInner) + lElement.innerHTML = lInner; + } + /* если js-файл уже загружен + * запускаем функцию onload + */ + else + Util.exec(lFunc); + + return lElement; + }, + + /** + * Функция загружает js-файл + * + * @param pSrc + * @param pFunc + */ + DOM.jsload = function(pSrc, pFunc){ + if( Util.isArray(pSrc) ){ + for(var i=0; i < pSrc.length; i++) + pSrc[i].name = 'script'; + + return DOM.anyload(pSrc); + } + + return DOM.anyload({ + name : 'script', + src : pSrc, + func : pFunc + }); + }, + + /** + * returns jsload functions + */ + DOM.retJSLoad = function(pSrc, pFunc){ + var lRet = function(){ + return DOM.jsload(pSrc, pFunc); + }; + + return lRet; + }, + + + /** + * Функция создаёт елемент style и записывает туда стили + * @param pParams_o - структура параметров, заполняеться таким + * образом: {src: ' ',func: '', id: '', element: '', inner: ''} + * все параметры опциональны + */ + DOM.cssSet = function(pParams_o){ + pParams_o.name = 'style'; + pParams_o.parent = pParams_o.parent || document.head; + + return DOM.anyload(pParams_o); + }, + + /** + * Function loads external css files + * @pParams_o - структура параметров, заполняеться таким + * образом: {src: ' ',func: '', id: '', element: '', inner: ''} + * все параметры опциональны + */ + DOM.cssLoad = function(pParams_o){ + if( Util.isArray(pParams_o) ){ + for(var i = 0, n = pParams_o.length; i < n; i++){ + pParams_o[i].name = 'link'; + pParams_o[i].parent = pParams_o.parent || document.head; + } + + return DOM.anyload(pParams_o); + } + + else if( Util.isString(pParams_o) ) + pParams_o = { src: pParams_o }; + + pParams_o.name = 'link'; + pParams_o.parent = pParams_o.parent || document.head; + + return DOM.anyload(pParams_o); + }; + + /** + * load jquery from google cdn or local copy + * @param pCallBack + */ + DOM.jqueryLoad = function(pCallBack){ + /* загружаем jquery: */ + DOM.jsload('//code.jquery.com/jquery-1.9.0.min.js',{ + onload: Util.retExec(pCallBack), + + onerror: function(){ + DOM.jsload('lib/client/jquery.js'); + + /* + * if could not load jquery from google server + * maybe we offline, load font from local + * directory + */ + DOM.cssSet({ + id :'local-droids-font', + element : document.head, + inner : '@font-face {font-family: "Droid Sans Mono";' + + 'font-style: normal;font-weight: normal;' + + 'src: local("Droid Sans Mono"), local("DroidSansMono"),'+ + ' url("font/DroidSansMono.woff") format("woff");}' + }); + } + }); + }; + + /** + * load socket.io + * @param pCallBack + */ + DOM.socketLoad = function(pCallBack){ + DOM.jsload('/lib/client/socket.js', Util.retExec(pCallBack) ); + }; + + /* DOM */ + + /** + * Function search element by tag + * @param pTag - className + * @param pElement - element + */ + DOM.getByTag = function(pTag, pElement){ + return (pElement || document).getElementsByTagName(pTag); + }; + + /** + * Function search element by id + * @param Id - className + * @param pElement - element + */ + DOM.getById = function(pId, pElement){ + return (pElement || document).getElementById(pId); + }; + + /** + * Function search element by class name + * @param pClass - className + * @param pElement - element + */ + DOM.getByClass = function(pClass, pElement){ + return (pElement || document).getElementsByClassName(pClass); + }; + + + DOM.Images = { + /** + * Function shows loading spinner + * pPosition = {top: true}; + */ + showLoad : function(pPosition){ + var lRet_b, + lLoadingImage = Images.loading(), + lErrorImage = Images.error(); + + DOM.hide(lErrorImage); + + var lCurrent; + if(pPosition && pPosition.top) + lCurrent = DOM.getRefreshButton().parentElement; + else + lCurrent = DOM.getCurrentFile().firstChild.nextSibling; + + /* show loading icon if it not showed */ + + var lParent = lLoadingImage.parentElement; + if(!lParent || (lParent && lParent !== lCurrent)) + lCurrent.appendChild(lLoadingImage); + + lRet_b = DOM.show(lLoadingImage); /* показываем загрузку*/ + + return lRet_b; + }, + + /** + * hide load image + */ + hideLoad : function(){ + + DOM.hide( Images.loading() ); + }, + + /** + * show error image (usualy after error on ajax request) + */ + showError : function(jqXHR, textStatus, errorThrown){ + var lLoadingImage = Images.loading(), + lErrorImage = Images.error(), + lResponce = jqXHR.responseText, + lStatusText = jqXHR.statusText, + lStatus = jqXHR.status, + lText = (lStatus === 404 ? lResponce : lStatusText); + + /* если файла не существует*/ + if( Util.isContainStr(lText, 'Error: ENOENT, ') ) + lText = lText.replace('Error: ENOENT, n','N'); + + /* если не хватает прав для чтения файла*/ + else if( Util.isContainStr(lText, 'Error: EACCES,') ) + lText = lText.replace('Error: EACCES, p','P'); + + + DOM.show(lErrorImage); + lErrorImage.title = lText; + + var lParent = lLoadingImage.parentElement; + if(lParent) + lParent.appendChild(lErrorImage); + + DOM.hide(lLoadingImage); + + Util.log(lText); + } + }; + + /** + * get current direcotory name + */ + DOM.getCurrentDirName = function(){ + var lRet, + lSubstr, + lPanel = DOM.getPanel(), + /* получаем имя каталога в котором находимся */ + lHref = DOM.getByClass('path', lPanel); + + lHref = lHref[0].textContent; + + lHref = CloudFunc.removeLastSlash(lHref); + lSubstr = lHref.substr(lHref , lHref.lastIndexOf('/')); + lRet = Util.removeStr(lHref, lSubstr + '/') || '/'; + + return lRet; + }; + + /** + * get current direcotory path + */ + DOM.getCurrentDirPath = function(){ + var lPath = DOM.getByClass('path')[0], + lRet; + + if(lPath) + lRet = lPath.textContent; + + return lRet; + }; + + /** + * unified way to get current file + * + * @pCurrentFile + */ + DOM.getCurrentFile = function(){ + var lRet = DOM.getByClass(CURRENT_FILE )[0]; + + return lRet; + }; + + /** + * + * @pCurrentFile + */ + DOM.getCurrentSize = function(pCurrentFile){ + var lRet, + lCurrent = pCurrentFile || DOM.getCurrentFile(), + lSize = DOM.getByClass('size', lCurrent); + lSize = lSize[0].textContent; + /* если это папка - возвращаем слово dir вместо размера*/ + lRet = Util.removeStr(lSize, ['<', '>']); + + return lRet; + }; + + /** + * + * @pCurrentFile + */ + DOM.getCurrentMode = function(pCurrentFile){ + var lRet, + lCurrent = pCurrentFile || DOM.getCurrentFile(), + lMode = DOM.getByClass('mode', lCurrent); + lRet = lMode[0].textContent; + + return lRet; + }; + + /** + * unified way to get current file content + * + * @pCallBack - callback function or data struct {sucess, error} + * @pCurrentFile + */ + DOM.getCurrentFileContent = function(pParams, pCurrentFile){ + var lRet, + lCurrentFile = pCurrentFile ? pCurrentFile : DOM.getCurrentFile(), + lParams = pParams ? pParams : {}, + lPath = DOM.getCurrentPath(lCurrentFile), + lErrorWas = pParams.error, + lError = function(jqXHR){ + Util.exec(lErrorWas); + DOM.Images.showError(jqXHR); + }; + if( Util.isFunction(lParams) ) + lParams.success = Util.retExec(pParams); + + lParams.error = lError; + + + if( DOM.isCurrentIsDir(lCurrentFile) ) + lPath += '?json'; + + if(!lParams.url) + lParams.url = CloudFunc.FS + lPath; + + lRet = DOM.ajax(lParams); + + return lRet; + }; + + /** + * unified way to get current file content + * + * @pCallBack - function({data, name}){} + * @pCurrentFile + */ + DOM.getCurrentData = function(pCallBack, pCurrentFile){ + + var lParams, + lCurrentFile = pCurrentFile ? pCurrentFile : DOM.getCurrentFile(), + lFunc = function(pData){ + var lName = DOM.getCurrentName(lCurrentFile); + if( Util.isObject(pData) ){ + pData = Util.stringifyJSON(pData); + + var lExt = '.json'; + if( !Util.checkExtension(lName, lExt) ) + lName += lExt; + } + + Util.exec(pCallBack, { + data: pData, + name: lName + }); + }; + + if( !Util.isObject(pCallBack) ) + lParams = lFunc; + else + lParams = { + success : lFunc, + error : pCallBack.error + }; + + + return DOM.getCurrentFileContent(lParams, lCurrentFile); + }; + + /** + * unified way to get RefreshButton + */ + DOM.getRefreshButton = function(){ + var lPanel = DOM.getPanel(), + lRefresh = DOM.getByClass(CloudFunc.REFRESHICON, lPanel); + + if (lRefresh.length) + lRefresh = lRefresh[0]; + else { + DOM.addCloudStatus({ + code : -3, + msg : 'Error Refresh icon not found' + }); + lRefresh = false; + } + + return lRefresh; + }; + + + /** + * unified way to set current file + */ + DOM.setCurrentFile = function(pCurrentFile){ + var lRet, + lCurrentFileWas = DOM.getCurrentFile(); + + if(pCurrentFile){ + if (pCurrentFile.className === 'path') + pCurrentFile = pCurrentFile.nextSibling; + + if (pCurrentFile.className === 'fm-header') + pCurrentFile = pCurrentFile.nextSibling; + + if(lCurrentFileWas) + unSetCurrentFile(lCurrentFileWas); + + DOM.addClass(pCurrentFile, CURRENT_FILE); + + /* scrolling to current file */ + DOM.scrollIntoViewIfNeeded(pCurrentFile); + + lRet = true; + } + + return lRet; + }; + + /** + * setting history wrapper + */ + DOM.setHistory = function(pData, pTitle, pUrl){ + var lRet = true; + + if(window.history) + history.pushState(pData, pTitle, pUrl); + else + lRet = false; + + return lRet; + }; + + /** + * set onclick handler on buttons f1-f10 + * @param pKey - 'f1'-'f10' + */ + DOM.setButtonKey = function(pKey, pFunc){ + return CloudCommander.KeysPanel[pKey].onclick = pFunc; + }; + + /** + * set title with pName + * create title element + * if it absent + * @param pName + */ + + DOM.setTitle = function(pName){ + if(!Title) + Title = DOM.getByTag('title')[0] || + DOM.anyload({ + name:'title', + parentElement: document.head, + innerHTML: pName + }); + if(Title) + Title.textContent = pName; + + return Title; + }; + + /** + * current file check + * + * @param pCurrentFile + */ + DOM.isCurrentFile = function(pCurrentFile){ + var lClass = pCurrentFile && pCurrentFile.className, + lIsCurrent = lClass && lClass.indexOf(CURRENT_FILE) >= 0; + + return lIsCurrent; + }; + + /** + * check is current file is a directory + * + * @param pCurrentFile + */ + DOM.isCurrentIsDir = function(pCurrentFile){ + var lSize = DOM.getCurrentSize(pCurrentFile), + lRet = lSize === 'dir'; + + return lRet; + }; + + + /** + * get link from current (or param) file + * + * @param pCurrentFile - current file by default + */ + DOM.getCurrentLink = function(pCurrentFile){ + var lLink = DOM.getByTag( 'a', pCurrentFile || DOM.getCurrentFile() ), + + lRet = lLink.length > 0 ? lLink[0] : -1; + + return lRet; + }; + + /** + * get link from current (or param) file + * + * @param pCurrentFile - current file by default + */ + DOM.getCurrentPath = function(pCurrentFile){ + var lCurrent = pCurrentFile || DOM.getCurrentFile(), + lPath = DOM.getCurrentLink( lCurrent ).href; + /* убираем адрес хоста*/ + lPath = Util.removeStr( lPath, [CloudCommander.HOST, CloudFunc.FS] ); + + return lPath; + }; + + /** + * get name from current (or param) file + * + * @param pCurrentFile + */ + DOM.getCurrentName = function(pCurrentFile){ + var lCurrent = pCurrentFile || DOM.getCurrentFile(), + lLink = DOM.getCurrentLink( lCurrent ); + + if( Util.isObject(lLink) ) + lLink = lLink.title || lLink.textContent; + + return lLink; + }; + + /** + * set name from current (or param) file + * + * @param pCurrentFile + */ + DOM.setCurrentName = function(pName, pCurrentFile){ + var lCurrent = pCurrentFile || DOM.getCurrentFile(), + lLink = DOM.getCurrentLink( lCurrent ); + + if(lLink) + lLink.title = lLink.textContent = pName; + + return lLink; + }; + + /** function getting FM + * @param pPanel_o = {active: true} + */ + DOM.getFM = function(){ + return DOM.getPanel().parentElement; + }; + + /** function getting panel active, or passive + * @param pPanel_o = {active: true} + */ + DOM.getPanel = function(pActive){ + var lPanel = DOM.getCurrentFile().parentElement; + + /* if {active : false} getting passive panel */ + if(pActive && !pActive.active){ + var lId = lPanel.id === 'left' ? 'right' : 'left'; + lPanel = DOM.getById(lId); + } + + /* if two panels showed + * then always work with passive + * panel + */ + if(window.innerWidth < CloudCommander.MIN_ONE_PANEL_WIDTH) + lPanel = DOM.getById('left'); + + + if(!lPanel) + Util.log('Error can not find Active Panel'); + + return lPanel; + }; + + /** prevent default event */ + DOM.preventDefault = function(pEvent){ + var lRet, + lPreventDefault = pEvent && pEvent.preventDefault, + lFunc = Util.bind(lPreventDefault, pEvent); + + lRet = Util.exec(lFunc); + + return lRet; + }; + + DOM.show = function(pElement){ + DOM.removeClass(pElement, 'hidden'); + }; + + /** + * shows panel right or left (or active) + */ + DOM.showPanel = function(pActive){ + var lRet = true, + lPanel = DOM.getPanel(pActive); + + if(lPanel) + DOM.show(lPanel); + else + lRet = false; + + return lRet; + }; + + /** + * hides panel right or left (or active) + */ + DOM.hidePanel = function(pActive){ + var lRet = false, + lPanel = DOM.getPanel(pActive); + + if(lPanel) + lRet = DOM.hide(lPanel); + + return lRet; + }; + + /** + * add class=hidden to element + * + * @param pElement + */ + DOM.hide = function(pElement){ + return DOM.addClass(pElement, 'hidden'); + }; + + /** + * open window with URL + * @param pUrl + */ + DOM.openWindow = function(pUrl){ + var left = 140, + top = 187, + width = 1000, + height = 650, + + lOptions = 'left=' + left + + ',top=' + top + + ',width=' + width + + ',height=' + height + + ',personalbar=0,toolbar=0' + + ',scrollbars=1,resizable=1'; + + var lWind = window.open(pUrl, 'Cloud Commander Auth', lOptions); + if(!lWind) + Util.log('Pupup blocked!'); + }; + + /** + * remove child of element + * @param pChild + * @param pElement + */ + DOM.remove = function(pChild, pElement){ + return (pElement || document.body).removeChild(pChild); + }; + + /** + * remove class pClass from element pElement + * @param pElement + * @param pClass + */ + DOM.removeClass = function(pElement, pClass){ + var lRet_b = true, + lClassList = pElement.classList; + + if(pElement && lClassList) + lClassList.remove(pClass); + + else + lRet_b = false; + + return lRet_b; + }; + + /** + * remove current file from file table + * @pCurrent + */ + DOM.deleteCurrent = function(pCurrent){ + var lCurrent = pCurrent || DOM.getCurrentFile(), + lParent = lCurrent.parentElement, + lName = DOM.getCurrentName(lCurrent), + lUrl = DOM.getCurrentPath(lCurrent); + + if( DOM.isCurrentIsDir(lCurrent) ) + lUrl += '?dir'; + + if(lCurrent && lParent && lName !== '..') + DOM.RESTfull.delete(lUrl, function(){ + var lNext = lCurrent.nextSibling, + lPrevious = lCurrent.previousSibling; + + if(lNext) + DOM.setCurrentFile(lNext); + else if(lPrevious) + DOM.setCurrentFile(lPrevious); + + lParent.removeChild(lCurrent); + }); + + return lCurrent; + }; + + /** + * rename current file + * + * @pCurrent + */ + DOM.renameCurrentFile = function(pCurrentFile){ + if( !DOM.isCurrentFile(pCurrentFile) ) + pCurrentFile = null; + + var lCurrent = pCurrentFile || DOM.getCurrentFile(), + lFrom = DOM.getCurrentName(lCurrent), + lTo = prompt("Rename", lFrom) || lFrom, + lDirPath = DOM.getCurrentDirPath(); + if( !Util.strCmp(lFrom, lTo) ){ + var lFiles = { + from : lDirPath + lFrom, + to : lDirPath + lTo + }; + + DOM.RESTfull.mv(lFiles, function(){ + DOM.setCurrentName(lTo, lCurrent); + }); + } + }; + + /** + * unified way to scrollIntoViewIfNeeded + * (native suporte by webkit only) + * @param pElement + */ + DOM.scrollIntoViewIfNeeded = function(pElement){ + var lRet = true; + + if(pElement && pElement.scrollIntoViewIfNeeded) + pElement.scrollIntoViewIfNeeded(); + else + lRet = false; + + return lRet; + }; + + /* scroll on one page*/ + DOM.scrollByPages = function(pElement, pPages){ + var lRet = true; + + if(pElement && pElement.scrollByPages && pPages) + pElement.scrollByPages(pPages); + else + lRet = false; + + return lRet; + }; + + /** + * function gets time + */ + DOM.getTime = function(){ + var date = new Date(), + hours = date.getHours(), + minutes = date.getMinutes(), + seconds = date.getSeconds(); + + minutes = minutes < 10 ? '0' + minutes : minutes; + seconds = seconds < 10 ? '0' + seconds : seconds; + + return hours + ":" + minutes + ":" + seconds; + }; + + /** + * array of all statuses of opertattions + */ + DOM.CloudStatus = []; + + /** + * adds status of operation + * @param pStatus + */ + DOM.addCloudStatus = function(pStatus){ + DOM.CloudStatus[DOM.CloudStatus.length] = pStatus; + }; +})(Util, DOM); \ No newline at end of file diff --git a/lib/client/editor/_ace.js b/lib/client/editor/_ace.js index 6ff8cd18..75097f2f 100644 --- a/lib/client/editor/_ace.js +++ b/lib/client/editor/_ace.js @@ -107,17 +107,12 @@ var CloudCommander, CloudFunc, ace; /* if directory - load json * not html data */ - if (lSize === ''){ - if (lA.indexOf(CloudFunc.NOJS) === - CloudFunc.FS.length) { - lA = lA.replace(CloudFunc.NOJS, ''); - /* when folder view - * is no need to edit - * data - */ - ReadOnly = true; - } - } + if (lSize === '') + /* when folder view + * is no need to edit + * data + */ + ReadOnly = true; } this.loading = true; diff --git a/lib/client/editor/_codemirror.js b/lib/client/editor/_codemirror.js index 82141574..6739c6d6 100644 --- a/lib/client/editor/_codemirror.js +++ b/lib/client/editor/_codemirror.js @@ -1,240 +1,214 @@ -var CloudCommander, Util, DOM, CodeMirror; -/* object contains editors CodeMirror */ - (function(){ - "use strict"; - var cloudcmd = CloudCommander, - KeyBinding = CloudCommander.KeyBinding, - CodeMirrorEditor = {}, - FM, - CodeMirrorElement, - CodeMirrorLoaded = false, - /* indicator says CodeMirror still loads */ - Loading = false, - ReadOnly = false, - - CallBacks = [ - hide, - initCodeMirror, - show, - load - ]; - - cloudcmd.Editor = { - get : (function(){ - return this.CodeMirror; - }) - }; - - /* private functions */ - - function setCSS(){ - var lPosition = DOM.getPanel().id, - lRet = DOM.cssSet({ - id : 'editor', - inner : '.CodeMirror{' + - 'font-family' + ': \'Droid Sans Mono\';' + - 'font-size' + ': 15px;' + - '}' + - '.CodeMirror-scroll{' + - 'height' + ':' + cloudcmd.HEIGHT + 'px' + - '}' + - '#CodeMirrorEditor{' + - 'float' + ':' + lPosition + - '}' - }); - - return lRet; - } - - /** - * function initialize CodeMirror - * @param {value, callback} - */ - function initCodeMirror(pData){ - if(!pData) - pData = {}; - - if(!FM) - FM = DOM.getFM(); - - var lCSS = setCSS(); - - CodeMirrorElement = DOM.anyload({ - name : 'div', - id : 'CodeMirrorEditor', - className : 'panel', - parent : FM - }); - - CodeMirrorEditor.CodeMirror = new CodeMirror(CodeMirrorElement,{ - mode : 'javascript', - value : pData.data, - theme : 'night', - lineNumbers : true, - //переносим длинные строки - lineWrapping: false, - autofocus : true, - extraKeys: { - //Сохранение - 'Esc': function(){ - Util.exec(pData.callback); - DOM.remove(lCSS, document.head); - } - }, - readOnly : ReadOnly - }); - } - - /** - * function loads CodeMirror js and css files - */ - function load(pCallBack){ - console.time('codemirror load'); - var lDir = cloudcmd.LIBDIRCLIENT + 'editor/codemirror/', - lFiles = - [ - [ - lDir + 'codemirror.css', - lDir + 'theme/night.css', - lDir + 'mode/javascript.js', - ], - - lDir + 'codemirror.js' - ]; - - DOM.anyLoadOnLoad(lFiles, function(){ - console.timeEnd('codemirror load'); - CodeMirrorLoaded = true; - Util.exec(pCallBack); - }); - } - - /** - * function shows CodeMirror editor - */ - function show(pCallBack){ - - /* if CodeMirror function show already - * called do not call it again - * if f4 key pressed couple times - */ - if(Loading) - return; - - /* getting link */ - var lCurrentFile = DOM.getCurrentFile(), - lPath = DOM.getCurrentPath(lCurrentFile); - - /* checking is this link is to directory */ - var lSize = DOM.getByClass('size', lCurrentFile); - if(lSize){ - lSize = lSize[0].textContent; - - /* when folder view - * is no need to edit - * data - */ - if (lSize === '') - ReadOnly = true; - - } - - Loading = true; - setTimeout(function(){ - Loading = false; - }, - 400); - - /* reading data from current file */ - DOM.ajax({ - url:lPath, - error: function(jqXHR, textStatus, errorThrown){ - Loading = false; - return DOM.Images.showError(jqXHR); - }, - - success:function(data, textStatus, jqXHR){ - /* if we got json - show it */ - if(typeof data === 'object') - data = JSON.stringify(data, null, 4); - - var lHided = DOM.hidePanel(); - if(lHided){ - Util.exec(pCallBack, data); - - /* removing keyBinding if set */ - KeyBinding.unSet(); - } - - DOM.Images.hideLoad(); - - Loading = false; - } - }); - } - - /** - * function hides CodeMirror editor - */ - function hide() { - var lElem = CodeMirrorElement; - KeyBinding.set(); - - if(lElem && FM) - FM.removeChild(lElem); - - DOM.showPanel(); - } - - - /** - * function calls all CodeMirror editor functions - */ - CodeMirrorEditor.show = function(){ - DOM.Images.showLoad(); - Util.loadOnLoad( CallBacks ); - }; - - /** - * function hides CodeMirror editor - */ - CodeMirrorEditor.hide = hide; - - /** - * function bind keys - */ - cloudcmd.Editor.init = function(pReadOnly){ - ReadOnly = pReadOnly; - - CodeMirrorEditor.show(); - CallBacks.pop(); - - var lKeyListener = function(pEvent){ - /* если клавиши можно обрабатывать */ - if( KeyBinding.get() ){ - /* if f4 or f3 pressed */ - var lF3 = cloudcmd.KEY.F3, - lF4 = cloudcmd.KEY.F4; - - if(!pEvent.shiftKey) - switch(pEvent.keyCode) - { - case lF4: - ReadOnly = false; - CodeMirrorEditor.show(); - break; - case lF3: - ReadOnly = true; - CodeMirrorEditor.show(); - break; - } - } - }; - - /* добавляем обработчик клавишь */ - DOM.addKeyListener( lKeyListener ); - DOM.setButtonKey('f4', CodeMirrorEditor.show); - }; - - cloudcmd.Editor.CodeMirror = CodeMirrorEditor; -})(); \ No newline at end of file +var CloudCommander, Util, DOM, CloudFunc, CodeMirror; +/* object contains editors CodeMirror */ + (function(CloudCmd, Util, DOM, CloudFunc){ + 'use strict'; + + var KeyBinding = CloudCommander.KeyBinding, + CodeMirrorEditor = {}, + FM, + CodeMirrorElement, + CodeMirrorLoaded = false, + /* indicator says CodeMirror still loads */ + Loading = false, + ReadOnly = false, + + CallBacks = [ + hide, + initCodeMirror, + show, + load + ]; + + CloudCmd.Editor = { + get : (function(){ + return this.CodeMirror; + }) + }; + + /* private functions */ + + function setCSS(){ + var lPosition = DOM.getPanel().id, + lRet = DOM.cssSet({ + id : 'editor', + inner : '.CodeMirror{' + + 'font-family' + ': \'Droid Sans Mono\';' + + 'font-size' + ': 15px;' + + '}' + + '.CodeMirror-scroll{' + + 'height' + ':' + CloudCmd.HEIGHT + 'px' + + '}' + + '#CodeMirrorEditor{' + + 'float' + ':' + lPosition + + '}' + }); + + return lRet; + } + + /** + * function initialize CodeMirror + * @param {value, callback} + */ + function initCodeMirror(pParams){ + if(!FM) + FM = DOM.getFM(); + + var lCSS = setCSS(); + + CodeMirrorElement = DOM.anyload({ + name : 'div', + id : 'CodeMirrorEditor', + className : 'panel', + parent : FM + }); + + var lEditor = CodeMirrorEditor.CodeMirror = new CodeMirror(CodeMirrorElement,{ + mode : 'javascript', + value : pParams && pParams.data && pParams.data.data, + theme : 'night', + lineNumbers : true, + //переносим длинные строки + lineWrapping: false, + autofocus : true, + extraKeys: { + //Сохранение + 'Esc': function(){ + Util.exec(pParams); + DOM.remove(lCSS, document.head); + }, + 'Ctrl-S': function(){ + DOM.RESTfull.save(DOM.getCurrentPath(), lEditor.getValue()); + } + }, + readOnly : ReadOnly + }); + } + + /** + * function loads CodeMirror js and css files + */ + function load(pCallBack){ + console.time('codemirror load'); + var lDir = CloudCmd.LIBDIRCLIENT + 'editor/codemirror/', + lFiles = + [ + [ + lDir + 'codemirror.css', + lDir + 'theme/night.css', + lDir + 'mode/javascript.js', + ], + + lDir + 'codemirror.js' + ]; + + DOM.anyLoadOnLoad(lFiles, function(){ + console.timeEnd('codemirror load'); + CodeMirrorLoaded = true; + Util.exec(pCallBack); + }); + } + + /** + * function shows CodeMirror editor + */ + function show(pCallBack){ + + /* if CodeMirror function show already + * called do not call it again + * if f4 key pressed couple times + */ + if(Loading) + return; + + /* checking is this link is to directory + * when folder view is no need to edit data + */ + if ( DOM.getCurrentSize() === '' ) + ReadOnly = true; + + Loading = true; + + var lFalseLoading = function(){ Loading = false; }; + + setTimeout(lFalseLoading, 400); + /* reading data from current file */ + DOM.getCurrentData({ + error : lFalseLoading, + success : function(data){ + if( DOM.hidePanel() ){ + Util.exec(pCallBack, data); + KeyBinding.unSet(); + } + + DOM.Images.hideLoad(); + lFalseLoading(); + } + }); + } + + /** + * function hides CodeMirror editor + */ + function hide() { + var lElem = CodeMirrorElement; + KeyBinding.set(); + + if(lElem && FM) + FM.removeChild(lElem); + + DOM.showPanel(); + } + + /** + * function calls all CodeMirror editor functions + */ + CodeMirrorEditor.show = function(){ + DOM.Images.showLoad(); + Util.loadOnLoad( CallBacks ); + }; + + /** + * function hides CodeMirror editor + */ + CodeMirrorEditor.hide = hide; + + /** + * function bind keys + */ + CloudCmd.Editor.init = function(pReadOnly){ + ReadOnly = pReadOnly; + + CodeMirrorEditor.show(); + CallBacks.pop(); + + var lKeyListener = function(pEvent){ + /* если клавиши можно обрабатывать */ + if( KeyBinding.get() ){ + /* if f4 or f3 pressed */ + var lF3 = CloudCmd.KEY.F3, + lF4 = CloudCmd.KEY.F4; + + if(!pEvent.shiftKey) + switch(pEvent.keyCode) + { + case lF4: + ReadOnly = false; + CodeMirrorEditor.show(); + break; + case lF3: + ReadOnly = true; + CodeMirrorEditor.show(); + break; + } + } + }; + + /* добавляем обработчик клавишь */ + DOM.addKeyListener( lKeyListener ); + DOM.setButtonKey('f4', CodeMirrorEditor.show); + }; + + CloudCmd.Editor.CodeMirror = CodeMirrorEditor; + +})(CloudCommander, Util, DOM, CloudFunc); \ No newline at end of file diff --git a/lib/client/editor/codemirror/codemirror.css b/lib/client/editor/codemirror/codemirror.css index 41b8d09e..59af303b 100644 --- a/lib/client/editor/codemirror/codemirror.css +++ b/lib/client/editor/codemirror/codemirror.css @@ -1,174 +1,176 @@ -.CodeMirror { - line-height: 1em; - font-family: monospace; - - /* Necessary so the scrollbar can be absolutely positioned within the wrapper on Lion. */ - position: relative; - /* This prevents unwanted scrollbars from showing up on the body and wrapper in IE. */ - overflow: hidden; -} - -.CodeMirror-scroll { - overflow: auto; - height: 300px; - /* This is needed to prevent an IE[67] bug where the scrolled content - is visible outside of the scrolling box. */ - position: relative; - outline: none; -} - -/* Vertical scrollbar */ -.CodeMirror-scrollbar { - position: absolute; - right: 0; top: 0; - overflow-x: hidden; - overflow-y: scroll; - z-index: 5; -} -.CodeMirror-scrollbar-inner { - /* This needs to have a nonzero width in order for the scrollbar to appear - in Firefox and IE9. */ - width: 1px; -} -.CodeMirror-scrollbar.cm-sb-overlap { - /* Ensure that the scrollbar appears in Lion, and that it overlaps the content - rather than sitting to the right of it. */ - position: absolute; - z-index: 1; - float: none; - right: 0; - min-width: 12px; -} -.CodeMirror-scrollbar.cm-sb-nonoverlap { - min-width: 12px; -} -.CodeMirror-scrollbar.cm-sb-ie7 { - min-width: 18px; -} - -.CodeMirror-gutter { - position: absolute; left: 0; top: 0; - z-index: 10; - background-color: #f7f7f7; - border-right: 1px solid #eee; - min-width: 2em; - height: 100%; -} -.CodeMirror-gutter-text { - color: #aaa; - text-align: right; - padding: .4em .2em .4em .4em; - white-space: pre !important; - cursor: default; -} -.CodeMirror-lines { - padding: .4em; - white-space: pre; - cursor: text; -} - -.CodeMirror pre { - -moz-border-radius: 0; - -webkit-border-radius: 0; - -o-border-radius: 0; - border-radius: 0; - border-width: 0; margin: 0; padding: 0; background: transparent; - font-family: inherit; - font-size: inherit; - padding: 0; margin: 0; - white-space: pre; - word-wrap: normal; - line-height: inherit; - color: inherit; - overflow: visible; -} - -.CodeMirror-wrap pre { - word-wrap: break-word; - white-space: pre-wrap; - word-break: normal; -} -.CodeMirror-wrap .CodeMirror-scroll { - overflow-x: hidden; -} - -.CodeMirror textarea { - outline: none !important; -} - -.CodeMirror pre.CodeMirror-cursor { - z-index: 10; - position: absolute; - visibility: hidden; - border-left: 1px solid black; - border-right: none; - width: 0; -} -.cm-keymap-fat-cursor pre.CodeMirror-cursor { - width: auto; - border: 0; - background: transparent; - background: rgba(0, 200, 0, .4); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800); -} -/* Kludge to turn off filter in ie9+, which also accepts rgba */ -.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) { - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); -} -.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {} -.CodeMirror-focused pre.CodeMirror-cursor { - visibility: visible; -} - -div.CodeMirror-selected { background: #d9d9d9; } -.CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; } - -.CodeMirror-searching { - background: #ffa; - background: rgba(255, 255, 0, .4); -} - -/* Default theme */ - -.cm-s-default span.cm-keyword {color: #708;} -.cm-s-default span.cm-atom {color: #219;} -.cm-s-default span.cm-number {color: #164;} -.cm-s-default span.cm-def {color: #00f;} -.cm-s-default span.cm-variable {color: black;} -.cm-s-default span.cm-variable-2 {color: #05a;} -.cm-s-default span.cm-variable-3 {color: #085;} -.cm-s-default span.cm-property {color: black;} -.cm-s-default span.cm-operator {color: black;} -.cm-s-default span.cm-comment {color: #a50;} -.cm-s-default span.cm-string {color: #a11;} -.cm-s-default span.cm-string-2 {color: #f50;} -.cm-s-default span.cm-meta {color: #555;} -.cm-s-default span.cm-error {color: #f00;} -.cm-s-default span.cm-qualifier {color: #555;} -.cm-s-default span.cm-builtin {color: #30a;} -.cm-s-default span.cm-bracket {color: #997;} -.cm-s-default span.cm-tag {color: #170;} -.cm-s-default span.cm-attribute {color: #00c;} -.cm-s-default span.cm-header {color: blue;} -.cm-s-default span.cm-quote {color: #090;} -.cm-s-default span.cm-hr {color: #999;} -.cm-s-default span.cm-link {color: #00c;} - -span.cm-header, span.cm-strong {font-weight: bold;} -span.cm-em {font-style: italic;} -span.cm-emstrong {font-style: italic; font-weight: bold;} -span.cm-link {text-decoration: underline;} - -span.cm-invalidchar {color: #f00;} - -div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} -div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} - -@media print { - - /* Hide the cursor when printing */ - .CodeMirror pre.CodeMirror-cursor { - visibility: hidden; - } - -} +.CodeMirror { + line-height: 1em; + font-family: monospace; + + /* Necessary so the scrollbar can be absolutely positioned within the wrapper on Lion. */ + position: relative; + /* This prevents unwanted scrollbars from showing up on the body and wrapper in IE. */ + overflow: hidden; +} + +.CodeMirror-scroll { + overflow: auto; + height: 300px; + /* This is needed to prevent an IE[67] bug where the scrolled content + is visible outside of the scrolling box. */ + position: relative; + outline: none; +} + +/* Vertical scrollbar */ +.CodeMirror-scrollbar { + position: absolute; + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; + z-index: 5; +} +.CodeMirror-scrollbar-inner { + /* This needs to have a nonzero width in order for the scrollbar to appear + in Firefox and IE9. */ + width: 1px; +} +.CodeMirror-scrollbar.cm-sb-overlap { + /* Ensure that the scrollbar appears in Lion, and that it overlaps the content + rather than sitting to the right of it. */ + position: absolute; + z-index: 1; + float: none; + right: 0; + min-width: 12px; +} +.CodeMirror-scrollbar.cm-sb-nonoverlap { + min-width: 12px; +} +.CodeMirror-scrollbar.cm-sb-ie7 { + min-width: 18px; +} + +.CodeMirror-gutter { + position: absolute; left: 0; top: 0; + z-index: 10; + background-color: #f7f7f7; + border-right: 1px solid #eee; + min-width: 2em; + height: 100%; +} +.CodeMirror-gutter-text { + color: #aaa; + text-align: right; + padding: .4em .2em .4em .4em; + white-space: pre !important; + cursor: default; +} +.CodeMirror-lines { + padding: .4em; + white-space: pre; + cursor: text; +} + +.CodeMirror pre { + -moz-border-radius: 0; + -webkit-border-radius: 0; + -o-border-radius: 0; + border-radius: 0; + border-width: 0; margin: 0; padding: 0; background: transparent; + font-family: inherit; + font-size: inherit; + padding: 0; margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + overflow: visible; +} + +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} +.CodeMirror-wrap .CodeMirror-scroll { + overflow-x: hidden; +} + +.CodeMirror textarea { + outline: none !important; +} + +.CodeMirror pre.CodeMirror-cursor { + z-index: 10; + position: absolute; + visibility: hidden; + border-left: 1px solid black; + border-right: none; + width: 0; +} +.cm-keymap-fat-cursor pre.CodeMirror-cursor { + width: auto; + border: 0; + background: transparent; + background: rgba(0, 200, 0, .4); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800); +} +/* Kludge to turn off filter in ie9+, which also accepts rgba */ +.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) { + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); +} +.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {} +.CodeMirror-focused pre.CodeMirror-cursor { + visibility: visible; +} + +div.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; } + +.CodeMirror-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* Default theme */ + +.cm-s-default span.cm-keyword {color: #708;} +.cm-s-default span.cm-atom {color: #219;} +.cm-s-default span.cm-number {color: #164;} +.cm-s-default span.cm-def {color: #00f;} +.cm-s-default span.cm-variable {color: black;} +.cm-s-default span.cm-variable-2 {color: #05a;} +.cm-s-default span.cm-variable-3 {color: #085;} +.cm-s-default span.cm-property {color: black;} +.cm-s-default span.cm-operator {color: black;} +.cm-s-default span.cm-comment {color: #a50;} +.cm-s-default span.cm-string {color: #a11;} +.cm-s-default span.cm-string-2 {color: #f50;} +.cm-s-default span.cm-meta {color: #555;} +.cm-s-default span.cm-error {color: #f00;} +.cm-s-default span.cm-qualifier {color: #555;} +.cm-s-default span.cm-builtin {color: #30a;} +.cm-s-default span.cm-bracket {color: #997;} +.cm-s-default span.cm-tag {color: #170;} +.cm-s-default span.cm-attribute {color: #00c;} +.cm-s-default span.cm-header {color: blue;} +.cm-s-default span.cm-quote {color: #090;} +.cm-s-default span.cm-hr {color: #999;} +.cm-s-default span.cm-link {color: #00c;} +span.cm-negative {color: #d44;} +span.cm-positive {color: #292;} + +span.cm-header, span.cm-strong {font-weight: bold;} +span.cm-em {font-style: italic;} +span.cm-emstrong {font-style: italic; font-weight: bold;} +span.cm-link {text-decoration: underline;} + +span.cm-invalidchar {color: #f00;} + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} + +@media print { + + /* Hide the cursor when printing */ + .CodeMirror pre.CodeMirror-cursor { + visibility: hidden; + } + +} \ No newline at end of file diff --git a/lib/client/editor/codemirror/codemirror.js b/lib/client/editor/codemirror/codemirror.js index e49481b5..800e2485 100644 --- a/lib/client/editor/codemirror/codemirror.js +++ b/lib/client/editor/codemirror/codemirror.js @@ -1,3165 +1,3190 @@ -// CodeMirror version 2.35 -// -// All functions that need access to the editor's state live inside -// the CodeMirror function. Below that, at the bottom of the file, -// some utilities are defined. - -// CodeMirror is the only global var we claim -window.CodeMirror = (function() { - "use strict"; - // This is the function that produces an editor instance. Its - // closure is used to store the editor state. - function CodeMirror(place, givenOptions) { - // Determine effective options based on given values and defaults. - var options = {}, defaults = CodeMirror.defaults; - for (var opt in defaults) - if (defaults.hasOwnProperty(opt)) - options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; - - var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em"); - input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); - // Wraps and hides input textarea - var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The empty scrollbar content, used solely for managing the scrollbar thumb. - var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner"); - // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself. - var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar"); - // DIVs containing the selection and the actual code - var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1"); - // Blinky cursor, and element used to ensure cursor fits at the end of a line - var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden"); - // Used to measure text size - var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;"); - var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0"); - var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter"); - // Moved around its parent to cover visible view - var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the text, causes scrolling - var sizer = elt("div", [mover], null, "position: relative"); - // Provides scrolling - var scroller = elt("div", [sizer], "CodeMirror-scroll"); - scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "")); - if (place.appendChild) place.appendChild(wrapper); else place(wrapper); - - themeChanged(); keyMapChanged(); - // Needed to hide big blue blinking cursor on Mobile Safari - if (ios) input.style.width = "0px"; - if (!webkit) scroller.draggable = true; - lineSpace.style.outline = "none"; - if (options.tabindex != null) input.tabIndex = options.tabindex; - if (options.autofocus) focusInput(); - if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; - // Needed to handle Tab key in KHTML - if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute"; - - // Check for OS X >= 10.7. This has transparent scrollbars, so the - // overlaying of one scrollbar with another won't work. This is a - // temporary hack to simply turn off the overlay scrollbar. See - // issue #727. - if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; } - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - else if (ie_lt8) scrollbar.style.minWidth = "18px"; - - // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval. - var poll = new Delayed(), highlight = new Delayed(), blinker; - - // mode holds a mode API object. doc is the tree of Line objects, - // frontier is the point up to which the content has been parsed, - // and history the undo history (instance of History constructor). - var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), frontier = 0, focused; - loadMode(); - // The selection. These are always maintained to point at valid - // positions. Inverted is used to remember that the user is - // selecting bottom-to-top. - var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false}; - // Selection-related flags. shiftSelecting obviously tracks - // whether the user is holding shift. - var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText, - overwrite = false, suppressEdits = false, pasteIncoming = false; - // Variables used by startOperation/endOperation to track what - // happened during the operation. - var updateInput, userSelChange, changes, textChanged, selectionChanged, - gutterDirty, callbacks; - // Current visible range (may be bigger than the view window). - var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0; - // bracketHighlighted is used to remember that a bracket has been - // marked. - var bracketHighlighted; - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true; - var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll - var goalColumn = null; - - // Initialize the content. - operation(function(){setValue(options.value || ""); updateInput = false;})(); - var history = new History(); - - // Register our event handlers. - connect(scroller, "mousedown", operation(onMouseDown)); - connect(scroller, "dblclick", operation(onDoubleClick)); - connect(lineSpace, "selectstart", e_preventDefault); - // Gecko browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for Gecko. - if (!gecko) connect(scroller, "contextmenu", onContextMenu); - connect(scroller, "scroll", onScrollMain); - connect(scrollbar, "scroll", onScrollBar); - connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);}); - var resizeHandler = connect(window, "resize", function() { - if (wrapper.parentNode) updateDisplay(true); - else resizeHandler(); - }, true); - connect(input, "keyup", operation(onKeyUp)); - connect(input, "input", fastPoll); - connect(input, "keydown", operation(onKeyDown)); - connect(input, "keypress", operation(onKeyPress)); - connect(input, "focus", onFocus); - connect(input, "blur", onBlur); - - function drag_(e) { - if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; - e_stop(e); - } - if (options.dragDrop) { - connect(scroller, "dragstart", onDragStart); - connect(scroller, "dragenter", drag_); - connect(scroller, "dragover", drag_); - connect(scroller, "drop", operation(onDrop)); - } - connect(scroller, "paste", function(){focusInput(); fastPoll();}); - connect(input, "paste", function(){pasteIncoming = true; fastPoll();}); - connect(input, "cut", operation(function(){ - if (!options.readOnly) replaceSelection(""); - })); - - // Needed to handle Tab key in KHTML - if (khtml) connect(sizer, "mouseup", function() { - if (document.activeElement == input) input.blur(); - focusInput(); - }); - - // IE throws unspecified error in certain cases, when - // trying to access activeElement before onload - var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { } - if (hasFocus || options.autofocus) setTimeout(onFocus, 20); - else onBlur(); - - function isLine(l) {return l >= 0 && l < doc.size;} - // The instance object that we'll return. Mostly calls out to - // local functions in the CodeMirror function. Some do some extra - // range checking and/or clipping. operation is used to wrap the - // call so that changes it makes are tracked, and the display is - // updated afterwards. - var instance = wrapper.CodeMirror = { - getValue: getValue, - setValue: operation(setValue), - getSelection: getSelection, - replaceSelection: operation(replaceSelection), - focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();}, - setOption: function(option, value) { - var oldVal = options[option]; - options[option] = value; - if (option == "mode" || option == "indentUnit") loadMode(); - else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();} - else if (option == "readOnly" && !value) {resetInput(true);} - else if (option == "theme") themeChanged(); - else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); - else if (option == "tabSize") updateDisplay(true); - else if (option == "keyMap") keyMapChanged(); - else if (option == "tabindex") input.tabIndex = value; - if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || - option == "theme" || option == "lineNumberFormatter") { - gutterChanged(); - updateDisplay(true); - } - }, - getOption: function(option) {return options[option];}, - getMode: function() {return mode;}, - undo: operation(undo), - redo: operation(redo), - indentLine: operation(function(n, dir) { - if (typeof dir != "string") { - if (dir == null) dir = options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(n)) indentLine(n, dir); - }), - indentSelection: operation(indentSelected), - historySize: function() {return {undo: history.done.length, redo: history.undone.length};}, - clearHistory: function() {history = new History();}, - setHistory: function(histData) { - history = new History(); - history.done = histData.done; - history.undone = histData.undone; - }, - getHistory: function() { - function cp(arr) { - for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { - nw.push(nwelt = []); - for (var j = 0, elt = arr[i]; j < elt.length; ++j) { - var old = [], cur = elt[j]; - nwelt.push({start: cur.start, added: cur.added, old: old}); - for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); - } - } - return nw; - } - return {done: cp(history.done), undone: cp(history.undone)}; - }, - matchBrackets: operation(function(){matchBrackets(true);}), - getTokenAt: operation(function(pos) { - pos = clipPos(pos); - return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch); - }), - getStateAfter: function(line) { - line = clipLine(line == null ? doc.size - 1: line); - return getStateBefore(line + 1); - }, - cursorCoords: function(start, mode) { - if (start == null) start = sel.inverted; - return this.charCoords(start ? sel.from : sel.to, mode); - }, - charCoords: function(pos, mode) { - pos = clipPos(pos); - if (mode == "local") return localCoords(pos, false); - if (mode == "div") return localCoords(pos, true); - return pageCoords(pos); - }, - coordsChar: function(coords) { - var off = eltOffset(lineSpace); - return coordsChar(coords.x - off.left, coords.y - off.top); - }, - markText: operation(markText), - setBookmark: setBookmark, - findMarksAt: findMarksAt, - setMarker: operation(addGutterMarker), - clearMarker: operation(removeGutterMarker), - setLineClass: operation(setLineClass), - hideLine: operation(function(h) {return setLineHidden(h, true);}), - showLine: operation(function(h) {return setLineHidden(h, false);}), - onDeleteLine: function(line, f) { - if (typeof line == "number") { - if (!isLine(line)) return null; - line = getLine(line); - } - (line.handlers || (line.handlers = [])).push(f); - return line; - }, - lineInfo: lineInfo, - getViewport: function() { return {from: showingFrom, to: showingTo};}, - addWidget: function(pos, node, scroll, vert, horiz) { - pos = localCoords(clipPos(pos)); - var top = pos.yBot, left = pos.x; - node.style.position = "absolute"; - sizer.appendChild(node); - if (vert == "over") top = pos.y; - else if (vert == "near") { - var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), - hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft(); - if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) - top = pos.y - node.offsetHeight; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = (top + paddingTop()) + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = (left + paddingLeft()) + "px"; - } - if (scroll) - scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - lineCount: function() {return doc.size;}, - clipPos: clipPos, - getCursor: function(start) { - if (start == null) start = sel.inverted; - return copyPos(start ? sel.from : sel.to); - }, - somethingSelected: function() {return !posEq(sel.from, sel.to);}, - setCursor: operation(function(line, ch, user) { - if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); - else setCursor(line, ch, user); - }), - setSelection: operation(function(from, to, user) { - (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); - }), - getLine: function(line) {if (isLine(line)) return getLine(line).text;}, - getLineHandle: function(line) {if (isLine(line)) return getLine(line);}, - setLine: operation(function(line, text) { - if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); - }), - removeLine: operation(function(line) { - if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0})); - }), - replaceRange: operation(replaceRange), - getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);}, - - triggerOnKeyDown: operation(onKeyDown), - execCommand: function(cmd) {return commands[cmd](instance);}, - // Stuff used by commands, probably not much use to outside code. - moveH: operation(moveH), - deleteH: operation(deleteH), - moveV: operation(moveV), - toggleOverwrite: function() { - if(overwrite){ - overwrite = false; - cursor.className = cursor.className.replace(" CodeMirror-overwrite", ""); - } else { - overwrite = true; - cursor.className += " CodeMirror-overwrite"; - } - }, - - posFromIndex: function(off) { - var lineNo = 0, ch; - doc.iter(0, doc.size, function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos({line: lineNo, ch: ch}); - }, - indexFromPos: function (coords) { - if (coords.line < 0 || coords.ch < 0) return 0; - var index = coords.ch; - doc.iter(0, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - scrollTo: function(x, y) { - if (x != null) scroller.scrollLeft = x; - if (y != null) scrollbar.scrollTop = scroller.scrollTop = y; - updateDisplay([]); - }, - getScrollInfo: function() { - return {x: scroller.scrollLeft, y: scrollbar.scrollTop, - height: scrollbar.scrollHeight, width: scroller.scrollWidth}; - }, - setSize: function(width, height) { - function interpret(val) { - val = String(val); - return /^\d+$/.test(val) ? val + "px" : val; - } - if (width != null) wrapper.style.width = interpret(width); - if (height != null) scroller.style.height = interpret(height); - instance.refresh(); - }, - - operation: function(f){return operation(f)();}, - compoundChange: function(f){return compoundChange(f);}, - refresh: function(){ - updateDisplay(true, null, lastScrollTop); - if (scrollbar.scrollHeight > lastScrollTop) - scrollbar.scrollTop = lastScrollTop; - }, - getInputField: function(){return input;}, - getWrapperElement: function(){return wrapper;}, - getScrollerElement: function(){return scroller;}, - getGutterElement: function(){return gutter;} - }; - - function getLine(n) { return getLineAt(doc, n); } - function updateLineHeight(line, height) { - gutterDirty = true; - var diff = height - line.height; - for (var n = line; n; n = n.parent) n.height += diff; - } - - function lineContent(line, wrapAt) { - if (!line.styles) - line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize); - return line.getContent(options.tabSize, wrapAt, options.lineWrapping); - } - - function setValue(code) { - var top = {line: 0, ch: 0}; - updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length}, - splitLines(code), top, top); - updateInput = true; - } - function getValue(lineSep) { - var text = []; - doc.iter(0, doc.size, function(line) { text.push(line.text); }); - return text.join(lineSep || "\n"); - } - - function onScrollBar(e) { - if (scrollbar.scrollTop != lastScrollTop) { - lastScrollTop = scroller.scrollTop = scrollbar.scrollTop; - updateDisplay([]); - } - } - - function onScrollMain(e) { - if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px") - gutter.style.left = scroller.scrollLeft + "px"; - if (scroller.scrollTop != lastScrollTop) { - lastScrollTop = scroller.scrollTop; - if (scrollbar.scrollTop != lastScrollTop) - scrollbar.scrollTop = lastScrollTop; - updateDisplay([]); - } - if (options.onScroll) options.onScroll(instance); - } - - function onMouseDown(e) { - setShift(e_prop(e, "shiftKey")); - // Check whether this is a click in a widget - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == sizer && n != mover) return; - - // See if this is a click in the gutter - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == gutterText) { - if (options.onGutterClick) - options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); - return e_preventDefault(e); - } - - var start = posFromMouse(e); - - switch (e_button(e)) { - case 3: - if (gecko) onContextMenu(e); - return; - case 2: - if (start) setCursor(start.line, start.ch, true); - setTimeout(focusInput, 20); - e_preventDefault(e); - return; - } - // For button 1, if it was clicked inside the editor - // (posFromMouse returning non-null), we have to adjust the - // selection. - if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;} - - if (!focused) onFocus(); - - var now = +new Date, type = "single"; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { - type = "triple"; - e_preventDefault(e); - setTimeout(focusInput, 20); - selectLine(start.line); - } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - e_preventDefault(e); - var word = findWordAt(start); - setSelectionUser(word.from, word.to); - } else { lastClick = {time: now, pos: start}; } - - function dragEnd(e2) { - if (webkit) scroller.draggable = false; - draggingText = false; - up(); drop(); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - setCursor(start.line, start.ch, true); - focusInput(); - } - } - var last = start, going; - if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) && - !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { - // Let the drag handler handle this. - if (webkit) scroller.draggable = true; - var up = connect(document, "mouseup", operation(dragEnd), true); - var drop = connect(scroller, "drop", operation(dragEnd), true); - draggingText = true; - // IE's approach to draggable - if (scroller.dragDrop) scroller.dragDrop(); - return; - } - e_preventDefault(e); - if (type == "single") setCursor(start.line, start.ch, true); - - var startstart = sel.from, startend = sel.to; - - function doSelect(cur) { - if (type == "single") { - setSelectionUser(start, cur); - } else if (type == "double") { - var word = findWordAt(cur); - if (posLess(cur, startstart)) setSelectionUser(word.from, startend); - else setSelectionUser(startstart, word.to); - } else if (type == "triple") { - if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0})); - else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0})); - } - } - - function extend(e) { - var cur = posFromMouse(e, true); - if (cur && !posEq(cur, last)) { - if (!focused) onFocus(); - last = cur; - doSelect(cur); - updateInput = false; - var visible = visibleLines(); - if (cur.line >= visible.to || cur.line < visible.from) - going = setTimeout(operation(function(){extend(e);}), 150); - } - } - - function done(e) { - clearTimeout(going); - var cur = posFromMouse(e); - if (cur) doSelect(cur); - e_preventDefault(e); - focusInput(); - updateInput = true; - move(); up(); - } - var move = connect(document, "mousemove", operation(function(e) { - clearTimeout(going); - e_preventDefault(e); - if (!ie && !e_button(e)) done(e); - else extend(e); - }), true); - var up = connect(document, "mouseup", operation(done), true); - } - function onDoubleClick(e) { - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == gutterText) return e_preventDefault(e); - e_preventDefault(e); - } - function onDrop(e) { - if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; - e_preventDefault(e); - var pos = posFromMouse(e, true), files = e.dataTransfer.files; - if (!pos || options.readOnly) return; - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - var reader = new FileReader; - reader.onload = function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(pos); - operation(function() { - var end = replaceRange(text.join(""), pos, pos); - setSelectionUser(pos, end); - })(); - } - }; - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { - // Don't do a replace if the drop happened inside of the selected text. - if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return; - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - compoundChange(function() { - var curFrom = sel.from, curTo = sel.to; - setSelectionUser(pos, pos); - if (draggingText) replaceRange("", curFrom, curTo); - replaceSelection(text); - focusInput(); - }); - } - } - catch(e){} - } - } - function onDragStart(e) { - var txt = getSelection(); - e.dataTransfer.setData("Text", txt); - - // Use dummy image instead of default browsers image. - if (e.dataTransfer.setDragImage) - e.dataTransfer.setDragImage(elt('img'), 0, 0); - } - - function doHandleBinding(bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - var prevShift = shiftSelecting; - try { - if (options.readOnly) suppressEdits = true; - if (dropShift) shiftSelecting = null; - bound(instance); - } catch(e) { - if (e != Pass) throw e; - return false; - } finally { - shiftSelecting = prevShift; - suppressEdits = false; - } - return true; - } - var maybeTransition; - function handleKeyBinding(e) { - // Handle auto keymap transitions - var startMap = getKeyMap(options.keyMap), next = startMap.auto; - clearTimeout(maybeTransition); - if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { - if (getKeyMap(options.keyMap) == startMap) { - options.keyMap = (next.call ? next.call(null, instance) : next); - } - }, 50); - - var name = keyNames[e_prop(e, "keyCode")], handled = false; - var flipCtrlCmd = opera && mac; - if (name == null || e.altGraphKey) return false; - if (e_prop(e, "altKey")) name = "Alt-" + name; - if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; - if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; - - var stopped = false; - function stop() { stopped = true; } - - if (e_prop(e, "shiftKey")) { - handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap, - function(b) {return doHandleBinding(b, true);}, stop) - || lookupKey(name, options.extraKeys, options.keyMap, function(b) { - if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b); - }, stop); - } else { - handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop); - } - if (stopped) handled = false; - if (handled) { - e_preventDefault(e); - restartBlink(); - if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } - } - return handled; - } - function handleCharBinding(e, ch) { - var handled = lookupKey("'" + ch + "'", options.extraKeys, - options.keyMap, function(b) { return doHandleBinding(b, true); }); - if (handled) { - e_preventDefault(e); - restartBlink(); - } - return handled; - } - - var lastStoppedKey = null; - function onKeyDown(e) { - if (!focused) onFocus(); - if (ie && e.keyCode == 27) { e.returnValue = false; } - if (pollingFast) { if (readInput()) pollingFast = false; } - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - var code = e_prop(e, "keyCode"); - // IE does strange things with escape. - setShift(code == 16 || e_prop(e, "shiftKey")); - // First give onKeyEvent option a chance to handle this. - var handled = handleKeyBinding(e); - if (opera) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) - replaceSelection(""); - } - } - function onKeyPress(e) { - if (pollingFast) readInput(); - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); - if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { - if (mode.electricChars.indexOf(ch) > -1) - setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75); - } - if (handleCharBinding(e, ch)) return; - fastPoll(); - } - function onKeyUp(e) { - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - if (e_prop(e, "keyCode") == 16) shiftSelecting = null; - } - - function onFocus() { - if (options.readOnly == "nocursor") return; - if (!focused) { - if (options.onFocus) options.onFocus(instance); - focused = true; - if (scroller.className.search(/\bCodeMirror-focused\b/) == -1) - scroller.className += " CodeMirror-focused"; - } - slowPoll(); - restartBlink(); - } - function onBlur() { - if (focused) { - if (options.onBlur) options.onBlur(instance); - focused = false; - if (bracketHighlighted) - operation(function(){ - if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; } - })(); - scroller.className = scroller.className.replace(" CodeMirror-focused", ""); - } - clearInterval(blinker); - setTimeout(function() {if (!focused) shiftSelecting = null;}, 150); - } - - // Replace the range from from to to by the strings in newText. - // Afterwards, set the selection to selFrom, selTo. - function updateLines(from, to, newText, selFrom, selTo) { - if (suppressEdits) return; - var old = []; - doc.iter(from.line, to.line + 1, function(line) { - old.push(newHL(line.text, line.markedSpans)); - }); - if (history) { - history.addChange(from.line, newText.length, old); - while (history.done.length > options.undoDepth) history.done.shift(); - } - var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); - updateLinesNoUndo(from, to, lines, selFrom, selTo); - } - function unredoHelper(from, to) { - if (!from.length) return; - var set = from.pop(), out = []; - for (var i = set.length - 1; i >= 0; i -= 1) { - var change = set[i]; - var replaced = [], end = change.start + change.added; - doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); }); - out.push({start: change.start, added: change.old.length, old: replaced}); - var pos = {line: change.start + change.old.length - 1, - ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))}; - updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, - change.old, pos, pos); - } - updateInput = true; - to.push(out); - } - function undo() {unredoHelper(history.done, history.undone);} - function redo() {unredoHelper(history.undone, history.done);} - - function updateLinesNoUndo(from, to, lines, selFrom, selTo) { - if (suppressEdits) return; - var recomputeMaxLength = false, maxLineLength = maxLine.text.length; - if (!options.lineWrapping) - doc.iter(from.line, to.line + 1, function(line) { - if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;} - }); - if (from.line != to.line || lines.length > 1) gutterDirty = true; - - var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line); - var lastHL = lst(lines); - - // First adjust the line structure - if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = [], prevLine = null; - for (var i = 0, e = lines.length - 1; i < e; ++i) - added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); - lastLine.update(lastLine.text, hlSpans(lastHL)); - if (nlines) doc.remove(from.line, nlines, callbacks); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (lines.length == 1) { - firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0])); - } else { - for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) - added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); - added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL))); - firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); - doc.insert(from.line + 1, added); - } - } else if (lines.length == 1) { - firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0])); - doc.remove(from.line + 1, nlines, callbacks); - } else { - var added = []; - firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); - lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); - for (var i = 1, e = lines.length - 1; i < e; ++i) - added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks); - doc.insert(from.line + 1, added); - } - if (options.lineWrapping) { - var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3); - doc.iter(from.line, from.line + lines.length, function(line) { - if (line.hidden) return; - var guess = Math.ceil(line.text.length / perLine) || 1; - if (guess != line.height) updateLineHeight(line, guess); - }); - } else { - doc.iter(from.line, from.line + lines.length, function(line) { - var l = line.text; - if (!line.hidden && l.length > maxLineLength) { - maxLine = line; maxLineLength = l.length; maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) updateMaxLine = true; - } - - // Adjust frontier, schedule worker - frontier = Math.min(frontier, from.line); - startWorker(400); - - var lendiff = lines.length - nlines - 1; - // Remember that these lines changed, for updating the display - changes.push({from: from.line, to: to.line + 1, diff: lendiff}); - if (options.onChange) { - // Normalize lines to contain only strings, since that's what - // the change event handler expects - for (var i = 0; i < lines.length; ++i) - if (typeof lines[i] != "string") lines[i] = lines[i].text; - var changeObj = {from: from, to: to, text: lines}; - if (textChanged) { - for (var cur = textChanged; cur.next; cur = cur.next) {} - cur.next = changeObj; - } else textChanged = changeObj; - } - - // Update the selection - function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;} - setSelection(clipPos(selFrom), clipPos(selTo), - updateLine(sel.from.line), updateLine(sel.to.line)); - } - - function needsScrollbar() { - var realHeight = doc.height * textHeight() + 2 * paddingTop(); - return realHeight * .99 > scroller.offsetHeight ? realHeight : false; - } - - function updateVerticalScroll(scrollTop) { - var scrollHeight = needsScrollbar(); - scrollbar.style.display = scrollHeight ? "block" : "none"; - if (scrollHeight) { - scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px"; - scrollbar.style.height = scroller.clientHeight + "px"; - if (scrollTop != null) { - scrollbar.scrollTop = scroller.scrollTop = scrollTop; - // 'Nudge' the scrollbar to work around a Webkit bug where, - // in some situations, we'd end up with a scrollbar that - // reported its scrollTop (and looked) as expected, but - // *behaved* as if it was still in a previous state (i.e. - // couldn't scroll up, even though it appeared to be at the - // bottom). - if (webkit) setTimeout(function() { - if (scrollbar.scrollTop != scrollTop) return; - scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1); - scrollbar.scrollTop = scrollTop; - }, 0); - } - } else { - sizer.style.minHeight = ""; - } - // Position the mover div to align with the current virtual scroll position - mover.style.top = displayOffset * textHeight() + "px"; - } - - function computeMaxLength() { - maxLine = getLine(0); maxLineChanged = true; - var maxLineLength = maxLine.text.length; - doc.iter(1, doc.size, function(line) { - var l = line.text; - if (!line.hidden && l.length > maxLineLength) { - maxLineLength = l.length; maxLine = line; - } - }); - updateMaxLine = false; - } - - function replaceRange(code, from, to) { - from = clipPos(from); - if (!to) to = from; else to = clipPos(to); - code = splitLines(code); - function adjustPos(pos) { - if (posLess(pos, from)) return pos; - if (!posLess(to, pos)) return end; - var line = pos.line + code.length - (to.line - from.line) - 1; - var ch = pos.ch; - if (pos.line == to.line) - ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0)); - return {line: line, ch: ch}; - } - var end; - replaceRange1(code, from, to, function(end1) { - end = end1; - return {from: adjustPos(sel.from), to: adjustPos(sel.to)}; - }); - return end; - } - function replaceSelection(code, collapse) { - replaceRange1(splitLines(code), sel.from, sel.to, function(end) { - if (collapse == "end") return {from: end, to: end}; - else if (collapse == "start") return {from: sel.from, to: sel.from}; - else return {from: sel.from, to: end}; - }); - } - function replaceRange1(code, from, to, computeSel) { - var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length; - var newSel = computeSel({line: from.line + code.length - 1, ch: endch}); - updateLines(from, to, code, newSel.from, newSel.to); - } - - function getRange(from, to, lineSep) { - var l1 = from.line, l2 = to.line; - if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); - var code = [getLine(l1).text.slice(from.ch)]; - doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); - code.push(getLine(l2).text.slice(0, to.ch)); - return code.join(lineSep || "\n"); - } - function getSelection(lineSep) { - return getRange(sel.from, sel.to, lineSep); - } - - function slowPoll() { - if (pollingFast) return; - poll.set(options.pollInterval, function() { - readInput(); - if (focused) slowPoll(); - }); - } - function fastPoll() { - var missed = false; - pollingFast = true; - function p() { - var changed = readInput(); - if (!changed && !missed) {missed = true; poll.set(60, p);} - else {pollingFast = false; slowPoll();} - } - poll.set(20, p); - } - - // Previnput is a hack to work with IME. If we reset the textarea - // on every change, that breaks IME. So we look for changes - // compared to the previous content instead. (Modern browsers have - // events that indicate IME taking place, but these are not widely - // supported or compatible enough yet to rely on.) - var prevInput = ""; - function readInput() { - if (!focused || hasSelection(input) || options.readOnly) return false; - var text = input.value; - if (text == prevInput) return false; - if (!nestedOperation) startOperation(); - shiftSelecting = null; - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput[same] == text[same]) ++same; - if (same < prevInput.length) - sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; - else if (overwrite && posEq(sel.from, sel.to) && !pasteIncoming) - sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))}; - replaceSelection(text.slice(same), "end"); - if (text.length > 1000) { input.value = prevInput = ""; } - else prevInput = text; - if (!nestedOperation) endOperation(); - pasteIncoming = false; - return true; - } - function resetInput(user) { - if (!posEq(sel.from, sel.to)) { - prevInput = ""; - input.value = getSelection(); - if (focused) selectInput(input); - } else if (user) prevInput = input.value = ""; - } - - function focusInput() { - if (options.readOnly != "nocursor") input.focus(); - } - - function scrollCursorIntoView() { - var coords = calculateCursorCoords(); - scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); - if (!focused) return; - var box = sizer.getBoundingClientRect(), doScroll = null; - if (coords.y + box.top < 0) doScroll = true; - else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null) { - var hidden = cursor.style.display == "none"; - if (hidden) { - cursor.style.display = ""; - cursor.style.left = coords.x + "px"; - cursor.style.top = (coords.y - displayOffset) + "px"; - } - cursor.scrollIntoView(doScroll); - if (hidden) cursor.style.display = "none"; - } - } - function calculateCursorCoords() { - var cursor = localCoords(sel.inverted ? sel.from : sel.to); - var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; - return {x: x, y: cursor.y, yBot: cursor.yBot}; - } - function scrollIntoView(x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(x1, y1, x2, y2); - if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;} - if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;} - } - function calculateScrollPos(x1, y1, x2, y2) { - var pl = paddingLeft(), pt = paddingTop(); - y1 += pt; y2 += pt; x1 += pl; x2 += pl; - var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {}; - var docBottom = needsScrollbar() || Infinity; - var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; - if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); - else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; - - var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft; - var gutterw = options.fixedGutter ? gutter.clientWidth : 0; - var atLeft = x1 < gutterw + pl + 10; - if (x1 < screenleft + gutterw || atLeft) { - if (atLeft) x1 = 0; - result.scrollLeft = Math.max(0, x1 - 10 - gutterw); - } else if (x2 > screenw + screenleft - 3) { - result.scrollLeft = x2 + 10 - screenw; - } - return result; - } - - function visibleLines(scrollTop) { - var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop(); - var fromHeight = Math.max(0, Math.floor(top / lh)); - var toHeight = Math.ceil((top + scroller.clientHeight) / lh); - return {from: lineAtHeight(doc, fromHeight), - to: lineAtHeight(doc, toHeight)}; - } - // Uses a set of changes plus the current scroll position to - // determine which DOM updates have to be made, and makes the - // updates. - function updateDisplay(changes, suppressCallback, scrollTop) { - if (!scroller.clientWidth) { - showingFrom = showingTo = displayOffset = 0; - return; - } - // Compute the new visible window - // If scrollTop is specified, use that to determine which lines - // to render instead of the current scrollbar position. - var visible = visibleLines(scrollTop); - // Bail out if the visible area is already rendered and nothing changed. - if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) { - updateVerticalScroll(scrollTop); - return; - } - var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100); - if (showingFrom < from && from - showingFrom < 20) from = showingFrom; - if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); - - // Create a range of theoretically intact lines, and punch holes - // in that using the change info. - var intact = changes === true ? [] : - computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes); - // Clip off the parts that won't be visible - var intactLines = 0; - for (var i = 0; i < intact.length; ++i) { - var range = intact[i]; - if (range.from < from) {range.domStart += (from - range.from); range.from = from;} - if (range.to > to) range.to = to; - if (range.from >= range.to) intact.splice(i--, 1); - else intactLines += range.to - range.from; - } - if (intactLines == to - from && from == showingFrom && to == showingTo) { - updateVerticalScroll(scrollTop); - return; - } - intact.sort(function(a, b) {return a.domStart - b.domStart;}); - - var th = textHeight(), gutterDisplay = gutter.style.display; - lineDiv.style.display = "none"; - patchDisplay(from, to, intact); - lineDiv.style.display = gutter.style.display = ""; - - var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; - // This is just a bogus formula that detects when the editor is - // resized or the font size changes. - if (different) lastSizeC = scroller.clientHeight + th; - if (from != showingFrom || to != showingTo && options.onViewportChange) - setTimeout(function(){ - if (options.onViewportChange) options.onViewportChange(instance, from, to); - }); - showingFrom = from; showingTo = to; - displayOffset = heightAtLine(doc, from); - startWorker(100); - - // Since this is all rather error prone, it is honoured with the - // only assertion in the whole file. - if (lineDiv.childNodes.length != showingTo - showingFrom) - throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + - " nodes=" + lineDiv.childNodes.length); - - function checkHeights() { - var curNode = lineDiv.firstChild, heightChanged = false; - doc.iter(showingFrom, showingTo, function(line) { - // Work around bizarro IE7 bug where, sometimes, our curNode - // is magically replaced with a new node in the DOM, leaving - // us with a reference to an orphan (nextSibling-less) node. - if (!curNode) return; - if (!line.hidden) { - var height = Math.round(curNode.offsetHeight / th) || 1; - if (line.height != height) { - updateLineHeight(line, height); - gutterDirty = heightChanged = true; - } - } - curNode = curNode.nextSibling; - }); - return heightChanged; - } - - if (options.lineWrapping) checkHeights(); - - gutter.style.display = gutterDisplay; - if (different || gutterDirty) { - // If the gutter grew in size, re-check heights. If those changed, re-draw gutter. - updateGutter() && options.lineWrapping && checkHeights() && updateGutter(); - } - updateVerticalScroll(scrollTop); - updateSelection(); - if (!suppressCallback && options.onUpdate) options.onUpdate(instance); - return true; - } - - function computeIntact(intact, changes) { - for (var i = 0, l = changes.length || 0; i < l; ++i) { - var change = changes[i], intact2 = [], diff = change.diff || 0; - for (var j = 0, l2 = intact.length; j < l2; ++j) { - var range = intact[j]; - if (change.to <= range.from && change.diff) - intact2.push({from: range.from + diff, to: range.to + diff, - domStart: range.domStart}); - else if (change.to <= range.from || change.from >= range.to) - intact2.push(range); - else { - if (change.from > range.from) - intact2.push({from: range.from, to: change.from, domStart: range.domStart}); - if (change.to < range.to) - intact2.push({from: change.to + diff, to: range.to + diff, - domStart: range.domStart + (change.to - range.from)}); - } - } - intact = intact2; - } - return intact; - } - - function patchDisplay(from, to, intact) { - function killNode(node) { - var tmp = node.nextSibling; - node.parentNode.removeChild(node); - return tmp; - } - // The first pass removes the DOM nodes that aren't intact. - if (!intact.length) removeChildren(lineDiv); - else { - var domPos = 0, curNode = lineDiv.firstChild, n; - for (var i = 0; i < intact.length; ++i) { - var cur = intact[i]; - while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} - for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;} - } - while (curNode) curNode = killNode(curNode); - } - // This pass fills in the lines that actually changed. - var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from; - doc.iter(from, to, function(line) { - if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); - if (!nextIntact || nextIntact.from > j) { - if (line.hidden) var lineElement = elt("pre"); - else { - var lineElement = lineContent(line); - if (line.className) lineElement.className = line.className; - // Kludge to make sure the styled element lies behind the selection (by z-index) - if (line.bgClassName) { - var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2"); - lineElement = elt("div", [pre, lineElement], null, "position: relative"); - } - } - lineDiv.insertBefore(lineElement, curNode); - } else { - curNode = curNode.nextSibling; - } - ++j; - }); - } - - function updateGutter() { - if (!options.gutter && !options.lineNumbers) return; - var hText = mover.offsetHeight, hEditor = scroller.clientHeight; - gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; - var fragment = document.createDocumentFragment(), i = showingFrom, normalNode; - doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { - if (line.hidden) { - fragment.appendChild(elt("pre")); - } else { - var marker = line.gutterMarker; - var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null; - if (marker && marker.text) - text = marker.text.replace("%N%", text != null ? text : ""); - else if (text == null) - text = "\u00a0"; - var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style)); - markerElement.innerHTML = text; - for (var j = 1; j < line.height; ++j) { - markerElement.appendChild(elt("br")); - markerElement.appendChild(document.createTextNode("\u00a0")); - } - if (!marker) normalNode = i; - } - ++i; - }); - gutter.style.display = "none"; - removeChildrenAndAdd(gutterText, fragment); - // Make sure scrolling doesn't cause number gutter size to pop - if (normalNode != null && options.lineNumbers) { - var node = gutterText.childNodes[normalNode - showingFrom]; - var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = ""; - while (val.length + pad.length < minwidth) pad += "\u00a0"; - if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild); - } - gutter.style.display = ""; - var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2; - lineSpace.style.marginLeft = gutter.offsetWidth + "px"; - gutterDirty = false; - return resized; - } - function updateSelection() { - var collapsed = posEq(sel.from, sel.to); - var fromPos = localCoords(sel.from, true); - var toPos = collapsed ? fromPos : localCoords(sel.to, true); - var headPos = sel.inverted ? fromPos : toPos, th = textHeight(); - var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv); - inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px"; - inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px"; - if (collapsed) { - cursor.style.top = headPos.y + "px"; - cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px"; - cursor.style.display = ""; - selectionDiv.style.display = "none"; - } else { - var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment(); - var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth; - var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight; - var add = function(left, top, right, height) { - var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px" - : "right: " + right + "px"; - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; " + rstyle + "; height: " + height + "px")); - }; - if (sel.from.ch && fromPos.y >= 0) { - var right = sameLine ? clientWidth - toPos.x : 0; - add(fromPos.x, fromPos.y, right, th); - } - var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0)); - var middleHeight = Math.min(toPos.y, clientHeight) - middleStart; - if (middleHeight > 0.2 * th) - add(0, middleStart, 0, middleHeight); - if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th) - add(0, toPos.y, clientWidth - toPos.x, th); - removeChildrenAndAdd(selectionDiv, fragment); - cursor.style.display = "none"; - selectionDiv.style.display = ""; - } - } - - function setShift(val) { - if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); - else shiftSelecting = null; - } - function setSelectionUser(from, to) { - var sh = shiftSelecting && clipPos(shiftSelecting); - if (sh) { - if (posLess(sh, from)) from = sh; - else if (posLess(to, sh)) to = sh; - } - setSelection(from, to); - userSelChange = true; - } - // Update the selection. Last two args are only used by - // updateLines, since they have to be expressed in the line - // numbers before the update. - function setSelection(from, to, oldFrom, oldTo) { - goalColumn = null; - if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} - if (posEq(sel.from, from) && posEq(sel.to, to)) return; - if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} - - // Skip over hidden lines. - if (from.line != oldFrom) { - var from1 = skipHidden(from, oldFrom, sel.from.ch); - // If there is no non-hidden line left, force visibility on current line - if (!from1) setLineHidden(from.line, false); - else from = from1; - } - if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); - - if (posEq(from, to)) sel.inverted = false; - else if (posEq(from, sel.to)) sel.inverted = false; - else if (posEq(to, sel.from)) sel.inverted = true; - - if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { - var head = sel.inverted ? from : to; - if (head.line != sel.from.line && sel.from.line < doc.size) { - var oldLine = getLine(sel.from.line); - if (/^\s+$/.test(oldLine.text)) - setTimeout(operation(function() { - if (oldLine.parent && /^\s+$/.test(oldLine.text)) { - var no = lineNo(oldLine); - replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); - } - }, 10)); - } - } - - sel.from = from; sel.to = to; - selectionChanged = true; - } - function skipHidden(pos, oldLine, oldCh) { - function getNonHidden(dir) { - var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1; - while (lNo != end) { - var line = getLine(lNo); - if (!line.hidden) { - var ch = pos.ch; - if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length; - return {line: lNo, ch: ch}; - } - lNo += dir; - } - } - var line = getLine(pos.line); - var toEnd = pos.ch == line.text.length && pos.ch != oldCh; - if (!line.hidden) return pos; - if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); - else return getNonHidden(-1) || getNonHidden(1); - } - function setCursor(line, ch, user) { - var pos = clipPos({line: line, ch: ch || 0}); - (user ? setSelectionUser : setSelection)(pos, pos); - } - - function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));} - function clipPos(pos) { - if (pos.line < 0) return {line: 0, ch: 0}; - if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length}; - var ch = pos.ch, linelen = getLine(pos.line).text.length; - if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; - else if (ch < 0) return {line: pos.line, ch: 0}; - else return pos; - } - - function findPosH(dir, unit) { - var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch; - var lineObj = getLine(line); - function findNextLine() { - for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { - var lo = getLine(l); - if (!lo.hidden) { line = l; lineObj = lo; return true; } - } - } - function moveOnce(boundToLine) { - if (ch == (dir < 0 ? 0 : lineObj.text.length)) { - if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; - else return false; - } else ch += dir; - return true; - } - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word") { - var sawWord = false; - for (;;) { - if (dir < 0) if (!moveOnce()) break; - if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; - else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} - if (dir > 0) if (!moveOnce()) break; - } - } - return {line: line, ch: ch}; - } - function moveH(dir, unit) { - var pos = dir < 0 ? sel.from : sel.to; - if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); - setCursor(pos.line, pos.ch, true); - } - function deleteH(dir, unit) { - if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); - else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); - else replaceRange("", sel.from, findPosH(dir, unit)); - userSelChange = true; - } - function moveV(dir, unit) { - var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true); - if (goalColumn != null) pos.x = goalColumn; - if (unit == "page") { - var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var target = coordsChar(pos.x, pos.y + screen * dir); - } else if (unit == "line") { - var th = textHeight(); - var target = coordsChar(pos.x, pos.y + .5 * th + dir * th); - } - if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y; - setCursor(target.line, target.ch, true); - goalColumn = pos.x; - } - - function findWordAt(pos) { - var line = getLine(pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - if (pos.after === false || end == line.length) --start; else ++end; - var startChar = line.charAt(start); - var check = isWordChar(startChar) ? isWordChar : - /\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 {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; - } - function selectLine(line) { - setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0})); - } - function indentSelected(mode) { - if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); - var e = sel.to.line - (sel.to.ch ? 0 : 1); - for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); - } - - function indentLine(n, how) { - if (!how) how = "add"; - if (how == "smart") { - if (!mode.indent) how = "prev"; - else var state = getStateBefore(n); - } - - var line = getLine(n), curSpace = line.indentation(options.tabSize), - curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (how == "smart") { - indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass) how = "prev"; - } - if (how == "prev") { - if (n) indentation = getLine(n-1).indentation(options.tabSize); - else indentation = 0; - } - else if (how == "add") indentation = curSpace + options.indentUnit; - else if (how == "subtract") indentation = curSpace - options.indentUnit; - indentation = Math.max(0, indentation); - var diff = indentation - curSpace; - - var indentString = "", pos = 0; - if (options.indentWithTabs) - for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";} - if (pos < indentation) indentString += spaceStr(indentation - pos); - - if (indentString != curSpaceString) - replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); - line.stateAfter = null; - } - - function loadMode() { - mode = CodeMirror.getMode(options, options.mode); - doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); - frontier = 0; - startWorker(100); - } - function gutterChanged() { - var visible = options.gutter || options.lineNumbers; - gutter.style.display = visible ? "" : "none"; - if (visible) gutterDirty = true; - else lineDiv.parentNode.style.marginLeft = 0; - } - function wrappingChanged(from, to) { - if (options.lineWrapping) { - wrapper.className += " CodeMirror-wrap"; - var perLine = scroller.clientWidth / charWidth() - 3; - doc.iter(0, doc.size, function(line) { - if (line.hidden) return; - var guess = Math.ceil(line.text.length / perLine) || 1; - if (guess != 1) updateLineHeight(line, guess); - }); - lineSpace.style.minWidth = widthForcer.style.left = ""; - } else { - wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); - computeMaxLength(); - doc.iter(0, doc.size, function(line) { - if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); - }); - } - changes.push({from: 0, to: doc.size}); - } - function themeChanged() { - scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") + - options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - } - function keyMapChanged() { - var style = keyMap[options.keyMap].style; - wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + - (style ? " cm-keymap-" + style : ""); - } - - function TextMarker(type, style) { this.lines = []; this.type = type; if (style) this.style = style; } - TextMarker.prototype.clear = operation(function() { - var min, max; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) min = lineNo(line); - if (span.to != null) max = lineNo(line); - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - } - if (min != null) changes.push({from: min, to: max + 1}); - this.lines.length = 0; - this.explicitlyCleared = true; - }); - TextMarker.prototype.find = function() { - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null || span.to != null) { - var found = lineNo(line); - if (span.from != null) from = {line: found, ch: span.from}; - if (span.to != null) to = {line: found, ch: span.to}; - } - } - if (this.type == "bookmark") return from; - return from && {from: from, to: to}; - }; - - function markText(from, to, className, options) { - from = clipPos(from); to = clipPos(to); - var marker = new TextMarker("range", className); - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - marker[opt] = options[opt]; - var curLine = from.line; - doc.iter(curLine, to.line + 1, function(line) { - var span = {from: curLine == from.line ? from.ch : null, - to: curLine == to.line ? to.ch : null, - marker: marker}; - line.markedSpans = (line.markedSpans || []).concat([span]); - marker.lines.push(line); - ++curLine; - }); - changes.push({from: from.line, to: to.line + 1}); - return marker; - } - - function setBookmark(pos) { - pos = clipPos(pos); - var marker = new TextMarker("bookmark"), line = getLine(pos.line); - history.addChange(pos.line, 1, [newHL(line.text, line.markedSpans)], true); - var span = {from: pos.ch, to: pos.ch, marker: marker}; - line.markedSpans = (line.markedSpans || []).concat([span]); - marker.lines.push(line); - return marker; - } - - function findMarksAt(pos) { - pos = clipPos(pos); - var markers = [], spans = getLine(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); - } - return markers; - } - - function addGutterMarker(line, text, className) { - if (typeof line == "number") line = getLine(clipLine(line)); - line.gutterMarker = {text: text, style: className}; - gutterDirty = true; - return line; - } - function removeGutterMarker(line) { - if (typeof line == "number") line = getLine(clipLine(line)); - line.gutterMarker = null; - gutterDirty = true; - } - - function changeLine(handle, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(clipLine(handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no)) changes.push({from: no, to: no + 1}); - else return null; - return line; - } - function setLineClass(handle, className, bgClassName) { - return changeLine(handle, function(line) { - if (line.className != className || line.bgClassName != bgClassName) { - line.className = className; - line.bgClassName = bgClassName; - return true; - } - }); - } - function setLineHidden(handle, hidden) { - return changeLine(handle, function(line, no) { - if (line.hidden != hidden) { - line.hidden = hidden; - if (!options.lineWrapping) { - if (hidden && line.text.length == maxLine.text.length) { - updateMaxLine = true; - } else if (!hidden && line.text.length > maxLine.text.length) { - maxLine = line; updateMaxLine = false; - } - } - updateLineHeight(line, hidden ? 0 : 1); - var fline = sel.from.line, tline = sel.to.line; - if (hidden && (fline == no || tline == no)) { - var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from; - var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to; - // Can't hide the last visible line, we'd have no place to put the cursor - if (!to) return; - setSelection(from, to); - } - return (gutterDirty = true); - } - }); - } - - function lineInfo(line) { - if (typeof line == "number") { - if (!isLine(line)) return null; - var n = line; - line = getLine(line); - if (!line) return null; - } else { - var n = lineNo(line); - if (n == null) return null; - } - var marker = line.gutterMarker; - return {line: n, handle: line, text: line.text, markerText: marker && marker.text, - markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName}; - } - - function measureLine(line, ch) { - if (ch == 0) return {top: 0, left: 0}; - var pre = lineContent(line, ch); - removeChildrenAndAdd(measure, pre); - var anchor = pre.anchor; - var top = anchor.offsetTop, left = anchor.offsetLeft; - // Older IEs report zero offsets for spans directly after a wrap - if (ie && top == 0 && left == 0) { - var backup = elt("span", "x"); - anchor.parentNode.insertBefore(backup, anchor.nextSibling); - top = backup.offsetTop; - } - return {top: top, left: left}; - } - function localCoords(pos, inLineWrap) { - var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); - if (pos.ch == 0) x = 0; - else { - var sp = measureLine(getLine(pos.line), pos.ch); - x = sp.left; - if (options.lineWrapping) y += Math.max(0, sp.top); - } - return {x: x, y: y, yBot: y + lh}; - } - // Coords must be lineSpace-local - function coordsChar(x, y) { - var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th); - if (heightPos < 0) return {line: 0, ch: 0}; - var lineNo = lineAtHeight(doc, heightPos); - if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length}; - var lineObj = getLine(lineNo), text = lineObj.text; - var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; - if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0}; - var wrongLine = false; - function getX(len) { - var sp = measureLine(lineObj, len); - if (tw) { - var off = Math.round(sp.top / th); - wrongLine = off != innerOff; - return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); - } - return sp.left; - } - var from = 0, fromX = 0, to = text.length, toX; - // Guess a suitable upper bound for our search. - var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); - for (;;) { - var estX = getX(estimated); - if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); - else {toX = estX; to = estimated; break;} - } - if (x > toX) return {line: lineNo, ch: to}; - // Try to guess a suitable lower bound as well. - estimated = Math.floor(to * 0.8); estX = getX(estimated); - if (estX < x) {from = estimated; fromX = estX;} - // Do a binary search between these bounds. - for (;;) { - if (to - from <= 1) { - var after = x - fromX < toX - x; - return {line: lineNo, ch: after ? from : to, after: after}; - } - var middle = Math.ceil((from + to) / 2), middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; } - else {from = middle; fromX = middleX;} - } - } - function pageCoords(pos) { - var local = localCoords(pos, true), off = eltOffset(lineSpace); - return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; - } - - var cachedHeight, cachedHeightFor, measurePre; - function textHeight() { - if (measurePre == null) { - measurePre = elt("pre"); - for (var i = 0; i < 49; ++i) { - measurePre.appendChild(document.createTextNode("x")); - measurePre.appendChild(elt("br")); - } - measurePre.appendChild(document.createTextNode("x")); - } - var offsetHeight = lineDiv.clientHeight; - if (offsetHeight == cachedHeightFor) return cachedHeight; - cachedHeightFor = offsetHeight; - removeChildrenAndAdd(measure, measurePre.cloneNode(true)); - cachedHeight = measure.firstChild.offsetHeight / 50 || 1; - removeChildren(measure); - return cachedHeight; - } - var cachedWidth, cachedWidthFor = 0; - function charWidth() { - if (scroller.clientWidth == cachedWidthFor) return cachedWidth; - cachedWidthFor = scroller.clientWidth; - var anchor = elt("span", "x"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(measure, pre); - return (cachedWidth = anchor.offsetWidth || 10); - } - function paddingTop() {return lineSpace.offsetTop;} - function paddingLeft() {return lineSpace.offsetLeft;} - - function posFromMouse(e, liberal) { - var offW = eltOffset(scroller, true), x, y; - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX; y = e.clientY; } catch (e) { return null; } - // This is a mess of a heuristic to try and determine whether a - // scroll-bar was clicked or not, and to return null if one was - // (and !liberal). - if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) - return null; - var offL = eltOffset(lineSpace, true); - return coordsChar(x - offL.left, y - offL.top); - } - var detectingSelectAll; - function onContextMenu(e) { - var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop; - if (!pos || opera) return; // Opera is difficult. - if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) - operation(setCursor)(pos.line, pos.ch); - - var oldCSS = input.style.cssText; - inputDiv.style.position = "absolute"; - input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + - "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - focusInput(); - resetInput(true); - // Adds "Select all" to context menu in FF - if (posEq(sel.from, sel.to)) input.value = prevInput = " "; - - function rehide() { - inputDiv.style.position = "relative"; - input.style.cssText = oldCSS; - if (ie_lt9) scrollbar.scrollTop = scrollPos; - slowPoll(); - - // Try to detect the user choosing select-all - if (input.selectionStart != null) { - clearTimeout(detectingSelectAll); - var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), i = 0; - prevInput = " "; - input.selectionStart = 1; input.selectionEnd = extval.length; - detectingSelectAll = setTimeout(function poll(){ - if (prevInput == " " && input.selectionStart == 0) - operation(commands.selectAll)(instance); - else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); - else resetInput(); - }, 200); - } - } - - if (gecko) { - e_stop(e); - var mouseup = connect(window, "mouseup", function() { - mouseup(); - setTimeout(rehide, 20); - }, true); - } else { - setTimeout(rehide, 50); - } - } - - // Cursor-blinking - function restartBlink() { - clearInterval(blinker); - var on = true; - cursor.style.visibility = ""; - blinker = setInterval(function() { - cursor.style.visibility = (on = !on) ? "" : "hidden"; - }, options.cursorBlinkRate); - } - - var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; - function matchBrackets(autoclear) { - var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1; - var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; - if (!match) return; - var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; - for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) - if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} - - var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; - function scan(line, from, to) { - if (!line.text) return; - var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; - for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { - var text = st[i]; - if (st[i+1] != style) {pos += d * text.length; continue;} - for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { - if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { - var match = matching[cur]; - if (match.charAt(1) == ">" == forward) stack.push(cur); - else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; - else if (!stack.length) return {pos: pos, match: true}; - } - } - } - } - for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) { - var line = getLine(i), first = i == head.line; - var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); - if (found) break; - } - if (!found) found = {pos: null, match: false}; - var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), - two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); - var clear = operation(function(){one.clear(); two && two.clear();}); - if (autoclear) setTimeout(clear, 800); - else bracketHighlighted = clear; - } - - // 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(n) { - var minindent, minline; - for (var search = n, lim = n - 40; search > lim; --search) { - if (search == 0) return 0; - var line = getLine(search-1); - if (line.stateAfter) return search; - var indented = line.indentation(options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - function getStateBefore(n) { - var pos = findStartLine(n), state = pos && getLine(pos-1).stateAfter; - if (!state) state = startState(mode); - else state = copyState(mode, state); - doc.iter(pos, n, function(line) { - line.process(mode, state, options.tabSize); - line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null; - }); - return state; - } - function highlightWorker() { - if (frontier >= showingTo) return; - var end = +new Date + options.workTime, state = copyState(mode, getStateBefore(frontier)); - var startFrontier = frontier; - doc.iter(frontier, showingTo, function(line) { - if (frontier >= showingFrom) { // Visible - line.highlight(mode, state, options.tabSize); - line.stateAfter = copyState(mode, state); - } else { - line.process(mode, state, options.tabSize); - line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null; - } - ++frontier; - if (+new Date > end) { - startWorker(options.workDelay); - return true; - } - }); - if (showingTo > startFrontier && frontier >= showingFrom) - operation(function() {changes.push({from: startFrontier, to: frontier});})(); - } - function startWorker(time) { - if (frontier < showingTo) - highlight.set(time, highlightWorker); - } - - // Operations are used to wrap changes in such a way that each - // change won't have to update the cursor and display (which would - // be awkward, slow, and error-prone), but instead updates are - // batched and then all combined and executed at once. - function startOperation() { - updateInput = userSelChange = textChanged = null; - changes = []; selectionChanged = false; callbacks = []; - } - function endOperation() { - if (updateMaxLine) computeMaxLength(); - if (maxLineChanged && !options.lineWrapping) { - var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left; - if (!ie_lt8) { - widthForcer.style.left = left + "px"; - lineSpace.style.minWidth = (left + cursorWidth) + "px"; - } - maxLineChanged = false; - } - var newScrollPos, updated; - if (selectionChanged) { - var coords = calculateCursorCoords(); - newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot); - } - if (changes.length || newScrollPos && newScrollPos.scrollTop != null) - updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop); - if (!updated) { - if (selectionChanged) updateSelection(); - if (gutterDirty) updateGutter(); - } - if (newScrollPos) scrollCursorIntoView(); - if (selectionChanged) restartBlink(); - - if (focused && (updateInput === true || (updateInput !== false && selectionChanged))) - resetInput(userSelChange); - - if (selectionChanged && options.matchBrackets) - setTimeout(operation(function() { - if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} - if (posEq(sel.from, sel.to)) matchBrackets(false); - }), 20); - var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks - if (textChanged && options.onChange && instance) - options.onChange(instance, textChanged); - if (sc && options.onCursorActivity) - options.onCursorActivity(instance); - for (var i = 0; i < cbs.length; ++i) cbs[i](instance); - if (updated && options.onUpdate) options.onUpdate(instance); - } - var nestedOperation = 0; - function operation(f) { - return function() { - if (!nestedOperation++) startOperation(); - try {var result = f.apply(this, arguments);} - finally {if (!--nestedOperation) endOperation();} - return result; - }; - } - - function compoundChange(f) { - history.startCompound(); - try { return f(); } finally { history.endCompound(); } - } - - for (var ext in extensions) - if (extensions.propertyIsEnumerable(ext) && - !instance.propertyIsEnumerable(ext)) - instance[ext] = extensions[ext]; - for (var i = 0; i < initHooks.length; ++i) initHooks[i](instance); - return instance; - } // (end of function CodeMirror) - - // The default configuration options. - CodeMirror.defaults = { - value: "", - mode: null, - theme: "default", - indentUnit: 2, - indentWithTabs: false, - smartIndent: true, - tabSize: 4, - keyMap: "default", - extraKeys: null, - electricChars: true, - autoClearEmptyLines: false, - onKeyEvent: null, - onDragEvent: null, - lineWrapping: false, - lineNumbers: false, - gutter: false, - fixedGutter: false, - firstLineNumber: 1, - readOnly: false, - dragDrop: true, - onChange: null, - onCursorActivity: null, - onViewportChange: null, - onGutterClick: null, - onUpdate: null, - onFocus: null, onBlur: null, onScroll: null, - matchBrackets: false, - cursorBlinkRate: 530, - workTime: 100, - workDelay: 200, - pollInterval: 100, - undoDepth: 40, - tabindex: null, - autofocus: null, - lineNumberFormatter: function(integer) { return integer; } - }; - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var win = /Win/.test(navigator.platform); - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) { - mode.dependencies = []; - for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); - } - modes[name] = mode; - }; - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) - spec = mimeModes[spec]; - else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) - return CodeMirror.resolveMode("application/xml"); - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.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)) modeObj[prop] = exts[prop]; - } - modeObj.name = spec.name; - return modeObj; - }; - CodeMirror.listModes = function() { - var list = []; - for (var m in modes) - if (modes.propertyIsEnumerable(m)) list.push(m); - return list; - }; - CodeMirror.listMIMEs = function() { - var list = []; - for (var m in mimeModes) - if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]}); - return list; - }; - - var extensions = CodeMirror.extensions = {}; - CodeMirror.defineExtension = function(name, func) { - extensions[name] = func; - }; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - for (var prop in properties) if (properties.hasOwnProperty(prop)) - exts[prop] = properties[prop]; - }; - - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, - killLine: function(cm) { - var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); - if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); - else cm.replaceRange("", from, sel ? to : {line: from.line}); - }, - deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - goDocStart: function(cm) {cm.setCursor(0, 0, true);}, - goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, - goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);}, - goLineStartSmart: function(cm) { - var cur = cm.getCursor(); - var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/)); - cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); - }, - goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);}, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharLeft: function(cm) {cm.deleteH(-1, "char");}, - delCharRight: function(cm) {cm.deleteH(1, "char");}, - delWordLeft: function(cm) {cm.deleteH(-1, "word");}, - delWordRight: function(cm) {cm.deleteH(1, "word");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t", "end");}, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.replaceSelection("\t", "end"); - }, - transposeChars: function(cm) { - var cur = cm.getCursor(), line = cm.getLine(cur.line); - if (cur.ch > 0 && cur.ch < line.length - 1) - cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), - {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); - }, - newlineAndIndent: function(cm) { - cm.replaceSelection("\n", "end"); - cm.indentLine(cm.getCursor().line); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - var keyMap = CodeMirror.keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" - }; - // Note that the save and find-related commands aren't defined by - // default. 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", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", - "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "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", - fallthrough: "basic" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", - "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft", - "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "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", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - 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": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft", - "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - - function getKeyMap(val) { - if (typeof val == "string") return keyMap[val]; - else return val; - } - function lookupKey(name, extraMap, map, handle, stop) { - function lookup(map) { - map = getKeyMap(map); - var found = map[name]; - if (found === false) { - if (stop) stop(); - return true; - } - if (found != null && handle(found)) return true; - if (map.nofallthrough) { - if (stop) stop(); - return true; - } - var fallthrough = map.fallthrough; - if (fallthrough == null) return false; - if (Object.prototype.toString.call(fallthrough) != "[object Array]") - return lookup(fallthrough); - for (var i = 0, e = fallthrough.length; i < e; ++i) { - if (lookup(fallthrough[i])) return true; - } - return false; - } - if (extraMap && lookup(extraMap)) return true; - return lookup(map); - } - function isModifierKey(event) { - var name = keyNames[e_prop(event, "keyCode")]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - CodeMirror.isModifierKey = isModifierKey; - - CodeMirror.fromTextArea = function(textarea, options) { - if (!options) options = {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabindex) - options.tabindex = textarea.tabindex; - // 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 = document.body; - // doc.activeElement occasionally throws on IE - try { hasFocus = document.activeElement; } catch(e) {} - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - - function save() {textarea.value = instance.getValue();} - if (textarea.form) { - // Deplorable hack to make the submit method do the right thing. - var rmSubmit = connect(textarea.form, "submit", save, true); - if (typeof textarea.form.submit == "function") { - var realSubmit = textarea.form.submit; - textarea.form.submit = function wrappedSubmit() { - save(); - textarea.form.submit = realSubmit; - textarea.form.submit(); - textarea.form.submit = wrappedSubmit; - }; - } - } - - textarea.style.display = "none"; - var instance = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - instance.save = save; - instance.getTextArea = function() { return textarea; }; - instance.toTextArea = function() { - save(); - textarea.parentNode.removeChild(instance.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - rmSubmit(); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; - } - }; - return instance; - }; - - var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); - var ie = /MSIE \d/.test(navigator.userAgent); - var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); - var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); - var quirksMode = ie && document.documentMode == 5; - var webkit = /WebKit\//.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var opera = /Opera\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var khtml = /KHTML\//.test(navigator.userAgent); - var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent); - - // Utility functions for working with state. Exported because modes - // sometimes need to do this. - 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; - } - CodeMirror.copyState = copyState; - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - CodeMirror.startState = startState; - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state}; - }; - - // The character stream used by a mode's parser. - function StringStream(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - } - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == 0;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() {return countColumn(this.string, this.start, this.tabSize);}, - indentation: function() {return countColumn(this.string, null, this.tabSize);}, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { - 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; - } - }, - current: function(){return this.string.slice(this.start, this.pos);} - }; - CodeMirror.StringStream = StringStream; - - function MarkedSpan(from, to, marker) { - this.from = from; this.to = to; this.marker = 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; - } - } - - 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; - } - - function markedSpansBefore(old, startCh, endCh) { - if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == startCh && span.from != endCh) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push({from: span.from, - to: endsAfter ? null : span.to, - marker: marker}); - } - } - return nw; - } - - function markedSpansAfter(old, endCh) { - if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == endCh) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, - to: span.to == null ? null : span.to - endCh, - marker: marker}); - } - } - return nw; - } - - function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { - if (!oldFirst && !oldLast) return newText; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh); - var last = markedSpansAfter(oldLast, endCh); - - // Next, merge those two ends - var sameLine = newText.length == 1, offset = lst(newText).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 = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - - var newMarkers = [newHL(newText[0], first)]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = newText.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); - for (var i = 0; i < gap; ++i) - newMarkers.push(newHL(newText[i+1], gapMarkers)); - newMarkers.push(newHL(lst(newText), last)); - } - return newMarkers; - } - - // hl stands for history-line, a data structure that can be either a - // string (line without markers) or a {text, markedSpans} object. - function hlText(val) { return typeof val == "string" ? val : val.text; } - function hlSpans(val) { - if (typeof val == "string") return null; - var spans = val.markedSpans, out = null; - 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; - } - function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; } - - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) { - var lines = spans[i].marker.lines; - var ix = indexOf(lines, line); - lines.splice(ix, 1); - } - line.markedSpans = null; - } - - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - var marker = spans[i].marker.lines.push(line); - line.markedSpans = spans; - } - - // When measuring the position of the end of a line, different - // browsers require different approaches. If an empty span is added, - // many browsers report bogus offsets. Of those, some (Webkit, - // recent IE) will accept a space without moving the whole span to - // the next line when wrapping it, others work with a zero-width - // space. - var eolSpanContent = " "; - if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b"; - else if (opera) eolSpanContent = ""; - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - function Line(text, markedSpans) { - this.text = text; - this.height = 1; - attachMarkedSpans(this, markedSpans); - } - Line.prototype = { - update: function(text, markedSpans) { - this.text = text; - this.stateAfter = this.styles = null; - detachMarkedSpans(this); - attachMarkedSpans(this, markedSpans); - }, - // Run the given mode's parser over a line, update the styles - // array, which contains alternating fragments of text and CSS - // classes. - highlight: function(mode, state, tabSize) { - var stream = new StringStream(this.text, tabSize), st = this.styles || (this.styles = []); - var pos = st.length = 0; - if (this.text == "" && mode.blankLine) mode.blankLine(state); - while (!stream.eol()) { - var style = mode.token(stream, state), substr = stream.current(); - stream.start = stream.pos; - if (pos && st[pos-1] == style) { - st[pos-2] += substr; - } else if (substr) { - st[pos++] = substr; st[pos++] = style; - } - // Give up when line is ridiculously long - if (stream.pos > 5000) { - st[pos++] = this.text.slice(stream.pos); st[pos++] = null; - break; - } - } - }, - process: function(mode, state, tabSize) { - var stream = new StringStream(this.text, tabSize); - if (this.text == "" && mode.blankLine) mode.blankLine(state); - while (!stream.eol() && stream.pos <= 5000) { - mode.token(stream, state); - stream.start = stream.pos; - } - }, - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(mode, state, tabSize, ch) { - var txt = this.text, stream = new StringStream(txt, tabSize); - while (stream.pos < ch && !stream.eol()) { - stream.start = stream.pos; - var style = mode.token(stream, state); - } - return {start: stream.start, - end: stream.pos, - string: stream.current(), - className: style || null, - state: state}; - }, - indentation: function(tabSize) {return countColumn(this.text, null, tabSize);}, - // Produces an HTML fragment for the line, taking selection, - // marking, and highlighting into account. - getContent: function(tabSize, wrapAt, compensateForWrapping) { - var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; - var pre = elt("pre"); - function span_(html, text, style) { - if (!text) return; - // Work around a bug where, in some compat modes, IE ignores leading spaces - if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); - first = false; - if (!specials.test(text)) { - col += text.length; - var content = document.createTextNode(text); - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - specials.lastIndex = pos; - var m = specials.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); - col += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabWidth = tabSize - col % tabSize; - content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - col += tabWidth; - } else { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + m[0].charCodeAt(0).toString(16); - content.appendChild(token); - col += 1; - } - } - } - if (style) html.appendChild(elt("span", [content], style)); - else html.appendChild(content); - } - var span = span_; - if (wrapAt != null) { - var outPos = 0, anchor = pre.anchor = elt("span"); - span = function(html, text, style) { - var l = text.length; - if (wrapAt >= outPos && wrapAt < outPos + l) { - var cut = wrapAt - outPos; - if (cut) { - span_(html, text.slice(0, cut), style); - // See comment at the definition of spanAffectsWrapping - if (compensateForWrapping) { - var view = text.slice(cut - 1, cut + 1); - if (spanAffectsWrapping.test(view)) html.appendChild(elt("wbr")); - else if (!ie_lt8 && /\w\w/.test(view)) html.appendChild(document.createTextNode("\u200d")); - } - } - html.appendChild(anchor); - span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style); - if (opera) span_(html, text.slice(cut + 1), style); - wrapAt--; - outPos += l; - } else { - outPos += l; - span_(html, text, style); - if (outPos == wrapAt && outPos == len) { - setTextContent(anchor, eolSpanContent); - html.appendChild(anchor); - } - // Stop outputting HTML when gone sufficiently far beyond measure - else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){}; - } - }; - } - - var st = this.styles, allText = this.text, marked = this.markedSpans; - var len = allText.length; - function styleToClass(style) { - if (!style) return null; - return "cm-" + style.replace(/ +/g, " cm-"); - } - if (!allText && wrapAt == null) { - span(pre, " "); - } else if (!marked || !marked.length) { - for (var i = 0, ch = 0; ch < len; i+=2) { - var str = st[i], style = st[i+1], l = str.length; - if (ch + l > len) str = str.slice(0, len - ch); - ch += l; - span(pre, str, styleToClass(style)); - } - } else { - marked.sort(function(a, b) { return a.from - b.from; }); - var pos = 0, i = 0, text = "", style, sg = 0; - var nextChange = marked[0].from || 0, marks = [], markpos = 0; - var advanceMarks = function() { - var m; - while (markpos < marked.length && - ((m = marked[markpos]).from == pos || m.from == null)) { - if (m.marker.type == "range") marks.push(m); - ++markpos; - } - nextChange = markpos < marked.length ? marked[markpos].from : Infinity; - for (var i = 0; i < marks.length; ++i) { - var to = marks[i].to; - if (to == null) to = Infinity; - if (to == pos) marks.splice(i--, 1); - else nextChange = Math.min(to, nextChange); - } - }; - var m = 0; - while (pos < len) { - if (nextChange == pos) advanceMarks(); - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - var appliedStyle = style; - for (var j = 0; j < marks.length; ++j) { - var mark = marks[j]; - appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style; - if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle; - if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle; - } - span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle); - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - } - text = st[i++]; style = styleToClass(st[i++]); - } - } - } - return pre; - }, - cleanUp: function() { - this.parent = null; - detachMarkedSpans(this); - } - }; - - // Data structure that holds the sequence of lines. - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, e = lines.length, height = 0; i < e; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - remove: function(at, n, callbacks) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - line.cleanUp(); - if (line.handlers) - for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]); - } - this.lines.splice(at, n); - }, - collapse: function(lines) { - lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); - }, - insertHeight: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; - }, - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0, e = children.length; i < e; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - remove: function(at, n, callbacks) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.remove(at, rm, callbacks); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - if (this.size - n < 25) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); - }, - insert: function(at, lines) { - var height = 0; - for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; - this.insertHeight(at, lines, height); - }, - insertHeight: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertHeight(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - 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(); - }, - iter: function(from, to, op) { this.iterN(from, to - from, op); }, - iterN: function(at, n, op) { - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.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; - } - } - }; - - function getLineAt(chunk, n) { - 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]; - } - 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, e = chunk.children.length; ; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no; - } - function lineAtHeight(chunk, h) { - var n = 0; - outer: do { - for (var i = 0, e = chunk.children.length; i < e; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0, e = chunk.lines.length; i < e; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - function heightAtLine(chunk, n) { - var h = 0; - outer: do { - for (var i = 0, e = chunk.children.length; i < e; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; continue outer; } - n -= sz; - h += child.height; - } - return h; - } while (!chunk.lines); - for (var i = 0; i < n; ++i) h += chunk.lines[i].height; - return h; - } - - // The history object 'chunks' changes that are made close together - // and at almost the same time into bigger undoable units. - function History() { - this.time = 0; - this.done = []; this.undone = []; - this.compound = 0; - this.closed = false; - } - History.prototype = { - addChange: function(start, added, old) { - this.undone.length = 0; - var time = +new Date, cur = lst(this.done), last = cur && lst(cur); - var dtime = time - this.time; - - if (cur && !this.closed && this.compound) { - cur.push({start: start, added: added, old: old}); - } else if (dtime > 400 || !last || this.closed || - last.start > start + old.length || last.start + last.added < start) { - this.done.push([{start: start, added: added, old: old}]); - this.closed = false; - } else { - var startBefore = Math.max(0, last.start - start), - endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); - for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); - for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); - if (startBefore) last.start = start; - last.added += added - (old.length - startBefore - endAfter); - } - this.time = time; - }, - startCompound: function() { - if (!this.compound++) this.closed = true; - }, - endCompound: function() { - if (!--this.compound) this.closed = true; - } - }; - - function stopMethod() {e_stop(this);} - // Ensure an event has a stop method. - function addStop(event) { - if (!event.stop) event.stop = stopMethod; - return event; - } - - 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_stop(e) {e_preventDefault(e); e_stopPropagation(e);} - CodeMirror.e_stop = e_stop; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - - 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; - } - - // Allow 3rd-party code to override event properties by adding an override - // object to an event object. - function e_prop(e, prop) { - var overridden = e.override && e.override.hasOwnProperty(prop); - return overridden ? e.override[prop] : e[prop]; - } - - // Event handler registration. If disconnect is true, it'll return a - // function that unregisters the handler. - function connect(node, type, handler, disconnect) { - if (typeof node.addEventListener == "function") { - node.addEventListener(type, handler, false); - if (disconnect) return function() {node.removeEventListener(type, handler, false);}; - } else { - var wrapHandler = function(event) {handler(event || window.event);}; - node.attachEvent("on" + type, wrapHandler); - if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; - } - } - CodeMirror.connect = connect; - - function Delayed() {this.id = null;} - Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; - - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - // 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_lt9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - // Feature-detect whether newlines in textareas are converted to \r\n - var lineSep = function () { - var te = elt("textarea"); - te.value = "foo\nbar"; - if (te.value.indexOf("\r") > -1) return "\r\n"; - return "\n"; - }(); - - // For a reason I have yet to figure out, some browsers disallow - // word wrapping between certain characters *only* if a new inline - // element is started between them. This makes it hard to reliably - // measure the position of things, since that requires inserting an - // extra span. This terribly fragile set of regexps matches the - // character combinations that suffer from this phenomenon on the - // various browsers. - var spanAffectsWrapping = /^$/; // Won't match any two-character string - if (gecko) spanAffectsWrapping = /$'/; - else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; - else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = 0, n = 0; i < end; ++i) { - if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); - else ++n; - } - return n; - } - - function eltOffset(node, screen) { - // Take the parts of bounding client rect that we are interested in so we are able to edit if need be, - // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page) - try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; } - catch(e) { box = {top: 0, left: 0}; } - if (!screen) { - // Get the toplevel scroll, working around browser differences. - if (window.pageYOffset == null) { - var t = document.documentElement || document.body.parentNode; - if (t.scrollTop == null) t = document.body; - box.top += t.scrollTop; box.left += t.scrollLeft; - } else { - box.top += window.pageYOffset; box.left += window.pageXOffset; - } - } - return box; - } - - function eltText(node) { - return node.textContent || node.innerText || node.nodeValue || ""; - } - - 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 selectInput(node) { - if (ios) { // Mobile Safari apparently has a bug where select() is broken. - node.selectionStart = 0; - node.selectionEnd = node.value.length; - } else node.select(); - } - - // Operations on {line, ch} objects. - function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} - function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} - function copyPos(x) {return {line: x.line, ch: x.ch};} - - 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") setTextContent(e, content); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - function removeChildren(e) { - e.innerHTML = ""; - return e; - } - function removeChildrenAndAdd(parent, e) { - removeChildren(parent).appendChild(e); - } - function setTextContent(e, str) { - if (ie_lt9) { - e.innerHTML = ""; - e.appendChild(document.createTextNode(str)); - } else e.textContent = str; - } - - // Used to position the cursor after an undo/redo by finding the - // last edited character. - function editEnd(from, to) { - if (!to) return 0; - if (!from) return to.length; - for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) - if (from.charAt(i) != to.charAt(j)) break; - return j + 1; - } - - function indexOf(collection, elt) { - if (collection.indexOf) return collection.indexOf(elt); - for (var i = 0, e = collection.length; i < e; ++i) - if (collection[i] == elt) return i; - return -1; - } - function isWordChar(ch) { - return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase() || /[\u4E00-\u9FA5]/.test(ch); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = "\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/);}; - CodeMirror.splitLines = splitLines; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - var keyNames = {3: "Enter", 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: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", - 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", - 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; - CodeMirror.keyNames = keyNames; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - CodeMirror.version = "2.35"; - - return CodeMirror; -})(); +// All functions that need access to the editor's state live inside +// the CodeMirror function. Below that, at the bottom of the file, +// some utilities are defined. + +// CodeMirror is the only global var we claim +window.CodeMirror = (function() { + "use strict"; + // This is the function that produces an editor instance. Its + // closure is used to store the editor state. + function CodeMirror(place, givenOptions) { + // Determine effective options based on given values and defaults. + var options = {}, defaults = CodeMirror.defaults; + for (var opt in defaults) + if (defaults.hasOwnProperty(opt)) + options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; + + var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em"); + input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); + // Wraps and hides input textarea + var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The empty scrollbar content, used solely for managing the scrollbar thumb. + var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner"); + // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself. + var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar"); + // DIVs containing the selection and the actual code + var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1"); + // Blinky cursor, and element used to ensure cursor fits at the end of a line + var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden"); + // Used to measure text size + var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;"); + var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0"); + var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter"); + // Moved around its parent to cover visible view + var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the text, causes scrolling + var sizer = elt("div", [mover], null, "position: relative"); + // Provides scrolling + var scroller = elt("div", [sizer], "CodeMirror-scroll"); + scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "")); + if (place.appendChild) place.appendChild(wrapper); else place(wrapper); + + themeChanged(); keyMapChanged(); + // Needed to hide big blue blinking cursor on Mobile Safari + if (ios) input.style.width = "0px"; + if (!webkit) scroller.draggable = true; + lineSpace.style.outline = "none"; + if (options.tabindex != null) input.tabIndex = options.tabindex; + if (options.autofocus) focusInput(); + if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; + // Needed to handle Tab key in KHTML + if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute"; + + // Check for OS X >= 10.7. This has transparent scrollbars, so the + // overlaying of one scrollbar with another won't work. This is a + // temporary hack to simply turn off the overlay scrollbar. See + // issue #727. + if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; } + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + else if (ie_lt8) scrollbar.style.minWidth = "18px"; + + // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval. + var poll = new Delayed(), highlight = new Delayed(), blinker; + + // mode holds a mode API object. doc is the tree of Line objects, + // frontier is the point up to which the content has been parsed, + // and history the undo history (instance of History constructor). + var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), frontier = 0, focused; + loadMode(); + // The selection. These are always maintained to point at valid + // positions. Inverted is used to remember that the user is + // selecting bottom-to-top. + var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false}; + // Selection-related flags. shiftSelecting obviously tracks + // whether the user is holding shift. + var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText, + overwrite = false, suppressEdits = false, pasteIncoming = false; + // Variables used by startOperation/endOperation to track what + // happened during the operation. + var updateInput, userSelChange, changes, textChanged, selectionChanged, + gutterDirty, callbacks; + // Current visible range (may be bigger than the view window). + var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0; + // bracketHighlighted is used to remember that a bracket has been + // marked. + var bracketHighlighted; + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true; + var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll + var goalColumn = null; + + // Initialize the content. + operation(function(){setValue(options.value || ""); updateInput = false;})(); + var history = new History(); + + // Register our event handlers. + connect(scroller, "mousedown", operation(onMouseDown)); + connect(scroller, "dblclick", operation(onDoubleClick)); + connect(lineSpace, "selectstart", e_preventDefault); + // Gecko browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for Gecko. + if (!gecko) connect(scroller, "contextmenu", onContextMenu); + connect(scroller, "scroll", onScrollMain); + connect(scrollbar, "scroll", onScrollBar); + connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);}); + var resizeHandler = connect(window, "resize", function() { + if (wrapper.parentNode) updateDisplay(true); + else resizeHandler(); + }, true); + connect(input, "keyup", operation(onKeyUp)); + connect(input, "input", fastPoll); + connect(input, "keydown", operation(onKeyDown)); + connect(input, "keypress", operation(onKeyPress)); + connect(input, "focus", onFocus); + connect(input, "blur", onBlur); + + function drag_(e) { + if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; + e_stop(e); + } + if (options.dragDrop) { + connect(scroller, "dragstart", onDragStart); + connect(scroller, "dragenter", drag_); + connect(scroller, "dragover", drag_); + connect(scroller, "drop", operation(onDrop)); + } + connect(scroller, "paste", function(){focusInput(); fastPoll();}); + connect(input, "paste", function(){pasteIncoming = true; fastPoll();}); + connect(input, "cut", operation(function(){ + if (!options.readOnly) replaceSelection(""); + })); + + // Needed to handle Tab key in KHTML + if (khtml) connect(sizer, "mouseup", function() { + if (document.activeElement == input) input.blur(); + focusInput(); + }); + + // IE throws unspecified error in certain cases, when + // trying to access activeElement before onload + var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { } + if (hasFocus || options.autofocus) setTimeout(onFocus, 20); + else onBlur(); + + function isLine(l) {return l >= 0 && l < doc.size;} + // The instance object that we'll return. Mostly calls out to + // local functions in the CodeMirror function. Some do some extra + // range checking and/or clipping. operation is used to wrap the + // call so that changes it makes are tracked, and the display is + // updated afterwards. + var instance = wrapper.CodeMirror = { + getValue: getValue, + setValue: operation(setValue), + getSelection: getSelection, + replaceSelection: operation(replaceSelection), + focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();}, + setOption: function(option, value) { + var oldVal = options[option]; + options[option] = value; + if (option == "mode" || option == "indentUnit") loadMode(); + else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();} + else if (option == "readOnly" && !value) {resetInput(true);} + else if (option == "theme") themeChanged(); + else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); + else if (option == "tabSize") updateDisplay(true); + else if (option == "keyMap") keyMapChanged(); + else if (option == "tabindex") input.tabIndex = value; + else if (option == "showCursorWhenSelecting") updateSelection(); + if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || + option == "theme" || option == "lineNumberFormatter") { + gutterChanged(); + updateDisplay(true); + } + }, + getOption: function(option) {return options[option];}, + getMode: function() {return mode;}, + undo: operation(undo), + redo: operation(redo), + indentLine: operation(function(n, dir) { + if (typeof dir != "string") { + if (dir == null) dir = options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(n)) indentLine(n, dir); + }), + indentSelection: operation(indentSelected), + historySize: function() {return {undo: history.done.length, redo: history.undone.length};}, + clearHistory: function() {history = new History();}, + setHistory: function(histData) { + history = new History(); + history.done = histData.done; + history.undone = histData.undone; + }, + getHistory: function() { + function cp(arr) { + for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { + nw.push(nwelt = []); + for (var j = 0, elt = arr[i]; j < elt.length; ++j) { + var old = [], cur = elt[j]; + nwelt.push({start: cur.start, added: cur.added, old: old}); + for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); + } + } + return nw; + } + return {done: cp(history.done), undone: cp(history.undone)}; + }, + matchBrackets: operation(function(){matchBrackets(true);}), + getTokenAt: operation(function(pos) { + pos = clipPos(pos); + return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch); + }), + getStateAfter: function(line) { + line = clipLine(line == null ? doc.size - 1: line); + return getStateBefore(line + 1); + }, + cursorCoords: function(start, mode) { + if (start == null) start = sel.inverted; + return this.charCoords(start ? sel.from : sel.to, mode); + }, + charCoords: function(pos, mode) { + pos = clipPos(pos); + if (mode == "local") return localCoords(pos, false); + if (mode == "div") return localCoords(pos, true); + return pageCoords(pos); + }, + coordsChar: function(coords) { + var off = eltOffset(lineSpace); + return coordsChar(coords.x - off.left, coords.y - off.top); + }, + defaultTextHeight: function() { return textHeight(); }, + markText: operation(markText), + setBookmark: setBookmark, + findMarksAt: findMarksAt, + setMarker: operation(addGutterMarker), + clearMarker: operation(removeGutterMarker), + setLineClass: operation(setLineClass), + hideLine: operation(function(h) {return setLineHidden(h, true);}), + showLine: operation(function(h) {return setLineHidden(h, false);}), + onDeleteLine: function(line, f) { + if (typeof line == "number") { + if (!isLine(line)) return null; + line = getLine(line); + } + (line.handlers || (line.handlers = [])).push(f); + return line; + }, + lineInfo: lineInfo, + getViewport: function() { return {from: showingFrom, to: showingTo};}, + addWidget: function(pos, node, scroll, vert, horiz) { + pos = localCoords(clipPos(pos)); + var top = pos.yBot, left = pos.x; + node.style.position = "absolute"; + sizer.appendChild(node); + if (vert == "over") top = pos.y; + else if (vert == "near") { + var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), + hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft(); + if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) + top = pos.y - node.offsetHeight; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = (top + paddingTop()) + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = (left + paddingLeft()) + "px"; + } + if (scroll) + scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + + lineCount: function() {return doc.size;}, + clipPos: clipPos, + getCursor: function(start) { + if (start == null || start == "head") start = sel.inverted; + if (start == "anchor") start = !sel.inverted; + if (start == "end") start = false; + return copyPos(start ? sel.from : sel.to); + }, + somethingSelected: function() {return !posEq(sel.from, sel.to);}, + setCursor: operation(function(line, ch, user) { + if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); + else setCursor(line, ch, user); + }), + setSelection: operation(function(from, to, user) { + (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); + }), + getLine: function(line) {if (isLine(line)) return getLine(line).text;}, + getLineHandle: function(line) {if (isLine(line)) return getLine(line);}, + setLine: operation(function(line, text) { + if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); + }), + removeLine: operation(function(line) { + if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0})); + }), + replaceRange: operation(replaceRange), + getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);}, + + triggerOnKeyDown: operation(onKeyDown), + execCommand: function(cmd) {return commands[cmd](instance);}, + // Stuff used by commands, probably not much use to outside code. + moveH: operation(moveH), + deleteH: operation(deleteH), + moveV: operation(moveV), + toggleOverwrite: function() { + if(overwrite){ + overwrite = false; + cursor.className = cursor.className.replace(" CodeMirror-overwrite", ""); + } else { + overwrite = true; + cursor.className += " CodeMirror-overwrite"; + } + }, + + posFromIndex: function(off) { + var lineNo = 0, ch; + doc.iter(0, doc.size, function(line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos({line: lineNo, ch: ch}); + }, + indexFromPos: function (coords) { + if (coords.line < 0 || coords.ch < 0) return 0; + var index = coords.ch; + doc.iter(0, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + scrollTo: function(x, y) { + if (x != null) scroller.scrollLeft = x; + if (y != null) scrollbar.scrollTop = scroller.scrollTop = y; + updateDisplay([]); + }, + getScrollInfo: function() { + return {x: scroller.scrollLeft, y: scrollbar.scrollTop, + height: scrollbar.scrollHeight, width: scroller.scrollWidth}; + }, + scrollIntoView: function(pos) { + var coords = localCoords(pos ? clipPos(pos) : sel.inverted ? sel.from : sel.to); + scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); + }, + + setSize: function(width, height) { + function interpret(val) { + val = String(val); + return /^\d+$/.test(val) ? val + "px" : val; + } + if (width != null) wrapper.style.width = interpret(width); + if (height != null) scroller.style.height = interpret(height); + instance.refresh(); + }, + + operation: function(f){return operation(f)();}, + compoundChange: function(f){return compoundChange(f);}, + refresh: function(){ + updateDisplay(true, null, lastScrollTop); + if (scrollbar.scrollHeight > lastScrollTop) + scrollbar.scrollTop = lastScrollTop; + }, + getInputField: function(){return input;}, + getWrapperElement: function(){return wrapper;}, + getScrollerElement: function(){return scroller;}, + getGutterElement: function(){return gutter;} + }; + + function getLine(n) { return getLineAt(doc, n); } + function updateLineHeight(line, height) { + gutterDirty = true; + var diff = height - line.height; + for (var n = line; n; n = n.parent) n.height += diff; + } + + function lineContent(line, wrapAt) { + if (!line.styles) + line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize); + return line.getContent(options.tabSize, wrapAt, options.lineWrapping); + } + + function setValue(code) { + var top = {line: 0, ch: 0}; + updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length}, + splitLines(code), top, top); + updateInput = true; + } + function getValue(lineSep) { + var text = []; + doc.iter(0, doc.size, function(line) { text.push(line.text); }); + return text.join(lineSep || "\n"); + } + + function onScrollBar(e) { + if (Math.abs(scrollbar.scrollTop - lastScrollTop) > 1) { + lastScrollTop = scroller.scrollTop = scrollbar.scrollTop; + updateDisplay([]); + } + } + + function onScrollMain(e) { + if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px") + gutter.style.left = scroller.scrollLeft + "px"; + if (Math.abs(scroller.scrollTop - lastScrollTop) > 1) { + lastScrollTop = scroller.scrollTop; + if (scrollbar.scrollTop != lastScrollTop) + scrollbar.scrollTop = lastScrollTop; + updateDisplay([]); + } + if (options.onScroll) options.onScroll(instance); + } + + function onMouseDown(e) { + setShift(e_prop(e, "shiftKey")); + // Check whether this is a click in a widget + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == sizer && n != mover) return; + + // See if this is a click in the gutter + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == gutterText) { + if (options.onGutterClick) + options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); + return e_preventDefault(e); + } + + var start = posFromMouse(e); + + switch (e_button(e)) { + case 3: + if (gecko) onContextMenu(e); + return; + case 2: + if (start) setCursor(start.line, start.ch, true); + setTimeout(focusInput, 20); + e_preventDefault(e); + return; + } + // For button 1, if it was clicked inside the editor + // (posFromMouse returning non-null), we have to adjust the + // selection. + if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;} + + if (!focused) onFocus(); + + var now = +new Date, type = "single"; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { + type = "triple"; + e_preventDefault(e); + setTimeout(focusInput, 20); + selectLine(start.line); + } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + e_preventDefault(e); + var word = findWordAt(start); + setSelectionUser(word.from, word.to); + } else { lastClick = {time: now, pos: start}; } + + function dragEnd(e2) { + if (webkit) scroller.draggable = false; + draggingText = false; + up(); drop(); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + setCursor(start.line, start.ch, true); + focusInput(); + } + } + var last = start, going; + if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) && + !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { + // Let the drag handler handle this. + if (webkit) scroller.draggable = true; + var up = connect(document, "mouseup", operation(dragEnd), true); + var drop = connect(scroller, "drop", operation(dragEnd), true); + draggingText = true; + // IE's approach to draggable + if (scroller.dragDrop) scroller.dragDrop(); + return; + } + e_preventDefault(e); + if (type == "single") setCursor(start.line, start.ch, true); + + var startstart = sel.from, startend = sel.to; + + function doSelect(cur) { + if (type == "single") { + setSelectionUser(clipPos(start), cur); + return; + } + startstart = clipPos(startstart); + startend = clipPos(startend); + if (type == "double") { + var word = findWordAt(cur); + if (posLess(cur, startstart)) setSelectionUser(word.from, startend); + else setSelectionUser(startstart, word.to); + } else if (type == "triple") { + if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0})); + else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0})); + } + } + + function extend(e) { + var cur = posFromMouse(e, true); + if (cur && !posEq(cur, last)) { + if (!focused) onFocus(); + last = cur; + doSelect(cur); + updateInput = false; + var visible = visibleLines(); + if (cur.line >= visible.to || cur.line < visible.from) + going = setTimeout(operation(function(){extend(e);}), 150); + } + } + + function done(e) { + clearTimeout(going); + var cur = posFromMouse(e); + if (cur) doSelect(cur); + e_preventDefault(e); + focusInput(); + updateInput = true; + move(); up(); + } + var move = connect(document, "mousemove", operation(function(e) { + clearTimeout(going); + e_preventDefault(e); + if (!ie && !e_button(e)) done(e); + else extend(e); + }), true); + var up = connect(document, "mouseup", operation(done), true); + } + function onDoubleClick(e) { + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == gutterText) return e_preventDefault(e); + e_preventDefault(e); + } + function onDrop(e) { + if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; + e_preventDefault(e); + var pos = posFromMouse(e, true), files = e.dataTransfer.files; + if (!pos || options.readOnly) return; + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function(file, i) { + var reader = new FileReader; + reader.onload = function() { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(pos); + operation(function() { + var end = replaceRange(text.join(""), pos, pos); + setSelectionUser(pos, end); + })(); + } + }; + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { + // Don't do a replace if the drop happened inside of the selected text. + if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return; + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + compoundChange(function() { + var curFrom = sel.from, curTo = sel.to; + setSelectionUser(pos, pos); + if (draggingText) replaceRange("", curFrom, curTo); + replaceSelection(text); + focusInput(); + }); + } + } + catch(e){} + } + } + function onDragStart(e) { + var txt = getSelection(); + e.dataTransfer.setData("Text", txt); + + // Use dummy image instead of default browsers image. + if (e.dataTransfer.setDragImage) + e.dataTransfer.setDragImage(elt('img'), 0, 0); + } + + function doHandleBinding(bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + var prevShift = shiftSelecting; + try { + if (options.readOnly) suppressEdits = true; + if (dropShift) shiftSelecting = null; + bound(instance); + } catch(e) { + if (e != Pass) throw e; + return false; + } finally { + shiftSelecting = prevShift; + suppressEdits = false; + } + return true; + } + var maybeTransition; + function handleKeyBinding(e) { + // Handle auto keymap transitions + var startMap = getKeyMap(options.keyMap), next = startMap.auto; + clearTimeout(maybeTransition); + if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { + if (getKeyMap(options.keyMap) == startMap) { + options.keyMap = (next.call ? next.call(null, instance) : next); + } + }, 50); + + var name = keyNames[e_prop(e, "keyCode")], handled = false; + if (name == null || e.altGraphKey) return false; + if (e_prop(e, "altKey")) name = "Alt-" + name; + if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; + if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; + + var stopped = false; + function stop() { stopped = true; } + + if (e_prop(e, "shiftKey")) { + handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap, + function(b) {return doHandleBinding(b, true);}, stop) + || lookupKey(name, options.extraKeys, options.keyMap, function(b) { + if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b); + }, stop); + } else { + handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop); + } + if (stopped) handled = false; + if (handled) { + e_preventDefault(e); + restartBlink(); + if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } + } + return handled; + } + function handleCharBinding(e, ch) { + var handled = lookupKey("'" + ch + "'", options.extraKeys, + options.keyMap, function(b) { return doHandleBinding(b, true); }); + if (handled) { + e_preventDefault(e); + restartBlink(); + } + return handled; + } + + var lastStoppedKey = null; + function onKeyDown(e) { + if (!focused) onFocus(); + if (ie && e.keyCode == 27) { e.returnValue = false; } + if (pollingFast) { if (readInput()) pollingFast = false; } + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + var code = e_prop(e, "keyCode"); + // IE does strange things with escape. + setShift(code == 16 || e_prop(e, "shiftKey")); + // First give onKeyEvent option a chance to handle this. + var handled = handleKeyBinding(e); + if (opera) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) + replaceSelection(""); + } + } + function onKeyPress(e) { + if (pollingFast) readInput(); + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); + if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { + if (mode.electricChars.indexOf(ch) > -1) + setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75); + } + if (handleCharBinding(e, ch)) return; + fastPoll(); + } + function onKeyUp(e) { + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + if (e_prop(e, "keyCode") == 16) shiftSelecting = null; + } + + function onFocus() { + if (options.readOnly == "nocursor") return; + if (!focused) { + if (options.onFocus) options.onFocus(instance); + focused = true; + if (scroller.className.search(/\bCodeMirror-focused\b/) == -1) + scroller.className += " CodeMirror-focused"; + } + slowPoll(); + restartBlink(); + } + function onBlur() { + if (focused) { + if (options.onBlur) options.onBlur(instance); + focused = false; + if (bracketHighlighted) + operation(function(){ + if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; } + })(); + scroller.className = scroller.className.replace(" CodeMirror-focused", ""); + } + clearInterval(blinker); + setTimeout(function() {if (!focused) shiftSelecting = null;}, 150); + } + + // Replace the range from from to to by the strings in newText. + // Afterwards, set the selection to selFrom, selTo. + function updateLines(from, to, newText, selFrom, selTo) { + if (suppressEdits) return; + var old = []; + doc.iter(from.line, to.line + 1, function(line) { + old.push(newHL(line.text, line.markedSpans)); + }); + if (history) { + history.addChange(from.line, newText.length, old); + while (history.done.length > options.undoDepth) history.done.shift(); + } + var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); + updateLinesNoUndo(from, to, lines, selFrom, selTo); + } + function unredoHelper(from, to) { + if (!from.length) return; + var set = from.pop(), out = []; + for (var i = set.length - 1; i >= 0; i -= 1) { + var change = set[i]; + var replaced = [], end = change.start + change.added; + doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); }); + out.push({start: change.start, added: change.old.length, old: replaced}); + var pos = {line: change.start + change.old.length - 1, + ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))}; + updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, + change.old, pos, pos); + } + updateInput = true; + to.push(out); + } + function undo() {unredoHelper(history.done, history.undone);} + function redo() {unredoHelper(history.undone, history.done);} + + function updateLinesNoUndo(from, to, lines, selFrom, selTo) { + if (suppressEdits) return; + var recomputeMaxLength = false, maxLineLength = maxLine.text.length; + if (!options.lineWrapping) + doc.iter(from.line, to.line + 1, function(line) { + if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;} + }); + if (from.line != to.line || lines.length > 1) gutterDirty = true; + + var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line); + var lastHL = lst(lines); + + // First adjust the line structure + if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = [], prevLine = null; + for (var i = 0, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + lastLine.update(lastLine.text, hlSpans(lastHL)); + if (nlines) doc.remove(from.line, nlines, callbacks); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (lines.length == 1) { + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0])); + } else { + for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL))); + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + doc.insert(from.line + 1, added); + } + } else if (lines.length == 1) { + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0])); + doc.remove(from.line + 1, nlines, callbacks); + } else { + var added = []; + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); + for (var i = 1, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks); + doc.insert(from.line + 1, added); + } + if (options.lineWrapping) { + var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3); + doc.iter(from.line, from.line + lines.length, function(line) { + if (line.hidden) return; + var guess = Math.ceil(line.text.length / perLine) || 1; + if (guess != line.height) updateLineHeight(line, guess); + }); + } else { + doc.iter(from.line, from.line + lines.length, function(line) { + var l = line.text; + if (!line.hidden && l.length > maxLineLength) { + maxLine = line; maxLineLength = l.length; maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) updateMaxLine = true; + } + + // Adjust frontier, schedule worker + frontier = Math.min(frontier, from.line); + startWorker(400); + + var lendiff = lines.length - nlines - 1; + // Remember that these lines changed, for updating the display + changes.push({from: from.line, to: to.line + 1, diff: lendiff}); + if (options.onChange) { + // Normalize lines to contain only strings, since that's what + // the change event handler expects + for (var i = 0; i < lines.length; ++i) + if (typeof lines[i] != "string") lines[i] = lines[i].text; + var changeObj = {from: from, to: to, text: lines}; + if (textChanged) { + for (var cur = textChanged; cur.next; cur = cur.next) {} + cur.next = changeObj; + } else textChanged = changeObj; + } + + // Update the selection + function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;} + setSelection(clipPos(selFrom), clipPos(selTo), + updateLine(sel.from.line), updateLine(sel.to.line)); + } + + function needsScrollbar() { + var realHeight = doc.height * textHeight() + 2 * paddingTop(); + return realHeight * .99 > scroller.offsetHeight ? realHeight : false; + } + + function updateVerticalScroll(scrollTop) { + var scrollHeight = needsScrollbar(); + scrollbar.style.display = scrollHeight ? "block" : "none"; + if (scrollHeight) { + scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px"; + scrollbar.style.height = scroller.clientHeight + "px"; + if (scrollTop != null) { + scrollbar.scrollTop = scroller.scrollTop = scrollTop; + // 'Nudge' the scrollbar to work around a Webkit bug where, + // in some situations, we'd end up with a scrollbar that + // reported its scrollTop (and looked) as expected, but + // *behaved* as if it was still in a previous state (i.e. + // couldn't scroll up, even though it appeared to be at the + // bottom). + if (webkit) setTimeout(function() { + if (scrollbar.scrollTop != scrollTop) return; + scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1); + scrollbar.scrollTop = scrollTop; + }, 0); + } + } else { + sizer.style.minHeight = ""; + } + // Position the mover div to align with the current virtual scroll position + mover.style.top = displayOffset * textHeight() + "px"; + } + + function computeMaxLength() { + maxLine = getLine(0); maxLineChanged = true; + var maxLineLength = maxLine.text.length; + doc.iter(1, doc.size, function(line) { + var l = line.text; + if (!line.hidden && l.length > maxLineLength) { + maxLineLength = l.length; maxLine = line; + } + }); + updateMaxLine = false; + } + + function replaceRange(code, from, to) { + from = clipPos(from); + if (!to) to = from; else to = clipPos(to); + code = splitLines(code); + function adjustPos(pos) { + if (posLess(pos, from)) return pos; + if (!posLess(to, pos)) return end; + var line = pos.line + code.length - (to.line - from.line) - 1; + var ch = pos.ch; + if (pos.line == to.line) + ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0)); + return {line: line, ch: ch}; + } + var end; + replaceRange1(code, from, to, function(end1) { + end = end1; + return {from: adjustPos(sel.from), to: adjustPos(sel.to)}; + }); + return end; + } + function replaceSelection(code, collapse) { + replaceRange1(splitLines(code), sel.from, sel.to, function(end) { + if (collapse == "end") return {from: end, to: end}; + else if (collapse == "start") return {from: sel.from, to: sel.from}; + else return {from: sel.from, to: end}; + }); + } + function replaceRange1(code, from, to, computeSel) { + var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length; + var newSel = computeSel({line: from.line + code.length - 1, ch: endch}); + updateLines(from, to, code, newSel.from, newSel.to); + } + + function getRange(from, to, lineSep) { + var l1 = from.line, l2 = to.line; + if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); + var code = [getLine(l1).text.slice(from.ch)]; + doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); + code.push(getLine(l2).text.slice(0, to.ch)); + return code.join(lineSep || "\n"); + } + function getSelection(lineSep) { + return getRange(sel.from, sel.to, lineSep); + } + + function slowPoll() { + if (pollingFast) return; + poll.set(options.pollInterval, function() { + readInput(); + if (focused) slowPoll(); + }); + } + function fastPoll() { + var missed = false; + pollingFast = true; + function p() { + var changed = readInput(); + if (!changed && !missed) {missed = true; poll.set(60, p);} + else {pollingFast = false; slowPoll();} + } + poll.set(20, p); + } + + // Previnput is a hack to work with IME. If we reset the textarea + // on every change, that breaks IME. So we look for changes + // compared to the previous content instead. (Modern browsers have + // events that indicate IME taking place, but these are not widely + // supported or compatible enough yet to rely on.) + var prevInput = ""; + function readInput() { + if (!focused || hasSelection(input) || options.readOnly) return false; + var text = input.value; + if (text == prevInput) return false; + if (!nestedOperation) startOperation(); + shiftSelecting = null; + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput[same] == text[same]) ++same; + if (same < prevInput.length) + sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; + else if (overwrite && posEq(sel.from, sel.to) && !pasteIncoming) + sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))}; + replaceSelection(text.slice(same), "end"); + if (text.length > 1000) { input.value = prevInput = ""; } + else prevInput = text; + if (!nestedOperation) endOperation(); + pasteIncoming = false; + return true; + } + function resetInput(user) { + if (!posEq(sel.from, sel.to)) { + prevInput = ""; + input.value = getSelection(); + if (focused) selectInput(input); + } else if (user) prevInput = input.value = ""; + } + + function focusInput() { + if (options.readOnly != "nocursor" && (ie_lt9 || document.activeElement != input)) + input.focus(); + } + + function scrollCursorIntoView() { + var coords = calculateCursorCoords(); + scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); + if (!focused) return; + var box = sizer.getBoundingClientRect(), doScroll = null; + if (coords.y + box.top < 0) doScroll = true; + else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null) { + var hidden = cursor.style.display == "none"; + if (hidden) { + cursor.style.display = ""; + cursor.style.left = coords.x + "px"; + cursor.style.top = (coords.y - displayOffset) + "px"; + } + cursor.scrollIntoView(doScroll); + if (hidden) cursor.style.display = "none"; + } + } + function calculateCursorCoords() { + var cursor = localCoords(sel.inverted ? sel.from : sel.to); + var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; + return {x: x, y: cursor.y, yBot: cursor.yBot}; + } + function scrollIntoView(x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(x1, y1, x2, y2); + if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;} + if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;} + } + function calculateScrollPos(x1, y1, x2, y2) { + var pl = paddingLeft(), pt = paddingTop(); + y1 += pt; y2 += pt; x1 += pl; x2 += pl; + var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {}; + var docBottom = needsScrollbar() || Infinity; + var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; + if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); + else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; + + var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft; + var gutterw = options.fixedGutter ? gutter.clientWidth : 0; + var atLeft = x1 < gutterw + pl + 10; + if (x1 < screenleft + gutterw || atLeft) { + if (atLeft) x1 = 0; + result.scrollLeft = Math.max(0, x1 - 10 - gutterw); + } else if (x2 > screenw + screenleft - 3) { + result.scrollLeft = x2 + 10 - screenw; + } + return result; + } + + function visibleLines(scrollTop) { + var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop(); + var fromHeight = Math.max(0, Math.floor(top / lh)); + var toHeight = Math.ceil((top + scroller.clientHeight) / lh); + return {from: lineAtHeight(doc, fromHeight), + to: lineAtHeight(doc, toHeight)}; + } + // Uses a set of changes plus the current scroll position to + // determine which DOM updates have to be made, and makes the + // updates. + function updateDisplay(changes, suppressCallback, scrollTop) { + if (!scroller.clientWidth) { + showingFrom = showingTo = displayOffset = 0; + return; + } + // Compute the new visible window + // If scrollTop is specified, use that to determine which lines + // to render instead of the current scrollbar position. + var visible = visibleLines(scrollTop); + // Bail out if the visible area is already rendered and nothing changed. + if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) { + updateVerticalScroll(scrollTop); + return; + } + var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100); + if (showingFrom < from && from - showingFrom < 20) from = showingFrom; + if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); + + // Create a range of theoretically intact lines, and punch holes + // in that using the change info. + var intact = changes === true ? [] : + computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes); + // Clip off the parts that won't be visible + var intactLines = 0; + for (var i = 0; i < intact.length; ++i) { + var range = intact[i]; + if (range.from < from) {range.domStart += (from - range.from); range.from = from;} + if (range.to > to) range.to = to; + if (range.from >= range.to) intact.splice(i--, 1); + else intactLines += range.to - range.from; + } + if (intactLines == to - from && from == showingFrom && to == showingTo) { + updateVerticalScroll(scrollTop); + return; + } + intact.sort(function(a, b) {return a.domStart - b.domStart;}); + + var th = textHeight(), gutterDisplay = gutter.style.display; + lineDiv.style.display = "none"; + patchDisplay(from, to, intact); + lineDiv.style.display = gutter.style.display = ""; + + var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; + // This is just a bogus formula that detects when the editor is + // resized or the font size changes. + if (different) lastSizeC = scroller.clientHeight + th; + if (from != showingFrom || to != showingTo && options.onViewportChange) + setTimeout(function(){ + if (options.onViewportChange) options.onViewportChange(instance, from, to); + }); + showingFrom = from; showingTo = to; + displayOffset = heightAtLine(doc, from); + startWorker(100); + + // Since this is all rather error prone, it is honoured with the + // only assertion in the whole file. + if (lineDiv.childNodes.length != showingTo - showingFrom) + throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + + " nodes=" + lineDiv.childNodes.length); + + function checkHeights() { + var curNode = lineDiv.firstChild, heightChanged = false; + doc.iter(showingFrom, showingTo, function(line) { + // Work around bizarro IE7 bug where, sometimes, our curNode + // is magically replaced with a new node in the DOM, leaving + // us with a reference to an orphan (nextSibling-less) node. + if (!curNode) return; + if (!line.hidden) { + var height = Math.round(curNode.offsetHeight / th) || 1; + if (line.height != height) { + updateLineHeight(line, height); + gutterDirty = heightChanged = true; + } + } + curNode = curNode.nextSibling; + }); + return heightChanged; + } + + if (options.lineWrapping) checkHeights(); + + gutter.style.display = gutterDisplay; + if (different || gutterDirty) { + // If the gutter grew in size, re-check heights. If those changed, re-draw gutter. + updateGutter() && options.lineWrapping && checkHeights() && updateGutter(); + } + updateVerticalScroll(scrollTop); + updateSelection(); + if (!suppressCallback && options.onUpdate) options.onUpdate(instance); + return true; + } + + function computeIntact(intact, changes) { + for (var i = 0, l = changes.length || 0; i < l; ++i) { + var change = changes[i], intact2 = [], diff = change.diff || 0; + for (var j = 0, l2 = intact.length; j < l2; ++j) { + var range = intact[j]; + if (change.to <= range.from && change.diff) + intact2.push({from: range.from + diff, to: range.to + diff, + domStart: range.domStart}); + else if (change.to <= range.from || change.from >= range.to) + intact2.push(range); + else { + if (change.from > range.from) + intact2.push({from: range.from, to: change.from, domStart: range.domStart}); + if (change.to < range.to) + intact2.push({from: change.to + diff, to: range.to + diff, + domStart: range.domStart + (change.to - range.from)}); + } + } + intact = intact2; + } + return intact; + } + + function patchDisplay(from, to, intact) { + function killNode(node) { + var tmp = node.nextSibling; + node.parentNode.removeChild(node); + return tmp; + } + // The first pass removes the DOM nodes that aren't intact. + if (!intact.length) removeChildren(lineDiv); + else { + var domPos = 0, curNode = lineDiv.firstChild, n; + for (var i = 0; i < intact.length; ++i) { + var cur = intact[i]; + while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} + for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;} + } + while (curNode) curNode = killNode(curNode); + } + // This pass fills in the lines that actually changed. + var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from; + doc.iter(from, to, function(line) { + if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); + if (!nextIntact || nextIntact.from > j) { + if (line.hidden) var lineElement = elt("pre"); + else { + var lineElement = lineContent(line); + if (line.className) lineElement.className = line.className; + // Kludge to make sure the styled element lies behind the selection (by z-index) + if (line.bgClassName) { + var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2"); + lineElement = elt("div", [pre, lineElement], null, "position: relative"); + } + } + lineDiv.insertBefore(lineElement, curNode); + } else { + curNode = curNode.nextSibling; + } + ++j; + }); + } + + function updateGutter() { + if (!options.gutter && !options.lineNumbers) return; + var hText = mover.offsetHeight, hEditor = scroller.clientHeight; + gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; + var fragment = document.createDocumentFragment(), i = showingFrom, normalNode; + doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { + if (line.hidden) { + fragment.appendChild(elt("pre")); + } else { + var marker = line.gutterMarker; + var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null; + if (marker && marker.text) + text = marker.text.replace("%N%", text != null ? text : ""); + else if (text == null) + text = "\u00a0"; + var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style)); + markerElement.innerHTML = text; + for (var j = 1; j < line.height; ++j) { + markerElement.appendChild(elt("br")); + markerElement.appendChild(document.createTextNode("\u00a0")); + } + if (!marker) normalNode = i; + } + ++i; + }); + gutter.style.display = "none"; + removeChildrenAndAdd(gutterText, fragment); + // Make sure scrolling doesn't cause number gutter size to pop + if (normalNode != null && options.lineNumbers) { + var node = gutterText.childNodes[normalNode - showingFrom]; + var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = ""; + while (val.length + pad.length < minwidth) pad += "\u00a0"; + if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild); + } + gutter.style.display = ""; + var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2; + lineSpace.style.marginLeft = gutter.offsetWidth + "px"; + gutterDirty = false; + return resized; + } + function updateSelection() { + var collapsed = posEq(sel.from, sel.to); + var fromPos = localCoords(sel.from, true); + var toPos = collapsed ? fromPos : localCoords(sel.to, true); + var headPos = sel.inverted ? fromPos : toPos, th = textHeight(); + var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv); + inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px"; + inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px"; + if (collapsed || options.showCursorWhenSelecting) { + cursor.style.top = headPos.y + "px"; + cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px"; + cursor.style.display = ""; + } else { + cursor.style.display = "none"; + } + if (!collapsed) { + var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment(); + var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth; + var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight; + var add = function(left, top, right, height) { + var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px" + : "right: " + (right - 1) + "px"; + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; " + rstyle + "; height: " + height + "px")); + }; + if (sel.from.ch && fromPos.y >= 0) { + var right = sameLine ? clientWidth - toPos.x : 0; + add(fromPos.x, fromPos.y, right, th); + } + var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0)); + var middleHeight = Math.min(toPos.y, clientHeight) - middleStart; + if (middleHeight > 0.2 * th) + add(0, middleStart, 0, middleHeight); + if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th) + add(0, toPos.y, clientWidth - toPos.x, th); + removeChildrenAndAdd(selectionDiv, fragment); + selectionDiv.style.display = ""; + } else { + selectionDiv.style.display = "none"; + } + } + + function setShift(val) { + if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); + else shiftSelecting = null; + } + function setSelectionUser(from, to) { + var sh = shiftSelecting && clipPos(shiftSelecting); + if (sh) { + if (posLess(sh, from)) from = sh; + else if (posLess(to, sh)) to = sh; + } + setSelection(from, to); + userSelChange = true; + } + // Update the selection. Last two args are only used by + // updateLines, since they have to be expressed in the line + // numbers before the update. + function setSelection(from, to, oldFrom, oldTo) { + goalColumn = null; + if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} + if (posEq(sel.from, from) && posEq(sel.to, to)) return; + if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} + + // Skip over hidden lines. + if (from.line != oldFrom) { + var from1 = skipHidden(from, oldFrom, sel.from.ch); + // If there is no non-hidden line left, force visibility on current line + if (!from1) setLineHidden(from.line, false); + else from = from1; + } + if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); + + if (posEq(from, to)) sel.inverted = false; + else if (posEq(from, sel.to)) sel.inverted = false; + else if (posEq(to, sel.from)) sel.inverted = true; + + if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { + var head = sel.inverted ? from : to; + if (head.line != sel.from.line && sel.from.line < doc.size) { + var oldLine = getLine(sel.from.line); + if (/^\s+$/.test(oldLine.text)) + setTimeout(operation(function() { + if (oldLine.parent && /^\s+$/.test(oldLine.text)) { + var no = lineNo(oldLine); + replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); + } + }, 10)); + } + } + + sel.from = from; sel.to = to; + selectionChanged = true; + } + function skipHidden(pos, oldLine, oldCh) { + function getNonHidden(dir) { + var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1; + while (lNo != end) { + var line = getLine(lNo); + if (!line.hidden) { + var ch = pos.ch; + if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length; + return {line: lNo, ch: ch}; + } + lNo += dir; + } + } + var line = getLine(pos.line); + var toEnd = pos.ch == line.text.length && pos.ch != oldCh; + if (!line.hidden) return pos; + if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); + else return getNonHidden(-1) || getNonHidden(1); + } + function setCursor(line, ch, user) { + var pos = clipPos({line: line, ch: ch || 0}); + (user ? setSelectionUser : setSelection)(pos, pos); + } + + function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));} + function clipPos(pos) { + if (pos.line < 0) return {line: 0, ch: 0}; + if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length}; + var ch = pos.ch, linelen = getLine(pos.line).text.length; + if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; + else if (ch < 0) return {line: pos.line, ch: 0}; + else return pos; + } + + function findPosH(dir, unit) { + var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch; + var lineObj = getLine(line); + function findNextLine() { + for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { + var lo = getLine(l); + if (!lo.hidden) { line = l; lineObj = lo; return true; } + } + } + function moveOnce(boundToLine) { + if (ch == (dir < 0 ? 0 : lineObj.text.length)) { + if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; + else return false; + } else ch += dir; + return true; + } + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word") { + var sawWord = false; + for (;;) { + if (dir < 0) if (!moveOnce()) break; + if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; + else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} + if (dir > 0) if (!moveOnce()) break; + } + } + return {line: line, ch: ch}; + } + function moveH(dir, unit) { + var pos = dir < 0 ? sel.from : sel.to; + if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); + setCursor(pos.line, pos.ch, true); + } + function deleteH(dir, unit) { + if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); + else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); + else replaceRange("", sel.from, findPosH(dir, unit)); + userSelChange = true; + } + function moveV(dir, unit) { + var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true); + if (goalColumn != null) pos.x = goalColumn; + if (unit == "page") { + var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var target = coordsChar(pos.x, pos.y + screen * dir); + } else if (unit == "line") { + var th = textHeight(); + var target = coordsChar(pos.x, pos.y + .5 * th + dir * th); + } + if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y; + setCursor(target.line, target.ch, true); + goalColumn = pos.x; + } + + function findWordAt(pos) { + var line = getLine(pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + if (pos.after === false || end == line.length) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar) ? isWordChar : + /\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 {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; + } + function selectLine(line) { + setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0})); + } + function indentSelected(mode) { + if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); + var e = sel.to.line - (sel.to.ch ? 0 : 1); + for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); + } + + function indentLine(n, how) { + if (!how) how = "add"; + if (how == "smart") { + if (!mode.indent) how = "prev"; + else var state = getStateBefore(n); + } + + var line = getLine(n), curSpace = line.indentation(options.tabSize), + curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (how == "smart") { + indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass) how = "prev"; + } + if (how == "prev") { + if (n) indentation = getLine(n-1).indentation(options.tabSize); + else indentation = 0; + } + else if (how == "add") indentation = curSpace + options.indentUnit; + else if (how == "subtract") indentation = curSpace - options.indentUnit; + indentation = Math.max(0, indentation); + var diff = indentation - curSpace; + + var indentString = "", pos = 0; + if (options.indentWithTabs) + for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) + replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); + line.stateAfter = null; + } + + function loadMode() { + mode = CodeMirror.getMode(options, options.mode); + doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); + frontier = 0; + startWorker(100); + } + function gutterChanged() { + var visible = options.gutter || options.lineNumbers; + gutter.style.display = visible ? "" : "none"; + if (visible) gutterDirty = true; + else lineDiv.parentNode.style.marginLeft = 0; + } + function wrappingChanged(from, to) { + if (options.lineWrapping) { + wrapper.className += " CodeMirror-wrap"; + var perLine = scroller.clientWidth / charWidth() - 3; + doc.iter(0, doc.size, function(line) { + if (line.hidden) return; + var guess = Math.ceil(line.text.length / perLine) || 1; + if (guess != 1) updateLineHeight(line, guess); + }); + lineSpace.style.minWidth = widthForcer.style.left = ""; + } else { + wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); + computeMaxLength(); + doc.iter(0, doc.size, function(line) { + if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); + }); + } + changes.push({from: 0, to: doc.size}); + } + function themeChanged() { + scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") + + options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + } + function keyMapChanged() { + var style = keyMap[options.keyMap].style; + wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + + (style ? " cm-keymap-" + style : ""); + } + + function TextMarker(type, style) { this.lines = []; this.type = type; if (style) this.style = style; } + TextMarker.prototype.clear = operation(function() { + var min, max; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) min = lineNo(line); + if (span.to != null) max = lineNo(line); + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + } + if (min != null) changes.push({from: min, to: max + 1}); + this.lines.length = 0; + this.explicitlyCleared = true; + }); + TextMarker.prototype.find = function() { + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null || span.to != null) { + var found = lineNo(line); + if (span.from != null) from = {line: found, ch: span.from}; + if (span.to != null) to = {line: found, ch: span.to}; + } + } + if (this.type == "bookmark") return from; + return from && {from: from, to: to}; + }; + + function markText(from, to, className, options) { + from = clipPos(from); to = clipPos(to); + var marker = new TextMarker("range", className); + if (options) for (var opt in options) if (options.hasOwnProperty(opt)) + marker[opt] = options[opt]; + var curLine = from.line; + doc.iter(curLine, to.line + 1, function(line) { + var span = {from: curLine == from.line ? from.ch : null, + to: curLine == to.line ? to.ch : null, + marker: marker}; + line.markedSpans = (line.markedSpans || []).concat([span]); + marker.lines.push(line); + ++curLine; + }); + changes.push({from: from.line, to: to.line + 1}); + return marker; + } + + function setBookmark(pos) { + pos = clipPos(pos); + var marker = new TextMarker("bookmark"), line = getLine(pos.line); + history.addChange(pos.line, 1, [newHL(line.text, line.markedSpans)], true); + var span = {from: pos.ch, to: pos.ch, marker: marker}; + line.markedSpans = (line.markedSpans || []).concat([span]); + marker.lines.push(line); + return marker; + } + + function findMarksAt(pos) { + pos = clipPos(pos); + var markers = [], spans = getLine(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); + } + return markers; + } + + function addGutterMarker(line, text, className) { + if (typeof line == "number") line = getLine(clipLine(line)); + line.gutterMarker = {text: text, style: className}; + gutterDirty = true; + return line; + } + function removeGutterMarker(line) { + if (typeof line == "number") line = getLine(clipLine(line)); + line.gutterMarker = null; + gutterDirty = true; + } + + function changeLine(handle, op) { + var no = handle, line = handle; + if (typeof handle == "number") line = getLine(clipLine(handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no)) changes.push({from: no, to: no + 1}); + else return null; + return line; + } + function setLineClass(handle, className, bgClassName) { + return changeLine(handle, function(line) { + if (line.className != className || line.bgClassName != bgClassName) { + line.className = className; + line.bgClassName = bgClassName; + return true; + } + }); + } + function setLineHidden(handle, hidden) { + return changeLine(handle, function(line, no) { + if (line.hidden != hidden) { + line.hidden = hidden; + if (!options.lineWrapping) { + if (hidden && line.text.length == maxLine.text.length) { + updateMaxLine = true; + } else if (!hidden && line.text.length > maxLine.text.length) { + maxLine = line; updateMaxLine = false; + } + } + updateLineHeight(line, hidden ? 0 : 1); + var fline = sel.from.line, tline = sel.to.line; + if (hidden && (fline == no || tline == no)) { + var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from; + var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to; + // Can't hide the last visible line, we'd have no place to put the cursor + if (!to) return; + setSelection(from, to); + } + return (gutterDirty = true); + } + }); + } + + function lineInfo(line) { + if (typeof line == "number") { + if (!isLine(line)) return null; + var n = line; + line = getLine(line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + var marker = line.gutterMarker; + return {line: n, handle: line, text: line.text, markerText: marker && marker.text, + markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName}; + } + + function measureLine(line, ch) { + if (ch == 0) return {top: 0, left: 0}; + var pre = lineContent(line, ch); + removeChildrenAndAdd(measure, pre); + var anchor = pre.anchor; + var top = anchor.offsetTop, left = anchor.offsetLeft; + // Older IEs report zero offsets for spans directly after a wrap + if (ie && top == 0 && left == 0) { + var backup = elt("span", "x"); + anchor.parentNode.insertBefore(backup, anchor.nextSibling); + top = backup.offsetTop; + } + return {top: top, left: left}; + } + function localCoords(pos, inLineWrap) { + var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); + if (pos.ch == 0) x = 0; + else { + var sp = measureLine(getLine(pos.line), pos.ch); + x = sp.left; + if (options.lineWrapping) y += Math.max(0, sp.top); + } + return {x: x, y: y, yBot: y + lh}; + } + // Coords must be lineSpace-local + function coordsChar(x, y) { + var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th); + if (heightPos < 0) return {line: 0, ch: 0}; + var lineNo = lineAtHeight(doc, heightPos); + if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length}; + var lineObj = getLine(lineNo), text = lineObj.text; + var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; + if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0}; + var wrongLine = false; + function getX(len) { + var sp = measureLine(lineObj, len); + if (tw) { + var off = Math.round(sp.top / th); + wrongLine = off != innerOff; + return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); + } + return sp.left; + } + var from = 0, fromX = 0, to = text.length, toX; + // Guess a suitable upper bound for our search. + var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); + for (;;) { + var estX = getX(estimated); + if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); + else {toX = estX; to = estimated; break;} + } + if (x > toX) return {line: lineNo, ch: to}; + // Try to guess a suitable lower bound as well. + estimated = Math.floor(to * 0.8); estX = getX(estimated); + if (estX < x) {from = estimated; fromX = estX;} + // Do a binary search between these bounds. + for (;;) { + if (to - from <= 1) { + var after = x - fromX < toX - x; + return {line: lineNo, ch: after ? from : to, after: after}; + } + var middle = Math.ceil((from + to) / 2), middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; } + else {from = middle; fromX = middleX;} + } + } + function pageCoords(pos) { + var local = localCoords(pos, true), off = eltOffset(lineSpace); + return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; + } + + var cachedHeight, cachedHeightFor, measurePre; + function textHeight() { + if (measurePre == null) { + measurePre = elt("pre"); + for (var i = 0; i < 49; ++i) { + measurePre.appendChild(document.createTextNode("x")); + measurePre.appendChild(elt("br")); + } + measurePre.appendChild(document.createTextNode("x")); + } + var offsetHeight = lineDiv.clientHeight; + if (offsetHeight == cachedHeightFor) return cachedHeight; + cachedHeightFor = offsetHeight; + removeChildrenAndAdd(measure, measurePre.cloneNode(true)); + cachedHeight = measure.firstChild.offsetHeight / 50 || 1; + removeChildren(measure); + return cachedHeight; + } + var cachedWidth, cachedWidthFor = 0; + function charWidth() { + if (scroller.clientWidth == cachedWidthFor) return cachedWidth; + cachedWidthFor = scroller.clientWidth; + var anchor = elt("span", "x"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(measure, pre); + return (cachedWidth = anchor.offsetWidth || 10); + } + function paddingTop() {return lineSpace.offsetTop;} + function paddingLeft() {return lineSpace.offsetLeft;} + + function posFromMouse(e, liberal) { + var offW = eltOffset(scroller, true), x, y; + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX; y = e.clientY; } catch (e) { return null; } + // This is a mess of a heuristic to try and determine whether a + // scroll-bar was clicked or not, and to return null if one was + // (and !liberal). + if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) + return null; + var offL = eltOffset(lineSpace, true); + return coordsChar(x - offL.left, y - offL.top); + } + var detectingSelectAll; + function onContextMenu(e) { + var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop; + if (!pos || opera) return; // Opera is difficult. + if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) + operation(setCursor)(pos.line, pos.ch); + + var oldCSS = input.style.cssText; + inputDiv.style.position = "absolute"; + input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + + "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + focusInput(); + resetInput(true); + // Adds "Select all" to context menu in FF + if (posEq(sel.from, sel.to)) input.value = prevInput = " "; + + function rehide() { + inputDiv.style.position = "relative"; + input.style.cssText = oldCSS; + if (ie_lt9) scrollbar.scrollTop = scrollPos; + slowPoll(); + + // Try to detect the user choosing select-all + if (input.selectionStart != null) { + clearTimeout(detectingSelectAll); + var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), i = 0; + prevInput = " "; + input.selectionStart = 1; input.selectionEnd = extval.length; + detectingSelectAll = setTimeout(function poll(){ + if (prevInput == " " && input.selectionStart == 0) + operation(commands.selectAll)(instance); + else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); + else resetInput(); + }, 200); + } + } + + if (gecko) { + e_stop(e); + var mouseup = connect(window, "mouseup", function() { + mouseup(); + setTimeout(rehide, 20); + }, true); + } else { + setTimeout(rehide, 50); + } + } + + // Cursor-blinking + function restartBlink() { + clearInterval(blinker); + var on = true; + cursor.style.visibility = ""; + blinker = setInterval(function() { + cursor.style.visibility = (on = !on) ? "" : "hidden"; + }, options.cursorBlinkRate); + } + + var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; + function matchBrackets(autoclear) { + var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1; + var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; + if (!match) return; + var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; + for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) + if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} + + var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; + function scan(line, from, to) { + if (!line.text) return; + var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; + for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { + var text = st[i]; + if (st[i+1] != style) {pos += d * text.length; continue;} + for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { + if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { + var match = matching[cur]; + if (match.charAt(1) == ">" == forward) stack.push(cur); + else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; + else if (!stack.length) return {pos: pos, match: true}; + } + } + } + } + for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) { + var line = getLine(i), first = i == head.line; + var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); + if (found) break; + } + if (!found) found = {pos: null, match: false}; + var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), + two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); + var clear = operation(function(){one.clear(); two && two.clear();}); + if (autoclear) setTimeout(clear, 800); + else bracketHighlighted = clear; + } + + // 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(n) { + var minindent, minline; + for (var search = n, lim = n - 40; search > lim; --search) { + if (search == 0) return 0; + var line = getLine(search-1); + if (line.stateAfter) return search; + var indented = line.indentation(options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + function getStateBefore(n) { + var pos = findStartLine(n), state = pos && getLine(pos-1).stateAfter; + if (!state) state = startState(mode); + else state = copyState(mode, state); + doc.iter(pos, n, function(line) { + line.process(mode, state, options.tabSize); + line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null; + }); + return state; + } + function highlightWorker() { + if (frontier >= showingTo) return; + var end = +new Date + options.workTime, state = copyState(mode, getStateBefore(frontier)); + var startFrontier = frontier; + doc.iter(frontier, showingTo, function(line) { + if (frontier >= showingFrom) { // Visible + line.highlight(mode, state, options.tabSize); + line.stateAfter = copyState(mode, state); + } else { + line.process(mode, state, options.tabSize); + line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null; + } + ++frontier; + if (+new Date > end) { + startWorker(options.workDelay); + return true; + } + }); + if (showingTo > startFrontier && frontier >= showingFrom) + operation(function() {changes.push({from: startFrontier, to: frontier});})(); + } + function startWorker(time) { + if (frontier < showingTo) + highlight.set(time, highlightWorker); + } + + // Operations are used to wrap changes in such a way that each + // change won't have to update the cursor and display (which would + // be awkward, slow, and error-prone), but instead updates are + // batched and then all combined and executed at once. + function startOperation() { + updateInput = userSelChange = textChanged = null; + changes = []; selectionChanged = false; callbacks = []; + } + function endOperation() { + if (updateMaxLine) computeMaxLength(); + if (maxLineChanged && !options.lineWrapping) { + var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left; + if (!ie_lt8) { + widthForcer.style.left = left + "px"; + lineSpace.style.minWidth = (left + cursorWidth) + "px"; + } + maxLineChanged = false; + } + var newScrollPos, updated; + if (selectionChanged) { + var coords = calculateCursorCoords(); + newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot); + } + if (changes.length || newScrollPos && newScrollPos.scrollTop != null) + updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop); + if (!updated) { + if (selectionChanged) updateSelection(); + if (gutterDirty) updateGutter(); + } + if (newScrollPos) scrollCursorIntoView(); + if (selectionChanged) restartBlink(); + + if (focused && (updateInput === true || (updateInput !== false && selectionChanged))) + resetInput(userSelChange); + + if (selectionChanged && options.matchBrackets) + setTimeout(operation(function() { + if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} + if (posEq(sel.from, sel.to)) matchBrackets(false); + }), 20); + var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks + if (textChanged && options.onChange && instance) + options.onChange(instance, textChanged); + if (sc && options.onCursorActivity) + options.onCursorActivity(instance); + for (var i = 0; i < cbs.length; ++i) cbs[i](instance); + if (updated && options.onUpdate) options.onUpdate(instance); + } + var nestedOperation = 0; + function operation(f) { + return function() { + if (!nestedOperation++) startOperation(); + try {var result = f.apply(this, arguments);} + finally {if (!--nestedOperation) endOperation();} + return result; + }; + } + + function compoundChange(f) { + history.startCompound(); + try { return f(); } finally { history.endCompound(); } + } + + for (var ext in extensions) + if (extensions.propertyIsEnumerable(ext) && + !instance.propertyIsEnumerable(ext)) + instance[ext] = extensions[ext]; + for (var i = 0; i < initHooks.length; ++i) initHooks[i](instance); + return instance; + } // (end of function CodeMirror) + + // The default configuration options. + CodeMirror.defaults = { + value: "", + mode: null, + theme: "default", + indentUnit: 2, + indentWithTabs: false, + smartIndent: true, + tabSize: 4, + keyMap: "default", + extraKeys: null, + electricChars: true, + autoClearEmptyLines: false, + onKeyEvent: null, + onDragEvent: null, + lineWrapping: false, + lineNumbers: false, + gutter: false, + fixedGutter: false, + firstLineNumber: 1, + showCursorWhenSelecting: false, + readOnly: false, + dragDrop: true, + onChange: null, + onCursorActivity: null, + onViewportChange: null, + onGutterClick: null, + onUpdate: null, + onFocus: null, onBlur: null, onScroll: null, + matchBrackets: false, + cursorBlinkRate: 530, + workTime: 100, + workDelay: 200, + pollInterval: 100, + undoDepth: 40, + tabindex: null, + autofocus: null, + lineNumberFormatter: function(integer) { return integer; } + }; + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var win = /Win/.test(navigator.platform); + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) { + mode.dependencies = []; + for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); + } + modes[name] = mode; + }; + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) + spec = mimeModes[spec]; + else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) + return CodeMirror.resolveMode("application/xml"); + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; + }; + CodeMirror.getMode = function(options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.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; + return modeObj; + }; + CodeMirror.listModes = function() { + var list = []; + for (var m in modes) + if (modes.propertyIsEnumerable(m)) list.push(m); + return list; + }; + CodeMirror.listMIMEs = function() { + var list = []; + for (var m in mimeModes) + if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]}); + return list; + }; + + var extensions = CodeMirror.extensions = {}; + CodeMirror.defineExtension = function(name, func) { + extensions[name] = func; + }; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + for (var prop in properties) if (properties.hasOwnProperty(prop)) + exts[prop] = properties[prop]; + }; + + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, + killLine: function(cm) { + var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); + if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); + else cm.replaceRange("", from, sel ? to : {line: from.line}); + }, + deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + goDocStart: function(cm) {cm.setCursor(0, 0, true);}, + goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, + goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);}, + goLineStartSmart: function(cm) { + var cur = cm.getCursor(); + var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/)); + cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); + }, + goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);}, + goLineUp: function(cm) {cm.moveV(-1, "line");}, + goLineDown: function(cm) {cm.moveV(1, "line");}, + goPageUp: function(cm) {cm.moveV(-1, "page");}, + goPageDown: function(cm) {cm.moveV(1, "page");}, + goCharLeft: function(cm) {cm.moveH(-1, "char");}, + goCharRight: function(cm) {cm.moveH(1, "char");}, + goColumnLeft: function(cm) {cm.moveH(-1, "column");}, + goColumnRight: function(cm) {cm.moveH(1, "column");}, + goWordLeft: function(cm) {cm.moveH(-1, "word");}, + goWordRight: function(cm) {cm.moveH(1, "word");}, + delCharLeft: function(cm) {cm.deleteH(-1, "char");}, + delCharRight: function(cm) {cm.deleteH(1, "char");}, + delWordLeft: function(cm) {cm.deleteH(-1, "word");}, + delWordRight: function(cm) {cm.deleteH(1, "word");}, + indentAuto: function(cm) {cm.indentSelection("smart");}, + indentMore: function(cm) {cm.indentSelection("add");}, + indentLess: function(cm) {cm.indentSelection("subtract");}, + insertTab: function(cm) {cm.replaceSelection("\t", "end");}, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.replaceSelection("\t", "end"); + }, + transposeChars: function(cm) { + var cur = cm.getCursor(), line = cm.getLine(cur.line); + if (cur.ch > 0 && cur.ch < line.length - 1) + cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), + {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); + }, + newlineAndIndent: function(cm) { + cm.replaceSelection("\n", "end"); + cm.indentLine(cm.getCursor().line); + }, + toggleOverwrite: function(cm) {cm.toggleOverwrite();} + }; + + var keyMap = CodeMirror.keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" + }; + // Note that the save and find-related commands aren't defined by + // default. 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", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", + "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "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", + fallthrough: "basic" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", + "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft", + "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "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", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + 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": "delCharRight", "Ctrl-H": "delCharLeft", + "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + + function getKeyMap(val) { + if (typeof val == "string") return keyMap[val]; + else return val; + } + function lookupKey(name, extraMap, map, handle, stop) { + function lookup(map) { + map = getKeyMap(map); + var found = map[name]; + if (found === false) { + if (stop) stop(); + return true; + } + if (found != null && handle(found)) return true; + if (map.nofallthrough) { + if (stop) stop(); + return true; + } + var fallthrough = map.fallthrough; + if (fallthrough == null) return false; + if (Object.prototype.toString.call(fallthrough) != "[object Array]") + return lookup(fallthrough); + for (var i = 0, e = fallthrough.length; i < e; ++i) { + if (lookup(fallthrough[i])) return true; + } + return false; + } + if (extraMap && lookup(extraMap)) return true; + return lookup(map); + } + function isModifierKey(event) { + var name = keyNames[e_prop(event, "keyCode")]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + CodeMirror.isModifierKey = isModifierKey; + + CodeMirror.fromTextArea = function(textarea, options) { + if (!options) options = {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabindex) + options.tabindex = textarea.tabindex; + // 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 = document.body; + // doc.activeElement occasionally throws on IE + try { hasFocus = document.activeElement; } catch(e) {} + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = instance.getValue();} + if (textarea.form) { + // Deplorable hack to make the submit method do the right thing. + var rmSubmit = connect(textarea.form, "submit", save, true); + var form = textarea.form, realSubmit = form.submit; + textarea.form.submit = function wrappedSubmit() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } + + textarea.style.display = "none"; + var instance = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + instance.save = save; + instance.getTextArea = function() { return textarea; }; + instance.toTextArea = function() { + save(); + textarea.parentNode.removeChild(instance.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + rmSubmit(); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + return instance; + }; + + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie = /MSIE \d/.test(navigator.userAgent); + var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); + var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); + var quirksMode = ie && document.documentMode == 5; + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var opera = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var khtml = /KHTML\//.test(navigator.userAgent); + var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent); + + var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (opera_version) opera_version = Number(opera_version[1]); + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); + + // Utility functions for working with state. Exported because modes + // sometimes need to do this. + 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; + } + CodeMirror.copyState = copyState; + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + CodeMirror.startState = startState; + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // The character stream used by a mode's parser. + function StringStream(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + } + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == 0;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() {return countColumn(this.string, this.start, this.tabSize);}, + indentation: function() {return countColumn(this.string, null, this.tabSize);}, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { + 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; + } + }, + current: function(){return this.string.slice(this.start, this.pos);} + }; + CodeMirror.StringStream = StringStream; + + function MarkedSpan(from, to, marker) { + this.from = from; this.to = to; this.marker = 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; + } + } + + 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; + } + + function markedSpansBefore(old, startCh, endCh) { + if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == startCh && span.from != endCh) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push({from: span.from, + to: endsAfter ? null : span.to, + marker: marker}); + } + } + return nw; + } + + function markedSpansAfter(old, endCh) { + if (old) for (var i = 0, nw; 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 || marker.type == "bookmark" && span.from == endCh) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, + to: span.to == null ? null : span.to - endCh, + marker: marker}); + } + } + return nw; + } + + function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { + if (!oldFirst && !oldLast) return newText; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh); + var last = markedSpansAfter(oldLast, endCh); + + // Next, merge those two ends + var sameLine = newText.length == 1, offset = lst(newText).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 = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + + var newMarkers = [newHL(newText[0], first)]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = newText.length - 2, gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); + for (var i = 0; i < gap; ++i) + newMarkers.push(newHL(newText[i+1], gapMarkers)); + newMarkers.push(newHL(lst(newText), last)); + } + return newMarkers; + } + + // hl stands for history-line, a data structure that can be either a + // string (line without markers) or a {text, markedSpans} object. + function hlText(val) { return typeof val == "string" ? val : val.text; } + function hlSpans(val) { + if (typeof val == "string") return null; + var spans = val.markedSpans, out = null; + 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; + } + function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; } + + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) { + var lines = spans[i].marker.lines; + var ix = indexOf(lines, line); + lines.splice(ix, 1); + } + line.markedSpans = null; + } + + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + var marker = spans[i].marker.lines.push(line); + line.markedSpans = spans; + } + + // When measuring the position of the end of a line, different + // browsers require different approaches. If an empty span is added, + // many browsers report bogus offsets. Of those, some (Webkit, + // recent IE) will accept a space without moving the whole span to + // the next line when wrapping it, others work with a zero-width + // space. + var eolSpanContent = " "; + if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b"; + else if (opera) eolSpanContent = ""; + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + function Line(text, markedSpans) { + this.text = text; + this.height = 1; + attachMarkedSpans(this, markedSpans); + } + Line.prototype = { + update: function(text, markedSpans) { + this.text = text; + this.stateAfter = this.styles = null; + detachMarkedSpans(this); + attachMarkedSpans(this, markedSpans); + }, + // Run the given mode's parser over a line, update the styles + // array, which contains alternating fragments of text and CSS + // classes. + highlight: function(mode, state, tabSize) { + var stream = new StringStream(this.text, tabSize), st = this.styles || (this.styles = []); + var pos = st.length = 0; + if (this.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + var style = mode.token(stream, state), substr = stream.current(); + stream.start = stream.pos; + if (pos && st[pos-1] == style) { + st[pos-2] += substr; + } else if (substr) { + st[pos++] = substr; st[pos++] = style; + } + // Give up when line is ridiculously long + if (stream.pos > 5000) { + st[pos++] = this.text.slice(stream.pos); st[pos++] = null; + break; + } + } + }, + process: function(mode, state, tabSize) { + var stream = new StringStream(this.text, tabSize); + if (this.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol() && stream.pos <= 5000) { + mode.token(stream, state); + stream.start = stream.pos; + } + }, + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(mode, state, tabSize, ch) { + var txt = this.text, stream = new StringStream(txt, tabSize); + while (stream.pos < ch && !stream.eol()) { + stream.start = stream.pos; + var style = mode.token(stream, state); + } + return {start: stream.start, + end: stream.pos, + string: stream.current(), + className: style || null, + state: state}; + }, + indentation: function(tabSize) {return countColumn(this.text, null, tabSize);}, + // Produces an HTML fragment for the line, taking selection, + // marking, and highlighting into account. + getContent: function(tabSize, wrapAt, compensateForWrapping) { + var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; + var pre = elt("pre"); + function span_(html, text, style) { + if (!text) return; + // Work around a bug where, in some compat modes, IE ignores leading spaces + if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); + first = false; + if (!specials.test(text)) { + col += text.length; + var content = document.createTextNode(text); + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + specials.lastIndex = pos; + var m = specials.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); + col += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabWidth = tabSize - col % tabSize; + content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + col += tabWidth; + } else { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + m[0].charCodeAt(0).toString(16); + content.appendChild(token); + col += 1; + } + } + } + if (style) html.appendChild(elt("span", [content], style)); + else html.appendChild(content); + } + var span = span_; + if (wrapAt != null) { + var outPos = 0, anchor = pre.anchor = elt("span"); + span = function(html, text, style) { + var l = text.length; + if (wrapAt >= outPos && wrapAt < outPos + l) { + var cut = wrapAt - outPos; + if (cut) { + span_(html, text.slice(0, cut), style); + // See comment at the definition of spanAffectsWrapping + if (compensateForWrapping) { + var view = text.slice(cut - 1, cut + 1); + if (spanAffectsWrapping.test(view)) html.appendChild(elt("wbr")); + else if (!ie_lt8 && /\w\w/.test(view)) html.appendChild(document.createTextNode("\u200d")); + } + } + html.appendChild(anchor); + span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style); + if (opera) span_(html, text.slice(cut + 1), style); + wrapAt--; + outPos += l; + } else { + outPos += l; + span_(html, text, style); + if (outPos == wrapAt && outPos == len) { + setTextContent(anchor, eolSpanContent); + html.appendChild(anchor); + } + // Stop outputting HTML when gone sufficiently far beyond measure + else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){}; + } + }; + } + + var st = this.styles, allText = this.text, marked = this.markedSpans; + var len = allText.length; + function styleToClass(style) { + if (!style) return null; + return "cm-" + style.replace(/ +/g, " cm-"); + } + if (!allText && wrapAt == null) { + span(pre, " "); + } else if (!marked || !marked.length) { + for (var i = 0, ch = 0; ch < len; i+=2) { + var str = st[i], style = st[i+1], l = str.length; + if (ch + l > len) str = str.slice(0, len - ch); + ch += l; + span(pre, str, styleToClass(style)); + } + } else { + marked.sort(function(a, b) { return a.from - b.from; }); + var pos = 0, i = 0, text = "", style, sg = 0; + var nextChange = marked[0].from || 0, marks = [], markpos = 0; + var advanceMarks = function() { + var m; + while (markpos < marked.length && + ((m = marked[markpos]).from == pos || m.from == null)) { + if (m.marker.type == "range") marks.push(m); + ++markpos; + } + nextChange = markpos < marked.length ? marked[markpos].from : Infinity; + for (var i = 0; i < marks.length; ++i) { + var to = marks[i].to; + if (to == null) to = Infinity; + if (to == pos) marks.splice(i--, 1); + else nextChange = Math.min(to, nextChange); + } + }; + var m = 0; + while (pos < len) { + if (nextChange == pos) advanceMarks(); + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + var appliedStyle = style; + for (var j = 0; j < marks.length; ++j) { + var mark = marks[j]; + appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style; + if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle; + if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle; + } + span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle); + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + } + text = st[i++]; style = styleToClass(st[i++]); + } + } + } + return pre; + }, + cleanUp: function() { + this.parent = null; + detachMarkedSpans(this); + } + }; + + // Data structure that holds the sequence of lines. + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, e = lines.length, height = 0; i < e; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length; }, + remove: function(at, n, callbacks) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + line.cleanUp(); + if (line.handlers) + for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]); + } + this.lines.splice(at, n); + }, + collapse: function(lines) { + lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); + }, + insertHeight: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; + }, + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + if (op(this.lines[at])) return true; + } + }; + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0, e = children.length; i < e; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + BranchChunk.prototype = { + chunkSize: function() { return this.size; }, + remove: function(at, n, callbacks) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.remove(at, rm, callbacks); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + if (this.size - n < 25) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); + }, + insert: function(at, lines) { + var height = 0; + for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; + this.insertHeight(at, lines, height); + }, + insertHeight: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0, e = this.children.length; i < e; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertHeight(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + 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(); + }, + iter: function(from, to, op) { this.iterN(from, to - from, op); }, + iterN: function(at, n, op) { + for (var i = 0, e = this.children.length; i < e; ++i) { + var child = this.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; + } + } + }; + + function getLineAt(chunk, n) { + 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]; + } + 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; + } + function lineAtHeight(chunk, h) { + var n = 0; + outer: do { + for (var i = 0, e = chunk.children.length; i < e; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0, e = chunk.lines.length; i < e; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + function heightAtLine(chunk, n) { + var h = 0; + outer: do { + for (var i = 0, e = chunk.children.length; i < e; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; continue outer; } + n -= sz; + h += child.height; + } + return h; + } while (!chunk.lines); + for (var i = 0; i < n; ++i) h += chunk.lines[i].height; + return h; + } + + // The history object 'chunks' changes that are made close together + // and at almost the same time into bigger undoable units. + function History() { + this.time = 0; + this.done = []; this.undone = []; + this.compound = 0; + this.closed = false; + } + History.prototype = { + addChange: function(start, added, old) { + this.undone.length = 0; + var time = +new Date, cur = lst(this.done), last = cur && lst(cur); + var dtime = time - this.time; + + if (cur && !this.closed && this.compound) { + cur.push({start: start, added: added, old: old}); + } else if (dtime > 400 || !last || this.closed || + last.start > start + old.length || last.start + last.added < start) { + this.done.push([{start: start, added: added, old: old}]); + this.closed = false; + } else { + var startBefore = Math.max(0, last.start - start), + endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); + for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); + for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); + if (startBefore) last.start = start; + last.added += added - (old.length - startBefore - endAfter); + } + this.time = time; + }, + startCompound: function() { + if (!this.compound++) this.closed = true; + }, + endCompound: function() { + if (!--this.compound) this.closed = true; + } + }; + + function stopMethod() {e_stop(this);} + // Ensure an event has a stop method. + function addStop(event) { + if (!event.stop) event.stop = stopMethod; + return event; + } + + 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_stop(e) {e_preventDefault(e); e_stopPropagation(e);} + CodeMirror.e_stop = e_stop; + CodeMirror.e_preventDefault = e_preventDefault; + CodeMirror.e_stopPropagation = e_stopPropagation; + + 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; + } + + // Allow 3rd-party code to override event properties by adding an override + // object to an event object. + function e_prop(e, prop) { + var overridden = e.override && e.override.hasOwnProperty(prop); + return overridden ? e.override[prop] : e[prop]; + } + + // Event handler registration. If disconnect is true, it'll return a + // function that unregisters the handler. + function connect(node, type, handler, disconnect) { + if (typeof node.addEventListener == "function") { + node.addEventListener(type, handler, false); + if (disconnect) return function() {node.removeEventListener(type, handler, false);}; + } else { + var wrapHandler = function(event) {handler(event || window.event);}; + node.attachEvent("on" + type, wrapHandler); + if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; + } + } + CodeMirror.connect = connect; + + function Delayed() {this.id = null;} + Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; + + var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; + + // 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_lt9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + + // Feature-detect whether newlines in textareas are converted to \r\n + var lineSep = function () { + var te = elt("textarea"); + te.value = "foo\nbar"; + if (te.value.indexOf("\r") > -1) return "\r\n"; + return "\n"; + }(); + + // For a reason I have yet to figure out, some browsers disallow + // word wrapping between certain characters *only* if a new inline + // element is started between them. This makes it hard to reliably + // measure the position of things, since that requires inserting an + // extra span. This terribly fragile set of regexps matches the + // character combinations that suffer from this phenomenon on the + // various browsers. + var spanAffectsWrapping = /^$/; // Won't match any two-character string + if (gecko) spanAffectsWrapping = /$'/; + else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; + else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + function countColumn(string, end, tabSize) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = 0, n = 0; i < end; ++i) { + if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); + else ++n; + } + return n; + } + + function eltOffset(node, screen) { + // Take the parts of bounding client rect that we are interested in so we are able to edit if need be, + // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page) + try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; } + catch(e) { box = {top: 0, left: 0}; } + if (!screen) { + // Get the toplevel scroll, working around browser differences. + if (window.pageYOffset == null) { + var t = document.documentElement || document.body.parentNode; + if (t.scrollTop == null) t = document.body; + box.top += t.scrollTop; box.left += t.scrollLeft; + } else { + box.top += window.pageYOffset; box.left += window.pageXOffset; + } + } + return box; + } + + function eltText(node) { + return node.textContent || node.innerText || node.nodeValue || ""; + } + + 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 selectInput(node) { + if (ios) { // Mobile Safari apparently has a bug where select() is broken. + node.selectionStart = 0; + node.selectionEnd = node.value.length; + } else node.select(); + } + + // Operations on {line, ch} objects. + function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} + function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} + function copyPos(x) {return {line: x.line, ch: x.ch};} + + 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") setTextContent(e, content); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + function removeChildren(e) { + e.innerHTML = ""; + return e; + } + function removeChildrenAndAdd(parent, e) { + removeChildren(parent).appendChild(e); + } + function setTextContent(e, str) { + if (ie_lt9) { + e.innerHTML = ""; + e.appendChild(document.createTextNode(str)); + } else e.textContent = str; + } + + // Used to position the cursor after an undo/redo by finding the + // last edited character. + function editEnd(from, to) { + if (!to) return 0; + if (!from) return to.length; + for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) + if (from.charAt(i) != to.charAt(j)) break; + return j + 1; + } + + function indexOf(collection, elt) { + if (collection.indexOf) return collection.indexOf(elt); + for (var i = 0, e = collection.length; i < e; ++i) + if (collection[i] == elt) return i; + return -1; + } + var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/; + function isWordChar(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLines = "\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/);}; + CodeMirror.splitLines = splitLines; + + var hasSelection = window.getSelection ? function(te) { + try { return te.selectionStart != te.selectionEnd; } + catch(e) { return false; } + } : function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + var keyNames = {3: "Enter", 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: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", + 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", + 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; + CodeMirror.keyNames = keyNames; + (function() { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + CodeMirror.version = "2.37 +"; + + return CodeMirror; +})(); \ No newline at end of file diff --git a/lib/client/editor/codemirror/mode/javascript.js b/lib/client/editor/codemirror/mode/javascript.js index 37f6f873..2526b276 100644 --- a/lib/client/editor/codemirror/mode/javascript.js +++ b/lib/client/editor/codemirror/mode/javascript.js @@ -1,409 +1,419 @@ -// TODO actually recognize syntax of TypeScript constructs - -CodeMirror.defineMode("javascript", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var jsonMode = parserConfig.json; - var isTS = parserConfig.typescript; - - // 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"); - var operator = kw("operator"), atom = {type: "atom", style: "atom"}; - - var jsKeywords = { - "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, - "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 - }; - - // Extend the 'normal' keywords with the TypeScript language extensions - if (isTS) { - var type = {type: "variable", style: "variable-3"}; - var tsKeywords = { - // object-like things - "interface": kw("interface"), - "class": kw("class"), - "extends": kw("extends"), - "constructor": kw("constructor"), - - // scope modifiers - "public": kw("public"), - "private": kw("private"), - "protected": kw("protected"), - "static": kw("static"), - - "super": kw("super"), - - // types - "string": type, "number": type, "bool": type, "any": type - }; - - for (var attr in tsKeywords) { - jsKeywords[attr] = tsKeywords[attr]; - } - } - - return jsKeywords; - }(); - - var isOperatorChar = /[+\-*&%=<>!?|]/; - - function chain(stream, state, f) { - state.tokenize = f; - return f(stream, state); - } - - function nextUntilUnescaped(stream, end) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (next == end && !escaped) - return false; - escaped = !escaped && next == "\\"; - } - return escaped; - } - - // 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 jsTokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") - return chain(stream, state, jsTokenString(ch)); - else if (/[\[\]{}\(\),;\:\.]/.test(ch)) - return ret(ch); - else if (ch == "0" && stream.eat(/x/i)) { - stream.eatWhile(/[\da-f]/i); - return ret("number", "number"); - } - else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { - stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); - return ret("number", "number"); - } - else if (ch == "/") { - if (stream.eat("*")) { - return chain(stream, state, jsTokenComment); - } - else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } - else if (state.lastType == "operator" || state.lastType == "keyword c" || - /^[\[{}\(,;:]$/.test(state.lastType)) { - nextUntilUnescaped(stream, "/"); - stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla - return ret("regexp", "string-2"); - } - else { - stream.eatWhile(isOperatorChar); - return ret("operator", null, stream.current()); - } - } - else if (ch == "#") { - stream.skipToEnd(); - return ret("error", "error"); - } - else if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return ret("operator", null, stream.current()); - } - else { - stream.eatWhile(/[\w\$_]/); - var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; - return (known && state.lastType != ".") ? ret(known.type, known.style, word) : - ret("variable", "variable", word); - } - } - - function jsTokenString(quote) { - return function(stream, state) { - if (!nextUntilUnescaped(stream, quote)) - state.tokenize = jsTokenBase; - return ret("string", "string"); - }; - } - - function jsTokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = jsTokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return ret("comment", "comment"); - } - - // Parser - - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": 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; - } - - 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; - - 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 register(varname) { - var state = cx.state; - if (state.context) { - cx.marked = "def"; - for (var v = state.localVars; v; v = v.next) - if (v.name == varname) return; - state.localVars = {name: varname, next: state.localVars}; - } - } - - // Combinators - - var defaultVars = {name: "this", next: {name: "arguments"}}; - function pushcontext() { - cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; - cx.state.localVars = defaultVars; - } - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - function pushlex(type, info) { - var result = function() { - var state = cx.state; - state.lexical = new JSLexical(state.indented, 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) { - return function expecting(type) { - if (type == wanted) return cont(); - else if (wanted == ";") return pass(); - else return cont(arguments.callee); - }; - } - - function statement(type) { - if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); - if (type == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type == "{") return cont(pushlex("}"), block, poplex); - if (type == ";") return cont(); - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), - poplex, statement, poplex); - if (type == "variable") return cont(pushlex("stat"), maybelabel); - if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), - block, poplex, poplex); - if (type == "case") return cont(expression, expect(":")); - if (type == "default") return cont(expect(":")); - if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), - statement, poplex, popcontext); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function expression(type) { - if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); - if (type == "function") return cont(functiondef); - if (type == "keyword c") return cont(maybeexpression); - if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); - if (type == "operator") return cont(expression); - if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); - if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - - function maybeoperator(type, value) { - if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); - if (type == "operator" && value == "?") return cont(expression, expect(":"), expression); - if (type == ";") return; - if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); - if (type == ".") return cont(property, maybeoperator); - if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); - } - function maybelabel(type) { - if (type == ":") return cont(poplex, statement); - return pass(maybeoperator, expect(";"), poplex); - } - function property(type) { - if (type == "variable") {cx.marked = "property"; return cont();} - } - function objprop(type) { - if (type == "variable") cx.marked = "property"; - if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); - } - function commasep(what, end) { - function proceed(type) { - if (type == ",") return cont(what, proceed); - if (type == end) return cont(); - return cont(expect(end)); - } - return function commaSeparated(type) { - if (type == end) return cont(); - else return pass(what, proceed); - }; - } - function block(type) { - if (type == "}") return cont(); - return pass(statement, block); - } - function maybetype(type) { - if (type == ":") return cont(typedef); - return pass(); - } - function typedef(type) { - if (type == "variable"){cx.marked = "variable-3"; return cont();} - return pass(); - } - function vardef1(type, value) { - if (type == "variable") { - register(value); - return isTS ? cont(maybetype, vardef2) : cont(vardef2); - } - return pass(); - } - function vardef2(type, value) { - if (value == "=") return cont(expression, vardef2); - if (type == ",") return cont(vardef1); - } - function forspec1(type) { - if (type == "var") return cont(vardef1, expect(";"), forspec2); - if (type == ";") return cont(forspec2); - if (type == "variable") return cont(formaybein); - return cont(forspec2); - } - function formaybein(type, value) { - if (value == "in") return cont(expression); - return cont(maybeoperator, forspec2); - } - function forspec2(type, value) { - if (type == ";") return cont(forspec3); - if (value == "in") return cont(expression); - return cont(expression, expect(";"), forspec3); - } - function forspec3(type) { - if (type != ")") cont(expression); - } - function functiondef(type, value) { - if (type == "variable") {register(value); return cont(functiondef);} - if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); - } - function funarg(type, value) { - if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();} - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: jsTokenBase, - lastType: null, - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && {vars: parserConfig.localVars}, - indented: 0 - }; - }, - - token: function(stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = false; - state.indented = stream.indentation(); - } - if (stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type; - return parseJS(state, style, type, content, stream); - }, - - indent: function(state, textAfter) { - if (state.tokenize == jsTokenComment) return CodeMirror.Pass; - if (state.tokenize != jsTokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; - if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; - var type = lexical.type, closing = firstChar == type; - if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); - else if (type == "form" && firstChar == "{") return lexical.indented; - else if (type == "form") return lexical.indented + indentUnit; - else if (type == "stat") - return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0); - else if (lexical.info == "switch" && !closing) - 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); - }, - - electricChars: ":{}" - }; -}); - -CodeMirror.defineMIME("text/javascript", "javascript"); -CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); -CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); -CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); +// TODO actually recognize syntax of TypeScript constructs + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var jsonMode = parserConfig.json; + var isTS = parserConfig.typescript; + + // 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"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + var jsKeywords = { + "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, + "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 + }; + + // Extend the 'normal' keywords with the TypeScript language extensions + if (isTS) { + var type = {type: "variable", style: "variable-3"}; + var tsKeywords = { + // object-like things + "interface": kw("interface"), + "class": kw("class"), + "extends": kw("extends"), + "constructor": kw("constructor"), + + // scope modifiers + "public": kw("public"), + "private": kw("private"), + "protected": kw("protected"), + "static": kw("static"), + + "super": kw("super"), + + // types + "string": type, "number": type, "bool": type, "any": type + }; + + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + + return jsKeywords; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function nextUntilUnescaped(stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + + // 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 jsTokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, jsTokenString(ch)); + else if (/[\[\]{}\(\),;\:\.]/.test(ch)) + return ret(ch); + else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } + else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, jsTokenComment); + } + else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else if (state.lastType == "operator" || state.lastType == "keyword c" || + /^[\[{}\(,;:]$/.test(state.lastType)) { + nextUntilUnescaped(stream, "/"); + stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla + return ret("regexp", "string-2"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + } + else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + else { + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + + function jsTokenString(quote) { + return function(stream, state) { + if (!nextUntilUnescaped(stream, quote)) + state.tokenize = jsTokenBase; + return ret("string", "string"); + }; + } + + function jsTokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": 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; + } + + 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; + + 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 register(varname) { + function inList(list) { + for (var v = list; v; v = v.next) + if (v.name == varname) return true; + return false; + } + var state = cx.state; + if (state.context) { + cx.marked = "def"; + if (inList(state.localVars)) return; + state.localVars = {name: varname, next: state.localVars}; + } else { + if (inList(state.globalVars)) return; + state.globalVars = {name: varname, next: state.globalVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: {name: "arguments"}}; + function pushcontext() { + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + cx.state.localVars = defaultVars; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = new JSLexical(state.indented, 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) { + return function expecting(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + function statement(type) { + if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), block, poplex); + if (type == ";") return cont(); + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), + poplex, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), + block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), + statement, poplex, popcontext); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); + if (type == "function") return cont(functiondef); + if (type == "keyword c") return cont(maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); + if (type == "operator") return cont(expression); + if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); + if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperator(type, value) { + if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); + if (type == "operator" && value == "?") return cont(expression, expect(":"), expression); + if (type == ";") return; + if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); + if (type == ".") return cont(property, maybeoperator); + if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperator, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type) { + if (type == "variable") cx.marked = "property"; + if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); + } + function commasep(what, end) { + function proceed(type) { + if (type == ",") return cont(what, proceed); + if (type == end) return cont(); + return cont(expect(end)); + } + return function commaSeparated(type) { + if (type == end) return cont(); + else return pass(what, proceed); + }; + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type) { + if (type == ":") return cont(typedef); + return pass(); + } + function typedef(type) { + if (type == "variable"){cx.marked = "variable-3"; return cont();} + return pass(); + } + function vardef1(type, value) { + if (type == "variable") { + register(value); + return isTS ? cont(maybetype, vardef2) : cont(vardef2); + } + return pass(); + } + function vardef2(type, value) { + if (value == "=") return cont(expression, vardef2); + if (type == ",") return cont(vardef1); + } + function forspec1(type) { + if (type == "var") return cont(vardef1, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybein); + return cont(forspec2); + } + function formaybein(type, value) { + if (value == "in") return cont(expression); + return cont(maybeoperator, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in") return cont(expression); + return cont(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); + } + function funarg(type, value) { + if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();} + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: jsTokenBase, + lastType: null, + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + globalVars: parserConfig.globalVars, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: 0 + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == jsTokenComment) return CodeMirror.Pass; + if (state.tokenize != jsTokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; + if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0); + else if (lexical.info == "switch" && !closing) + 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); + }, + + electricChars: ":{}", + + jsonMode: jsonMode + }; +}); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); \ No newline at end of file diff --git a/lib/client/editor/codemirror/mode/xml.js b/lib/client/editor/codemirror/mode/xml.js index 860e368f..d761fcc9 100644 --- a/lib/client/editor/codemirror/mode/xml.js +++ b/lib/client/editor/codemirror/mode/xml.js @@ -1,318 +1,322 @@ -CodeMirror.defineMode("xml", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var Kludges = parserConfig.htmlMode ? { - autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, - 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, - 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, - 'track': true, 'wbr': true}, - implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, - 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, - 'th': true, 'tr': true}, - contextGrabbers: { - 'dd': {'dd': true, 'dt': true}, - 'dt': {'dd': true, 'dt': true}, - 'li': {'li': true}, - 'option': {'option': true, 'optgroup': true}, - 'optgroup': {'optgroup': true}, - 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, - 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, - 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, - 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, - 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, - 'rp': {'rp': true, 'rt': true}, - 'rt': {'rp': true, 'rt': true}, - 'tbody': {'tbody': true, 'tfoot': true}, - 'td': {'td': true, 'th': true}, - 'tfoot': {'tbody': true}, - 'th': {'td': true, 'th': true}, - 'thead': {'tbody': true, 'tfoot': true}, - 'tr': {'tr': true} - }, - doNotIndent: {"pre": true}, - allowUnquoted: true, - allowMissing: true - } : { - autoSelfClosers: {}, - implicitlyClosed: {}, - contextGrabbers: {}, - doNotIndent: {}, - allowUnquoted: false, - allowMissing: false - }; - var alignCDATA = parserConfig.alignCDATA; - - // Return variables for tokenizers - var tagName, type; - - function inText(stream, state) { - function chain(parser) { - state.tokenize = parser; - return parser(stream, state); - } - - var ch = stream.next(); - if (ch == "<") { - if (stream.eat("!")) { - if (stream.eat("[")) { - if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); - else return null; - } - else if (stream.match("--")) return chain(inBlock("comment", "-->")); - else if (stream.match("DOCTYPE", true, true)) { - stream.eatWhile(/[\w\._\-]/); - return chain(doctype(1)); - } - else return null; - } - else if (stream.eat("?")) { - stream.eatWhile(/[\w\._\-]/); - state.tokenize = inBlock("meta", "?>"); - return "meta"; - } - else { - type = stream.eat("/") ? "closeTag" : "openTag"; - stream.eatSpace(); - tagName = ""; - var c; - while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; - state.tokenize = inTag; - return "tag"; - } - } - else if (ch == "&") { - var ok; - if (stream.eat("#")) { - if (stream.eat("x")) { - ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); - } else { - ok = stream.eatWhile(/[\d]/) && stream.eat(";"); - } - } else { - ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); - } - return ok ? "atom" : "error"; - } - else { - stream.eatWhile(/[^&<]/); - return null; - } - } - - function inTag(stream, state) { - var ch = stream.next(); - if (ch == ">" || (ch == "/" && stream.eat(">"))) { - state.tokenize = inText; - type = ch == ">" ? "endTag" : "selfcloseTag"; - return "tag"; - } - else if (ch == "=") { - type = "equals"; - return null; - } - else if (/[\'\"]/.test(ch)) { - state.tokenize = inAttribute(ch); - return state.tokenize(stream, state); - } - else { - stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/); - return "word"; - } - } - - function inAttribute(quote) { - return function(stream, state) { - while (!stream.eol()) { - if (stream.next() == quote) { - state.tokenize = inTag; - break; - } - } - return "string"; - }; - } - - function inBlock(style, terminator) { - return function(stream, state) { - while (!stream.eol()) { - if (stream.match(terminator)) { - state.tokenize = inText; - break; - } - stream.next(); - } - return style; - }; - } - function doctype(depth) { - return function(stream, state) { - var ch; - while ((ch = stream.next()) != null) { - if (ch == "<") { - state.tokenize = doctype(depth + 1); - return state.tokenize(stream, state); - } else if (ch == ">") { - if (depth == 1) { - state.tokenize = inText; - break; - } else { - state.tokenize = doctype(depth - 1); - return state.tokenize(stream, state); - } - } - } - return "meta"; - }; - } - - var curState, setStyle; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - - function pushContext(tagName, startOfLine) { - var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); - curState.context = { - prev: curState.context, - tagName: tagName, - indent: curState.indented, - startOfLine: startOfLine, - noIndent: noIndent - }; - } - function popContext() { - if (curState.context) curState.context = curState.context.prev; - } - - function element(type) { - if (type == "openTag") { - curState.tagName = tagName; - return cont(attributes, endtag(curState.startOfLine)); - } else if (type == "closeTag") { - var err = false; - if (curState.context) { - if (curState.context.tagName != tagName) { - if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { - popContext(); - } - err = !curState.context || curState.context.tagName != tagName; - } - } else { - err = true; - } - if (err) setStyle = "error"; - return cont(endclosetag(err)); - } - return cont(); - } - function endtag(startOfLine) { - return function(type) { - if (type == "selfcloseTag" || - (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase()))) { - maybePopContext(curState.tagName.toLowerCase()); - return cont(); - } - if (type == "endTag") { - maybePopContext(curState.tagName.toLowerCase()); - pushContext(curState.tagName, startOfLine); - return cont(); - } - return cont(); - }; - } - function endclosetag(err) { - return function(type) { - if (err) setStyle = "error"; - if (type == "endTag") { popContext(); return cont(); } - setStyle = "error"; - return cont(arguments.callee); - }; - } - function maybePopContext(nextTagName) { - var parentTagName; - while (true) { - if (!curState.context) { - return; - } - parentTagName = curState.context.tagName.toLowerCase(); - if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || - !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { - return; - } - popContext(); - } - } - - function attributes(type) { - if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} - if (type == "endTag" || type == "selfcloseTag") return pass(); - setStyle = "error"; - return cont(attributes); - } - function attribute(type) { - if (type == "equals") return cont(attvalue, attributes); - if (!Kludges.allowMissing) setStyle = "error"; - return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); - } - function attvalue(type) { - if (type == "string") return cont(attvaluemaybe); - if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} - setStyle = "error"; - return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); - } - function attvaluemaybe(type) { - if (type == "string") return cont(attvaluemaybe); - else return pass(); - } - - return { - startState: function() { - return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null}; - }, - - token: function(stream, state) { - if (stream.sol()) { - state.startOfLine = true; - state.indented = stream.indentation(); - } - if (stream.eatSpace()) return null; - - setStyle = type = tagName = null; - var style = state.tokenize(stream, state); - state.type = type; - if ((style || type) && style != "comment") { - curState = state; - while (true) { - var comb = state.cc.pop() || element; - if (comb(type || style)) break; - } - } - state.startOfLine = false; - return setStyle || style; - }, - - indent: function(state, textAfter, fullLine) { - var context = state.context; - if ((state.tokenize != inTag && state.tokenize != inText) || - context && context.noIndent) - return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; - if (alignCDATA && /")); + else return null; + } + else if (stream.match("--")) return chain(inBlock("comment", "-->")); + else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } + else return null; + } + else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } + else { + var isClose = stream.eat("/"); + tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; + if (!tagName) return "error"; + type = isClose ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag"; + } + } + else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } + else { + stream.eatWhile(/[^&<]/); + return null; + } + } + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag"; + } + else if (ch == "=") { + type = "equals"; + return null; + } + else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } + else { + stream.eatWhile(/[^\s\u00a0=<>\"\']/); + return "word"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + var curState, setStyle; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + + function pushContext(tagName, startOfLine) { + var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); + curState.context = { + prev: curState.context, + tagName: tagName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; + } + function popContext() { + if (curState.context) curState.context = curState.context.prev; + } + + function element(type) { + if (type == "openTag") { + curState.tagName = tagName; + return cont(attributes, endtag(curState.startOfLine)); + } else if (type == "closeTag") { + var err = false; + if (curState.context) { + if (curState.context.tagName != tagName) { + if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { + popContext(); + } + err = !curState.context || curState.context.tagName != tagName; + } + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endclosetag(err)); + } + return cont(); + } + function endtag(startOfLine) { + return function(type) { + if (type == "selfcloseTag" || + (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase()))) { + maybePopContext(curState.tagName.toLowerCase()); + return cont(); + } + if (type == "endTag") { + maybePopContext(curState.tagName.toLowerCase()); + pushContext(curState.tagName, startOfLine); + return cont(); + } + return cont(); + }; + } + function endclosetag(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endTag") { popContext(); return cont(); } + setStyle = "error"; + return cont(arguments.callee); + }; + } + function maybePopContext(nextTagName) { + var parentTagName; + while (true) { + if (!curState.context) { + return; + } + parentTagName = curState.context.tagName.toLowerCase(); + if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || + !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(); + } + } + + function attributes(type) { + if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} + if (type == "endTag" || type == "selfcloseTag") return pass(); + setStyle = "error"; + return cont(attributes); + } + function attribute(type) { + if (type == "equals") return cont(attvalue, attributes); + if (!Kludges.allowMissing) setStyle = "error"; + else if (type == "word") setStyle = "attribute"; + return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); + } + function attvalue(type) { + if (type == "string") return cont(attvaluemaybe); + if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} + setStyle = "error"; + return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); + } + function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); + } + + return { + startState: function() { + return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null}; + }, + + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + + setStyle = type = tagName = null; + var style = state.tokenize(stream, state); + state.type = type; + if ((style || type) && style != "comment") { + curState = state; + while (true) { + var comb = state.cc.pop() || element; + if (comb(type || style)) break; + } + } + state.startOfLine = false; + return setStyle || style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + if ((state.tokenize != inTag && state.tokenize != inText) || + context && context.noIndent) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + if (alignCDATA && / ' + url + " : " + line]); - - if(typeof lOnError_f === 'function') - lOnError_f(); - - return preventErrorAlert; - }; + }); - DOM.jsload('http://google-analytics.com/ga.js'); -})(); \ No newline at end of file + DOM.jsload('//google-analytics.com/ga.js'); + +})(DOM, _gaq); \ No newline at end of file diff --git a/lib/client/ie.js b/lib/client/ie.js index 45136ac7..b0c63dfc 100644 --- a/lib/client/ie.js +++ b/lib/client/ie.js @@ -1,221 +1,273 @@ -/* script, fixes ie */ -var Util, DOM, $; - -(function(){ - "use strict"; - - /* setting head ie6 - ie8 */ - if(!document.head){ - document.head = document.getElementsByTagName("head")[0]; - - /* - {name: '', src: ' ',func: '', style: '', id: '', parent: '', - async: false, inner: 'id{color:red, }, class:'', not_append: false} - */ - DOM.cssSet = function(pParams_o){ - var lElement = ''; + + return $(lElement) + .appendTo(pParams_o.parent || document.head); + }; + } + + /* setting function context (this) */ + Util.bind = function(pFunction, pContext){ + var lRet; + + lRet = $.proxy(pFunction, pContext); + + return lRet; + }; + + /* + * typeof callback === "function" should not be used, + * as older browsers may report objects to be a function, + * which they are not + */ + Util.isFunction = $.isFunction; + + if (!document.addEventListener) + /** + * safe add event listener on ie + * @param pType + * @param pListener + */ + DOM.addListener = function(pType, pListener, pCapture, pElement){ + var lRet; + + if(!pElement) + pElement = window; + + lRet = $(pElement).bind(pType, null, pListener); + + return lRet; + }; + + if(!document.removeEventListener){ + DOM.removeListener = function(pType, pListener, pCapture, pElement){ + var lRet; + + if(!pElement) + pElement = window; + + $(pElement).unbind(pType, pListener); + + return lRet; + }; + } + + if(!document.getElementsByClassName){ + DOM.getByClass = function(pClass, pElement){ + var lClass = '.' + pClass, + lResult; + + if(pElement) + lResult = $(pElement).find(lClass); + else lResult = $.find(lClass); + + return lResult; + }; + } + + DOM.scrollByPages = Util.retFalse; + /* function polyfill webkit standart function */ + DOM.scrollIntoViewIfNeeded = function(pElement, centerIfNeeded){ + if(!window.getComputedStyle) + return; + /* + https://gist.github.com/2581101 + */ + centerIfNeeded = arguments.length === 0 ? true : !!centerIfNeeded; + + var parent = pElement.parentNode, + parentComputedStyle = window.getComputedStyle(parent, null), + parentBorderTopWidth = + parseInt(parentComputedStyle.getPropertyValue('border-top-width'), 10), + + parentBorderLeftWidth = + parseInt(parentComputedStyle.getPropertyValue('border-left-width'), 10), + + overTop = pElement.offsetTop - parent.offsetTop < parent.scrollTop, + overBottom = + (pElement.offsetTop - + parent.offsetTop + + pElement.clientHeight - + parentBorderTopWidth) > + (parent.scrollTop + parent.clientHeight), + + overLeft = pElement.offsetLeft - + parent.offsetLeft < parent.scrollLeft, + + overRight = + (pElement.offsetLeft - + parent.offsetLeft + + pElement.clientWidth - + parentBorderLeftWidth) > + (parent.scrollLeft + parent.clientWidth), + + alignWithTop = overTop && !overBottom; + + if ((overTop || overBottom) && centerIfNeeded) + parent.scrollTop = + pElement.offsetTop - + parent.offsetTop - + parent.clientHeight / 2 - + parentBorderTopWidth + + pElement.clientHeight / 2; + + if ((overLeft || overRight) && centerIfNeeded) + parent.scrollLeft = + pElement.offsetLeft - + parent.offsetLeft - + parent.clientWidth / 2 - + parentBorderLeftWidth + + pElement.clientWidth / 2; + + if ( (overTop || overBottom || overLeft || overRight) && + !centerIfNeeded) + pElement.scrollIntoView(alignWithTop); + }; + + if(!document.body.classList){ + DOM.addClass = function(pElement, pClass){ + var lSpaceChar = '', + lClassName = pElement.className, + lRet_b = true; + + if(lClassName) lSpaceChar = ' '; + + if( lClassName.indexOf(pClass) < 0 ) + pElement.className += lSpaceChar + pClass; + else + lRet_b = false; + }; + + DOM.removeClass = function(pElement, pClass){ + var lClassName = pElement.className; + + if(lClassName.length > pClass.length) + pElement.className = lClassName.replace(pClass, ''); + }; + } + + if(!window.JSON){ + Util.parseJSON = $.parseJSON; + + /* https://gist.github.com/754454 */ + Util.stringifyJSON = function(pObj){ + var lRet; + + if (!Util.isObject(pObj) || pObj === null) { + // simple data type + if (Util.isString(pObj)) pObj = '"' + pObj + '"'; + lRet = String(pObj); + } else { + // recurse array or object + var n, v, json = [], isArray = Util.isArray(pObj); + + for (n in pObj) { + v = pObj[n]; + + if (pObj.hasOwnProperty(n)) { + if (Util.isString(v)) + v = '"' + v + '"'; + else if (v && Util.isObject(v)) + v = DOM.stringifyJSON(v); + + json.push((isArray ? "" : '"' + n + '":') + String(v)); + } + } + lRet = (isArray ? "[" : "{") + String(json) + (isArray ? "]" : "}"); + } + + return lRet; + }; + } + + if(!window.localStorage){ + var Cache = function(){ + /* приватный переключатель возможности работы с кэшем */ + var CacheAllowed, + Data = {}; + + /* функция проверяет возможно ли работать с кэшем каким-либо образом */ + this.isAllowed = function(){ + return CacheAllowed; + }; + + this.setAllowed = function(){ + CacheAllowed = true; + }; + + this.UnSetAllowed = function(){ + CacheAllowed = false; + }; + + /** remove element */ + this.remove = function(pItem){ + var lRet = this; + if(CacheAllowed) + delete Data[pItem]; + + return lRet; + }; + + /** если доступен localStorage и + * в нём есть нужная нам директория - + * записываем данные в него + */ + this.set = function(pName, pData){ + var lRet = this; + + if(CacheAllowed && pName && pData) + Data[pName] = pData; + + return lRet; + }, + + /** Если доступен Cache принимаем из него данные*/ + this.get = function(pName){ + var lRet = false; + + if(CacheAllowed) + lRet = Data[pName]; + + return lRet; + }, + + /** функция чистит весь кэш для всех каталогов*/ + this.clear = function(){ + var lRet = this; + + if(CacheAllowed) + Data = {}; + + return lRet; + }; + }; + + DOM.Cache = new Cache(); + } + + +})(Util, DOM, jQuery); \ No newline at end of file diff --git a/lib/client/jquery.js b/lib/client/jquery.js index daa58a6b..6c5f4a69 100644 --- a/lib/client/jquery.js +++ b/lib/client/jquery.js @@ -1,5 +1,5 @@ /*! - * jQuery JavaScript Library v1.8.0 + * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js @@ -9,7 +9,7 @@ * Released under the MIT license * http://jquery.org/license * - * Date: Thu Aug 09 2012 16:24:48 GMT-0400 (Eastern Daylight Time) + * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function( window, undefined ) { var @@ -51,8 +51,8 @@ var core_rnotwhite = /\S/, core_rspace = /\s+/, - // IE doesn't match non-breaking spaces with \s - rtrim = core_rnotwhite.test("\xA0") ? (/^[\s\xA0]+|[\s\xA0]+$/g) : /^\s+|\s+$/g, + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) @@ -186,7 +186,7 @@ jQuery.fn = jQuery.prototype = { selector: "", // The current version of jQuery being used - jquery: "1.8.0", + jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, @@ -573,7 +573,7 @@ jQuery.extend({ }, nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only @@ -619,7 +619,7 @@ jQuery.extend({ }, // Use native String.trim function wherever possible - trim: core_trim ? + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : @@ -630,7 +630,7 @@ jQuery.extend({ function( text ) { return text == null ? "" : - text.toString().replace( rtrim, "" ); + ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only @@ -776,7 +776,7 @@ jQuery.extend({ }; // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, @@ -844,9 +844,10 @@ jQuery.ready.promise = function( obj ) { readyList = jQuery.Deferred(); - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" || ( document.readyState !== "loading" && document.addEventListener ) ) { + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); @@ -997,9 +998,12 @@ jQuery.Callbacks = function( options ) { var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { - if ( jQuery.isFunction( arg ) && ( !options.unique || !self.has( arg ) ) ) { - list.push( arg ); - } else if ( arg && arg.length ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } @@ -1141,7 +1145,7 @@ jQuery.extend({ // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { - return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise; + return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; @@ -1251,24 +1255,23 @@ jQuery.support = (function() { clickFn, div = document.createElement("div"); - // Preliminary tests + // Setup div.setAttribute( "className", "t" ); div.innerHTML = "
a"; + // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; - a.style.cssText = "top:1px;float:left;opacity:.5"; - - // Can't get basic test support - if ( !all || !all.length || !a ) { + if ( !all || !a || !all.length ) { return {}; } - // First batch of supports tests + // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; + a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), @@ -1310,7 +1313,7 @@ jQuery.support = (function() { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", - // Tests for enctype support on a form(#6743) + // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems @@ -1452,10 +1455,8 @@ jQuery.support = (function() { support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); - // NOTE: To any future maintainer, window.getComputedStyle was used here - // instead of getComputedStyle because it gave a better gzip size. - // The difference between window.getComputedStyle and getComputedStyle is - // 7 bytes + // NOTE: To any future maintainer, we've window.getComputedStyle + // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; @@ -1505,7 +1506,7 @@ jQuery.support = (function() { return support; })(); -var rbrace = /^(?:\{.*\}|\[.*\])$/, +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ @@ -1513,7 +1514,7 @@ jQuery.extend({ deletedIds: [], - // Please use with caution + // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page @@ -1565,7 +1566,7 @@ jQuery.extend({ // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { - elem[ internalKey ] = id = jQuery.deletedIds.pop() || ++jQuery.uuid; + elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } @@ -1739,7 +1740,7 @@ jQuery.fn.extend({ for ( l = attr.length; i < l; i++ ) { name = attr[i].name; - if ( name.indexOf( "data-" ) === 0 ) { + if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); @@ -1868,6 +1869,7 @@ jQuery.extend({ type = type || "fx"; var queue = jQuery.queue( elem, type ), + startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { @@ -1877,6 +1879,7 @@ jQuery.extend({ // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); + startLength--; } if ( fn ) { @@ -1891,7 +1894,8 @@ jQuery.extend({ delete hooks.stop; fn.call( elem, next, hooks ); } - if ( !queue.length && hooks ) { + + if ( !startLength && hooks ) { hooks.empty.fire(); } }, @@ -1977,7 +1981,8 @@ jQuery.fn.extend({ type = type || "fx"; while( i-- ) { - if ( (tmp = jQuery._data( elements[ i ], type + "queueHooks" )) && tmp.empty ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } @@ -2045,7 +2050,7 @@ jQuery.fn.extend({ setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } @@ -2078,7 +2083,7 @@ jQuery.fn.extend({ // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, - while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) { + while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } @@ -2132,7 +2137,7 @@ jQuery.fn.extend({ i = 0, l = this.length; for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } @@ -2213,26 +2218,25 @@ jQuery.extend({ }, select: { get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], + var value, option, options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); @@ -2247,11 +2251,6 @@ jQuery.extend({ } } - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - return values; }, @@ -2310,7 +2309,7 @@ jQuery.extend({ return ret; } else { - elem.setAttribute( name, "" + value ); + elem.setAttribute( name, value + "" ); return value; } @@ -2574,7 +2573,7 @@ if ( !jQuery.support.style ) { return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); + return ( elem.style.cssText = value + "" ); } }; } @@ -2707,6 +2706,7 @@ jQuery.event = { handler: handler, guid: handler.guid, selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); @@ -2942,7 +2942,7 @@ jQuery.event = { } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } @@ -2987,10 +2987,10 @@ jQuery.event = { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); - var i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related, + var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, - args = [].slice.call( arguments ), + args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; @@ -3008,23 +3008,20 @@ jQuery.event = { // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this; - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #xxxx) + // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; - jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = jqcur.is( sel ); + selMatch[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); @@ -3165,11 +3162,6 @@ jQuery.event = { }, special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true @@ -3236,7 +3228,7 @@ jQuery.removeEvent = document.removeEventListener ? if ( elem.detachEvent ) { - // #8545, #7054, preventing memory leaks for custom events in IE6-8 – + // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; @@ -3458,7 +3450,7 @@ if ( !jQuery.support.changeBubbles ) { teardown: function() { jQuery.event.remove( this, "._change" ); - return rformElems.test( this.nodeName ); + return !rformElems.test( this.nodeName ); } }; } @@ -3599,7 +3591,7 @@ jQuery.fn.extend({ }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { @@ -3670,30 +3662,73 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl }); /*! * Sizzle CSS Selector Engine - * Copyright 2012 jQuery Foundation and other contributors - * Released under the MIT license - * http://sizzlejs.com/ + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, - dirruns, - sortOrder, - siblingCheck, assertGetIdNotName, + Expr, + getText, + isXML, + contains, + compile, + sortOrder, + hasDuplicate, + outermostContext, - document = window.document, - docElem = document.documentElement, - - strundefined = "undefined", - hasDuplicate = false, baseHasDuplicate = true, - done = 0, - slice = [].slice, - push = [].push, + strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), + Token = String, + document = window.document, + docElem = document.documentElement, + dirruns = 0, + done = 0, + pop = [].pop, + push = [].push, + slice = [].slice, + // Use a stripped-down indexOf if a native one is unavailable + indexOf = [].indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + // Augment a function for special use by Sizzle + markFunction = function( fn, value ) { + fn[ expando ] = value == null || value; + return fn; + }, + + createCache = function() { + var cache = {}, + keys = []; + + return markFunction(function( key, value ) { + // Only keep the most recent entries + if ( keys.push( key ) > Expr.cacheLength ) { + delete cache[ keys.shift() ]; + } + + // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) + return (cache[ key + " " ] = value); + }, cache ); + }, + + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace @@ -3710,29 +3745,29 @@ var cachedruns, operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", - pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", - combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*", - groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+", + + // Prefer arguments not in parens/brackets, + // then attribute selectors and non-pseudos (denoted by :), + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", + + // For matchExpr.POS and matchExpr.needsContext + pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - rcombinators = new RegExp( "^" + combinators ), - - // All simple (non-comma) selectors, excluding insignifant trailing whitespace - rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ), - - // A selector, or everything after leading whitespace - // Optionally followed in either case by a ")" for terminating sub-selectors - rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ), - - // All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive - rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ), + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, + rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, @@ -3745,56 +3780,46 @@ var cachedruns, "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "[-", "[-\\*" ) + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + + "POS": new RegExp( pos, "i" ), + "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "POS": new RegExp( pos, "ig" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, - classCache = {}, - cachedClasses = [], - compilerCache = {}, - cachedSelectors = [], - - // Mark a function for use in filtering - markFunction = function( fn ) { - fn.sizzleFilter = true; - return fn; - }, - - // Returns a function to use in pseudos for input types - createInputFunction = function( type ) { - return function( elem ) { - // Check the input's nodeName and type - return elem.nodeName.toLowerCase() === "input" && elem.type === type; - }; - }, - - // Returns a function to use in pseudos for buttons - createButtonFunction = function( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; - }, + // Support // Used for testing something on an element assert = function( fn ) { - var pass = false, - div = document.createElement("div"); + var div = document.createElement("div"); + try { - pass = fn( div ); - } catch (e) {} - // release memory in IE - div = null; - return pass; + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } }, + // Check if getElementsByTagName("*") returns only elements + assertTagNameNoComments = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }), + + // Check if getAttribute returns normalized href attributes + assertHrefNotNormalized = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }), + // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = ""; @@ -3803,6 +3828,19 @@ var cachedruns, return type !== "boolean" && type !== "string"; }), + // Check if getElementsByClassName can be trusted + assertUsableClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }), + // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { @@ -3814,58 +3852,45 @@ var cachedruns, // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 - document.getElementsByName( expando ).length === + document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 - 2 + document.getElementsByName( expando + 0 ).length; + document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; - }), - - // Check if the browser returns only elements - // when doing getElementsByTagName("*") - assertTagNameNoComments = assert(function( div ) { - div.appendChild( document.createComment("") ); - return div.getElementsByTagName("*").length === 0; - }), - - // Check if getAttribute returns normalized href attributes - assertHrefNotNormalized = assert(function( div ) { - div.innerHTML = ""; - return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && - div.firstChild.getAttribute("href") === "#"; - }), - - // Check if getElementsByClassName can be trusted - assertUsableClassName = assert(function( div ) { - // Opera can't find a second classname (in 9.6) - div.innerHTML = ""; - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return false; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - return div.getElementsByClassName("e").length !== 1; }); -var Sizzle = function( selector, context, results, seed ) { +// If slice is not available, provide a backup +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; - if ( nodeType !== 1 && nodeType !== 9 ) { - return []; - } - if ( !selector || typeof selector !== "string" ) { return results; } + if ( nodeType !== 1 && nodeType !== 9 ) { + return []; + } + xml = isXML( context ); if ( !xml && !seed ) { @@ -3909,21 +3934,157 @@ var Sizzle = function( selector, context, results, seed ) { } // All others - return select( selector, context, results, seed, xml ); + return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); +} + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); }; -var Expr = Sizzle.selectors = { +Sizzle.matchesSelector = function( elem, expr ) { + return Sizzle( expr, null, null, [ elem ] ).length > 0; +}; + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + } else { + + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } + return ret; +}; + +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Element contains another +contains = Sizzle.contains = docElem.contains ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); + } : + docElem.compareDocumentPosition ? + function( a, b ) { + return b && !!( a.compareDocumentPosition( b ) & 16 ); + } : + function( a, b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + return false; + }; + +Sizzle.attr = function( elem, name ) { + var val, + xml = isXML( elem ); + + if ( !xml ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( xml || assertAttributes ) { + return elem.getAttribute( name ); + } + val = elem.getAttributeNode( name ); + return val ? + typeof elem[ name ] === "boolean" ? + elem[ name ] ? name : null : + val.specified ? val.value : null : + null; +}; + +Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, + createPseudo: markFunction, + match: matchExpr, - order: [ "ID", "TAG" ], - - attrHandle: {}, - - createPseudo: markFunction, + // IE6/7 return a modified href + attrHandle: assertHrefNotNormalized ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }, find: { "ID": assertGetIdNotName ? @@ -3971,7 +4132,19 @@ var Expr = Sizzle.selectors = { return tmp; } return results; + }, + + "NAME": assertUsableName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); } + }, + + "CLASS": assertUsableClassName && function( className, context, xml ) { + if ( typeof context.getElementsByClassName !== strundefined && !xml ) { + return context.getElementsByClassName( className ); + } + } }, relative: { @@ -3996,7 +4169,7 @@ var Expr = Sizzle.selectors = { }, "CHILD": function( match ) { - /* matches from matchExpr.CHILD + /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) @@ -4027,24 +4200,30 @@ var Expr = Sizzle.selectors = { }, "PSEUDO": function( match ) { - var argument, - unquoted = match[4]; - + var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } - // Relinquish our claim on characters in `unquoted` from a closing parenthesis on - if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) { + if ( match[3] ) { + match[2] = match[3]; + } else if ( (unquoted = match[4]) ) { + // Only check arguments that contain a pseudo + if ( rpseudo.test(unquoted) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 ); - unquoted = argument[0].slice( 0, -1 ); + // excess is a negative index + unquoted = unquoted.slice( 0, excess ); + match[0] = match[0].slice( 0, excess ); + } + match[2] = unquoted; } - // Quoted or unquoted, we have the full argument // Return only captures needed by the pseudo filter method (type and argument) - match.splice( 2, 3, unquoted || match[3] ); - return match; + return match.slice( 0, 3 ); } }, @@ -4076,91 +4255,65 @@ var Expr = Sizzle.selectors = { }, "CLASS": function( className ) { - var pattern = classCache[ className ]; - if ( !pattern ) { - pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); - cachedClasses.push( className ); - // Avoid too large of a cache - if ( cachedClasses.length > Expr.cacheLength ) { - delete classCache[ cachedClasses.shift() ]; - } - } - return function( elem ) { - return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); - }; + var pattern = classCache[ expando ][ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); }, "ATTR": function( name, operator, check ) { - if ( !operator ) { - return function( elem ) { - return Sizzle.attr( elem, name ) != null; - }; - } - - return function( elem ) { - var result = Sizzle.attr( elem, name ), - value = result + ""; + return function( elem, context ) { + var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } - - switch ( operator ) { - case "=": - return value === check; - case "!=": - return value !== check; - case "^=": - return check && value.indexOf( check ) === 0; - case "*=": - return check && value.indexOf( check ) > -1; - case "$=": - return check && value.substr( value.length - check.length ) === check; - case "~=": - return ( " " + value + " " ).indexOf( check ) > -1; - case "|=": - return value === check || value.substr( 0, check.length + 1 ) === check + "-"; + if ( !operator ) { + return true; } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.substr( result.length - check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : + false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { - var doneName = done++; - return function( elem ) { - var parent, diff, - count = 0, - node = elem; + var node, diff, + parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } - parent = elem.parentNode; - - if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { + if ( parent ) { + diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { - node.sizset = ++count; - if ( node === elem ) { + diff++; + if ( elem === node ) { break; } } } - - parent[ expando ] = doneName; } - diff = elem.sizset - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } + // Incorporate the offset (or cast to NaN), then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } @@ -4195,35 +4348,82 @@ var Expr = Sizzle.selectors = { }; }, - "PSEUDO": function( pseudo, argument, context, xml ) { + "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); - if ( !fn ) { - Sizzle.error( "unsupported pseudo: " + pseudo ); - } - - // The user may set fn.sizzleFilter to indicate - // that arguments are needed to create the filter function + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function // just as Sizzle does - if ( !fn.sizzleFilter ) { - return fn; + if ( fn[ expando ] ) { + return fn( argument ); } - return fn( argument, context, xml ); + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; } }, pseudos: { - "not": markFunction(function( selector, context, xml ) { + "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators - var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { return function( elem ) { - return !matcher( elem ); + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), @@ -4273,18 +4473,6 @@ var Expr = Sizzle.selectors = { return true; }, - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - "header": function( elem ) { return rheader.test( elem.nodeName ); }, @@ -4299,14 +4487,14 @@ var Expr = Sizzle.selectors = { }, // Input types - "radio": createInputFunction("radio"), - "checkbox": createInputFunction("checkbox"), - "file": createInputFunction("file"), - "password": createInputFunction("password"), - "image": createInputFunction("image"), + "radio": createInputPseudo("radio"), + "checkbox": createInputPseudo("checkbox"), + "file": createInputPseudo("file"), + "password": createInputPseudo("password"), + "image": createInputPseudo("image"), - "submit": createButtonFunction("submit"), - "reset": createButtonFunction("reset"), + "submit": createButtonPseudo("submit"), + "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); @@ -4319,210 +4507,76 @@ var Expr = Sizzle.selectors = { "focus": function( elem ) { var doc = elem.ownerDocument; - return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); + return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; - } - }, - - setFilters: { - "first": function( elements, argument, not ) { - return not ? elements.slice( 1 ) : [ elements[0] ]; }, - "last": function( elements, argument, not ) { - var elem = elements.pop(); - return not ? elements : [ elem ]; - }, + // Positional types + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), - "even": function( elements, argument, not ) { - var results = [], - i = not ? 1 : 0, - len = elements.length; - for ( ; i < len; i = i + 2 ) { - results.push( elements[i] ); + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 0; i < length; i += 2 ) { + matchIndexes.push( i ); } - return results; - }, + return matchIndexes; + }), - "odd": function( elements, argument, not ) { - var results = [], - i = not ? 0 : 1, - len = elements.length; - for ( ; i < len; i = i + 2 ) { - results.push( elements[i] ); + "odd": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 1; i < length; i += 2 ) { + matchIndexes.push( i ); } - return results; - }, + return matchIndexes; + }), - "lt": function( elements, argument, not ) { - return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); - }, + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), - "gt": function( elements, argument, not ) { - return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); - }, - - "eq": function( elements, argument, not ) { - var elem = elements.splice( +argument, 1 ); - return not ? elements : elem; - } + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) } }; -// Deprecated -Expr.setFilters["nth"] = Expr.setFilters["eq"]; +function siblingCheck( a, b, ret ) { + if ( a === b ) { + return ret; + } -// Back-compat -Expr.filters = Expr.pseudos; + var cur = a.nextSibling; -// IE6/7 return a modified href -if ( !assertHrefNotNormalized ) { - Expr.attrHandle = { - "href": function( elem ) { - return elem.getAttribute( "href", 2 ); - }, - "type": function( elem ) { - return elem.getAttribute("type"); + while ( cur ) { + if ( cur === b ) { + return -1; } - }; + + cur = cur.nextSibling; + } + + return 1; } -// Add getElementsByName if usable -if ( assertUsableName ) { - Expr.order.push("NAME"); - Expr.find["NAME"] = function( name, context ) { - if ( typeof context.getElementsByName !== strundefined ) { - return context.getElementsByName( name ); - } - }; -} - -// Add getElementsByClassName if usable -if ( assertUsableClassName ) { - Expr.order.splice( 1, 0, "CLASS" ); - Expr.find["CLASS"] = function( className, context, xml ) { - if ( typeof context.getElementsByClassName !== strundefined && !xml ) { - return context.getElementsByClassName( className ); - } - }; -} - -// If slice is not available, provide a backup -try { - slice.call( docElem.childNodes, 0 )[0].nodeType; -} catch ( e ) { - slice = function( i ) { - var elem, results = []; - for ( ; (elem = this[i]); i++ ) { - results.push( elem ); - } - return results; - }; -} - -var isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -// Element contains another -var contains = Sizzle.contains = docElem.compareDocumentPosition ? +sortOrder = docElem.compareDocumentPosition ? function( a, b ) { - return !!( a.compareDocumentPosition( b ) & 16 ); - } : - docElem.contains ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); - } : - function( a, b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - return false; - }; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - } else { - - // If no nodeType, this is expected to be an array - for ( ; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } - return ret; -}; - -Sizzle.attr = function( elem, name ) { - var attr, - xml = isXML( elem ); - - if ( !xml ) { - name = name.toLowerCase(); - } - if ( Expr.attrHandle[ name ] ) { - return Expr.attrHandle[ name ]( elem ); - } - if ( assertAttributes || xml ) { - return elem.getAttribute( name ); - } - attr = elem.getAttributeNode( name ); - return attr ? - typeof elem[ name ] === "boolean" ? - elem[ name ] ? name : null : - attr.specified ? attr.value : null : - null; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -// Check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - return (baseHasDuplicate = 0); -}); - - -if ( docElem.compareDocumentPosition ) { - sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; @@ -4532,10 +4586,8 @@ if ( docElem.compareDocumentPosition ) { a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { + } : + function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; @@ -4595,397 +4647,532 @@ if ( docElem.compareDocumentPosition ) { siblingCheck( ap[i], b, 1 ); }; - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, - i = 1; + duplicates = [], + i = 1, + j = 0; - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); - if ( hasDuplicate ) { - for ( ; (elem = results[i]); i++ ) { - if ( elem === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); } } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } } return results; }; -function multipleContexts( selector, contexts, results, seed ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results, seed ); - } -} +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; -function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { - var results, - fn = Expr.setFilters[ posfilter.toLowerCase() ]; +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ expando ][ selector + " " ]; - if ( !fn ) { - Sizzle.error( posfilter ); + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); } - if ( selector || !(results = seed) ) { - multipleContexts( selector || "*", contexts, (results = []), seed ); - } + soFar = selector; + groups = []; + preFilters = Expr.preFilter; - return results.length > 0 ? fn( results, argument, not ) : []; -} + while ( soFar ) { -function handlePOS( selector, context, results, seed, groups ) { - var match, not, anchor, ret, elements, currentContexts, part, lastIndex, - i = 0, - len = groups.length, - rpos = matchExpr["POS"], - // This is generated here in case matchExpr["POS"] is extended - rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), - // This is for making sure non-participating - // matching groups are represented cross-browser (IE6-8) - setUndefined = function() { - var i = 1, - len = arguments.length - 2; - for ( ; i < len; i++ ) { - if ( arguments[i] === undefined ) { - match[i] = undefined; - } + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; } - }; + groups.push( tokens = [] ); + } - for ( ; i < len; i++ ) { - // Reset regex index to 0 - rpos.exec(""); - selector = groups[i]; - ret = []; - anchor = 0; - elements = seed; - while ( (match = rpos.exec( selector )) ) { - lastIndex = rpos.lastIndex = match.index + match[0].length; - if ( lastIndex > anchor ) { - part = selector.slice( anchor, match.index ); - anchor = lastIndex; - currentContexts = [ context ]; + matched = false; - if ( rcombinators.test(part) ) { - if ( elements ) { - currentContexts = elements; - } - elements = seed; - } + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); - if ( (not = rendsWithNot.test( part )) ) { - part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); - } + // Cast descendant combinators to space + matched.type = match[0].replace( rtrim, " " ); + } - if ( match.length > 1 ) { - match[0].replace( rposgroups, setUndefined ); - } - elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + matched.type = type; + matched.matches = match; } } - if ( elements ) { - ret = ret.concat( elements ); - - if ( (part = selector.slice( anchor )) && part !== ")" ) { - if ( rcombinators.test(part) ) { - multipleContexts( part, ret, results, seed ); - } else { - Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); - } - } else { - push.apply( results, ret ); - } - } else { - Sizzle( selector, context, results, seed ); + if ( !matched ) { + break; } } - // Do not sort if this is a single filter - return len === 1 ? results : Sizzle.uniqueSort( results ); + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); } -function tokenize( selector, context, xml ) { - var tokens, soFar, type, - groups = [], - i = 0, - - // Catch obvious selector issues: terminal ")"; nonempty fallback match - // rselector never fails to match *something* - match = rselector.exec( selector ), - matched = !match.pop() && !match.pop(), - selectorGroups = matched && selector.match( rgroups ) || [""], - - preFilters = Expr.preFilter, - filters = Expr.filter, - checkContext = !xml && context !== document; - - for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) { - groups.push( tokens = [] ); - - // Need to make sure we're within a narrower context if necessary - // Adding a descendant combinator will generate what is needed - if ( checkContext ) { - soFar = " " + soFar; - } - - while ( soFar ) { - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - soFar = soFar.slice( match[0].length ); - - // Cast descendant combinators to space - matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match }); - } - - // Filters - for ( type in filters ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match, context, xml )) ) ) { - - soFar = soFar.slice( match.shift().length ); - matched = tokens.push({ part: type, captures: match }); - } - } - - if ( !matched ) { - break; - } - } - } - - if ( !matched ) { - Sizzle.error( selector ); - } - - return groups; -} - -function addCombinator( matcher, combinator, context ) { +function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, + checkNonElements = base && combinator.dir === "parentNode", doneName = done++; - if ( !matcher ) { - // If there is no matcher to check, check against the context - matcher = function( elem ) { - return elem === context; - }; - } return combinator.first ? - function( elem, context ) { + // Check against closest ancestor/preceding element + function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 ) { - return matcher( elem, context ) && elem; + if ( checkNonElements || elem.nodeType === 1 ) { + return matcher( elem, context, xml ); } } } : - function( elem, context ) { - var cache, - dirkey = doneName + "." + dirruns, - cachedkey = dirkey + "." + cachedruns; - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 ) { - if ( (cache = elem[ expando ]) === cachedkey ) { - return elem.sizset; - } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { - if ( elem.sizset ) { + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( !xml ) { + var cache, + dirkey = dirruns + " " + doneName + " ", + cachedkey = dirkey + cachedruns; + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( (cache = elem[ expando ]) === cachedkey ) { + return elem.sizset; + } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { + if ( elem.sizset ) { + return elem; + } + } else { + elem[ expando ] = cachedkey; + if ( matcher( elem, context, xml ) ) { + elem.sizset = true; + return elem; + } + elem.sizset = false; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( matcher( elem, context, xml ) ) { return elem; } - } else { - elem[ expando ] = cachedkey; - if ( matcher( elem, context ) ) { - elem.sizset = true; - return elem; - } - elem.sizset = false; } } } }; } -function addMatcher( higher, deeper ) { - return higher ? - function( elem, context ) { - var result = deeper( elem, context ); - return result && higher( result === true ? elem : result, context ); +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; } : - deeper; + matchers[0]; } -// ["TAG", ">", "ID", " ", "CLASS"] -function matcherFromTokens( tokens, context, xml ) { - var token, matcher, - i = 0; +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; - for ( ; (token = tokens[i]); i++ ) { - if ( Expr.relative[ token.part ] ) { - matcher = addCombinator( matcher, Expr.relative[ token.part ], context ); - } else { - token.captures.push( context, xml ); - matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) ); - } - } - - return matcher; -} - -function matcherFromGroupMatchers( matchers ) { - return function( elem, context ) { - var matcher, - j = 0; - for ( ; (matcher = matchers[j]); j++ ) { - if ( matcher(elem, context) ) { - return true; + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } } } - return false; - }; + } + + return newUnmatched; } -var compile = Sizzle.compile = function( selector, context, xml ) { - var tokens, group, i, - cached = compilerCache[ selector ]; +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, - // Return a cached group function if already generated (context dependent) - if ( cached && cached.context === context ) { - return cached; + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && tokens.join("") + ); + } + matchers.push( matcher ); + } } - // Generate a function of recursive functions that can be used to check each element - group = tokenize( selector, context, xml ); - for ( i = 0; (tokens = group[i]); i++ ) { - group[i] = matcherFromTokens( tokens, context, xml ); - } + return elementMatcher( matchers ); +} - // Cache the compiled function - cached = compilerCache[ selector ] = matcherFromGroupMatchers( group ); - cached.context = context; - cached.runs = cached.dirruns = 0; - cachedSelectors.push( selector ); - // Ensure only the most recent are cached - if ( cachedSelectors.length > Expr.cacheLength ) { - delete compilerCache[ cachedSelectors.shift() ]; +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Nested matchers should use non-integer dirruns + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = superMatcher.el; + } + + // Add elements passing elementMatchers directly to results + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + for ( j = 0; (matcher = elementMatchers[j]); j++ ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++superMatcher.el; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + for ( j = 0; (matcher = setMatchers[j]); j++ ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + superMatcher.el = 0; + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ expando ][ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - return Sizzle( expr, null, null, [ elem ] ).length > 0; -}; - -var select = function( selector, context, results, seed, xml ) { - // Remove excessive whitespace - selector = selector.replace( rtrim, "$1" ); - var elements, matcher, i, len, elem, token, - type, findContext, notTokens, - match = selector.match( rgroups ), - tokens = selector.match( rtokens ), - contextNodeType = context.nodeType; - - // POS handling - if ( matchExpr["POS"].test(selector) ) { - return handlePOS( selector, context, results, seed, match ); +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); } + return results; +} - if ( seed ) { - elements = slice.call( seed, 0 ); +function select( selector, context, results, seed, xml ) { + var i, tokens, token, type, find, + match = tokenize( selector ), + j = match.length; - // To maintain document order, only narrow the - // set if there is one group - } else if ( match && match.length === 1 ) { + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { - // Take a shortcut and set the context if the root selector is an ID - if ( tokens.length > 1 && contextNodeType === 9 && !xml && - (match = matchExpr["ID"].exec( tokens[0] )) ) { + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !xml && + Expr.relative[ tokens[1].type ] ) { - context = Expr.find["ID"]( match[1], context, xml )[0]; - if ( !context ) { - return results; - } - - selector = selector.slice( tokens.shift().length ); - } - - findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context; - - // Get the last token, excluding :not - notTokens = tokens.pop(); - token = notTokens.split(":not")[0]; - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = matchExpr[ type ].exec( token )) ) { - elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml ); - - if ( elements == null ) { - continue; + context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; + if ( !context ) { + return results; } - if ( token === notTokens ) { - selector = selector.slice( 0, selector.length - notTokens.length ) + - token.replace( matchExpr[ type ], "" ); + selector = selector.slice( tokens.shift().length ); + } - if ( !selector ) { - push.apply( results, slice.call(elements, 0) ); + // Fetch a seed set for right-to-left matching + for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( rbackslash, "" ), + rsibling.test( tokens[0].type ) && context.parentNode || context, + xml + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && tokens.join(""); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; } } - break; - } - } - } - - // Only loop over the given elements once - // If selector is empty, we're already done - if ( selector ) { - matcher = compile( selector, context, xml ); - dirruns = matcher.dirruns++; - - if ( elements == null ) { - elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); - } - for ( i = 0; (elem = elements[i]); i++ ) { - cachedruns = matcher.runs++; - if ( matcher(elem, context) ) { - results.push( elem ); } } } + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + xml, + results, + rsibling.test( selector ) + ); return results; -}; +} if ( document.querySelectorAll ) { (function() { @@ -4993,11 +5180,15 @@ if ( document.querySelectorAll ) { oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, - rbuggyQSA = [], + + // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ], + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active - rbuggyMatches = [":active"], + rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || @@ -5007,7 +5198,12 @@ if ( document.querySelectorAll ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { - div.innerHTML = ""; + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { @@ -5033,42 +5229,52 @@ if ( document.querySelectorAll ) { // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) - div.innerHTML = ""; + div.innerHTML = ""; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + // rbuggyQSA always contains :focus, so no need for a length check + rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply - if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - if ( context.nodeType === 9 ) { - try { - push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); - return results; - } catch(qsaError) {} + if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { + var groups, i, + old = true, + nid = expando, + newContext = context, + newSelector = context.nodeType === 9 && selector; + // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var old = context.getAttribute("id"), - nid = old || expando, - newContext = rsibling.test( selector ) && context.parentNode || context; + if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); - if ( old ) { - nid = nid.replace( rescape, "\\$&" ); + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } + nid = "[id='" + nid + "'] "; + i = groups.length; + while ( i-- ) { + groups[i] = nid + groups[i].join(""); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( - selector.replace( rgroups, "[id='" + nid + "'] $&" ) + newSelector ), 0 ) ); return results; } catch(qsaError) { @@ -5093,11 +5299,11 @@ if ( document.querySelectorAll ) { // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); - rbuggyMatches.push( Expr.match.PSEUDO ); + rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); - // rbuggyMatches always contains :active, so no need for a length check + // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { @@ -5105,7 +5311,7 @@ if ( document.querySelectorAll ) { expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check - if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) { + if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); @@ -5125,6 +5331,14 @@ if ( document.querySelectorAll ) { })(); } +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Back-compat +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; @@ -5923,15 +6137,11 @@ jQuery.buildFragment = function( args, context, scripts ) { first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node + // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & + // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; - context = (context[0] || context).ownerDocument || context[0] || context; - - // Ensure that an attr object doesn't incorrectly stand in as a document object - // Chrome and Firefox seem to allow this to occur and will throw exception - // Fixes #8950 - if ( typeof context.createDocumentFragment === "undefined" ) { - context = document; - } + context = !context.nodeType && context[0] || context; + context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them @@ -6076,8 +6286,8 @@ jQuery.extend({ }, clean: function( elems, context, fragment, scripts ) { - var j, safe, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, - i = 0, + var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, + safe = context === document && safeFragment, ret = []; // Ensure that context is a document @@ -6086,7 +6296,7 @@ jQuery.extend({ } // Use the already-created safe fragment if context permits - for ( safe = context === document && safeFragment; (elem = elems[i]) != null; i++ ) { + for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } @@ -6102,7 +6312,8 @@ jQuery.extend({ } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); - div = div || safe.appendChild( context.createElement("div") ); + div = context.createElement("div"); + safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1>"); @@ -6145,21 +6356,20 @@ jQuery.extend({ elem = div.childNodes; - // Remember the top-level container for proper cleanup - div = safe.lastChild; + // Take out of fragment container (we need a fresh div each time) + div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { - ret = jQuery.merge( ret, elem ); + jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { - safe.removeChild( div ); elem = div = safe = null; } @@ -6294,9 +6504,10 @@ if ( matched.browser ) { browser.version = matched.version; } -// Deprecated, use jQuery.browser.webkit instead -// Maintained for back-compat only -if ( browser.webkit ) { +// Chrome is Webkit, but Webkit is also Safari. +if ( browser.chrome ) { + browser.webkit = true; +} else if ( browser.webkit ) { browser.safari = true; } @@ -6322,23 +6533,25 @@ jQuery.sub = function() { var rootjQuerySub = jQuerySub(document); return jQuerySub; }; - + })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), - elemdisplay = {}, + elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, - fontWeight: 400, - lineHeight: 1 + fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], @@ -6604,18 +6817,20 @@ jQuery.extend({ } }); -// NOTE: To any future maintainer, we've used both window.getComputedStyle -// and getComputedStyle here to produce a better gzip size +// NOTE: To any future maintainer, we've window.getComputedStyle +// because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, - computed = getComputedStyle( elem, null ), + computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { - ret = computed[ name ]; - if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } @@ -6738,7 +6953,10 @@ function getWidthOrHeight( elem, name, extra ) { valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; - if ( val <= 0 ) { + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { @@ -6817,12 +7035,14 @@ jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { - if ( elem.offsetWidth !== 0 || curCSS( elem, "display" ) !== "none" ) { - return getWidthOrHeight( elem, name, extra ); - } else { + // certain elements can have dimension info if we invisibly show them + // however, it must have a current display style that would benefit from this + if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); + } else { + return getWidthOrHeight( elem, name, extra ); } } }, @@ -7056,10 +7276,10 @@ function buildParams( prefix, obj, traditional, add ) { add( prefix, obj ); } } -var // Document location - ajaxLocation, - // Document location segments +var + // Document location ajaxLocParts, + ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL @@ -7228,7 +7448,7 @@ jQuery.fn.load = function( url, params, callback ) { params = undefined; // Otherwise, build a param string - } else if ( typeof params === "object" ) { + } else if ( params && typeof params === "object" ) { type = "POST"; } @@ -7576,7 +7796,7 @@ jQuery.extend({ // Set data for the fake xhr object jqXHR.status = status; - jqXHR.statusText = "" + ( nativeStatusText || statusText ); + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { @@ -7636,11 +7856,11 @@ jQuery.extend({ // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); - // Determine if a cross-domain request is in order + // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && - ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || + ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); @@ -8262,7 +8482,7 @@ if ( jQuery.support.ajax ) { // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; - } catch( _ ) { + } catch( e ) { } // Firefox throws an exception when accessing @@ -8338,12 +8558,13 @@ var fxNow, timerId, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { - var end, unit, prevScale, + var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, - scale = 1; + scale = 1, + maxIterations = 20; if ( parts ) { end = +parts[2]; @@ -8359,17 +8580,15 @@ var fxNow, timerId, do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below - prevScale = scale = scale || ".5"; + scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); - // Update scale, tolerating zeroes from tween.cur() - scale = tween.cur() / target; - - // Stop looping if we've hit the mark or scale is unchanged - } while ( scale !== 1 && scale !== prevScale ); + // Update scale, tolerating zero or NaN from tween.cur() + // And breaking the loop if scale is unchanged or perfect, or if we've just had enough + } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; @@ -8416,7 +8635,9 @@ function Animation( elem, properties, options ) { tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - percent = 1 - ( remaining / animation.duration || 0 ), + // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, index = 0, length = animation.tweens.length; @@ -8568,7 +8789,7 @@ jQuery.Animation = jQuery.extend( Animation, { }); function defaultPrefilter( elem, props, opts ) { - var index, prop, value, length, dataShow, tween, hooks, oldfire, + var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, @@ -8642,6 +8863,7 @@ function defaultPrefilter( elem, props, opts ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; + toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } @@ -8652,6 +8874,14 @@ function defaultPrefilter( elem, props, opts ) { length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + + // store state if its toggle - enables .stop().toggle() to "reverse" + if ( toggle ) { + dataShow.hidden = !hidden; + } if ( hidden ) { jQuery( elem ).show(); } else { @@ -8709,7 +8939,13 @@ Tween.prototype = { var eased, hooks = Tween.propHooks[ this.prop ]; - this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { @@ -8867,6 +9103,7 @@ function genFx( type, includeWidth ) { // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right + includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; @@ -8941,6 +9178,8 @@ jQuery.fx.tick = function() { timers = jQuery.timers, i = 0; + fxNow = jQuery.now(); + for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed @@ -8952,6 +9191,7 @@ jQuery.fx.tick = function() { if ( !timers.length ) { jQuery.fx.stop(); } + fxNow = undefined; }; jQuery.fx.timer = function( timer ) { @@ -8995,7 +9235,8 @@ jQuery.fn.offset = function( options ) { }); } - var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, + var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, + box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; @@ -9009,21 +9250,25 @@ jQuery.fn.offset = function( options ) { docElem = doc.documentElement; - // Make sure we're not dealing with a disconnected DOM node + // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { - return { top: 0, left: 0 }; + return box; } - box = elem.getBoundingClientRect(); + // If we don't have gBCR, just use 0,0 rather than error + // BlackBerry 5, iOS 3 (original iPhone) + if ( typeof elem.getBoundingClientRect !== "undefined" ) { + box = elem.getBoundingClientRect(); + } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; - top = box.top + scrollTop - clientTop; - left = box.left + scrollLeft - clientLeft; - - return { top: top, left: left }; + return { + top: box.top + scrollTop - clientTop, + left: box.left + scrollLeft - clientLeft + }; }; jQuery.offset = { @@ -9201,7 +9446,7 @@ jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { // Set width or height on the element jQuery.style( elem, type, value, extra ); - }, type, chainable ? margin : undefined, chainable ); + }, type, chainable ? margin : undefined, chainable, null ); }; }); }); diff --git a/lib/client/keyBinding.js b/lib/client/keyBinding.js index 89f16980..4ef0d5c2 100644 --- a/lib/client/keyBinding.js +++ b/lib/client/keyBinding.js @@ -1,382 +1,310 @@ -var CloudCommander, Util, DOM; -(function(){ - "use strict"; - - DOM.Images.hideLoad(); - - var cloudcmd = CloudCommander, - /* private property set or set key binding */ - keyBinded; - - /* Key constants*/ - cloudcmd.KEY = { - TAB : 9, - ENTER : 13, - ESC : 27, - - PAGE_UP : 33, - PAGE_DOWN : 34, - END : 35, - HOME : 36, - UP : 38, - DOWN : 40, - - Delete : 46, - - D : 68, - - G : 71, - - O : 79, - Q : 81, - R : 82, - S : 83, - T : 84, - - F2 : 113, - F3 : 114, - F4 : 115, - F10 : 121, - - TRA : 192 /* Typewritten Reverse Apostrophe (`) */ - }; - - var KEY = cloudcmd.KEY; - - cloudcmd.KeyBinding = {}; - - var KeyBinding = cloudcmd.KeyBinding; - - KeyBinding.get = function(){return keyBinded;}; - - KeyBinding.set = function(){keyBinded = true;}; - - KeyBinding.unSet = function(){keyBinded = false;}; - - KeyBinding.init = function(){ - /* saving state of tabs varibles */ - var lTabPanel = { - left : 0, - right : 0 - - }; - - var key_event = function(event){ - /* получаем выдленный файл*/ - var lCurrentFile = DOM.getCurrentFile(), - lName, i; - /* если клавиши можно обрабатывать*/ - if(keyBinded && event){ - var lKeyCode = event.keyCode; - - /* open configuration window */ - if(lKeyCode === KEY.O && event.altKey){ - console.log('openning config window...'); - - DOM.Images.showLoad({top: true}); - - Util.exec(cloudcmd.Config); - } - - else if(lKeyCode === KEY.G && event.altKey) - Util.exec(cloudcmd.GitHub); - - else if(lKeyCode === KEY.D && event.altKey){ - Util.exec(cloudcmd.DropBox); - event.preventDefault(); - } - - /* если нажали таб: - * переносим курсор на - * правую панель, если - * мы были на левой и - * наоборот - */ - else if(lKeyCode === KEY.TAB){ - console.log('Tab pressed'); - - Util.tryCatchLog(function(){ - /* changing parent panel of curent-file */ - var lPanel = DOM.getPanel(), - lId = lPanel.id; - - lTabPanel[lId] = lCurrentFile; - - lPanel = DOM.getPanel({active:false}); - lId = lPanel.id; - - if(lTabPanel[lId]) - DOM.setCurrentFile(lTabPanel[lId]); - else{ - var lFirstFileOnList = DOM.getByTag('li', lPanel)[2]; - - DOM.setCurrentFile(lFirstFileOnList); - } - }); - - event.preventDefault();//запрет на дальнейшее действие - } - else if(lKeyCode === KEY.Delete) - DOM.promptRemoveCurrent(lCurrentFile); - - /* if f3 or shift+f3 or alt+f3 pressed */ - else if(lKeyCode === KEY.F3){ - var lEditor = cloudcmd[event.shiftKey ? - 'Viewer' : 'Editor']; - - Util.exec(lEditor, true); - - event.preventDefault();//запрет на дальнейшее действие - } - - /* if f4 pressed */ - else if(lKeyCode === KEY.F4) { - DOM.Images.showLoad(); - - Util.exec(cloudcmd.Editor); - - event.preventDefault();//запрет на дальнейшее действие - } - else if(lKeyCode === KEY.F10 && event.shiftKey){ - Util.exec(cloudcmd.Menu); - - event.preventDefault();//запрет на дальнейшее действие - } - - else if (lKeyCode === KEY.TRA){ - DOM.Images.showLoad({top: true}); - Util.exec(cloudcmd.Terminal); - } - /* навигация по таблице файлов*/ - /* если нажали клавишу вверх*/ - else if(lKeyCode === KEY.UP){ - /* если ненайдены выделенные файлы - выходим*/ - if(!lCurrentFile) return; - - /* если это строка существет и - * если она не заголовок - * файловой таблицы - */ - lCurrentFile = lCurrentFile.previousSibling; - if(lCurrentFile){ - /* выделяем предыдущую строку*/ - DOM.setCurrentFile(lCurrentFile); - } - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали клавишу в низ*/ - else if(lKeyCode === KEY.DOWN){ - /* если ненайдены выделенные файлы - выходим*/ - if(!lCurrentFile)return; - - lCurrentFile = lCurrentFile.nextSibling; - /* если это не последняя строка */ - if(lCurrentFile){ - /* выделяем следующую строку*/ - DOM.setCurrentFile(lCurrentFile); - - event.preventDefault();//запрет на дальнейшее действие - } - } - - /* если нажали клавишу Home - * переходим к самому верхнему - * элементу - */ - else if(lKeyCode === KEY.HOME){ - /* получаем первый элемент - * пропускаем путь и заголовки столбиков - * выделяем верхий файл - */ - lCurrentFile = lCurrentFile. - parentElement.firstChild; - - /* set current file and - * move scrollbar to top - */ - DOM.setCurrentFile(lCurrentFile); - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали клавишу End - * выделяем последний элемент - */ - else if(lKeyCode === KEY.END){ - /* выделяем самый нижний файл */ - lCurrentFile = lCurrentFile. - parentElement.lastElementChild; - - /* set current file and - * move scrollbar to bottom - */ - DOM.setCurrentFile(lCurrentFile); - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали клавишу page down - * проматываем экран - */ - else if(lKeyCode === KEY.PAGE_DOWN){ - DOM.getPanel().scrollByPages(1); - - for(i=0; i<30; i++){ - if(!lCurrentFile.nextSibling) break; - - lCurrentFile = lCurrentFile.nextSibling; - } - DOM.setCurrentFile(lCurrentFile); - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали клавишу page up - * проматываем экран - */ - else if(lKeyCode === KEY.PAGE_UP){ - DOM.getPanel().scrollByPages(-1); - - var lC = lCurrentFile, - tryCatch = function(pCurrentFile){ - Util.tryCatch(function(){ - return pCurrentFile - .previousSibling - .previousSibling - .previousSibling - .previousSibling; - }); - }; - - for(i = 0; i < 30; i++){ - if(!lC.previousSibling || tryCatch(lC) ) break; - - lC = lC.previousSibling; - } - DOM.setCurrentFile(lC); - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали Enter - открываем папку*/ - else if(lKeyCode === KEY.ENTER){ - /* если ненайдены выделенные файлы - выходим*/ - if(!lCurrentFile)return; - - /* из него достаём спан с именем файла*/ - lName = DOM.getByClass('name', lCurrentFile); - - /* если нету (что вряд ли) - выходим*/ - if(!lName)return false; - - /* достаём все ссылки*/ - var lATag = DOM.getByTag('a', lName[0]); - - /* если нету - выходим */ - if(!lATag)return false; - - /* вызываем ajaxload привязанный через changelinks - * пробуем нажать на ссылку, если не получиться - * (opera, ie), вызываем событие onclick, - */ - - if(lCurrentFile.onclick) - lCurrentFile.onclick(true); - else try{ - lATag[0].click(); - } - catch(error){ - console.log(error); - } - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали +r - * обновляем страницу, - * загружаем содержимое каталога - * при этом данные берём всегда с - * сервера, а не из кэша - * (обновляем кэш) - */ - else if(lKeyCode === KEY.R && - event.ctrlKey){ - console.log('+r pressed\n' + - 'reloading page...\n' + - 'press +q to remove all key-handlers'); - - /* Программно нажимаем на кнопку перезагрузки - * содержимого каталога - */ - var lRefreshIcon = DOM.getRefreshButton(); - if(lRefreshIcon){ - /* получаем название файла*/ - var lSelectedName = DOM.getCurrentName(); - - /* если нашли элемент нажимаем него - * а если не можем - нажимаем на - * ссылку, на которую повешен eventHandler - * onclick - */ - lRefreshIcon.onclick(); - cloudcmd._currentToParent(lSelectedName); - event.preventDefault();//запрет на дальнейшее действие - } - } - - /* если нажали +d чистим кэш */ - else if(lKeyCode === KEY.D && - event.ctrlKey){ - console.log('+d pressed\n' + - 'clearing cache...\n' + - 'press +q to remove all key-handlers'); - - var lClearCache = DOM.getById('clear-cache'); - if(lClearCache && lClearCache.onclick) - lClearCache.onclick(); - - event.preventDefault();//запрет на дальнейшее действие - } - - /* если нажали +q - * убираем все обработчики - * нажатий клавиш - */ - else if(lKeyCode === KEY.Q && event.altKey){ - console.log('+q pressed\n' + - '+r reload key-handerl - removed' + - '+s clear cache key-handler - removed'+ - 'press +s to to set them'); - - /* обработчик нажатий клавиш снят*/ - keyBinded = false; - - event.preventDefault();//запрет на дальнейшее действие - } - } - - /* если нажали +s - * устанавливаем все обработчики - * нажатий клавиш - */ - else if(event.keyCode === KEY.S && event.altKey){ - /* обрабатываем нажатия на клавиши*/ - keyBinded = true; - - console.log('+s pressed\n' + - '+r reload key-handerl - set\n' + - '+s clear cache key-handler - set\n' + - 'press +q to remove them'); - - event.preventDefault();//запрет на дальнейшее действие - } - }; - - /* добавляем обработчик клавишь */ - DOM.addKeyListener(key_event); - - /* клавиши назначены*/ - keyBinded = true; - }; -})(); \ No newline at end of file +var CloudCommander, Util, DOM; +(function(CloudCmd, Util, DOM){ + 'use strict'; + + /* private property set or set key binding */ + var keyBinded; + + /* Key constants*/ + CloudCmd.KEY = { + TAB : 9, + ENTER : 13, + ESC : 27, + + PAGE_UP : 33, + PAGE_DOWN : 34, + END : 35, + HOME : 36, + UP : 38, + DOWN : 40, + + Delete : 46, + + D : 68, + + G : 71, + + O : 79, + Q : 81, + R : 82, + S : 83, + T : 84, + + F1 : 112, + F2 : 113, + F3 : 114, + F4 : 115, + F10 : 121, + + TRA : 192 /* Typewritten Reverse Apostrophe (`) */ + }; + + var KEY = CloudCmd.KEY; + + CloudCmd.KeyBinding = {}; + + var KeyBinding = CloudCmd.KeyBinding; + + KeyBinding.get = function(){return keyBinded;}; + + KeyBinding.set = function(){keyBinded = true;}; + + KeyBinding.unSet = function(){keyBinded = false;}; + + KeyBinding.init = function(){ + /* saving state of tabs varibles */ + var lTabPanel = { + left : 0, + right : 0 + + }; + + var key_event = function(pEvent){ + /* получаем выдленный файл*/ + var lCurrentFile = DOM.getCurrentFile(), i; + /* если клавиши можно обрабатывать*/ + if(keyBinded && pEvent){ + var lKeyCode = pEvent.keyCode; + + /* open configuration window */ + if(lKeyCode === KEY.O && pEvent.altKey){ + console.log('openning config window...'); + + DOM.Images.showLoad({top: true}); + + Util.exec(CloudCmd.Config); + } + + else if(lKeyCode === KEY.G && pEvent.altKey) + Util.exec(CloudCmd.GitHub); + + else if(lKeyCode === KEY.D && pEvent.altKey){ + Util.exec(CloudCmd.DropBox); + DOM.preventDefault(pEvent); + } + + /* если нажали таб: + * переносим курсор на + * правую панель, если + * мы были на левой и + * наоборот + */ + else if(lKeyCode === KEY.TAB){ + console.log('Tab pressed'); + + Util.tryCatchLog(function(){ + /* changing parent panel of curent-file */ + var lPanel = DOM.getPanel(), + lId = lPanel.id; + + lTabPanel[lId] = lCurrentFile; + + lPanel = DOM.getPanel({active:false}); + lId = lPanel.id; + + if(lTabPanel[lId]) + DOM.setCurrentFile(lTabPanel[lId]); + else{ + var lFirstFileOnList = DOM.getByTag('li', lPanel)[2]; + + DOM.setCurrentFile(lFirstFileOnList); + } + }); + + DOM.preventDefault(pEvent);//запрет на дальнейшее действие + } + else if(lKeyCode === KEY.Delete){ + if(pEvent.shiftKey) + DOM.deleteCurrent(lCurrentFile); + else + DOM.promptDeleteCurrent(lCurrentFile); + } + else if(lKeyCode === KEY.F1){ + DOM.preventDefault(pEvent); + } + else if(lKeyCode === KEY.F2) + DOM.renameCurrentFile(lCurrentFile); + /* if f3 or shift+f3 or alt+f3 pressed */ + else if(lKeyCode === KEY.F3){ + var lEditor = CloudCmd[pEvent.shiftKey ? + 'Viewer' : 'Editor']; + + Util.exec(lEditor, true); + + DOM.preventDefault(pEvent); + } + + /* if f4 pressed */ + else if(lKeyCode === KEY.F4) { + DOM.Images.showLoad(); + + Util.exec(CloudCmd.Editor); + + DOM.preventDefault(pEvent); + } + else if(lKeyCode === KEY.F10 && pEvent.shiftKey){ + Util.exec(CloudCmd.Menu); + + DOM.preventDefault(pEvent); + } + + else if (lKeyCode === KEY.TRA){ + DOM.Images.showLoad({top: true}); + Util.exec(CloudCmd.Terminal); + } + /* навигация по таблице файлов * + * если нажали клавишу вверх * + * выделяем предыдущую строку */ + else if(lKeyCode === KEY.UP){ + DOM.setCurrentFile( lCurrentFile.previousSibling ); + DOM.preventDefault( pEvent ); + } + + /* если нажали клавишу в низ * + * выделяем следующую строку */ + else if(lKeyCode === KEY.DOWN){ + DOM.setCurrentFile( lCurrentFile.nextSibling ); + DOM.preventDefault( pEvent ); + } + + /* если нажали клавишу Home * + * переходим к самому верхнему * + * элементу */ + else if(lKeyCode === KEY.HOME){ + DOM.setCurrentFile( lCurrentFile.parentElement.firstChild ); + DOM.preventDefault(pEvent); + } + + /* если нажали клавишу End + * выделяем последний элемент + */ + else if(lKeyCode === KEY.END){ + DOM.setCurrentFile( lCurrentFile.parentElement.lastElementChild ); + DOM.preventDefault( pEvent ); + } + + /* если нажали клавишу page down + * проматываем экран + */ + else if(lKeyCode === KEY.PAGE_DOWN){ + DOM.scrollByPages( DOM.getPanel(), 1 ); + + for(i=0; i<30; i++){ + if(!lCurrentFile.nextSibling) break; + + lCurrentFile = lCurrentFile.nextSibling; + } + DOM.setCurrentFile(lCurrentFile); + DOM.preventDefault(pEvent); + } + + /* если нажали клавишу page up + * проматываем экран + */ + else if(lKeyCode === KEY.PAGE_UP){ + DOM.scrollByPages( DOM.getPanel(), -1 ); + + var lC = lCurrentFile, + tryCatch = function(pCurrentFile){ + Util.tryCatch(function(){ + return pCurrentFile + .previousSibling + .previousSibling + .previousSibling + .previousSibling; + }); + }; + + for(i = 0; i < 30; i++){ + if(!lC.previousSibling || tryCatch(lC) ) break; + + lC = lC.previousSibling; + } + DOM.setCurrentFile(lC); + DOM.preventDefault(pEvent); + } + + /* если нажали Enter - открываем папку*/ + else if(lKeyCode === KEY.ENTER && DOM.isCurrentIsDir()) + Util.exec(CloudCmd._loadDir()); + + /* если нажали +r + * обновляем страницу, + * загружаем содержимое каталога + * при этом данные берём всегда с + * сервера, а не из кэша + * (обновляем кэш) + */ + else if(lKeyCode === KEY.R && pEvent.ctrlKey){ + console.log('+r pressed\n' + + 'reloading page...\n' + + 'press +q to remove all key-handlers'); + + /* Программно нажимаем на кнопку перезагрузки + * содержимого каталога + */ + var lRefreshIcon = DOM.getRefreshButton(); + if(lRefreshIcon){ + /* если нашли элемент нажимаем него + * а если не можем - нажимаем на + * ссылку, на которую повешен eventHandler + * onclick + */ + Util.exec( DOM.getListener(lRefreshIcon) ); + + DOM.preventDefault(pEvent); + } + } + + /* если нажали +d чистим кэш */ + else if(lKeyCode === KEY.D && pEvent.ctrlKey){ + Util.log('+d pressed\n' + + 'clearing cache...\n' + + 'press +q to remove all key-handlers'); + + DOM.Cache.clear(); + DOM.preventDefault(); + } + + /* если нажали +q + * убираем все обработчики + * нажатий клавиш + */ + else if(lKeyCode === KEY.Q && pEvent.altKey){ + console.log('+q pressed\n' + + '+r reload key-handerl - removed' + + '+s clear cache key-handler - removed'+ + 'press +s to to set them'); + + /* обработчик нажатий клавиш снят*/ + keyBinded = false; + + pEvent.preventDefault();//запрет на дальнейшее действие + } + } + + /* если нажали +s + * устанавливаем все обработчики + * нажатий клавиш + */ + else if(pEvent.keyCode === KEY.S && pEvent.altKey){ + /* обрабатываем нажатия на клавиши*/ + keyBinded = true; + + console.log('+s pressed\n' + + '+r reload key-handerl - set\n' + + '+s clear cache key-handler - set\n' + + 'press +q to remove them'); + + pEvent.preventDefault();//запрет на дальнейшее действие + } + }; + + /* добавляем обработчик клавишь */ + DOM.addKeyListener(key_event); + + /* клавиши назначены*/ + keyBinded = true; + }; + +})(CloudCommander, Util, DOM); \ No newline at end of file diff --git a/lib/client/menu.js b/lib/client/menu.js index 6babe02e..d9c7b30e 100644 --- a/lib/client/menu.js +++ b/lib/client/menu.js @@ -1,263 +1,309 @@ -/* object contains jQuery-contextMenu - * https://github.com/medialize/jQuery-contextMenu - */ -var CloudCommander, Util, DOM, CloudFunc, $; -(function(){ - "use strict"; - - var cloudcmd = CloudCommander, - KeyBinding = cloudcmd.KeyBinding, - MenuSeted = false, - Menu = {}, - Position; - - Menu.dir = '/lib/client/menu/'; - - /* enable and disable menu constant */ - Menu.ENABLED = false; - - /* PRIVATE FUNCTIONS */ - - /** function shows editor - * @param pReadOnly - */ - function showEditor(pReadOnly){ - DOM.Images.showLoad(); - var lEditor = cloudcmd[pReadOnly ? 'Viewer' : 'Editor'], - - lResult = Util.exec(lEditor, pReadOnly); - - if(!lResult){ - lEditor = lEditor.get(); - if(lEditor) - Util.exec(lEditor.show); - } - } - - /** function return configureation for menu */ - function getConfig (){ - return{ - // define which elements trigger this menu - selector: 'li', - - callback: function(key, options) { - var m = "clicked: " + key; - console.log(m, options); - - KeyBinding.set(); - }, - - // define the elements of the menu - items: { - view: {name: 'View', callback: function(key, opt){ - showEditor(true); - }}, - - edit: {name: 'Edit', callback: function(key, opt){ - showEditor(); - }}, - - delete: {name: 'Delete', - callback: function(key, opt){ - DOM.promptRemoveCurrent(); - }}, - - upload: { - name: "Upload to", - items: { - 'upload_to_gist': {name: 'Gist', - callback: function(key, opt){ - var lCurrent = DOM.getCurrentFile(), - lPath = DOM.getCurrentPath(), - lName = DOM.getCurrentName(lCurrent); - - DOM.ajax({ - url : lPath, - error : DOM.Images.showError, - success : function(data, textStatus, jqXHR){ - if( Util.isObject(data) ) - data = JSON.stringify(data, null, 4); - - var lGitHub = cloudcmd.GitHub; - - if('init' in lGitHub) - lGitHub.createGist(data, lName); - else - Util.exec(cloudcmd.GitHub, - function(){ - lGitHub.createGist(data, lName); - }); - } - }); - - Util.log('Uploading to gist...'); - } - }, - }, - }, - download: {name: 'Download',callback: function(key, opt){ - DOM.Images.showLoad(); - - var lCurrent = DOM.getCurrentFile(), - lLink = DOM.getByTag('a', lCurrent)[0].href; - - console.log('downloading file ' + lLink +'...'); - - lLink = lLink + '?download'; - - lLink = Util.removeStr( lLink, CloudFunc.NOJS ); - var lId = DOM.getIdBySrc(lLink); - - if(!DOM.getById(lId)){ - var lDownload = DOM.anyload({ - name : 'iframe', - async : false, - className : 'hidden', - src : lLink, - func : function(){ - DOM.Images.hideLoad(); - } - }); - - DOM.Images.hideLoad(); - setTimeout(function() { - document.body.removeChild(lDownload); - }, 10000); - } - else - DOM.Images.showError({ - responseText: 'Error: You trying to' + - 'download same file to often'}); - }} - } - }; - } - - /** function loads css and js of Menu - * @param pCallBack - */ - function load(pCallBack){ - console.time('menu load'); - - var lDir = Menu.dir, - lFiles = [ - lDir + 'contextMenu.js', - lDir + 'contextMenu.css' - ]; - - DOM.anyLoadInParallel(lFiles, function(){ - console.timeEnd('menu load'); - Util.exec(pCallBack); - }); - } - - function set(){ - if(!MenuSeted){ - $.contextMenu(getConfig()); - - var lFunc_f = document.onclick; - /* - * Menu works in some crazy way so need a - * little hack to get every thing work out. - * When menu shows up, it drawing invisible - * layer wich hides all elements of - * Cloud Commander so it could not handle - * onclick events. To get every thing work - * how expected we hide out invisible layer - * so for observer it is nothing special - * is not going on. All magic happening in - * DOM tree - */ - document.onclick = function(pEvent){ - if(pEvent && pEvent.x && pEvent.y){ - var lLayer = DOM.getById('context-menu-layer'); - if(lLayer){ - var lStyle; - - if(lLayer) - lStyle = lLayer.style.cssText; - /* hide invisible menu layer */ - if(lStyle) - lLayer.style.cssText = lStyle - .replace('z-index: 1', 'z-index:-1'); - - /* get element by point */ - var lElement = document.elementFromPoint(pEvent.x, pEvent.y), - lTag = lElement.tagName, - lParent; - - if(lTag === 'A' || lTag === 'SPAN'){ - if (lElement.tagName === 'A') - lParent = lElement.parentElement.parentElement; - else if(lElement.tagName === 'SPAN') - lParent = lElement.parentElement; - - if(lParent.className === '') - DOM.setCurrentFile(lParent); - } - - /* show invisible menu layer */ - if(lLayer && lStyle) - lLayer.style.cssText = lStyle; - - /* if document.onclick was set up - * before us, it's best time to call it - */ - if(typeof lFunc_f === 'function') - lFunc_f(); - - KeyBinding.set(); - } - } - }; - - MenuSeted = true; - } - } - - - /** function shows menu for the first time - * right away after loading - */ - Menu.show = function(){ - set(); - - DOM.Images.hideLoad(); - - if(Position && Position.x && Position.y) - $('li').contextMenu(Position); - else - $('li').contextMenu(); - }; - - /* key binding function */ - Menu.init = function(pPosition){ - Position = pPosition; - - DOM.jqueryLoad( Util.retLoadOnLoad([ - Menu.show, - load - ])); - - var key_event = function(pEvent){ - /* если клавиши можно обрабатывать */ - if( KeyBinding.get() ){ - /* if shift + F10 pressed */ - if(pEvent.keyCode === cloudcmd.KEY.F10 && pEvent.shiftKey){ - var lCurrent = DOM.getCurrentFile(); - if(lCurrent) - $(lCurrent).contextMenu(); - - pEvent.preventDefault(); - } - } - else if (pEvent.keyCode === cloudcmd.KEY.ESC) - KeyBinding.set(); - }; - - /* добавляем обработчик клавишь */ - DOM.addKeyListener( key_event ); - }; - - cloudcmd.Menu = Menu; -})(); \ No newline at end of file +/* object contains jQuery-contextMenu + * https://github.com/medialize/jQuery-contextMenu + */ +var CloudCommander, Util, DOM, CloudFunc, $; +(function(CloudCmd, Util, DOM, CloudFunc){ + 'use strict'; + + var KeyBinding = CloudCmd.KeyBinding, + MenuSeted = false, + Menu = {}, + Position, + UploadToItemNames; + + Menu.dir = '/lib/client/menu/'; + + /* enable and disable menu constant */ + Menu.ENABLED = false; + + /* PRIVATE FUNCTIONS */ + + /** function shows editor + * @param pReadOnly + */ + function showEditor(pReadOnly){ + DOM.Images.showLoad(); + var lEditor = CloudCmd[pReadOnly ? 'Viewer' : 'Editor'], + lResult = Util.exec(lEditor, pReadOnly); + + if(!lResult){ + lEditor = lEditor.get(); + if(lEditor) + Util.exec(lEditor.show); + } + } + + /* function read data from modules.json + * and build array of menu items of "upload to" + * menu + */ + function setUploadToItemNames(pCallBack){ + CloudCmd.getModules(function(pModules){ + var lStorageObj = Util.findObjByNameInArr( pModules, 'storage' ); + UploadToItemNames = Util.getNamesFromObjArray( lStorageObj ) || []; + + Util.exec(pCallBack); + }); + } + + /** + * function get menu item object for Upload To + */ + function getUploadToItems(pObjectName){ + var lObj = {}; + if( Util.isArray(pObjectName) ){ + + var n = pObjectName.length; + for(var i = 0; i < n; i++){ + var lStr = pObjectName[i]; + lObj[lStr] = getUploadToItems( lStr ); + } + } + else if( Util.isString(pObjectName) ){ + lObj.name = pObjectName; + + lObj.callback = function(key, opt){ + DOM.getCurrentData(function(pParams){ + var lObject = CloudCmd[pObjectName]; + + Util.ifExec('init' in lObject, + function(){ + CloudCmd[pObjectName].uploadFile(pParams); + }, + + function(pCallBack){ + Util.exec(lObject, pCallBack); + }); + }); + + Util.log('Uploading to ' + pObjectName+ '...'); + }; + } + + return lObj; + } + + /** + * get menu item + */ + function getItem(pName, pCallBack){ + var lRet = { + name : pName + }; + + if(Util.isFunction(pCallBack) ) + lRet.callback = pCallBack; + + else if (Util.isObject(pCallBack)) + lRet.items = pCallBack; + + return lRet; + } + + /** + * get all menu items + * pItems = [{pName, pFunc}] + */ + function getAllItems(pItems){ + var lRet = {}, + lName, + lFunc; + + if(pItems) + for(lName in pItems){ + lFunc = pItems[lName]; + lRet[lName] = getItem(lName, lFunc); + } + + return lRet; + } + + /** + * download menu item callback + */ + function downloadFromMenu(key, opt){ + DOM.Images.showLoad(); + + var lPath = DOM.getCurrentPath(), + lId = DOM.getIdBySrc(lPath); + + Util.log('downloading file ' + lPath +'...'); + + var lDir = DOM.isCurrentIsDir() ? '&&json' : ''; + + lPath = CloudFunc.FS + lPath + '?download' + lDir; + + if(!DOM.getById(lId)){ + var lDownload = DOM.anyload({ + name : 'iframe', + async : false, + className : 'hidden', + src : lPath, + func : Util.retFunc(DOM.Images.hideLoad) + }); + + DOM.Images.hideLoad(); + setTimeout(function() { + document.body.removeChild(lDownload); + }, 10000); + } + else + DOM.Images.showError({ + responseText: 'Error: You trying to' + + 'download same file to often'}); + } + + /** + * function return configureation for menu + */ + function getConfig (){ + var lRet, + lMenuItems = { + 'View' : Util.retExec(showEditor, true), + 'Edit' : Util.retExec(showEditor, false), + 'Rename' : function(){ + setTimeout( Util.retExec(DOM.renameCurrentFile), 100); + }, + 'Delete' : Util.retExec(DOM.promptDeleteCurrent), + }; + + if(UploadToItemNames.length) + lMenuItems['Upload to'] = getUploadToItems(UploadToItemNames); + + lMenuItems.Download = Util.retExec(downloadFromMenu); + + lRet = { + // define which elements trigger this menu + selector: 'li', + + callback: function(key, options) { + var m = "clicked: " + key; + Util.log(m, options); + + KeyBinding.set(); + }, + + // define the elements of the menu + items : getAllItems(lMenuItems), + events :{ + hide: clickProcessing + } + }; + + return lRet; + } + + /** function loads css and js of Menu + * @param pCallBack + */ + function load(pCallBack){ + console.time('menu load'); + + var lDir = Menu.dir, + lFiles = [ + lDir + 'contextMenu.js', + lDir + 'contextMenu.css' + ]; + + DOM.anyLoadInParallel(lFiles, function(){ + console.timeEnd('menu load'); + $.contextMenu.handle.keyStop = $.noop; + Util.exec(pCallBack); + }); + } + + /* + * Menu works in some crazy way so need a + * little hack to get every thing work out. + * When menu shows up, it draws invisible + * layer wich hides all elements of + * Cloud Commander so it could not handle + * onclick events. To get every thing work + * how expected we remove invisible layer + * so for observer it is nothing special + * is not going on. All magic happening in + * DOM tree. + */ + function clickProcessing(){ + var lLayer = DOM.getById('context-menu-layer'); + if(lLayer){ + document.body.removeChild(lLayer); + + var lElement = document.elementFromPoint(Position.x, Position.y), + lTag = lElement.tagName; + + if(lTag === 'A' || lTag === 'SPAN'){ + if (lElement.tagName === 'A') + lElement = lElement.parentElement.parentElement; + else if(lElement.tagName === 'SPAN') + lElement = lElement.parentElement; + + if(lElement.className === '') + DOM.setCurrentFile(lElement); + } + + KeyBinding.set(); + } + } + + + function set(){ + if(!MenuSeted){ + $.contextMenu(getConfig()); + MenuSeted = true; + //DOM.addListener('mousedown', clickProcessing); + DOM.addListener('mousemove', function(pEvent){ + Position = { + x : pEvent.clientX, + y : pEvent.clientY + }; + }); + } + } + + + /** function shows menu for the first time + * right away after loading + */ + Menu.show = function(){ + set(); + DOM.Images.hideLoad(); + + if(Position && !Position.x ) + Position = undefined; + + $('li').contextMenu(Position); + }; + + /* key binding function */ + Menu.init = function(pPosition){ + Position = pPosition; + + Util.loadOnLoad([ + Menu.show, + setUploadToItemNames, + load, + DOM.jqueryLoad + ]); + + var key_event = function(pEvent){ + var lKEY = CloudCmd.KEY, + lKeyCode = pEvent.keyCode; + /* если клавиши можно обрабатывать */ + if( KeyBinding.get() ){ + /* if shift + F10 pressed */ + if(lKeyCode === lKEY.F10 && pEvent.shiftKey){ + $( DOM.getCurrentFile() ).contextMenu(); + DOM.preventDefault(pEvent); + } + } + else if (lKeyCode === lKEY.ESC) + KeyBinding.set(); + }; + + /* добавляем обработчик клавишь */ + DOM.addKeyListener( key_event ); + }; + + CloudCmd.Menu = Menu; +})(CloudCommander, Util, DOM, CloudFunc); \ No newline at end of file diff --git a/lib/client/menu/README.md b/lib/client/menu/README.md index 5471c487..c3551ada 100644 --- a/lib/client/menu/README.md +++ b/lib/client/menu/README.md @@ -69,7 +69,7 @@ You're (obviously) able to use the context menu with your mouse. Once it is open * ⇞ (page up) captured and ignore to avoid page scrolling (for consistency with native menus) * ⇟ (page down) captured and ignore to avoid page scrolling (for consistency with native menus) * ↖ (home) first item in list, will skip disabled elements -* ↘ (end) last item in, will skip disabled elements +* ↘ (end) last item in list, will skip disabled elements Besides the obvious, browser also react to alphanumeric key strokes. Hitting r in a context menu will make Firefox (8) reload the page immediately. Chrome selects the option to see infos on the page, Safari selects the option to print the document. Awesome, right? Until trying the same on Windows I did not realize that the browsers were using the access-key for this. I would've preferred typing the first character of something, say "s" for "save" and then iterate through all the commands beginning with s. But that's me - what do I know about UX? Anyways, $.contextMenu now also supports accesskey handling. @@ -82,9 +82,9 @@ use [Google Closure Compiler](http://closure-compiler.appspot.com/home): // ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS // @output_file_name contextMenu.js -// @code_url http://medialize.github.com/jQuery-contextMenu/jquery-1.7.1.min.js -// @code_url http://medialize.github.com/jQuery-contextMenu/jquery.ui.position.js -// @code_url http://medialize.github.com/jQuery-contextMenu/jquery.contextMenu.js +// @code_url http://medialize.github.com/jQuery-contextMenu/jquery-1.8.2.min.js +// @code_url http://medialize.github.com/jQuery-contextMenu/src/jquery.ui.position.js +// @code_url http://medialize.github.com/jQuery-contextMenu/src/jquery.contextMenu.js // ==/ClosureCompiler== ``` @@ -103,155 +103,213 @@ $.contextMenu is published under the [MIT license](http://www.opensource.org/lic ## Changelog ## -### 1.5.22 ### +### 1.6.5 (January 20th 2013) ### -* Fixing issue with animation and remove on hide (Issue #64) +* fixing "opening a second menu can break the layer" - ([Issue #105](https://github.com/medialize/jQuery-contextMenu/issues/105)) -### 1.5.21 ### +### 1.6.4 (January 19th 2013) ### -* Fixing backdrop would not remove on destroy (Issue #63) +* fixing [jQuery plugin manifest](https://github.com/medialize/jQuery-contextMenu/commit/413b1ecaba0aeb4e50f97cee35f7c367435e7830#commitcomment-2465216), again. yep. I'm that kind of a guy. :( -### 1.5.20 ### +### 1.6.3 (January 19th 2013) ### -* Fixing backdrop would not position properly in IE6 (Issue #59) -* Fixing nested input elements not accessible in Chrome / Safari (Issue #58) +* fixing [jQuery plugin manifest](https://github.com/medialize/jQuery-contextMenu/commit/413b1ecaba0aeb4e50f97cee35f7c367435e7830#commitcomment-2465216) + +### 1.6.2 (January 19th 2013) ### + +* fixing "menu won't close" regression introduced by 1.6.1 + +### 1.6.1 (January 19th 2013) ### + +* fixing potential html parsing problem +* upgrading to jQuery UI position v1.10.0 +* replaced `CRLF` by `LF` (no idea how this happened in the first place...) +* adding `options.reposition` to dis/allow simply relocating a menu instead of rebuilding it ([Issue #104](https://github.com/medialize/jQuery-contextMenu/issues/104)) + +### 1.6.0 (December 29th 2012) ### + +* adding [DOM Element bound context menus](http://medialize.github.com/jQuery-contextMenu/demo/on-dom-element.html) - ([Issue 88](https://github.com/medialize/jQuery-contextMenu/issues/88)) +* adding class `context-menu-active` to define state on active trigger element - ([Issue 92](https://github.com/medialize/jQuery-contextMenu/issues/92)) +* adding [demo for TouchSwipe](http://medialize.github.com/jQuery-contextMenu/demo/trigger-swipe.html) activation +* adding export of internal functions and event handlers - ([Issue 101](https://github.com/medialize/jQuery-contextMenu/issues/101)) +* fixing key "watch" might translate to Object.prototype.watch in callbacks map - ([Issue 93](https://github.com/medialize/jQuery-contextMenu/issues/93)) +* fixing menu and submenu width calculation - ([Issue 18](https://github.com/medialize/jQuery-contextMenu/issues/18)) +* fixing unused variables - ([Issue 100](https://github.com/medialize/jQuery-contextMenu/issues/100)) +* fixing iOS "click" compatibility problem - ([Issue 83](https://github.com/medialize/jQuery-contextMenu/issues/83)) +* fixing separators to not be clickable - ([Issue 85](https://github.com/medialize/jQuery-contextMenu/issues/85)) +* fixing issues with fixed positioned triggers ([Issue 95](https://github.com/medialize/jQuery-contextMenu/issues/95)) +* fixing word break problem - ([Issue 80](https://github.com/medialize/jQuery-contextMenu/issues/80)) + +### 1.5.25 (October 8th 2012) ### + +* upgrading to jQuery 1.8.2 ([Issue 78](https://github.com/medialize/jQuery-contextMenu/issues/78)) +* upgrading to jQuery UI position 1.9.0 RC1 ([Issue 78](https://github.com/medialize/jQuery-contextMenu/issues/78)) + +### 1.5.24 (August 30th 2012) ### + +* adding context menu options to input command events ([Issue 72](https://github.com/medialize/jQuery-contextMenu/issues/72), dtex) +* code cosmetics for JSLint + +### 1.5.23 (August 22nd 2012) ### + +* fixing reposition/close issue on scrolled documents ([Issue 69](https://github.com/medialize/jQuery-contextMenu/issues/69)) +* fixing jQuery reference ([Issue 68](https://github.com/medialize/jQuery-contextMenu/issues/68)) + +### 1.5.22 (July 16th 2012) ### + +* fixing issue with animation and remove on hide (Issue #64) + +### 1.5.21 (July 14th 2012) ### + +* fixing backdrop would not remove on destroy (Issue #63) + +### 1.5.20 (June 26th 2012) ### + +Note: git tag of version is `v1.6.20`?! + +* fixing backdrop would not position properly in IE6 (Issue #59) +* fixing nested input elements not accessible in Chrome / Safari (Issue #58) ### 1.5.19 ### +Note: git tag of version is missing...?! + * fixing sub-menu positioning when `$.ui.position` is not available (Issue #56) ### 1.5.18 ### +Note: git tag of version is missing...?! + * fixing html5 `` import (Issue #53) -### 1.5.17 ### +### 1.5.17 (June 4th 2012) ### * fixing `options` to default to `options.trigger = "right"` * fixing variable name typo (Within Issue #51) * fixing menu not closing while opening other menu (Within Issue #51) * adding workaround for `contextmenu`-bug in Firefox 12 (Within Issue #51) -### 1.5.16 ### +### 1.5.16 (May 29th 2012) ### * added vendor-prefixed user-select to CSS * fixed issue with z-indexing when `` is used as a trigger (Issue #49) -### 1.5.15 ### +### 1.5.15 (May 26th 2012) ### * allowing to directly open another element's menu while a menu is shown (Issue #48) * fixing autohide option that would not properly hide the menu -### 1.5.14 ### +### 1.5.14 (May 22nd 2012) ### * options.build() would break default options (Issue #47) * $.contextMenu('destroy') would not remove backdrop -### 1.5.13 ### +### 1.5.13 (May 4th 2012) ### * exposing $trigger to dynamically built custom menu-item types (Issue #42) * fixing repositioning of open menu (formerly accidental re-open) * adding asynchronous example * dropping ignoreRightClick in favor of proper event-type detection -### 1.5.12 ### +### 1.5.12 (May 2nd 2012) ### * prevent invoking callback of first item of a sub-menu when clicking on the sub-menu-item (Issue #41) -### 1.5.11 ### +### 1.5.11 (April 27th 2012) ### * providing `opt.$trigger` to show event (Issue #39) -### 1.5.10 ### +### 1.5.10 (April 21st 2012) ### * ignoreRightClick would not prevent right click when menu is already open (Issue #38) -### 1.5.9 ### +### 1.5.9 (March 10th 2012) ### * If build() did not return any items, an empty menu was shown (Issue #33) -### 1.5.8 ### +### 1.5.8 (January 28th 2012) ### * Capturing Page Up and Page Down keys to ignore like space (Issue #30) * Added Home / End keys to jump to first / last command of menu (Issue #29) * Bug hitting enter in an <input> would yield an error (Issue #28) -### 1.5.7 ### +### 1.5.7 (January 21st 2012) ### * Non-ASCII character in jquery.contextMenu.js caused compatibility issues in Rails (Issue #27) -### 1.5.6 ### +### 1.5.6 (January 8th 2012) ### * Bug contextmenu event was not passed to build() callback (Issue #24) * Bug sub-menu markers would not display properly in Safari and Chrome (Issue #25) -### 1.5.5 ### +### 1.5.5 (January 6th 2012) ### * Bug Internet Explorer would not close menu when giving input elements focus (Issue #23) -### 1.5.4 ### +### 1.5.4 (January 5th 2012) ## * Bug not set z-index of sub-menus might not overlap the main menu correctly (Issue #22) -### 1.5.3 ### +### 1.5.3 (January 1st 2012) ### * Bug `console.log is undefined` -### 1.5.2 ### +### 1.5.2 (December 25th 2012) ### * Bug sub-menus would not properly update their disabled states (Issue #16) [again…] * Bug sub-menus would not properly adjust width accoring to min-width and max-width (Issue #18) -### 1.5.1 ### +### 1.5.1 (December 18th 2011) ### * Bug sub-menus would not properly update their disabled states (Issue #16) -### 1.5 ### +### 1.5 (December 13th 2011) ### * Added [dynamic menu creation](http://medialize.github.com/jQuery-contextMenu/demo/dynamic-create.html) (Issue #15) -### 1.4.4 ### +### 1.4.4 (December 12th 2011) ### * Bug positioning <menu> when trigger element is `position:fixed` (Issue #14) -### 1.4.3 ### +### 1.4.3 (December 11th 2011) ### * Bug key handler would caputure all key strokes while menu was visible (essentially disabling F5 and co.) -### 1.4.2 ### +### 1.4.2 (December 6th 2011) ### * Bug opt.$trigger was not available to disabled callbacks * jQuery bumped to 1.7.1 -### 1.4.1 ### +### 1.4.1 (November 9th 2011) ### * Bug where <menu> imports would not pass action (click event) properly -### 1.4 ### +### 1.4 (November 7th 2011) ### * Upgraded to jQuery 1.7 (changed dependecy!) * Added internal events `contextmenu:focus`, `contextmenu:blur` and `contextmenu:hide` * Added custom <command> types * Bug where `className` wasn't properly set on <menu> -### 1.3 ### +### 1.3 (September 5th 2011) ### * Added support for accesskeys * Bug where two sub-menus could be open simultaneously -### 1.2.2 ### +### 1.2.2 (August 24th 2011) ### * Bug in HTML5 import -### 1.2.1 ### +### 1.2.1 (August 24th 2011) ### * Bug in HTML5 detection -### 1.2 ### +### 1.2 (August 24th 2011) ### * Added compatibility to <menuitem> for Firefox 8 * Upgraded to jQuery 1.6.2 -### 1.1 ### +### 1.1 (August 11th 2011) ### * Bug #1 TypeError on HTML5 action passthru * Bug #2 disbaled callback not invoked properly @@ -259,6 +317,6 @@ $.contextMenu is published under the [MIT license](http://www.opensource.org/lic * Feature #4 option to use a single callback for all commands, rather than registering the same function for each item * Option to ignore right-click (original "contextmenu" event trigger) for non-right-click triggers -### 1.0 ### +### 1.0 (July 7th 2011) ### * Initial $.contextMenu handler \ No newline at end of file diff --git a/lib/client/menu/contextMenu.css b/lib/client/menu/contextMenu.css index 04f7f015..ee58116f 100644 --- a/lib/client/menu/contextMenu.css +++ b/lib/client/menu/contextMenu.css @@ -1,142 +1,142 @@ -/*! - * jQuery contextMenu - Plugin for simple contextMenu handling - * - * Version: 1.5.22 - * - * Authors: Rodney Rehm, Addy Osmani (patches for FF) - * Web: http://medialize.github.com/jQuery-contextMenu/ - * - * Licensed under - * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 - * - */ - -.context-menu-list { - margin:0; - padding:0; - - min-width: 120px; - max-width: 250px; - display: inline-block; - position: absolute; - list-style-type: none; - - border: 1px solid #DDD; - background: #EEE; - - -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -o-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - - font-family: Verdana, Arial, Helvetica, sans-serif; - font-size: 11px; -} - -.context-menu-item { - padding: 2px 2px 2px 24px; - background-color: #EEE; - position: relative; - -webkit-user-select: none; - -moz-user-select: -moz-none; - -ms-user-select: none; - user-select: none; -} - -.context-menu-separator { - padding-bottom:0; - border-bottom: 1px solid #DDD; -} - -.context-menu-item > label > input, -.context-menu-item > label > textarea { - -webkit-user-select: text; - -moz-user-select: text; - -ms-user-select: text; - user-select: text; -} - -.context-menu-item.hover { - cursor: pointer; - background-color: #39F; -} - -.context-menu-item.disabled { - color: #666; -} - -.context-menu-input.hover, -.context-menu-item.disabled.hover { - cursor: default; - background-color: #EEE; -} - -.context-menu-submenu:after { - content: ">"; - color: #666; - position: absolute; - top: 0; - right: 3px; - z-index: 1; -} - -/* icons - #protip: - In case you want to use sprites for icons (which I would suggest you do) have a look at - http://css-tricks.com/13224-pseudo-spriting/ to get an idea of how to implement - .context-menu-item.icon:before {} - */ -.context-menu-item.icon { min-height: 18px; background-repeat: no-repeat; background-position: 4px 2px; } -.context-menu-item.icon-edit { background-image: url(images/page_white_edit.png); } -.context-menu-item.icon-cut { background-image: url(images/cut.png); } -.context-menu-item.icon-copy { background-image: url(images/page_white_copy.png); } -.context-menu-item.icon-paste { background-image: url(images/page_white_paste.png); } -.context-menu-item.icon-delete { background-image: url(images/page_white_delete.png); } -.context-menu-item.icon-add { background-image: url(images/page_white_add.png); } -.context-menu-item.icon-quit { background-image: url(images/door.png); } - -/* vertically align inside labels */ -.context-menu-input > label > * { vertical-align: top; } - -/* position checkboxes and radios as icons */ -.context-menu-input > label > input[type="checkbox"], -.context-menu-input > label > input[type="radio"] { - margin-left: -17px; -} -.context-menu-input > label > span { - margin-left: 5px; -} - -.context-menu-input > label, -.context-menu-input > label > input[type="text"], -.context-menu-input > label > textarea, -.context-menu-input > label > select { - display: block; - width: 100%; - - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - -ms-box-sizing: border-box; - -o-box-sizing: border-box; - box-sizing: border-box; -} - -.context-menu-input > label > textarea { - height: 100px; -} -.context-menu-item > .context-menu-list { - display: none; - /* re-positioned by js */ - right: -5px; - top: 5px; -} - -.context-menu-item.hover > .context-menu-list { - display: block; -} - -.context-menu-accesskey { - text-decoration: underline; -} +/*! + * jQuery contextMenu - Plugin for simple contextMenu handling + * + * Version: git-master + * + * Authors: Rodney Rehm, Addy Osmani (patches for FF) + * Web: http://medialize.github.com/jQuery-contextMenu/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * GPL v3 http://opensource.org/licenses/GPL-3.0 + * + */ + +.context-menu-list { + margin:0; + padding:0; + + min-width: 120px; + max-width: 250px; + display: inline-block; + position: absolute; + list-style-type: none; + + border: 1px solid #DDD; + background: #EEE; + + -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -o-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 11px; +} + +.context-menu-item { + padding: 2px 2px 2px 24px; + background-color: #EEE; + position: relative; + -webkit-user-select: none; + -moz-user-select: -moz-none; + -ms-user-select: none; + user-select: none; +} + +.context-menu-separator { + padding-bottom:0; + border-bottom: 1px solid #DDD; +} + +.context-menu-item > label > input, +.context-menu-item > label > textarea { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} + +.context-menu-item.hover { + cursor: pointer; + background-color: #39F; +} + +.context-menu-item.disabled { + color: #666; +} + +.context-menu-input.hover, +.context-menu-item.disabled.hover { + cursor: default; + background-color: #EEE; +} + +.context-menu-submenu:after { + content: ">"; + color: #666; + position: absolute; + top: 0; + right: 3px; + z-index: 1; +} + +/* icons + #protip: + In case you want to use sprites for icons (which I would suggest you do) have a look at + http://css-tricks.com/13224-pseudo-spriting/ to get an idea of how to implement + .context-menu-item.icon:before {} + */ +.context-menu-item.icon { min-height: 18px; background-repeat: no-repeat; background-position: 4px 2px; } +.context-menu-item.icon-edit { background-image: url(images/page_white_edit.png); } +.context-menu-item.icon-cut { background-image: url(images/cut.png); } +.context-menu-item.icon-copy { background-image: url(images/page_white_copy.png); } +.context-menu-item.icon-paste { background-image: url(images/page_white_paste.png); } +.context-menu-item.icon-delete { background-image: url(images/page_white_delete.png); } +.context-menu-item.icon-add { background-image: url(images/page_white_add.png); } +.context-menu-item.icon-quit { background-image: url(images/door.png); } + +/* vertically align inside labels */ +.context-menu-input > label > * { vertical-align: top; } + +/* position checkboxes and radios as icons */ +.context-menu-input > label > input[type="checkbox"], +.context-menu-input > label > input[type="radio"] { + margin-left: -17px; +} +.context-menu-input > label > span { + margin-left: 5px; +} + +.context-menu-input > label, +.context-menu-input > label > input[type="text"], +.context-menu-input > label > textarea, +.context-menu-input > label > select { + display: block; + width: 100%; + + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + -o-box-sizing: border-box; + box-sizing: border-box; +} + +.context-menu-input > label > textarea { + height: 100px; +} +.context-menu-item > .context-menu-list { + display: none; + /* re-positioned by js */ + right: -5px; + top: 5px; +} + +.context-menu-item.hover > .context-menu-list { + display: block; +} + +.context-menu-accesskey { + text-decoration: underline; +} diff --git a/lib/client/menu/contextMenu.js b/lib/client/menu/contextMenu.js index 2b4da541..f0fc31a6 100644 --- a/lib/client/menu/contextMenu.js +++ b/lib/client/menu/contextMenu.js @@ -1,1585 +1,1686 @@ -/*! - * jQuery contextMenu - Plugin for simple contextMenu handling - * - * Version: 1.5.22 - * - * Authors: Rodney Rehm, Addy Osmani (patches for FF) - * Web: http://medialize.github.com/jQuery-contextMenu/ - * - * Licensed under - * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 - * - */ - -(function($, undefined){ - - // TODO: - - // ARIA stuff: menuitem, menuitemcheckbox und menuitemradio - // create structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative - -// determine html5 compatibility -$.support.htmlMenuitem = ('HTMLMenuItemElement' in window); -$.support.htmlCommand = ('HTMLCommandElement' in window); -$.support.eventSelectstart = ("onselectstart" in document.documentElement); -/* // should the need arise, test for css user-select -$.support.cssUserSelect = (function(){ - var t = false, - e = document.createElement('div'); - - $.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) { - var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect', - prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select'; - - e.style.cssText = prop + ': text;'; - if (e.style[propCC] == 'text') { - t = true; - return false; - } - - return true; - }); - - return t; -})(); -*/ - -var // currently active contextMenu trigger - $currentTrigger = null, - // is contextMenu initialized with at least one menu? - initialized = false, - // window handle - $win = $(window), - // number of registered menus - counter = 0, - // mapping selector to namespace - namespaces = {}, - // mapping namespace to options - menus = {}, - // custom command type handlers - types = {}, - // default values - defaults = { - // selector of contextMenu trigger - selector: null, - // where to append the menu to - appendTo: null, - // method to trigger context menu ["right", "left", "hover"] - trigger: "right", - // hide menu when mouse leaves trigger / menu elements - autoHide: false, - // ms to wait before showing a hover-triggered context menu - delay: 200, - // determine position to show menu at - determinePosition: function($menu) { - // position to the lower middle of the trigger element - if ($.ui && $.ui.position) { - // .position() is provided as a jQuery UI utility - // (...and it won't work on hidden elements) - $menu.css('display', 'block').position({ - my: "center top", - at: "center bottom", - of: this, - offset: "0 5", - collision: "fit" - }).css('display', 'none'); - } else { - // determine contextMenu position - var offset = this.offset(); - offset.top += this.outerHeight(); - offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2; - $menu.css(offset); - } - }, - // position menu - position: function(opt, x, y) { - var $this = this, - offset; - // determine contextMenu position - if (!x && !y) { - opt.determinePosition.call(this, opt.$menu); - return; - } else if (x === "maintain" && y === "maintain") { - // x and y must not be changed (after re-show on command click) - offset = opt.$menu.position(); - } else { - // x and y are given (by mouse event) - var triggerIsFixed = opt.$trigger.parents().andSelf() - .filter(function() { - return $(this).css('position') == "fixed"; - }).length; - - if (triggerIsFixed) { - y -= $win.scrollTop(); - x -= $win.scrollLeft(); - } - offset = {top: y, left: x}; - } - - // correct offset if viewport demands it - var bottom = $win.scrollTop() + $win.height(), - right = $win.scrollLeft() + $win.width(), - height = opt.$menu.height(), - width = opt.$menu.width(); - - if (offset.top + height > bottom) { - offset.top -= height; - } - - if (offset.left + width > right) { - offset.left -= width; - } - - opt.$menu.css(offset); - }, - // position the sub-menu - positionSubmenu: function($menu) { - if ($.ui && $.ui.position) { - // .position() is provided as a jQuery UI utility - // (...and it won't work on hidden elements) - $menu.css('display', 'block').position({ - my: "left top", - at: "right top", - of: this, - collision: "fit" - }).css('display', ''); - } else { - // determine contextMenu position - var offset = { - top: 0, - left: this.outerWidth() - }; - $menu.css(offset); - } - }, - // offset to add to zIndex - zIndex: 1, - // show hide animation settings - animation: { - duration: 50, - show: 'slideDown', - hide: 'slideUp' - }, - // events - events: { - show: $.noop, - hide: $.noop - }, - // default callback - callback: null, - // list of contextMenu items - items: {} - }, - // mouse position for hover activation - hoveract = { - timer: null, - pageX: null, - pageY: null - }, - // determine zIndex - zindex = function($t) { - var zin = 0, - $tt = $t; - - while (true) { - zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0); - $tt = $tt.parent(); - if (!$tt || !$tt.length || "html body".indexOf($tt.prop('nodeName').toLowerCase()) > -1 ) { - break; - } - } - - return zin; - }, - // event handlers - handle = { - // abort anything - abortevent: function(e){ - e.preventDefault(); - e.stopImmediatePropagation(); - }, - - // contextmenu show dispatcher - contextmenu: function(e) { - var $this = $(this); - - // disable actual context-menu - e.preventDefault(); - e.stopImmediatePropagation(); - - // abort native-triggered events unless we're triggering on right click - if (e.data.trigger != 'right' && e.originalEvent) { - return; - } - - if (!$this.hasClass('context-menu-disabled')) { - // theoretically need to fire a show event at - // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus - // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); - // e.data.$menu.trigger(evt); - - $currentTrigger = $this; - if (e.data.build) { - var built = e.data.build($currentTrigger, e); - // abort if build() returned false - if (built === false) { - return; - } - - // dynamically build menu on invocation - e.data = $.extend(true, {}, defaults, e.data, built || {}); - - // abort if there are no items to display - if (!e.data.items || $.isEmptyObject(e.data.items)) { - // Note: jQuery captures and ignores errors from event handlers - if (window.console) { - (console.error || console.log)("No items specified to show in contextMenu"); - } - - throw new Error('No Items sepcified'); - } - - // backreference for custom command type creation - e.data.$trigger = $currentTrigger; - - op.create(e.data); - } - // show menu - op.show.call($this, e.data, e.pageX, e.pageY); - } - }, - // contextMenu left-click trigger - click: function(e) { - e.preventDefault(); - e.stopImmediatePropagation(); - $(this).trigger(jQuery.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); - }, - // contextMenu right-click trigger - mousedown: function(e) { - // register mouse down - var $this = $(this); - - // hide any previous menus - if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) { - $currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide'); - } - - // activate on right click - if (e.button == 2) { - $currentTrigger = $this.data('contextMenuActive', true); - } - }, - // contextMenu right-click trigger - mouseup: function(e) { - // show menu - var $this = $(this); - if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) { - e.preventDefault(); - e.stopImmediatePropagation(); - $currentTrigger = $this; - $this.trigger(jQuery.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); - } - - $this.removeData('contextMenuActive'); - }, - // contextMenu hover trigger - mouseenter: function(e) { - var $this = $(this), - $related = $(e.relatedTarget), - $document = $(document); - - // abort if we're coming from a menu - if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { - return; - } - - // abort if a menu is shown - if ($currentTrigger && $currentTrigger.length) { - return; - } - - hoveract.pageX = e.pageX; - hoveract.pageY = e.pageY; - hoveract.data = e.data; - $document.on('mousemove.contextMenuShow', handle.mousemove); - hoveract.timer = setTimeout(function() { - hoveract.timer = null; - $document.off('mousemove.contextMenuShow'); - $currentTrigger = $this; - $this.trigger(jQuery.Event("contextmenu", { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY })); - }, e.data.delay ); - }, - // contextMenu hover trigger - mousemove: function(e) { - hoveract.pageX = e.pageX; - hoveract.pageY = e.pageY; - }, - // contextMenu hover trigger - mouseleave: function(e) { - // abort if we're leaving for a menu - var $related = $(e.relatedTarget); - if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { - return; - } - - try { - clearTimeout(hoveract.timer); - } catch(e) {} - - hoveract.timer = null; - }, - - // click on layer to hide contextMenu - layerClick: function(e) { - var $this = $(this), - root = $this.data('contextMenuRoot'), - mouseup = false, - button = e.button, - x = e.pageX, - y = e.pageY, - target, - offset, - selectors; - - e.preventDefault(); - e.stopImmediatePropagation(); - - // This hack looks about as ugly as it is - // Firefox 12 (at least) fires the contextmenu event directly "after" mousedown - // for some reason `root.$layer.hide(); document.elementFromPoint()` causes this - // contextmenu event to be triggered on the uncovered element instead of on the - // layer (where every other sane browser, including Firefox nightly at the time) - // triggers the event. This workaround might be obsolete by September 2012. - $this.on('mouseup', function() { - mouseup = true; - }); - setTimeout(function() { - var $window, hideshow; - - // test if we need to reposition the menu - if ((root.trigger == 'left' && button == 0) || (root.trigger == 'right' && button == 2)) { - if (document.elementFromPoint) { - root.$layer.hide(); - target = document.elementFromPoint(x, y); - root.$layer.show(); - - selectors = []; - for (var s in namespaces) { - selectors.push(s); - } - - target = $(target).closest(selectors.join(', ')); - - if (target.length) { - if (target.is(root.$trigger[0])) { - root.position.call(root.$trigger, root, x, y); - return; - } - } - } else { - offset = root.$trigger.offset(); - $window = $(window); - // while this looks kinda awful, it's the best way to avoid - // unnecessarily calculating any positions - offset.top += $window.scrollTop(); - if (offset.top <= e.pageY) { - offset.left += $window.scrollLeft(); - if (offset.left <= e.pageX) { - offset.bottom = offset.top + root.$trigger.outerHeight(); - if (offset.bottom >= e.pageY) { - offset.right = offset.left + root.$trigger.outerWidth(); - if (offset.right >= e.pageX) { - // reposition - root.position.call(root.$trigger, root, x, y); - return; - } - } - } - } - } - } - - hideshow = function(e) { - if (e) { - e.preventDefault(); - e.stopImmediatePropagation(); - } - - root.$menu.trigger('contextmenu:hide'); - if (target && target.length) { - setTimeout(function() { - target.contextMenu({x: x, y: y}); - }, 50); - } - }; - - if (mouseup) { - // mouseup has already happened - hideshow(); - } else { - // remove only after mouseup has completed - $this.on('mouseup', hideshow); - } - }, 50); - }, - // key handled :hover - keyStop: function(e, opt) { - if (!opt.isInput) { - e.preventDefault(); - } - - e.stopPropagation(); - }, - key: function(e) { - var opt = $currentTrigger.data('contextMenu') || {}, - $children = opt.$menu.children(), - $round; - - switch (e.keyCode) { - case 9: - case 38: // up - handle.keyStop(e, opt); - // if keyCode is [38 (up)] or [9 (tab) with shift] - if (opt.isInput) { - if (e.keyCode == 9 && e.shiftKey) { - e.preventDefault(); - opt.$selected && opt.$selected.find('input, textarea, select').blur(); - opt.$menu.trigger('prevcommand'); - return; - } else if (e.keyCode == 38 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { - // checkboxes don't capture this key - e.preventDefault(); - return; - } - } else if (e.keyCode != 9 || e.shiftKey) { - opt.$menu.trigger('prevcommand'); - return; - } - - case 9: // tab - case 40: // down - handle.keyStop(e, opt); - if (opt.isInput) { - if (e.keyCode == 9) { - e.preventDefault(); - opt.$selected && opt.$selected.find('input, textarea, select').blur(); - opt.$menu.trigger('nextcommand'); - return; - } else if (e.keyCode == 40 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { - // checkboxes don't capture this key - e.preventDefault(); - return; - } - } else { - opt.$menu.trigger('nextcommand'); - return; - } - break; - - case 37: // left - handle.keyStop(e, opt); - if (opt.isInput || !opt.$selected || !opt.$selected.length) { - break; - } - - if (!opt.$selected.parent().hasClass('context-menu-root')) { - var $parent = opt.$selected.parent().parent(); - opt.$selected.trigger('contextmenu:blur'); - opt.$selected = $parent; - return; - } - break; - - case 39: // right - handle.keyStop(e, opt); - if (opt.isInput || !opt.$selected || !opt.$selected.length) { - break; - } - - var itemdata = opt.$selected.data('contextMenu') || {}; - if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) { - opt.$selected = null; - itemdata.$selected = null; - itemdata.$menu.trigger('nextcommand'); - return; - } - break; - - case 35: // end - case 36: // home - if (opt.$selected && opt.$selected.find('input, textarea, select').length) { - return; - } else { - (opt.$selected && opt.$selected.parent() || opt.$menu) - .children(':not(.disabled, .not-selectable)')[e.keyCode == 36 ? 'first' : 'last']() - .trigger('contextmenu:focus'); - e.preventDefault(); - return; - } - break; - - case 13: // enter - handle.keyStop(e, opt); - if (opt.isInput) { - if (opt.$selected && !opt.$selected.is('textarea, select')) { - e.preventDefault(); - return; - } - break; - } - opt.$selected && opt.$selected.trigger('mouseup'); - return; - - case 32: // space - case 33: // page up - case 34: // page down - // prevent browser from scrolling down while menu is visible - handle.keyStop(e, opt); - return; - - case 27: // esc - handle.keyStop(e, opt); - opt.$menu.trigger('contextmenu:hide'); - return; - - default: // 0-9, a-z - var k = (String.fromCharCode(e.keyCode)).toUpperCase(); - if (opt.accesskeys[k]) { - // according to the specs accesskeys must be invoked immediately - opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu - ? 'contextmenu:focus' - : 'mouseup' - ); - return; - } - break; - } - // pass event to selected item, - // stop propagation to avoid endless recursion - e.stopPropagation(); - opt.$selected && opt.$selected.trigger(e); - }, - - // select previous possible command in menu - prevItem: function(e) { - e.stopPropagation(); - var opt = $(this).data('contextMenu') || {}; - - // obtain currently selected menu - if (opt.$selected) { - var $s = opt.$selected; - opt = opt.$selected.parent().data('contextMenu') || {}; - opt.$selected = $s; - } - - var $children = opt.$menu.children(), - $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(), - $round = $prev; - - // skip disabled - while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) { - if ($prev.prev().length) { - $prev = $prev.prev(); - } else { - $prev = $children.last(); - } - if ($prev.is($round)) { - // break endless loop - return; - } - } - - // leave current - if (opt.$selected) { - handle.itemMouseleave.call(opt.$selected.get(0), e); - } - - // activate next - handle.itemMouseenter.call($prev.get(0), e); - - // focus input - var $input = $prev.find('input, textarea, select'); - if ($input.length) { - $input.focus(); - } - }, - // select next possible command in menu - nextItem: function(e) { - e.stopPropagation(); - var opt = $(this).data('contextMenu') || {}; - - // obtain currently selected menu - if (opt.$selected) { - var $s = opt.$selected; - opt = opt.$selected.parent().data('contextMenu') || {}; - opt.$selected = $s; - } - - var $children = opt.$menu.children(), - $next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(), - $round = $next; - - // skip disabled - while ($next.hasClass('disabled') || $next.hasClass('not-selectable')) { - if ($next.next().length) { - $next = $next.next(); - } else { - $next = $children.first(); - } - if ($next.is($round)) { - // break endless loop - return; - } - } - - // leave current - if (opt.$selected) { - handle.itemMouseleave.call(opt.$selected.get(0), e); - } - - // activate next - handle.itemMouseenter.call($next.get(0), e); - - // focus input - var $input = $next.find('input, textarea, select'); - if ($input.length) { - $input.focus(); - } - }, - - // flag that we're inside an input so the key handler can act accordingly - focusInput: function(e) { - var $this = $(this).closest('.context-menu-item'), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - root.$selected = opt.$selected = $this; - root.isInput = opt.isInput = true; - }, - // flag that we're inside an input so the key handler can act accordingly - blurInput: function(e) { - var $this = $(this).closest('.context-menu-item'), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - root.isInput = opt.isInput = false; - }, - - // :hover on menu - menuMouseenter: function(e) { - var root = $(this).data().contextMenuRoot; - root.hovering = true; - }, - // :hover on menu - menuMouseleave: function(e) { - var root = $(this).data().contextMenuRoot; - if (root.$layer && root.$layer.is(e.relatedTarget)) { - root.hovering = false; - } - }, - - // :hover done manually so key handling is possible - itemMouseenter: function(e) { - var $this = $(this), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - root.hovering = true; - - // abort if we're re-entering - if (e && root.$layer && root.$layer.is(e.relatedTarget)) { - e.preventDefault(); - e.stopImmediatePropagation(); - } - - // make sure only one item is selected - (opt.$menu ? opt : root).$menu - .children('.hover').trigger('contextmenu:blur'); - - if ($this.hasClass('disabled') || $this.hasClass('not-selectable')) { - opt.$selected = null; - return; - } - - $this.trigger('contextmenu:focus'); - }, - // :hover done manually so key handling is possible - itemMouseleave: function(e) { - var $this = $(this), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) { - root.$selected && root.$selected.trigger('contextmenu:blur'); - e.preventDefault(); - e.stopImmediatePropagation(); - root.$selected = opt.$selected = opt.$node; - return; - } - - $this.trigger('contextmenu:blur'); - }, - // contextMenu item click - itemClick: function(e) { - var $this = $(this), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot, - key = data.contextMenuKey, - callback; - - // abort if the key is unknown or disabled or is a menu - if (!opt.items[key] || $this.hasClass('disabled') || $this.hasClass('context-menu-submenu')) { - return; - } - - e.preventDefault(); - e.stopImmediatePropagation(); - - if ($.isFunction(root.callbacks[key])) { - // item-specific callback - callback = root.callbacks[key]; - } else if ($.isFunction(root.callback)) { - // default callback - callback = root.callback; - } else { - // no callback, no action - return; - } - - // hide menu if callback doesn't stop that - if (callback.call(root.$trigger, key, root) !== false) { - root.$menu.trigger('contextmenu:hide'); - } else if (root.$menu.parent().length) { - op.update.call(root.$trigger, root); - } - }, - // ignore click events on input elements - inputClick: function(e) { - e.stopImmediatePropagation(); - }, - - // hide - hideMenu: function(e, data) { - var root = $(this).data('contextMenuRoot'); - op.hide.call(root.$trigger, root, data && data.force); - }, - // focus - focusItem: function(e) { - e.stopPropagation(); - var $this = $(this), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - $this.addClass('hover') - .siblings('.hover').trigger('contextmenu:blur'); - - // remember selected - opt.$selected = root.$selected = $this; - - // position sub-menu - do after show so dumb $.ui.position can keep up - if (opt.$node) { - root.positionSubmenu.call(opt.$node, opt.$menu); - } - }, - // blur - blurItem: function(e) { - e.stopPropagation(); - var $this = $(this), - data = $this.data(), - opt = data.contextMenu, - root = data.contextMenuRoot; - - $this.removeClass('hover'); - opt.$selected = null; - } - }, - // operations - op = { - show: function(opt, x, y) { - var $this = $(this), - offset, - css = {}; - - // hide any open menus - $('#context-menu-layer').trigger('mousedown'); - - // backreference for callbacks - opt.$trigger = $this; - - // show event - if (opt.events.show.call($this, opt) === false) { - $currentTrigger = null; - return; - } - - // create or update context menu - op.update.call($this, opt); - - // position menu - opt.position.call($this, opt, x, y); - - // make sure we're in front - if (opt.zIndex) { - css.zIndex = zindex($this) + opt.zIndex; - } - - // add layer - op.layer.call(opt.$menu, opt, css.zIndex); - - // adjust sub-menu zIndexes - opt.$menu.find('ul').css('zIndex', css.zIndex + 1); - - // position and show context menu - opt.$menu.css( css )[opt.animation.show](opt.animation.duration); - // make options available - $this.data('contextMenu', opt); - // register key handler - $(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key); - // register autoHide handler - if (opt.autoHide) { - // trigger element coordinates - var pos = $this.position(); - pos.right = pos.left + $this.outerWidth(); - pos.bottom = pos.top + this.outerHeight(); - // mouse position handler - $(document).on('mousemove.contextMenuAutoHide', function(e) { - if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) { - // if mouse in menu... - opt.$menu.trigger('contextmenu:hide'); - } - }); - } - }, - hide: function(opt, force) { - var $this = $(this); - if (!opt) { - opt = $this.data('contextMenu') || {}; - } - - // hide event - if (!force && opt.events && opt.events.hide.call($this, opt) === false) { - return; - } - - if (opt.$layer) { - // keep layer for a bit so the contextmenu event can be aborted properly by opera - setTimeout((function($layer){ return function(){ - $layer.remove(); - }; - })(opt.$layer), 10); - - try { - delete opt.$layer; - } catch(e) { - opt.$layer = null; - } - } - - // remove handle - $currentTrigger = null; - // remove selected - opt.$menu.find('.hover').trigger('contextmenu:blur'); - opt.$selected = null; - // unregister key and mouse handlers - //$(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705 - $(document).off('.contextMenuAutoHide').off('keydown.contextMenu'); - // hide menu - opt.$menu && opt.$menu[opt.animation.hide](opt.animation.duration, function (){ - // tear down dynamically built menu after animation is completed. - if (opt.build) { - opt.$menu.remove(); - $.each(opt, function(key, value) { - switch (key) { - case 'ns': - case 'selector': - case 'build': - case 'trigger': - return true; - - default: - opt[key] = undefined; - try { - delete opt[key]; - } catch (e) {} - return true; - } - }); - } - }); - }, - create: function(opt, root) { - if (root === undefined) { - root = opt; - } - // create contextMenu - opt.$menu = $('
    ').data({ - 'contextMenu': opt, - 'contextMenuRoot': root - }); - - $.each(['callbacks', 'commands', 'inputs'], function(i,k){ - opt[k] = {}; - if (!root[k]) { - root[k] = {}; - } - }); - - root.accesskeys || (root.accesskeys = {}); - - // create contextMenu items - $.each(opt.items, function(key, item){ - var $t = $('
  • '), - $label = null, - $input = null; - - item.$node = $t.data({ - 'contextMenu': opt, - 'contextMenuRoot': root, - 'contextMenuKey': key - }); - - // register accesskey - // NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that - if (item.accesskey) { - var aks = splitAccesskey(item.accesskey); - for (var i=0, ak; ak = aks[i]; i++) { - if (!root.accesskeys[ak]) { - root.accesskeys[ak] = item; - item._name = item.name.replace(new RegExp('(' + ak + ')', 'i'), '$1'); - break; - } - } - } - - if (typeof item == "string") { - $t.addClass('context-menu-separator not-selectable'); - } else if (item.type && types[item.type]) { - // run custom type handler - types[item.type].call($t, item, opt, root); - // register commands - $.each([opt, root], function(i,k){ - k.commands[key] = item; - if ($.isFunction(item.callback)) { - k.callbacks[key] = item.callback; - } - }); - } else { - // add label for input - if (item.type == 'html') { - $t.addClass('context-menu-html not-selectable'); - } else if (item.type) { - $label = $('').appendTo($t); - $('').html(item._name || item.name).appendTo($label); - $t.addClass('context-menu-input'); - opt.hasTypes = true; - $.each([opt, root], function(i,k){ - k.commands[key] = item; - k.inputs[key] = item; - }); - } else if (item.items) { - item.type = 'sub'; - } - - switch (item.type) { - case 'text': - $input = $('') - .val(item.value || "").appendTo($label); - break; - - case 'textarea': - $input = $('') - .val(item.value || "").appendTo($label); - - if (item.height) { - $input.height(item.height); - } - break; - - case 'checkbox': - $input = $('') - .val(item.value || "").prop("checked", !!item.selected).prependTo($label); - break; - - case 'radio': - $input = $('') - .val(item.value || "").prop("checked", !!item.selected).prependTo($label); - break; - - case 'select': - $input = $(' - if (item.type && item.type != 'sub' && item.type != 'html') { - $input - .on('focus', handle.focusInput) - .on('blur', handle.blurInput); - - if (item.events) { - $input.on(item.events); - } - } - - // add icons - if (item.icon) { - $t.addClass("icon icon-" + item.icon); - } - } - - // cache contained elements - item.$input = $input; - item.$label = $label; - - // attach item to menu - $t.appendTo(opt.$menu); - - // Disable text selection - if (!opt.hasTypes && $.support.eventSelectstart) { - // browsers support user-select: none, - // IE has a special event for text-selection - // browsers supporting neither will not be preventing text-selection - $t.on('selectstart.disableTextSelect', handle.abortevent); - } - }); - // attach contextMenu to (to bypass any possible overflow:hidden issues on parents of the trigger element) - if (!opt.$node) { - opt.$menu.css('display', 'none').addClass('context-menu-root'); - } - opt.$menu.appendTo(opt.appendTo || document.body); - }, - update: function(opt, root) { - var $this = this; - if (root === undefined) { - root = opt; - // determine widths of submenus, as CSS won't grow them automatically - // position:absolute > position:absolute; min-width:100; max-width:200; results in width: 100; - // kinda sucks hard... - opt.$menu.find('ul').andSelf().css({position: 'static', display: 'block'}).each(function(){ - var $this = $(this); - $this.width($this.css('position', 'absolute').width()) - .css('position', 'static'); - }).css({position: '', display: ''}); - } - // re-check disabled for each item - opt.$menu.children().each(function(){ - var $item = $(this), - key = $item.data('contextMenuKey'), - item = opt.items[key], - disabled = ($.isFunction(item.disabled) && item.disabled.call($this, key, root)) || item.disabled === true; - - // dis- / enable item - $item[disabled ? 'addClass' : 'removeClass']('disabled'); - - if (item.type) { - // dis- / enable input elements - $item.find('input, select, textarea').prop('disabled', disabled); - - // update input states - switch (item.type) { - case 'text': - case 'textarea': - item.$input.val(item.value || ""); - break; - - case 'checkbox': - case 'radio': - item.$input.val(item.value || "").prop('checked', !!item.selected); - break; - - case 'select': - item.$input.val(item.selected || ""); - break; - } - } - - if (item.$menu) { - // update sub-menu - op.update.call($this, item, root); - } - }); - }, - layer: function(opt, zIndex) { - // add transparent layer for click area - // filter and background for Internet Explorer, Issue #23 - var $layer = opt.$layer = $('
    ') - .css({height: $win.height(), width: $win.width(), display: 'block'}) - .data('contextMenuRoot', opt) - .insertBefore(this) - .on('contextmenu', handle.abortevent) - .on('mousedown', handle.layerClick); - - // IE6 doesn't know position:fixed; - if (!$.support.fixedPosition) { - $layer.css({ - 'position' : 'absolute', - 'height' : $(document).height() - }); - } - - return $layer; - } - }; - -// split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key -function splitAccesskey(val) { - var t = val.split(/\s+/), - keys = []; - - for (var i=0, k; k = t[i]; i++) { - k = k[0].toUpperCase(); // first character only - // theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it. - // a map to look up already used access keys would be nice - keys.push(k); - } - - return keys; -} - -// handle contextMenu triggers -$.fn.contextMenu = function(operation) { - if (operation === undefined) { - this.first().trigger('contextmenu'); - } else if (operation.x && operation.y) { - this.first().trigger(jQuery.Event("contextmenu", {pageX: operation.x, pageY: operation.y})); - } else if (operation === "hide") { - var $menu = this.data('contextMenu').$menu; - $menu && $menu.trigger('contextmenu:hide'); - } else if (operation) { - this.removeClass('context-menu-disabled'); - } else if (!operation) { - this.addClass('context-menu-disabled'); - } - - return this; -}; - -// manage contextMenu instances -$.contextMenu = function(operation, options) { - if (typeof operation != 'string') { - options = operation; - operation = 'create'; - } - - if (typeof options == 'string') { - options = {selector: options}; - } else if (options === undefined) { - options = {}; - } - - // merge with default options - var o = $.extend(true, {}, defaults, options || {}), - $document = $(document); - - switch (operation) { - case 'create': - // no selector no joy - if (!o.selector) { - throw new Error('No selector specified'); - } - // make sure internal classes are not bound to - if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) { - throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className'); - } - if (!o.build && (!o.items || $.isEmptyObject(o.items))) { - throw new Error('No Items sepcified'); - } - counter ++; - o.ns = '.contextMenu' + counter; - namespaces[o.selector] = o.ns; - menus[o.ns] = o; - - // default to right click - if (!o.trigger) { - o.trigger = 'right'; - } - - if (!initialized) { - // make sure item click is registered first - $document - .on({ - 'contextmenu:hide.contextMenu': handle.hideMenu, - 'prevcommand.contextMenu': handle.prevItem, - 'nextcommand.contextMenu': handle.nextItem, - 'contextmenu.contextMenu': handle.abortevent, - 'mouseenter.contextMenu': handle.menuMouseenter, - 'mouseleave.contextMenu': handle.menuMouseleave - }, '.context-menu-list') - .on('mouseup.contextMenu', '.context-menu-input', handle.inputClick) - .on({ - 'mouseup.contextMenu': handle.itemClick, - 'contextmenu:focus.contextMenu': handle.focusItem, - 'contextmenu:blur.contextMenu': handle.blurItem, - 'contextmenu.contextMenu': handle.abortevent, - 'mouseenter.contextMenu': handle.itemMouseenter, - 'mouseleave.contextMenu': handle.itemMouseleave - }, '.context-menu-item'); - - initialized = true; - } - - // engage native contextmenu event - $document - .on('contextmenu' + o.ns, o.selector, o, handle.contextmenu); - - switch (o.trigger) { - case 'hover': - $document - .on('mouseenter' + o.ns, o.selector, o, handle.mouseenter) - .on('mouseleave' + o.ns, o.selector, o, handle.mouseleave); - break; - - case 'left': - $document.on('click' + o.ns, o.selector, o, handle.click); - break; - /* - default: - // http://www.quirksmode.org/dom/events/contextmenu.html - $document - .on('mousedown' + o.ns, o.selector, o, handle.mousedown) - .on('mouseup' + o.ns, o.selector, o, handle.mouseup); - break; - */ - } - - // create menu - if (!o.build) { - op.create(o); - } - break; - - case 'destroy': - if (!o.selector) { - $document.off('.contextMenu .contextMenuAutoHide'); - $.each(namespaces, function(key, value) { - $document.off(value); - }); - - namespaces = {}; - menus = {}; - counter = 0; - initialized = false; - - $('#context-menu-layer, .context-menu-list').remove(); - } else if (namespaces[o.selector]) { - var $visibleMenu = $('.context-menu-list').filter(':visible'); - if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) { - $visibleMenu.trigger('contextmenu:hide', {force: true}); - } - - try { - if (menus[namespaces[o.selector]].$menu) { - menus[namespaces[o.selector]].$menu.remove(); - } - - delete menus[namespaces[o.selector]]; - } catch(e) { - menus[namespaces[o.selector]] = null; - } - - $document.off(namespaces[o.selector]); - } - break; - - case 'html5': - // if or are not handled by the browser, - // or options was a bool true, - // initialize $.contextMenu for them - if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options == "boolean" && options)) { - $('menu[type="context"]').each(function() { - if (this.id) { - $.contextMenu({ - selector: '[contextmenu=' + this.id +']', - items: $.contextMenu.fromMenu(this) - }); - } - }).css('display', 'none'); - } - break; - - default: - throw new Error('Unknown operation "' + operation + '"'); - } - - return this; -}; - -// import values into commands -$.contextMenu.setInputValues = function(opt, data) { - if (data === undefined) { - data = {}; - } - - $.each(opt.inputs, function(key, item) { - switch (item.type) { - case 'text': - case 'textarea': - item.value = data[key] || ""; - break; - - case 'checkbox': - item.selected = data[key] ? true : false; - break; - - case 'radio': - item.selected = (data[item.radio] || "") == item.value ? true : false; - break; - - case 'select': - item.selected = data[key] || ""; - break; - } - }); -}; - -// export values from commands -$.contextMenu.getInputValues = function(opt, data) { - if (data === undefined) { - data = {}; - } - - $.each(opt.inputs, function(key, item) { - switch (item.type) { - case 'text': - case 'textarea': - case 'select': - data[key] = item.$input.val(); - break; - - case 'checkbox': - data[key] = item.$input.prop('checked'); - break; - - case 'radio': - if (item.$input.prop('checked')) { - data[item.radio] = item.value; - } - break; - } - }); - - return data; -}; - -// find