MDL-21400 finalising JS api - removing ->on_dom_ready (now bool param in js() and js_init_call()) and after_delay() (again int parameter) - the reason is it was adding unnecessary complexity and it is used in just a few places that will be eventually converted to the new js_init_call() anyway

This commit is contained in:
Petr Skoda
2010-02-06 14:45:17 +00:00
parent 60409fe103
commit 593f9b8703
12 changed files with 42 additions and 471 deletions
+31 -229
View File
@@ -33,34 +33,34 @@
*
* Typical useage would be
* <pre>
* $PAGE->requires->init_js_call('M.mod_forum.init_view');
* </pre>
*
* It also supports obsoleted coding style withouth YUI3 modules.
* <pre>
* $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overriddable via themes!
* $PAGE->requires->js('/mod/mymod/script.js');
* $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
* $PAGE->requires->js_function_call('init_mymod', array($data))->on_dom_ready();
* $PAGE->requires->js_function_call('init_mymod', array($data), true);
* </pre>
*
* There are some natural restrictions on some methods. For example, {@link css()}
* can only be called before the <head> tag is output. See the comments on the
* individual methods for details.
*
* @copyright 2009 Tim Hunt
* @copyright 2009 Tim Hunt, 2010 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class page_requirements_manager {
const WHEN_IN_HEAD = 0;
const WHEN_AT_END = 10;
const WHEN_IN_YUI = 20;
const WHEN_ON_DOM_READY = 30;
protected $requiredjscode = array();
/** List of string available from JS */
protected $stringsforjs = array();
/** List of JS variables to be initialised */
protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
/** Included JS scripts */
protected $jsincludes = array('head'=>array(), 'footer'=>array());
/** List of needed function calls */
protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
/**
* List of skip links, those are needed for accessibility reasons
* @var array
@@ -92,8 +92,9 @@ class page_requirements_manager {
* @var array
*/
protected $extramodules = array();
/** Flag indicated head stuff already printed */
protected $headdone = false;
/** Flag indicating top of body already printed */
protected $topofbodydone = false;
/** YUI PHPLoader instance responsible for YUI2 loading from PHP only */
@@ -386,7 +387,7 @@ class page_requirements_manager {
throw new coding_exception('Missing YUI3 module details.');
}
$module['fullpath'] = $this->js_fix_url($module['fullpath'])->out();
$module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
if ($this->headdone) {
$this->extramodules[$module['name']] = $module;
@@ -467,6 +468,7 @@ class page_requirements_manager {
}
/**
* !!!DEPRECATED!!! please use js_init_call() if possible
* Ensure that the specified JavaScript function is called from an inline script
* somewhere on this page.
*
@@ -486,16 +488,13 @@ class page_requirements_manager {
* @param array $arguments and array of arguments to be passed to the function.
* When generating the function call, this will be escaped using json_encode,
* so passing objects and arrays should work.
* @return required_js_function_call The required_js_function_call object.
* This allows you to control when the link to the script is output by
* calling methods like {@link required_js_function_call::in_head()},
* {@link required_js_function_call::on_dom_ready()} or
* {@link required_js_function_call::after_delay()} methods.
* @param bool $ondomready
* @param int $delay
* @return void
*/
public function js_function_call($function, array $arguments = null) {
$requirement = new required_js_function_call($this, $function, $arguments);
$this->requiredjscode[] = $requirement;
return $requirement;
public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
$where = $ondomready ? 'ondomready' : 'normal';
$this->jscalls[$where][] = array($function, $arguments, $delay);
}
/**
@@ -668,15 +667,17 @@ class page_requirements_manager {
/**
* Get the inline JavaScript code that need to appear in a particular place.
* @param $when one of the WHEN_... constants.
* @return string the javascript that should be output in that place.
* @return bool $ondomready
*/
protected function get_javascript_code($when, $indent = '') {
protected function get_javascript_code($ondomready) {
$where = $ondomready ? 'ondomready' : 'normal';
$output = '';
foreach ($this->requiredjscode as $requirement) {
if (!$requirement->is_done() && $requirement->get_when() == $when) {
$output .= $indent . $requirement->get_js_code();
$requirement->mark_done();
if ($this->jscalls[$where]) {
foreach ($this->jscalls[$where] as $data) {
$output = js_writer::function_call($data[0], $data[1], $data[2]);
}
if (!empty($ondomready)) {
$output = " Y.on('domready', function() {\n$output\n });";
}
}
return $output;
@@ -830,9 +831,6 @@ class page_requirements_manager {
}
}
// finally all JS that should go directly into head tag
$output .= html_writer::script($this->get_javascript_code(self::WHEN_IN_HEAD));
// mark head sending done, it is not possible to anything there
$this->headdone = true;
@@ -901,20 +899,14 @@ class page_requirements_manager {
$output .= html_writer::script($js);
}
$js = $this->get_javascript_code(self::WHEN_AT_END);
$inyuijs = $this->get_javascript_code(self::WHEN_IN_YUI, ' ');
$ondomreadyjs = $this->get_javascript_code(self::WHEN_ON_DOM_READY, ' ');
$inyuijs = $this->get_javascript_code(false);
$ondomreadyjs = $this->get_javascript_code(true);
$jsinit = $this->get_javascript_init_code();
$handlersjs = $this->get_event_handler_code();
if (!empty($ondomreadyjs)) {
$ondomreadyjs = " Y.on('domready', function() {\n$ondomreadyjs\n });";
}
// the global Y can be used only after it is fully loaded, that means
// from code executed from the following block
$js .= "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
$js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
$output .= html_writer::script($js);
@@ -937,196 +929,6 @@ class page_requirements_manager {
}
/**
* This is the base class for all sorts of requirements. just to factor out some
* common code.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
abstract class requirement_base {
protected $manager;
protected $when;
protected $done = false;
/**
* Constructor. Normally the class and its subclasses should not be created
* directly. Client code should create them via a page_requirements_manager
* method like ->js(...).
*
* @param page_requirements_manager $manager the page_requirements_manager we are associated with.
*/
protected function __construct(page_requirements_manager $manager) {
$this->manager = $manager;
}
/**
* Mark that this requirement has been satisfied (that is, that the HTML
* returned by {@link get_html()} has been output.
* @return boolean has this requirement been satisfied yet? That is, has
* that the HTML returned by {@link get_html()} has been output already.
*/
public function is_done() {
return $this->done;
}
/**
* Mark that this requirement has been satisfied (that is, that the HTML
* returned by {@link get_html()} has been output.
*/
public function mark_done() {
$this->done = true;
}
/**
* Where on the page the HTML this requirement is meant to go.
* @return integer One of the {@link page_requirements_manager}::WHEN_... constants.
*/
public function get_when() {
return $this->when;
}
}
/**
* This class represents something that must be output somewhere in the HTML.
*
* Examples include links to JavaScript or CSS files. However, it should not
* necessarily be output immediately, we may have to wait for an appropriate time.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
abstract class linked_requirement extends requirement_base {
protected $url;
/**
* Constructor. Normally the class and its subclasses should not be created
* directly. Client code should create them via a page_requirements_manager
* method like ->js(...).
*
* @param page_requirements_manager $manager the page_requirements_manager we are associated with.
* @param string $url The URL of the thing we are linking to.
*/
protected function __construct(page_requirements_manager $manager, $url) {
parent::__construct($manager);
$this->url = $url;
}
/**
* @return string the HTML needed to satisfy this requirement.
*/
abstract public function get_html();
}
/**
* This is the base class for requirements that are JavaScript code.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
abstract class required_js_code extends requirement_base {
/**
* Constructor.
* @param page_requirements_manager $manager the page_requirements_manager we are associated with.
*/
protected function __construct(page_requirements_manager $manager) {
parent::__construct($manager);
$this->when = page_requirements_manager::WHEN_AT_END;
}
/**
* @return string the JavaScript code needed to satisfy this requirement.
*/
abstract public function get_js_code();
/**
* Indicate that the link to this JavaScript file should be output in the
* <head> section of the HTML. If it too late for this request to be
* satisfied, an exception is thrown.
*/
public function in_head() {
if ($this->is_done() || $this->when <= page_requirements_manager::WHEN_IN_HEAD) {
return;
}
if ($this->manager->is_head_done()) {
throw new coding_exception('Too late to ask for some JavaScript code to be output in &lt;head>.');
}
$this->when = page_requirements_manager::WHEN_IN_HEAD;
}
}
/**
* This class represents a JavaScript function that must be called from the HTML
* page. By default the call will be made at the end of the page when YUI initialised,
* but you can chage that using the {@link in_head()}, etc. methods.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class required_js_function_call extends required_js_code {
protected $function;
protected $arguments;
protected $delay = 0;
/**
* Constructor. Normally instances of this class should not be created directly.
* Client code should create them via the page_requirements_manager
* method {@link page_requirements_manager::js_function_call()}.
*
* @param page_requirements_manager $manager the page_requirements_manager we are associated with.
* @param string $function the name of the JavaScritp function to call.
* Can be a compound name like 'Y.Event.purgeElement'. Do not use old YUI2 YAHOO. function names.
* @param array $arguments and array of arguments to be passed to the function.
* When generating the function call, this will be escaped using json_encode,
* so passing objects and arrays should work.
*/
public function __construct(page_requirements_manager $manager, $function, $arguments) {
parent::__construct($manager);
$this->when = page_requirements_manager::WHEN_IN_YUI;
$this->function = $function;
$this->arguments = $arguments;
}
public function get_js_code() {
return js_writer::function_call($this->function, $this->arguments, $this->delay);
}
/**
* Indicate that this function should be called in YUI's onDomReady event.
*
* Thisis needed mostly for buggy IE browsers because they have problems
* when JS starts modifying DOM structure before the DOM is ready.
*/
public function on_dom_ready() {
if ($this->is_done() || $this->when < page_requirements_manager::WHEN_IN_YUI) {
return;
}
$this->when = page_requirements_manager::WHEN_ON_DOM_READY;
}
/**
* Indicate that this function should be called a certain number of seconds
* after the page has finished loading. (More exactly, a number of seconds
* after the onDomReady event fires.)
*
* @param integer $seconds the number of seconds delay.
*/
public function after_delay($seconds) {
if ($seconds) {
$this->on_dom_ready();
}
$this->delay = $seconds;
}
}
/**
* Returns whether ajax is enabled/allowed or not.
*/
-231
View File
@@ -29,237 +29,6 @@ if (!defined('MOODLE_INTERNAL')) {
require_once($CFG->libdir . '/ajax/ajaxlib.php');
/**
* Helper class, adds some useful stuff to UnitTestCase that the other test cases
* classes in this file can benefit from.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class ajaxlib_unit_test_base extends UnitTestCase {
protected $requires;
public static $includecoverage = array('lib/ajax/ajaxlib.php');
public function setUp() {
parent::setUp();
$this->requires = new page_requirements_manager();
}
public function tearDown() {
$this->requires = null;
parent::tearDown();
}
public function assertContains($actual, $expectedsubstring) {
$this->assertNotIdentical(strpos($actual, (string) $expectedsubstring), false,
"[$actual] does not containg the substring [$expectedsubstring].");
}
}
/**
* Unit tests for the requriement_base base class. Don't be confused by the
* fact we are using a specific subclass to test with.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class requriement_base_test extends ajaxlib_unit_test_base {
protected $classname = 'required_css';
public function test_not_done_initially() {
$requirement = new $this->classname($this->requires, '');
$this->assertFalse($requirement->is_done());
}
public function test_done_when_marked() {
$requirement = new $this->classname($this->requires, '');
$requirement->mark_done();
$this->assertTrue($requirement->is_done());
}
}
/**
* Unit tests for the required_css class.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class required_css_test extends ajaxlib_unit_test_base {
protected $cssurl = 'http://example.com/styles.css';
public function test_when() {
$requirement = new required_css($this->requires, $this->cssurl);
$this->assertEqual($requirement->get_when(), page_requirements_manager::WHEN_IN_HEAD);
}
public function test_round_trip_url_to_html() {
$requirement = new required_css($this->requires, $this->cssurl);
$html = $requirement->get_html();
$this->assertContains($html, $this->cssurl);
$this->assertContains($html, '<link ');
$this->assertContains($html, 'type="text/css"');
}
}
/**
* Unit tests for the required_js_code class. Once again we are tesing the
* behaviour of an abstract class by creating instances one particular subclass.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class required_js_code_test extends ajaxlib_unit_test_base {
protected $classname = 'required_data_for_js';
/* TODO: MDL-21361
public function test_when() {
$requirement = new $this->classname($this->requires, '', '');
$this->assertEqual($requirement->get_when(), page_requirements_manager::WHEN_AT_END);
}
public function test_setting_when_to_head() {
$requirement = new $this->classname($this->requires, '', '');
$requirement->in_head();
$this->assertEqual($requirement->get_when(), page_requirements_manager::WHEN_IN_HEAD);
}
public function test_in_head_when_too_late_throws_exception() {
$requirement = new $this->classname($this->requires, '', '');
$this->requires->get_head_code();
$this->expectException();
$requirement->in_head();
}
public function test_in_head_when_too_late_no_exception_if_done() {
$requirement = new $this->classname($this->requires, '', '');
$requirement->mark_done();
$this->requires->get_head_code();
$requirement->in_head();
$this->pass('No exception thrown as expected.');
}
*/
}
/**
* Unit tests for the required_js_function_call class.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class required_js_function_call_test extends ajaxlib_unit_test_base {
protected $function = 'object.method';
protected $params = array('arg1', 2);
public function test_round_trip_to_js_code() {
$requirement = new required_js_function_call($this->requires, $this->function, $this->params);
$js = $requirement->get_js_code();
$this->assertContains($js, $this->function . '(');
$this->assertContains($js, $this->params[0]);
$this->assertContains($js, $this->params[1]);
}
public function test_setting_when_on_dom_ready() {
$requirement = new required_js_function_call($this->requires, $this->function, $this->params);
$requirement->on_dom_ready();
$this->assertEqual($requirement->get_when(), page_requirements_manager::WHEN_ON_DOM_READY);
}
}
/**
* Unit tests for the page_requirements_manager class.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class page_requirements_manager_test extends ajaxlib_unit_test_base {
/* TODO: MDL-21361
public function test_outputting_head_marks_it_done() {
$this->requires->get_head_code();
$this->assertTrue($this->requires->is_head_done());
}
public function test_outputting_body_top_marks_it_done() {
$this->requires->get_top_of_body_code();
$this->assertTrue($this->requires->is_top_of_body_done());
}
public function test_requiring_js() {
global $CFG;
$jsfile = 'lib/javascript-static.js'; // Just needs to be a JS file that exists.
$this->requires->js($jsfile);
$html = $this->requires->get_end_code();
$this->assertContains($html, $CFG->httpswwwroot . '/' . $jsfile);
}
public function test_requiring_js_with_argument() {
global $CFG;
$jsfile = 'lib/javascript-static.js?d=434'; // Just needs to be a JS file that exists.
$this->requires->js($jsfile);
$html = $this->requires->get_end_code();
$this->assertContains($html, $CFG->httpswwwroot . '/' . $jsfile);
}
public function test_nonexistant_js_throws_exception() {
$jsfile = 'js/file/that/does/not/exist.js';
$this->expectException();
$this->requires->js($jsfile);
}
public function test_requiring_skip_link() {
$this->requires->skip_link_to('target', 'Link text');
$html = $this->requires->get_top_of_body_code();
$this->assertContains($html, 'target');
$this->assertContains($html, 'Link text');
}
public function test_requiring_js_function_call() {
$this->requires->js_function_call('fn');
$html = $this->requires->get_end_code();
$this->assertContains($html, 'fn()');
}
public function test_requiring_string_for_js() {
$this->requires->string_for_js('course', 'moodle');
$html = $this->requires->get_end_code();
$this->assertContains($html, 'mstr');
$this->assertContains($html, 'course');
$this->assertContains($html, 'moodle');
}
public function test_repeat_string_different_a_throws_exception() {
$this->requires->string_for_js('added', 'moodle', 'this');
$this->expectException();
$this->requires->string_for_js('added', 'moodle', 'that');
}
public function test_repeat_string_same_a_is_ok() {
$this->requires->string_for_js('added', 'moodle', 'same$a');
$this->requires->string_for_js('added', 'moodle', 'same$a');
$this->pass('No exception thrown as expected.');
}
public function test_requiring_js_function_call_on_dom_ready() {
$this->requires->js_function_call('fn')->on_dom_ready();
$html = $this->requires->get_end_code();
$this->assertPattern('/<script.*src=".*event.*\.js"/', $html);
$this->assertContains($html, 'YAHOO.util.Event.onDOMReady');
$this->assertContains($html, 'fn()');
}*/
}
/**
* Unit tests for ../ajaxlib.php functions.
*
+2 -2
View File
@@ -546,7 +546,7 @@ class core_renderer extends renderer_base {
if (!$debugdisableredirect) {
// Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
$this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
$this->page->requires->js_function_call('document.location.replace', array($url))->after_delay($delay + 3);
$this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
}
$output = $this->header();
break;
@@ -558,7 +558,7 @@ class core_renderer extends renderer_base {
// We really shouldn't be here but we can deal with this
debugging("You should really redirect before you start page output");
if (!$debugdisableredirect) {
$this->page->requires->js_function_call('document.location.replace', array($url))->after_delay($delay);
$this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
}
$output = $this->opencontainers->pop_all_but_last();
break;
+1 -1
View File
@@ -817,7 +817,7 @@ function close_window($delay = 0, $reloadopener = false) {
}
echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
$PAGE->requires->js_function_call($function)->after_delay($delay);
$PAGE->requires->js_function_call($function, null, false, $delay);
echo $OUTPUT->footer();
exit;
+1 -1
View File
@@ -70,7 +70,7 @@ foreach ($chatusers as $chatuser) {
}
$PAGE->requires->data_for_js('uidles', $uidles);
$PAGE->requires->js('/mod/chat/gui_header_js/chat_gui_header.js');
$PAGE->requires->js_function_call('start')->on_dom_ready();
$PAGE->requires->js_function_call('start', null, true);
ob_start();
echo $OUTPUT->header();
+1 -1
View File
@@ -5882,7 +5882,7 @@ function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode,
echo '<div class="ratingsubmit">';
echo '<input type="submit" id="forumpostratingsubmit" value="'.get_string('sendinratings', 'forum').'" />';
if (ajaxenabled() && !empty($CFG->forum_ajaxrating)) { /// AJAX enabled, standard submission form
$PAGE->requires->js_function_call('add_menu_listeners', array($OUTPUT->pix_url('i/loading_small')))->on_dom_ready();
$PAGE->requires->js_function_call('add_menu_listeners', array($OUTPUT->pix_url('i/loading_small')), true);
}
if ($forum->scale < 0) {
if ($scale = $DB->get_record("scale", array("id" => abs($forum->scale)))) {
+1 -1
View File
@@ -426,7 +426,7 @@
default:
$iframe_id = 'hotpot_iframe';
$PAGE->requires->js('/mod/hotpot/iframe.js');
$PAGE->requires->js_function_call('set_iframe_height', array($iframe_id))->on_dom_ready();
$PAGE->requires->js_function_call('set_iframe_height', array($iframe_id), true);
echo $OUTPUT->header();
if (!empty($available_msg)) {
echo $OUTPUT->notification($available_msg);
+1 -1
View File
@@ -1037,7 +1037,7 @@ function lesson_get_media_html($lesson, $context) {
$code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
$PAGE->requires->yui2_lib('dom');
$PAGE->requires->js('/mod/url/functions.js');
$PAGE->requires->js_function_call('imscp_setup_object')->on_dom_ready();
$PAGE->requires->js_function_call('imscp_setup_object', null, true);
}
return $code;
+1 -1
View File
@@ -27,7 +27,7 @@ $returnurl = $exporter->get('caller')->get_return_url();
echo $OUTPUT->notification('<a href="' . $returnurl . '">' . get_string('returntowhereyouwere', 'portfolio') . '</a><br />');
$PAGE->requires->js('/portfolio/download/helper.js');
$PAGE->requires->js_function_call('submit_download_form')->on_dom_ready();
$PAGE->requires->js_function_call('submit_download_form', null, true);
// if they don't have javascript, they can submit the form here to get the file.
// if they do, it does it nicely for them.
+1 -1
View File
@@ -110,7 +110,7 @@
$efile = get_file_url($filename, null, 'questionfile');
echo '<p><div class="boxaligncenter">' .
get_string('yourfileshoulddownload', 'question', $efile) . '</div></p>';
$PAGE->requires->js_function_call('document.location.replace', array($efile))->after_delay(1);
$PAGE->requires->js_function_call('document.location.replace', array($efile), false, 1);
}
echo $OUTPUT->continue_button(new moodle_url('edit.php', $thispageurl->params()));
+1 -1
View File
@@ -269,7 +269,7 @@ function coursetag_get_jscript_links($coursetagslinks) {
if (!empty($coursetagslinks)) {
foreach ($coursetagslinks as $a) {
$PAGE->requires->js_function_call('add_tag_footer_link', array('coursetagslinks', $a['title'], $a['onclick'], $a['text']))->on_dom_ready();
$PAGE->requires->js_function_call('add_tag_footer_link', array('coursetagslinks', $a['title'], $a['onclick'], $a['text']), true);
}
}
+1 -1
View File
@@ -138,6 +138,6 @@ $tagform->display();
if (ajaxenabled()) {
$PAGE->requires->js('/tag/tag.js');
$PAGE->requires->js_function_call('init_tag_autocomplete')->on_dom_ready();
$PAGE->requires->js_function_call('init_tag_autocomplete', null, true);
}
echo $OUTPUT->footer();