UserCSS Plugin
This extension has not been updated in over 2 years. It may no longer be maintained or supported and may have compatibility issues.
Download and Installation
Search and install the plugin using the Extension Manager. Refer to Plugins on how to install plugins manually.
In addition two event hooks have to be inserted into lib/exe/css.php . The first change is in the function css_out() in order to append the data to the output:
The second change is in css_cacheok() and allows to add the wiki page to the cache checks.
// some additional files to check $files[] = DOKU_CONF.'dokuwiki.php'; $files[] = DOKU_CONF.'local.php'; $files[] = $tplinc.'style.ini'; $files[] = __FILE__; //>>>>>> ask for further files to check trigger_event('TPL_CSS_CACHEOK', $files); // // now walk the files
// cache influencers $tplinc = tpl_basedir($tpl); $cache_files = getConfigFiles('main'); $cache_files[] = $tplinc.'style.ini'; $cache_files[] = $tplinc.'style.local.ini'; // @deprecated $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini"; $cache_files[] = __FILE__; //>>>>>> ask for further files to check : usercss plugin trigger_event('TPL_CSS_CACHEOK', $files); //
Usage
The plugin reads all CSS definitions contained in blocks from the wiki page :usercss and inserts them into the CSS output. This allows normal users to work on the websites design. This is especially interesting in combination with user-defined style classes like provided by the class plugin. After editing it is necessary to use the reload button of the browser. Otherwise the browser wouldn’t reload the CSS files.
Replacement of placeholder values from the template’s style.ini is performed as usual. To ease their use, a special syntax [templatename]>> is provided. It shows the current contents of the template’s style.ini file.
References in url() values are interpreted as media links and are corrected accordingly.
Implementation
All work is performed by the action plugin. The syntax plugin merely provides *>> .
action.php
/** * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Randolf Rotta */ // must be run within Dokuwiki if (!defined('DOKU_INC')) die(); if (!defined('DOKU_LF')) define('DOKU_LF', "\n"); if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t"); if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); require_once(DOKU_PLUGIN.'action.php'); class action_plugin_usercss extends DokuWiki_Action_Plugin{ var $pagename = ':usercss'; function getInfo(){ return array( 'author' => 'Randolf Rotta', 'email' => 'rrotta@informatik.tu-cottbus.de', 'date' => '2009-04-05', 'name' => 'user-editable CSS', 'desc' => 'Uses CSS definitions from a wiki page', 'url' => 'http://www.dokuwiki.org/plugin:usercss', ); } function register(&$contr){ $contr->register_hook( 'TPL_CSS_OUTPUT', 'BEFORE', $this, 'add_css', array() ); $contr->register_hook( 'TPL_CSS_CACHEOK', 'BEFORE', $this, 'add_cached_files', array() ); } function add_css(&$event, $param) { // get content from wiki page $txt = io_readWikiPage(wikiFN($this->pagename), $this->pagename); // filter for CSS definitions in blocks preg_match_all('/(.*?)/sm', $txt, $matches); $usercss = implode("\n", $matches[1]); // fix url() locations $usercss = preg_replace_callback( '#(url\([ \'"]*)([^\'"]*)#', create_function('$matches', 'global $ID; $m = $matches[2]; resolve_mediaid(getNS($ID), $m, $exists); return $matches[1].ml($m);'), $usercss); // append all $event->data .= $usercss; } function add_cached_files(&$event, $param) { $event->data[] = wikiFN($this->pagename); } } //Setup VIM: ex: et ts=4 enc=utf-8 :
syntax.php
/** * insert information about a template configuration (style.ini) * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Randolf Rotta */ if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/'); if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); require_once(DOKU_PLUGIN.'syntax.php'); class syntax_plugin_usercss extends DokuWiki_Syntax_Plugin { /** * return some info */ function getInfo(){ return array( 'author' => 'Randolf Rotta', 'email' => 'RRotta@Informatik.TU-Cottbus.DE', 'date' => '2009-04-05', 'name' => 'output template information', 'desc' => 'insert information about a template (style.ini)', 'url' => 'http://www.dokuwiki.org/plugin:usercss', ); } // where we might be placed function getType() { return 'substition'; } // divs can contain paragraphs and divs function getPType() { return 'block'; } // what we may contain function getAllowedTypes() { return array(); } function getSort(){ return 303; } function connectTo($mode) { $this->Lexer->addSpecialPattern('.+?>>', $mode, 'plugin_usercss'); } function handle($match, $state, $pos, &$handler) { // break the pattern up into its constituent parts $match = substr($match, 2, -2); // strip markup list($include, $tplname) = explode('>', $match, 2); if (!preg_match('/^[\w\d_]+$/', $tplname)) $tplname="default"; return array($include, $tplname); } function render($mode, &$renderer, $data) { if($mode == 'xhtml'){ list($inc,$tplname) = $data; $file = DOKU_INC.'lib/tpl/'.$tplname.'/style.ini'; $renderer->code(io_readFile($file), 'ini'); return true; } return false; } } //Setup VIM: ex: et ts=4 enc=utf-8 :
Discussion
Can someone give an example of how this works? I followed the instructions as closely as I could and it seems to do nothing.
Reloaded a page that uses the h1 tag expecting to see a big 25 pixel bottom border, but there was no change to the h1 tag.
Please look at download_and_installation. There you can see that you have to do two changes in the file lib/exe/css.php . — Moni 2012/10/23 16:38
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
User CSS — браузерное расширение для добавления пользовательских стилей к сайтам
Представляю вашему вниманию свое расширение для браузеров, работающих на движке chromium / blink /webkit, суть которого заключается в возможности изменять оформление просматриваемого сайта «на лету» путем добавления собственного CSS-кода.
Предыстория
Когда-то давно я был пользователем браузера Opera, тогда еще работающего на движке Presto. И присутствовала в нем одна замечательная технология, называемая UserCSS. Она позволяла создавать CSS-файлы, в которых прописывались желаемые стили для каких-то конкретных сайтов, и затем эти файлы легко подключались к соответствующим сайтам. После вынужденного отказа от пользования Opera Presto (когда движок поменяли на Blink), потребность в применении пользовательских стилей к сайтам никуда не пропала, поэтому я решил данный вопрос путем создания расширения к браузеру. И назвал его одноименно — User CSS (только добавился пробел).
Особенности расширения
- Изменения на сайте наблюдаются мгновенно при добавлении ваших стилей.
- Возможности редактора (основан на библиотеке CodeMirror):
- Менять полупрозрачность.
- Менять положение: вертикально справа или горизонтально снизу.
- Менять ширину и высоту «на лету», двигая за левый или верхний край.
- Включать/отключать пользовательские стили для сайта.
- Настраиваемая гарнитура и размер шрифта.
- Множество цветовых схем оформления кода.
- Подключен инструмент Emmet для ускорения написания CSS.
Стоит отметить, что данное решение — не 100%-я замена технологии UserCSS. Последняя работает на уровне движка браузера, расширение же срабатывает только после загрузки страницы, поэтому можно наблюдать «мигание» стилей сайта — сначала оригинальных, потом с вашими изменениями. С этим, к сожалению, невозможно ничего сделать.
Расширение я протестировал в браузерах Chrome, Opera (Blink) и Vivaldi. По логике оно должно работать и во многих других браузерах на том же движке, однако я не гарантирую это.
Установить
Расширение для браузера «User CSS»
Версия: 2.1 | Дата последнего обновления: 28.05.2016
История изменений
- v2.1 (28.05.2016)
- Добавлено: импорт/экспорт.
- Добавлено: возможность менять стили прямо на странице настроек.
- Изменено: некоторые сайты очищают локальное хранилище при загрузке страниц, поэтому стили теперь загружаются из хранилища расширения, а не просматриваемого сайта.
- Добавлено: настройки перенесены на отдельную страницу.
- Добавлено: стили для всех сайтов теперь собираются в одном месте на странице настроек.
- Добавлено: больше цветовых схем.
- Добавлено: новая опция — «Tab size».
- Добавлено: возможность менять полупрозрачность редактора.
- Добавлено: возможность включать/выключать свои стили на текущем сайте.
- Добавлено: возможность переключать положение редактора (справа или снизу).
- Добавлено: возможность менять ширину или высоту редактора «на лету».
- Исправлено: не отображалась вертикальная полоса прокрутки.
- Добавлена кнопка на панели расширений вместо горячей клавиши.
- На кнопке присутствует зеленый индикатор, если для текущего сайта добавлены пользовательские стили.
- Исходная версия.
Смотрите также