Debian Codegraph @

www/src/content/essays/hypermedia-friendly-scripting.md

raw symbols SCIP
1 ---
2 title: "Hypermedia-Friendly Scripting"
3 description: "In this essay, Carson Gross discusses hypermedia-friendly scripting approaches for web applications, explaining how to incorporate JavaScript while maintaining REST architectural principles and HATEOAS (Hypermedia as the Engine of Application State). Carson outlines key guidelines for using scripting to enhance hypermedia-driven applications without undermining their fundamental REST-ful architecture, covering topics like client-side state management, event communication, and the islands architecture pattern."
4 created: 2022-11-17
5 modified: 2022-11-29
6 authors: ["Carson Gross"]
7 tags: ["guides"]
8 ---
9
10 > The final addition to our constraint set for REST comes from the code-on-demand style of Section 3.5.3 (Figure 5-8).
11 > REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts.
12 > This simplifies clients by reducing the number of features required to be pre-implemented. Allowing features to be
13 > downloaded after deployment improves system extensibility. However, it also reduces visibility, and thus is only an
14 > optional constraint within REST.
15 >
16 > \-\-[Roy Fielding - Representational State Transfer (REST)](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_7)
17
18 ## Scripting & The Web
19
20 In [Hypermedia-Driven Applications](/essays/hypermedia-driven-applications) we discuss how to build
21 web applications in such a manner that they are _hypermedia_-driven, in contrast with the popular SPA approach, in which
22 they are _JavaScript_ and, at the network-level, [RPC-driven](/essays/how-did-rest-come-to-mean-the-opposite-of-rest).
23
24 In the HDA article we mention scripting briefly:
25
26 > In an HDA, hypermedia (HTML) is the primary medium for building the application, which means that:
27 >
28 > * All communication with the server is still managed via HTTP requests with hypermedia (HTML) responses
29 > * Scripting is used mainly to enhance the front-end experience of the application
30 >
31 > Scripting augments the existing hypermedia (HTML) but does not supersede it or subvert the fundamental REST-ful
32 > architecture of the HDA.
33
34 In this article we would like to expand on this last comment and describe what scripting that does not "supersede" or
35 "subvert" a REST-ful, Hypermedia-Driven Application looks like. These rules of thumb apply to scripting written
36 directly to support a web application, as well as to general purpose JavaScript libraries.
37
38 The basic rules for hypermedia-friendly scripting are:
39
40 * [Respect HATEOAS](#prime_directive)
41 * [Client-side only state is OK](#state)
42 * [Use events to communicate between components](#events)
43 * [Use islands to isolate non-hypermedia components from the rest of your application](#islands)
44 * [Optionally, consider inline scripting](#inline)
45
46 Each of these rules will be elaborated on below.
47
48 ## The Prime Directive
49
50 The prime directive of an HDA is to use [Hypermedia As The Engine of Application State](/essays/hateoas).
51 A hypermedia-friendly scripting approach will follow this directive.
52
53 **Practically, this means that scripting should avoid making non-hypermedia exchanges over the network with a server.**
54
55 So, in general, hypermedia-friendly scripting should avoid the use of `fetch()` and `XMLHttpRequest` _unless_ the
56 responses
57 from the server use a hypermedia of some sort (e.g. HTML), rather than a data API format (e.g. plain JSON).
58
59 Respecting HATEOAS also means that, in general, complicated state stored in JavaScript (rather than in the DOM) should
60 be avoided.
61
62 However, this last statement needs to be qualified: state may be stored client-side in JavaScript so long as it is
63 directly supporting a more sophisticated front-end experience (e.g. widget) than pure HTML allows.
64
65 To reiterate what Fielding says regarding the purpose of scripting in REST:
66
67 > Allowing features to be downloaded after deployment improves system extensibility.
68
69 So scripting is a legitimate part a REST-ful system, in order to allow the creation of additional features not directly
70 implemented
71 within the underlying hypermedia, thus making a hypermedia (e.g. HTML) more extensible.
72
73 A good example of this sort of feature is a rich-text editor: it might have an extremely sophisticated JavaScript model
74 of the editor's document, including selection information, highlighting information, code completion and so forth.
75 However, this model should be isolated from the rest of the DOM and the rich text editor should expose its information
76 to the DOM using standard hypermedia features. For example, it should use a hidden input to communicate the contents of
77 the
78 editor to the surrounding DOM, rather than requiring a JavaScript API call to get the content.
79
80 The idea is to use scripting to improve the hypermedia experience by providing features and functionality that are
81 not part of the standard hypermedia (HTML) tool set, but do so in a way that plays well with HTML, rather than
82 relegating
83 HTML to a mere UI description language within a larger JavaScript application, as many SPA frameworks do.
84
85 ## State
86
87 Note that using Hypermedia As The Engine Of Application State does not mean that you cannot have _any_ client-side
88 state.
89 Obviously, the rich-text editor example cited above may have a significant amount of client-side state. But
90 there are simpler cases where client-side state are warranted and perfectly consistent with a Hypermedia-Driven
91 Application.
92
93 Consider a simple visibility toggle, where clicking a button or anchor adds a class to another element, making it
94 visible.
95
96 This ephemeral client-side state is fine in a Hypermedia-Driven Application, because the state is purely front-end. No
97 system state is being updated with this sort of scripting. If system state were to be mutated (that is, if showing or
98 hiding the element had an effect on the data stored on the server), then it would be necessary to use a hypermedia
99 exchange.
100
101 The crucial aspect to consider is whether any state updated on the client side needs to be synchronized with the
102 server.
103 If yes, then a hypermedia exchange should be used. If no, then it is fine to keep the state client-side only.
104
105 ## Events
106
107 One excellent way for a JavaScript library to enable hypermedia-friendly scripting is for it to have
108 [a rich custom event model](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events).
109
110 A JavaScript-based component that triggers events allows for hypermedia-oriented JavaScript libraries, such as htmx,
111 to listen for those events and trigger hypermedia exchanges. This, in turn, makes any JavaScript library a potential
112 _hypermedia control_, able to drive the Hypermedia-Driven Application via user-selected actions.
113
114 A good example of this is the [Sortable.js](/patterns/records/drag-to-reorder) example, in which htmx listens for
115 the `end` event triggered by Sortable.js:
116
117 ```html
118 <form class="sortable" hx-post="/items" hx-trigger="end">
119 <div class="htmx-indicator">Updating...</div>
120 <div><input type='hidden' name='item' value='1'/>Item 1</div>
121 <div><input type='hidden' name='item' value='2'/>Item 2</div>
122 <div><input type='hidden' name='item' value='3'/>Item 3</div>
123 <div><input type='hidden' name='item' value='4'/>Item 4</div>
124 <div><input type='hidden' name='item' value='5'/>Item 5</div>
125 </form>
126 ```
127
128 The `end` event is triggered by Sortable.js when a drag-and-drop completes. htmx listens for this event via the
129 [`hx-trigger`](/reference/attributes/hx-trigger) attribute and then issues an HTTP request, exchanging hypermedia with
130 the
131 server. This turns this Sortable.js drag-and-drop powered widget into a new, powerful hypermedia control.
132
133 ## Islands
134
135 A recent trend in web development is the notion of ["islands"](https://www.patterns.dev/posts/islands-architecture/):
136
137 > The islands architecture encourages small, focused chunks of interactivity within server-rendered web pages.
138
139 In cases where a more sophisticated scripting approach is required and where communication with a server
140 outside of the normal hypermedia-exchange mechanism is necessary, the most hypermedia-friendly approach is to use the
141 island
142 architecture. This isolates non-hypermedia components from the rest of the Hypermedia-Driven Application.
143
144 Events are a clean way to integrate your non-hypermedia-driven islands within a broader Hypermedia-Driven Application,
145 allowing you to convert an "inner" island into an "outer" hypermedia control, just as in the case of the Sortable.js
146 example
147 above.
148
149 Deniz Akşimşek has made the observation that it is typically easier to embed non-hypermedia islands within a larger
150 Hypermedia-Driven Application, rather than vice-versa.
151
152 ## Inline Scripts
153
154 A final rule for hypermedia-friendly scripting is inline scripting: writing your scripts directly within a hypermedia,
155 rather than locating your scripts in an external file. This is a controversial concept compared with the others
156 listed here, and we consider it an "optional" rule for hypermedia-friendly scripting: worth considering but not
157 required.
158
159 This approach to scripting, while idiosyncratic, has been adopted by some HTML scripting libraries, notably
160 [Alpine.js](https://alpinejs.dev/) and [hyperscript](https://hyperscript.org).
161
162 Here is some example hyperscript, showing an inline script:
163
164 ```html
165 <button _="on click toggle .visible on the next <section/>">
166 Show Next Section
167 </button>
168 <section>
169 ....
170 </section>
171 ```
172
173 This button, as it says, toggles the `.visible` class on the `section` element when it is clicked.
174
175 A primary advantage of this inline approach to hypermedia scripting is that, conceptually, the hypermedia itself is
176 emphasized, rather than the scripting of the hypermedia.
177
178 Contrast this code with [JSX Components](https://reactjs.org/docs/components-and-props.html), where the
179 scripting language (JavaScript) is the core concept, with hypermedia/HTML embedded within it:
180
181 ```js
182 class Button extends React.Component {
183 constructor(props) {
184 // ...
185 }
186 toggleVisibilityOnNextSection() {
187 // ...
188 }
189 render() {
190 return <button onClick={this.toggleVisibilityOnNextSection}>{this.props.text}</button>;
191 }
192 }
193 ```
194
195 Here, you can see that the JavaScript is the primary technology in use, with the hypermedia/HTML being used as a UI
196 description mechanism. The fact that the HTML is a hypermedia is almost immaterial in this case.
197
198 That being said, the inline scripting and the JSX approach do share an advantage in common: both satisfy
199 the [Locality of Behavior(LoB)](/essays/locality-of-behaviour),
200 design principle. They both _localize_ behavior to the elements or components in question, which makes it easier to see
201 what these elements and components do.
202
203 Of course, with inline scripts, there should be a soft limit to the amount of scripting done directly within the
204 hypermedia. You don't want to overwhelm your hypermedia with scripting, so that it becomes difficult to understand "the
205 shape"
206 of the hypermedia document.
207
208 Using techniques like invoking library functions or
209 using [hyperscript behaviors](https://hyperscript.org/features/behavior/)
210 allow you to use inline scripting while pulling implementations out to a separate file or location.
211
212 Inline scripting isn't required for scripting to be hypermedia-friendly, but it is worth considering as an alternative
213 to a
214 more traditional scripting/hypermedia split.
215
216 ## Pragmatism
217
218 Of course, here in the real world, there are many useful JavaScript libraries that violate HATEOAS and that do not
219 trigger
220 events. This often makes them difficult fits for a Hypermedia-Driven Application. Nonetheless, these libraries may
221 provide crucial bits of functionality that are difficult to find elsewhere.
222
223 In cases like this, we advocate pragmatism: if it is easy enough to alter the library to be hypermedia-friendly or to
224 wrap it in a hypermedia-friendly way, that may be a good option. You never know, the upstream author might
225 [consider a pull request](https://github.com/dropzone/dropzone/commit/64771e35baf032ee0910d1e56e6f44457efe138e)
226 to help improve their library.
227
228 But, if not, and if there are no good alternatives, then just use the JavaScript library as it is designed.
229
230 Try to isolate a hypermedia-unfriendly library from the rest of your application, but, in general, do not
231 spend too much of your [complexity budget](https://hyperscript.org/docs/#debugging) on maintaining conceptual purity:
232 sufficient unto the day is the evil thereof.