Adds a javascript widget tutorial to the dev tiddlywiki edition (#7016)

* Initial widget tutorials extracted from https://btheado.github.io/tw-widget-tutorial/

* Fixes for refresh behavior change
This commit is contained in:
btheado 2022-10-30 12:10:12 -04:00 committed by GitHub
parent 941c09fae2
commit 6af3eb539b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 1090 additions and 2 deletions

View File

@ -1,5 +1,5 @@
created: 20190115173333457
modified: 20190115173723915
modified: 20221029175754753
tags: TableOfContents
title: HelloThere
type: text/vnd.tiddlywiki
@ -15,6 +15,7 @@ Welcome to the developer documentation for TiddlyWiki (https://tiddlywiki.com/).
** [[Using ES2016 for Writing Plugins]]
** [[Adding Babel Polyfill to TiddlyWiki]]
** [[TiddlyWiki Drag and Drop Interoperability]]
** [[Javascript Widget Tutorial]]
* The original developer documentation from https://tiddlywiki.com:
** [[TiddlyWiki for Developers]]
** [[TiddlyWiki Coding Style Guidelines]]

View File

@ -0,0 +1,140 @@
created: 20190202160512541
modified: 20190222231130254
title: Child widgets tutorial
type: text/vnd.tiddlywiki
\define showTrees(wikitext)
<table>
<thead>
<tr><th>wiki text</th><th>html</th><th>renders as</th></tr>
</thead>
<tbody>
<tr>
<td>`$wikitext$`</td>
<td>
<$wikify name=html text="""$wikitext$""" output=html mode=inline>
<$text text=<<html>>/>
</$wikify>
</td>
<td>$wikitext$</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr><th>parse tree</th><th>widget tree</th></tr>
</thead>
<tbody>
<tr>
<td style="vertical-align: text-top">
<pre><code>
<$wikify name=parsetree text="""$wikitext$""" output=parsetree mode=inline>
<<parsetree>>
</$wikify>
</code></pre>
</td>
<td style="vertical-align: text-top">
<pre><code>
<$wikify name=widgettree text="""$wikitext$""" output=widgettree mode=inline>
<<widgettree>>
</$wikify>
</code></pre>
</td>
</tr>
</tbody>
</table>
\end
! Introduction
Until now the examples have covered only simple, leaf widgets, but widgets can be arranged into a hierarchy. Compared to a leaf-only widget, widget classes which support having children must contain code to instantiate the children.
Not all widgets need to support having children. Widgets whose only purpose is to integrate third party javascript libraries, for example may not need it.
! wiki text ⇨ parse tree ⇨ widget tree ⇨ DOM tree
# [[wiki text|https://tiddlywiki.com/#WikiText]] - Users write content in tiddlers using wiki text.
# [[parse tree|https://tiddlywiki.com/dev/#ParsingMechanism]] - A parse tree is a JSON data structure describing the wiki text. Wiki text can be converted into a parse tree using `this.wiki.parseText`.
# ''widget tree'' - Most items in the parse tree correspond to one or more items in the widget tree. The `this.makeChildWidgets` method is used to convert the parse tree into a widget tree.
# [[DOM tree|https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction]] - A DOM tree is a standard javascript datastructure used by browsers to display a web page. The `this.renderChildren` method is used to instantiate the widget class and then render each widget in the widget tree. If a given widget will be visible in the browser, then one or more DOM nodes will be created.
!Examples
!! Simple trees without nesting
[[Widgets in wiki text|https://tiddlywiki.com/#Widgets%20in%20WikiText]] have a syntax similar to html (i.e. `<$list/>`). But all [[wiki markup|https://tiddlywiki.com/#WikiText]] is seen by the tiddlywiki code as widgets.
Even a simple string with no special syntax will be treated as a widget. In this case a widget of type `text`:
<<showTrees """hello""">>
The above bare string of text is mostly just a synonym for this widget syntax:
<<showTrees """<$text text=hello/>""">>
Some of the details of the parseTree and widgetTree are different in the two examples, but the general structure is the same and the rendered output is the same.
In these two simple examples, there is no nesting and so no child widgets are created.
!! Trees with one level of nesting
This next example shows the structure for bold wiki syntax. It is still simple, but does introduce one level of nesting: `element`→`text`
The wiki syntax for bold converts to the standard html element `strong`. Any standard html element is represented in tiddlywiki as a widget of type `element`:
<<showTrees """''bold''""">>
Another example showing one level of nesting (`link`→`text`):
<<showTrees """<$link to=atiddler>link</$link>""">>
!!Widgets with no DOM contribution
Not all widgets contribute items to the DOM. The purpose of some widgets is to affect the display of descendant widgets by changing some state. The `$set` widget for example sets a variable which will be accessible to the descendant widgets:
<<showTrees """<$set name=myvar value=hi/>""">>
Nothing is rendered and there is no html, but the parse tree and widget tree contain information about the variable.
!! Dynamic widget children using this.wiki.parseText
In all the examples so far, there has been a close mapping between the nesting structure of the parse tree and the widget tree. If the item is in the parse tree, then it is in the widget tree. If the parse tree item has children, then the widget tree has the same number of children.
However, there are several examples of widgets in which more levels of nesting are created dynamically during the widget rendering process
The `$macrocall` widget is one example:
<<showTrees """<$macrocall $name=now/>""" >>
The parse tree has just a single type=$macrocall element with no children. The widget tree has that same type=$macrocall element, but it also has a child widget which wasn't in the parse tree.
In all cases, the `$macrocall` widget calls the given macro and then calls `this.wiki.parseText` on the output. This results in a new parse tree which is used to make the child widgets.
In this particular case, the `now` macro is called. It returns a simple string of text, so when it is parsed the result causes the creation of a single child text widget containing the current date and time.
!! Widgets which do not support nesting
Just as some widgets can cause widget trees to have more nesting than the parse tree, some widgets can cause widget trees to have less nesting.
This happens when there is no use for the widget to have any children. The `$text` widget, for example, has no use for displaying any descendants.
This behavior is accomplished by not calling the `makeChildWidgets` method. Without that method call, the child widgets are not created from the child parse tree items. For example:
<$macrocall $name=showTrees wikitext="""<$text text="hi">ignored child text</$text>"""/>
Since the `$text` widget does not have a call to `makeChildWidgets`, 'ignored child text' above is present in the parse tree, but not in the widget tree.
!Reference
|!method|!when to call|!what it does|
|`makeChildWidgets`|directly or indirectly from `render` method|converts child parse tree items into widget tree items|
|`renderChildren`|directly or indirectly from `render` method, after the `makeChildWidgets` call|calls the `render` method of the child widget|
|`refreshChildren`|directly or indirectly from `refresh` method, only needed if `refreshSelf` is not called|calls the `refresh` method of of the child widgets so they can check if refresh is needed|
|`this.wiki.parseText`|pass the output parse tree to `makeChildWidgets`|converts the given text to a parse tree...only needed for dynamically constructed parsetree|
|!example call|!purpose|!widgets using this approach|
|`this.makeChildWidgets()`|construct child widgets from the static parse tree|[[$link|$:/core/modules/widgets/link.js]], [[$button|$:/core/modules/widgets/button.js]], etc.|
|`this.makeChildWidgets(parseTreeNodes)`|construct child widgets from a dynamic parse tree|[[$list|$:/core/modules/widgets/list.js]], [[$transclude|$:/core/modules/widgets/transclude.js]], [[$macrocall|$:/core/modules/widgets/macrocall.js]], etc|
|`this.renderChildren(parent, nextSibling)`|when the widget adds nothing to the dom, just pass the `render` arguments through to the children|[[$set|$:/core/modules/widgets/set.js]], [[$importvariables|$:/core/modules/widgets/importvariables.js]], [[$tiddler|$:/core/modules/widgets/tiddler.js]], [[$wikify|$:/core/modules/widgets/wikify.js]], etc.|
|`this.renderChildren(domNode, null)`|passes the dom node generated by this widget into the children|[[$link|$:/core/modules/widgets/link.js]], [[$button|$:/core/modules/widgets/button.js]], etc|

View File

@ -0,0 +1,22 @@
created: 20190201120100249
modified: 20190201222600576
tags:
title: Do nothing widget demo
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[donothing.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[do nothing widget]]"/>
<$data $tiddler=donothing.js/>
<$data title="do nothing widget" text="""
```
<$donothing/>
```
Renders as:
<$donothing/>
"""/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,25 @@
created: 20190201232102417
modified: 20190202145547621
tags:
title: Do nothing widget tutorial
type: text/vnd.tiddlywiki
In order to define a widget in a tiddler, the tiddler must satisfy these requirements:
* type field is application/javascript
* module-type field is widget
* the text field contains the javascript code
The [[donothing.js]] tiddler fulfills the requirements and its code looks like this:
{{donothing.js}}
That code does 2 key things:
* Imports the core Widget class ([[$:/core/modules/widgets/widget.js]])
* exports the class in an attribute with the name we want our widget to have (`donothing`)
Here's what it looks like:
{{Do nothing widget demo}}
And it worked. No error message this time.
''Exercise'': Modify [[donothing.js]] and [[Do nothing widget demo]] so the widget is named `noop` instead of `donothing`

View File

@ -0,0 +1,23 @@
created: 20190201114718313
modified: 20190201231556294
tags:
title: Hello World demo
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[hello.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[hello world widget]]"/>
<$data $tiddler=hello.js/>
<$data title="hello world widget" text="""
```
<$hello/>
```
Renders as:
<$hello/>
"""/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,18 @@
created: 20190201232200698
modified: 20190216175629825
tags:
title: Hello World widget tutorial
type: text/vnd.tiddlywiki
Now let's create a widget which actually has output.
When tiddlywiki encounters a widget definition like `<$hello>` it will create an object which is an instance of the class which is exported by the widget code.
In addition to creating an instance of the class, tiddlywiki will call the render method of the resulting object. The render method is expected to create a dom node which will be display in place of the widget.
In the `donothing` example the core widget was exported. The core widget class doesn't have a render method which creates a dom node and that's why there is no output. Getting output requires writing a widget class which inherits from the core `Widget` class. Code in the render method of this class will display the hello world message.
The [[hello.js]] tiddler has code which accomplishes that:
{{hello.js}}
The code for importing the core widget class remains, but now we also have code to create our own class which inherits from it. In addition an implementation of the `render` method is included. Here is the result:
{{Hello World demo}}

View File

@ -0,0 +1,37 @@
created: 20190202035524804
modified: 20221029161501848
tags:
title: Javascript Widget Tutorial
type: text/vnd.tiddlywiki
! Introduction
This tutorial provides step-by-step, interactive examples of how to write code for tiddlywiki widgets. The demo javascript code can be modified without having to reload the entire wiki.
Intended audience:
# Those who know tiddlywiki well and know programming and javascript and want to write their own widget. I don't make any effort to explain javascript here. For that you will need other resources.
# Those who know tiddlywiki well and don't know javascript, but want to understand more about how tiddlywiki works. You should be able to skim through and interact with the demos and learn something.
!The tutorial
*[[Undefined widget tutorial]]
*[[Do nothing widget tutorial]]
*[[Hello World widget tutorial]]
*[[Widget refresh tutorial part I]]
*[[Widget refresh tutorial part II]]
*[[Widget refresh tutorial part III]]
*[[Widget attributes tutorial part I]]
*[[Widget attributes tutorial part II]]
*[[Child widgets tutorial]]
! Notes
tiddlywiki doesn't support dynamically reloading javascript. If you change a javascript tiddler, then you need to save and reload the wiki before the changes will take affect.
To avoid the need for such reloads, the excellent [[innerwiki plugin|https://tiddlywiki.com/prerelease/plugins/tiddlywiki/innerwiki/]] is used. This allows an inner wiki to be created from a subset of tiddlers in the outer wiki. Each time the inner wiki is refreshed, its entire wiki is reloaded and the javascript changes in the inner wiki will take affect.
Without the need for reloads, a tiddlywiki instance with the [[innerwiki plugin|https://tiddlywiki.com/prerelease/plugins/tiddlywiki/innerwiki/]] installed works great as a playground for interacting with tiddlywiki javascript.
! Other documentation on writing TW widgets
*WidgetModules
*[[Widgets]]

View File

@ -0,0 +1,18 @@
created: 20190201212238781
modified: 20190201213112748
tags:
title: Undefined widget demo
type: text/vnd.tiddlywiki
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[Undefined widget]]"/>
<$data title="Undefined widget" text="""
```
<$donothing/>
```
Renders as:
<$donothing/>
"""/>
</$innerwiki>

View File

@ -0,0 +1,11 @@
created: 20190201232001970
modified: 20190202145655413
tags:
title: Undefined widget tutorial
type: text/vnd.tiddlywiki
Let's start be defining a minimal widget which does nothing. It doesn't support any attributes, no child elements, and it doesn't output anything. The name of the widget will be `donothing`. If it does nothing, then how can we verify after writing the code that we accomplished anything? Well, let's see what happens when an undefined widget is referenced.
{{Undefined widget demo}}
Since we haven't written the code, the attempt to render the widget gives an undefined widget error. So we will know the donothing code accomplishes something if we don't get the undefined widget error when rendering.

View File

@ -0,0 +1,48 @@
created: 20190204020507195
modified: 20190204031520013
tags:
title: Widget attributes demo I
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[hello-attribute.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[hello world widget]]"/>
<$data $tiddler=hello-attribute.js/>
<$data title="hello world widget" text="""
```
<$hello/>
```
Renders as:
<$hello/>
---
```
<$hello message="pale blue dot"/>
```
Renders as:
<$hello message="pale blue dot"/>
---
<$edit-text focus=yes tiddler=test tag=input/>
```
<$hello message={{test!!text}}/>
```
Renders as:
<$hello message={{test!!text}}/>
"""/>
<$data title="test" text="Alice"/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,48 @@
created: 20190205024953535
modified: 20190205025028737
tags:
title: Widget attributes demo II
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[hello-attribute-optimized.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[hello world widget]]"/>
<$data $tiddler=hello-attribute-optimized.js/>
<$data title="hello world widget" text="""
```
<$hello/>
```
Renders as:
<$hello/>
---
```
<$hello message="pale blue dot"/>
```
Renders as:
<$hello message="pale blue dot"/>
---
<$edit-text focus=yes tiddler=test tag=input/>
```
<$hello message={{test!!text}}/>
```
Renders as:
<$hello message={{test!!text}}/>
"""/>
<$data title="test" text="Alice"/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,50 @@
created: 20190202035425715
modified: 20190205023518575
tags:
title: Widget attributes tutorial part I
type: text/vnd.tiddlywiki
So far none of the widgets we've implemented have had any code for handling widget attributes A vast majority of useful widgets will need to support attributes in order to make them useful.
As an example, let's change the Hello World widget so it can greet not just the world, but whoever/whatever the user wants. To do that we can add support for an attribute named `what` and call it like `<$hello what="pale blue dot"/>`.
The tiddlywiki widget class provides methods `computeAttributes` and `getAttribute` which can together be used by the widget code to discover what values are passed into the widget.
The `computeAttributes` and `getAttribute` methods can be called like this (the second parameter to `getAttribute` will be used as the default value if the user doesn't provide that attribute in the widget call):
```javascript
this.computeAttributes();
var message = this.getAttribute("message", "World");
```
Then the `message` variable can be used to construct the Hello XXX string:
```javascript
var textNode = this.document.createTextNode("Hello, " + message + "!");
```
The original [[hello.js]] code only implements a `render` method. The `refresh` method is not needed because the output from the widget can never be different...it will always be "Hello, World!".
Even with a `message` attribute, you might think the `render` by itself is enough. After all, the value of the input parameter `message` can only be changed by modifying the wiki text which means the tiddler will be redisplayed from scratch.
However, tiddlywiki has a syntax which allows parameter values to vary without modifying the wiki text. See https://tiddlywiki.com/#Widgets%20in%20WikiText for details. As one example, if the widget were called like `<$hello message={{MyTiddler!!field}}/>`, then every time the `field` field of `MyTiddler` were modified, only the `refresh` method would be called. Therefore, in order to get the widget display to update, the refresh method needs to be implemented.
If the `computeAttributes` and `getAttribute` calls are placed in the `render` method then we can implement a performance unoptimized version of refresh as was done in [[Widget refresh tutorial part II]]:
```javascript
/*
A widget with optimized performance will selectively refresh, but here we refresh always
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and
// replace the existing DOM node
this.refreshSelf();
return true;
};
```
The full code can be seen at [[hello-attribute.js]] and here is the result ([[Widget attributes demo I]]):
{{Widget attributes demo I}}
The third example above is the only one which requires the refresh method in order to behave properly.

View File

@ -0,0 +1,33 @@
created: 20190205023543910
modified: 20190217012121130
tags:
title: Widget attributes tutorial part II
type: text/vnd.tiddlywiki
This example will build on the previous one. The only modification will be to add a check to the `refresh` method. The `refreshSelf` will only be called if a change to the attributes is detected.
The `computeAttributes` method returns a Javascript object containing properties for each attribute which has changed. So a check like `if (changedAttributes.attr1 || changedAttributes.attr2 || changedAttributes.attr3)` etc. can be used to detect the change. See the refresh method in [[$:/core/modules/widgets/view.js]] for an example showing the check for multiple attributes.
For this example, `message` is the only attribute implemented.
```javascript
/*
Refresh if the attribute value changed since render
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Find which attributes have changed
var changedAttributes = this.computeAttributes();
if (changedAttributes.message) {
this.refreshSelf();
return true;
} else {
return false;
}
};
```
The full code can be seen at [[hello-attribute-optimized.js]] and here is the result ([[Widget attributes demo II]]):
{{Widget attributes demo II}}
The visible behavior here should be identical to the unoptimized behavior of the previous tutorial.

View File

@ -0,0 +1,44 @@
created: 20190201233806976
modified: 20221029194854112
tags:
title: Widget refresh demo I
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[tiddlerfield-norefresh.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[tiddler field widget]]"/>
<$data title="test" text="type new text here"/>
<$data $tiddler=tiddlerfield-norefresh.js/>
<$data title="tiddler field widget" text="""
<$edit-text focus=yes tiddler=test tag=input/>
<$button set="!!refresh" setTo={{test}}>Force refresh</$button>
<$list filter="[{!!refresh}]">
<div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$tiddlerfield/>
```
Renders as:
<$tiddlerfield/>
</div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$view tiddler="test"/>
```
Renders as:
<$view tiddler="test"/>
</div>
</div>
</$list>
"""/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,40 @@
created: 20190202032354223
modified: 20190217005540498
tags:
title: Widget refresh demo II
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[tiddlerfield.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[tiddler field widget]]"/>
<$data title="test" text="type new text here"/>
<$data $tiddler=tiddlerfield.js/>
<$data title="tiddler field widget" text="""
<$edit-text focus=yes tiddler=test tag=input/>
<div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$tiddlerfield/>
```
Renders as:
<$tiddlerfield/>
</div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$view tiddler="test"/>
```
Renders as:
<$view tiddler="test"/>
</div>
"""/>
</$innerwiki>
</$list>

View File

@ -0,0 +1,50 @@
created: 20190202122928187
modified: 20190216191939585
tags:
title: Widget refresh demo III
type: text/vnd.tiddlywiki
<!-- The innerwiki doesn't refresh on its own when tiddlers on the outside change, so use the list widget to force a dependency -->
<$list name=refresh filter=[[refreshcount.js]get[text]]>
<$innerwiki width="600" height="400" style="width:100%;">
<$data title="$:/DefaultTiddlers" text="[[refresh count widget]]"/>
<$data title="test" text="Text field of tiddler='test'"/>
<$data $tiddler=refreshcount.js/>
<$data title="refresh count widget" text="""
*<$button set="test!!test" setTo="hello">Modify a different tiddler</$button>
*<$button set="!!test" setTo="hello">Modify this tiddler</$button>
*<$edit-text focus=yes tiddler=test tag=input/>
<div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$refreshcount/>
```
Renders as:
<$refreshcount/>
</div>
<div style="display:inline-block;width: 49%;vertical-align: text-top;word-wrap: break-word;}">
```
<$list filter="[[test]get[text]]">
<<currentTiddler>><br>
<$refreshcount/>
</$list>
```
Renders as:
<$list filter="[[test]get[text]]">
<<currentTiddler>><br>
<$refreshcount/>
</$list>
"""/>
</div>
</div>
</$innerwiki>
</$list>

View File

@ -0,0 +1,47 @@
created: 20190201232847949
modified: 20221029203553291
tags:
title: Widget refresh tutorial part I
type: text/vnd.tiddlywiki
But what if we want to display dynamic content? How can we display information and keep it up to date as it changes? Let's display the content of a tiddler field.
The [[tiddlerfield-norefresh.js]] which defines the `tiddlerfield` widget is almost the same as [[hello.js]] except for this part:
```javascript
MyWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
var text = this.wiki.getTiddlerText("test", "<empty>")
var textNode = this.document.createTextNode(text);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
```
Instead of creating the text dom node from a static string, the text field of the `test` tiddler is used. This is similar to using the view widget like this: `<$view tiddler="test"/>`
Here's how it looks (see [[Widget refresh demo I]] to look at the code):
{{Widget refresh demo I}}
Notice if you change the text in the input box, the output from the `tiddlerfield` widget doesn't change, but the output of the `view` widget does. Only after the ''Force refresh'' button is clicked does the output of `tiddlerfield` update to match the input box contents.
What's going on here? The render method of the widget code is only called by tiddlywiki core when the widget is first created. After that, it isn't called again unless the widget is completely destroyed and then created again.
The tiddlywiki ~ViewWidget has a properly written `refresh` method so typing in the input box will cause its content to update. However, the `tiddlerfield` widget does not have a `refresh` method at all. It has no way of being notified that the `test` tiddler content has changed. Its output will not change until the ''Force refresh'' button is clicked.
See the next example for an implementation of the `refresh` method for the `tiddlerfield` widget.
The code for the refresh button looks like this:
```
<$button set="!!refresh" setTo={{test}}>Force refresh</$button>
```
and the widgets are enclosed in a list widget like this:
```
<$list filter="[{!!refresh}]">...</$list>
```
When the button is clicked the field `refresh` in the containing tiddler is modified and it causes the children of the list widget to be created from scratch. The render method is called and the output of the `tiddlerfield` widget updates.

View File

@ -0,0 +1,37 @@
created: 20190201232910076
modified: 20190217014335419
tags:
title: Widget refresh tutorial part II
type: text/vnd.tiddlywiki
This example is like [[Widget refresh tutorial part I]] except the widget output will be automatically refreshed when the tiddler field changes.
[[tiddlerfield.js]] is the same as [[tiddlerfield-norefresh.js]], except this `refresh` method is added:
```javascript
/*
A widget with optimized performance will selectively refresh, but here we refresh always
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and
// replace the existing DOM node
this.refreshSelf();
return true;
};
```
The `refreshSelf` method called above is implemented by the core widget class and it takes care of cleaning the old dom node and calling the render function.
Here is the result ([[Widget refresh demo II]]):
{{Widget refresh demo II}}
And now any typing into the input box will cause both the `tiddlerfield` and the `view` widget output to refresh immediately.
Note this is a naive version of `refresh`. It unconditionally refreshes itself. This is far from optimal since the `refresh` method for all visible widgets is called every time the tiddler store changes. But the way we've defined our widget, the output ONLY depends on the tiddler titled `text`.
In tiddlywiki the tiddler store is used for everything and almost any interaction will result in an update to the store. This means almost any interaction will cause the refresh method to be called. If you type into the search box, for example, the `tiddlerfield` widget will be refreshed with every keystroke.
Adding and removing dom elements is a relatively expensive operation, so if someone has used the list widget to create a few hundred instances of this widget, then such tiddlywiki interactions might gain a noticable lag. Therefore, it usually makes sense to avoid modifying the dom when possible by writing a smarter `refresh` method.
''Exercise'' - change the refresh method above to only call `refreshSelf` when the `changedTiddlers` input array contains `test` as one of its entries (Hint: see the refresh method in $:/core/modules/widgets/view.js for an example).

View File

@ -0,0 +1,26 @@
created: 20190202034841184
modified: 20221029201023638
tags:
title: Widget refresh tutorial part III
type: text/vnd.tiddlywiki
This tutorial is intended to demonstrate a few examples of when calls to the `refresh` method happen vs. when a widget is recreated from scratch.
This is accomplished with a [[refreshcount.js]] widget which sets a counter to zero when the widget is created and increments the counter every time the `refresh` method is called. Here is the full code:
{{refreshcount.js}}
These are the key parts of the code from above:
```javascript
this.refreshCount = 0;
this.document.createTextNode(this.refreshCount + " refreshes");
this.refreshCount++;
```
In the following example (see [[Widget refresh demo III]] for the code), two instances of the `refreshcount` widget are created. One at the top level and the other inside a list widget whose filter results depend on the value in the `text` field of the `test` widget. The tiddler store can be modified in a few ways via two buttons and an input box:
{{Widget refresh demo III}}
* ''Modify a different tiddler'' - every time this button is clicked, both counters increment, indicating the `refresh` method is being called
* ''Modify this tiddler'' - clicking this button modifies the tiddler itself. In earlier ~TiddlyWiki versions that caused both widgets to be recreated from scratch and the counters are thereby reset to zero. Since [[version 5.2.0|https://tiddlywiki.com/#Release%205.2.0]] modifying another field in this tiddler does not cause the widgets to be recreated and the counters are not reset.
* ''Text field of tiddler='test''' - typing text into the input box causes the counter in the standalone `refreshcount` widget to be incremented. But the other instance of the widget is embedded inside a list widget whose filter output depends on the value of the tiddler field which is being modified. This causes it to recreate its children from scratch and the counter is reset every time. So with every keystroke, the counter on the left is incremented, but the counter on the right goes to/stays at zero.

View File

@ -0,0 +1,47 @@
/*\
Library function for creating widget using a dom creating function
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
function createDomWidget(domCreatorFunction) {
var MyWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
var domNode = domCreatorFunction(this.document);
parent.insertBefore(domNode, nextSibling);
this.domNodes.push(domNode);
};
/*
A widget with optimized performance will selectively refresh, but here we refresh always
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and replace the existing DOM node
this.refreshSelf();
return true;
};
return MyWidget;
}
module.exports = createDomWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190201025244440
modified: 20190201030708723
module-type: library
tags:
title: domwidget.js
type: application/javascript

View File

@ -0,0 +1,16 @@
/*\
Do nothing widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
exports.donothing = Widget;
})();

View File

@ -0,0 +1,6 @@
created: 20190201115945945
modified: 20190201222441271
module-type: widget
tags:
title: donothing.js
type: application/javascript

View File

@ -0,0 +1,51 @@
/*\
Hello, World widget
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
var message = this.getAttribute("message", "World");
var textNode = this.document.createTextNode("Hello, " + message + "!");
parent.insertBefore(textNode, nextSibling);
this.domNodes.push(textNode);
};
/*
Refresh if the attribute value changed since render
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Find which attributes have changed
var changedAttributes = this.computeAttributes();
if (changedAttributes.message) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.hello = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190205024846183
modified: 20190205025110882
module-type: widget
tags:
title: hello-attribute-optimized.js
type: application/javascript

View File

@ -0,0 +1,47 @@
/*\
Hello, World widget
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
var message = this.getAttribute("message", "World");
var textNode = this.document.createTextNode("Hello, " + message + "!");
parent.insertBefore(textNode, nextSibling);
this.domNodes.push(textNode);
};
/*
A widget with optimized performance will selectively refresh, but here we refresh always
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and
// replace the existing DOM node
this.refreshSelf();
return true;
};
exports.hello = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190204020011193
modified: 20190204030332147
module-type: widget
tags:
title: hello-attribute.js
type: application/javascript

View File

@ -0,0 +1,35 @@
/*\
Hello, World widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
var textNode = this.document.createTextNode("Hello, World!");
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
exports.hello = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190201114558816
modified: 20190201224846870
module-type: widget
tags:
title: hello.js
type: application/javascript

View File

@ -0,0 +1,43 @@
/*\
widget to count the number of times this widget refreshes
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode, options) {
this.refreshCount = 0;
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
var textNode = this.document.createTextNode(this.refreshCount + " refreshes");
parent.insertBefore(textNode, nextSibling);
this.domNodes.push(textNode);
};
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and replace the existing DOM node
this.refreshCount++;
this.refreshSelf();
return true;
};
exports.refreshcount = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190201005026324
modified: 20190202143451303
module-type: widget
tags:
title: refreshcount.js
type: application/javascript

View File

@ -0,0 +1,36 @@
/*\
Hello, World widget
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
var text = this.wiki.getTiddlerText("test", "<empty>")
var textNode = this.document.createTextNode(text);
parent.insertBefore(textNode, nextSibling);
this.domNodes.push(textNode);
};
exports.tiddlerfield = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190201233714872
modified: 20190202030615781
module-type: widget
tags:
title: tiddlerfield-norefresh.js
type: application/javascript

View File

@ -0,0 +1,46 @@
/*\
Hello, World widget
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MyWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
var text = this.wiki.getTiddlerText("test", "<empty>")
var textNode = this.document.createTextNode(text);
parent.insertBefore(textNode, nextSibling);
this.domNodes.push(textNode);
};
/*
A widget with optimized performance will selectively refresh, but here we refresh always
*/
MyWidget.prototype.refresh = function(changedTiddlers) {
// Regenerate and rerender the widget and
// replace the existing DOM node
this.refreshSelf();
return true;
};
exports.tiddlerfield = MyWidget;
})();

View File

@ -0,0 +1,6 @@
created: 20190202032530728
modified: 20190202032700995
module-type: widget
tags:
title: tiddlerfield.js
type: application/javascript

View File

@ -5,7 +5,8 @@
"tiddlywiki/nodewebkitsaver",
"tiddlywiki/github-fork-ribbon",
"tiddlywiki/menubar",
"tiddlywiki/internals"
"tiddlywiki/internals",
"tiddlywiki/innerwiki"
],
"themes": [
"tiddlywiki/vanilla",