<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fred Every on Medium]]></title>
        <description><![CDATA[Stories by Fred Every on Medium]]></description>
        <link>https://medium.com/@fredevery.typecode?source=rss-d1ddb7f4638e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i-vMW3f9BtbTPWUQbW1DFA.jpeg</url>
            <title>Stories by Fred Every on Medium</title>
            <link>https://medium.com/@fredevery.typecode?source=rss-d1ddb7f4638e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:09:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fredevery.typecode/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Typester Series: Formatters]]></title>
            <link>https://medium.com/typecode/the-typester-series-formatters-c9ed8f78424e?source=rss-d1ddb7f4638e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ed8f78424e</guid>
            <category><![CDATA[mediator]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[modular-design]]></category>
            <dc:creator><![CDATA[Fred Every]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 20:41:15 GMT</pubDate>
            <atom:updated>2018-07-30T20:41:15.248Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Fred Every, Lead Developer on the Typester project.</em></p><p><em>This article is the second in a series offering a look into the inner workings of the open-source project Typester, a WYSIWYG editor designed and developed at </em><a href="https://medium.com/u/e5b4c9ccb65c"><em>Type/Code</em></a><em> to return standardised, sanitised, and predictable HTML.</em></p><p><em>For more information on Typester, demos, or to get started with the editor, visit </em><a href="http://typester.io/"><em>http://typester.io/</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxGT8wjhp0UWgkq8QAjRGA.jpeg" /></figure><p>The real magic in Typester comes from its formatters, the modules it uses to perform the user requested formatting on the selected content. For anyone who has looked into creating a WYSIWYG you may be familiar with the document.execCommand API method exposed by the browser, which can perform various formatting tasks on selected content inside an editable element. There are some pitfalls with the execCommand api though, which include:</p><ul><li><strong>Malformed HTML output</strong>: including illegally nested elements, inline styling, and if you really push it you can even break the DOM completely where open and close tags for elements no longer exist at the same level.</li><li><strong>Non-standardised output</strong>: each browser has its own implementation and often the results of performing a formatting task differ from browser to browser.</li></ul><p>That said, the document.execCommand does, for the most part, do a very good job. So what we’ve done is wrap the api with our formatter modules that perform pre- and post-processing on the content along with the document.execCommand API. We’ve also sandboxed the formatting in an iframe (referred to as “the canvas”) which allows us to do all the processing we want without polluting the edit history of the editable content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*mh9KbDxYo3klYtbiVePXqQ.jpeg" /></figure><p>Before we dive into the various components associated with formatting content in Typester, here is the flow of how the plugin performs its formatting:</p><ol><li>The user selects a range of content inside an editable container.</li><li>Typester then shows a contextual toolbar with various formatting controls.</li><li>When the user clicks on a control the toolbar module will send an exec command to the relevant formatter.</li><li>The contents of the editor are then cloned into the canvas.</li><li>The selection range coordinates that we cached earlier are then applied inside the iframe canvas to mirror the user’s selection.</li><li>The relevant formatter will then perform the tasks necessary to format the selected content. This can involve calling document.execCommand as well as DOM manipulation where it may unwrap, remove, shuffle, or modify the DOM structure of the content in the canvas.</li><li>Some formatters will perform post-processing on the content to ensure that it is well formed and standardised.</li><li>The new selection range in the canvas is then resolved to coordinates and cached.</li><li>The canvas, with the formatter result, is then cleaned. Invalid elements are removed, orphaned text nodes are converted to paragraph tags, br tags are removed, all block type elements are hoisted to the root element, all inline attributes are removed, and any empty nodes are stripped.</li><li>The canvas content is then injected back into the editor using the paste command.</li><li>The cached selection coordinates from the canvas is then applied to the updated content in the editor.</li><li>The user can now continue writing and editing as per usual.</li></ol><h3>Formatters</h3><p>The formatters in Typester have been decomposed into separate modules based on the <em>type </em>of formatting they will need to perform.</p><h4>The base formatter</h4><p>The base formatter is a general, foundational formatter that assists with exporting/importing content to/from the canvas, resolving, caching and re-applying selection coordinates, and performing the cleanup flow.</p><h4>The block level formatter</h4><p>This formatter handles all the formatting for block level content including headers (H1~H6 etc.), paragraphs, and blockquotes.</p><h4>The list formatter</h4><p>This formatter handles ordered and unordered lists, including toggling content into/out of lists, indenting/outdenting nested lists, etc.</p><h4>The link formatter</h4><p>This formatter is responsible for wrapping and unwrapping links around content, as well as presenting the necessary tools for editing links and handling the user input.</p><h4>The text / inline formatter</h4><p>This formatter handles toggling content to/from bold and italic.</p><h3>Selections &amp; Ranges</h3><p>Typester has a lot of logic around selections and ranges and the manipulation and mapping of these to ensure that the correct content is formatted and when presented back to the user the selection range is identical to the pre-formatted range. This does become quite involved when moving the range between the page and the canvas as well as remapping it after formatting. We found that some of the document.execCommand calls would either lose the range completely or it would not map it back to the content accurately. So we had to put in logic to fix that.</p><p>On top of that we implemented a pseudo range/selection feature for when the user needs to create or edit a link. The issue we found was that when focusing the link input field in the toolbar, the selection range would be removed from the editable element as it loses focus. To combat this we <em>paint </em>a faux selection box around the content selected so that while the user is inputting, or editing, the link they can still clearly see the content that will be affected.</p><h3>The Canvas</h3><p>The canvas, as we’ve come to call it, is created by way of a iframe that is injected into the DOM of the page. Because iframes are naturally sandboxed from their parent pages, this allows us to be able to import content and then edit and manipulate it as much as is needed without messing with the edit history of the page. The reason for this is that in order to standardise the HTML output from the document.execCommand the plugin needs to manipulate the DOM structure of the content. The problem here being that in doing so the edit history is polluted, resulting in undesired and wonky behaviour when the user undoes any of their edits using CTRL+Z or similar.</p><p>Often what happens is the resulting <em>undone </em>content is malformed and not what the user expected, resulting in the user having to re-write a lot of their content.</p><p>To circumvent this we created the <em>canvas</em>.</p><p>And, as an added bonus, it also allows us to handle the pasting of content in a way that sandboxes that as well. By intercepting the paste event and redirecting it to the canvas we are able to clean the content, sanitize it using DOMPurify to eliminate XSS threats, and then standardise the HTML.</p><h3>The Toolbar</h3><p>The toolbar for Typester mimics the toolbar developed by Medium for their editing very closely. It is contextual and appears only when required, when a user has selected content for formatting.</p><p>We have also made it smarter than the average toolbar, in that it protects the content by stopping the user from performing illegal formatting. Illegal formatting in this sense includes things like injecting a &lt;b&gt; tag into a header that already has the font-weight set to bold. Or injecting a H1 tag into a list. The toolbar does this by inspecting the selected content and then adapting its controls to give the user only those formatters that make sense in the current situation.</p><p>And that’s it really. For more info checkout <a href="http://typester.io/">http://typester.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ed8f78424e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/typecode/the-typester-series-formatters-c9ed8f78424e">The Typester Series: Formatters</a> was originally published in <a href="https://medium.com/typecode">Type/Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unpacking Typester: A New Open Source Text Editor]]></title>
            <link>https://medium.com/typecode/the-typester-series-core-abc63affaef0?source=rss-d1ddb7f4638e------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc63affaef0</guid>
            <category><![CDATA[mediator]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[modular-design]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-architecture]]></category>
            <dc:creator><![CDATA[Fred Every]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 21:31:01 GMT</pubDate>
            <atom:updated>2019-12-20T02:55:29.533Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Fred Every, Lead Developer on the Typester project.</em></p><p><em>This article is the first in a series offering a look into the inner workings of the open-source project Typester, a WYSIWYG editor designed and developed at </em><a href="https://medium.com/u/e5b4c9ccb65c"><em>Type/Code</em></a><em> to return standardised, sanitised, and predictable HTML. This article will cover the core components of Typester.</em></p><p><em>For more information on Typester, demos, or to get started with the editor, visit </em><a href="http://typester.io/"><em>http://typester.io/</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYKdHK_3RB3deFH27asGhw.jpeg" /></figure><p>Typester uses modules in order to decompose the complexity of the plugin into independent, cohesive, and interchangeable components. By doing so we leverage all the good stuff that comes from <a href="https://en.wikipedia.org/wiki/Modular_programming">modular software design principles</a>.</p><p>But, the modules in Typester have a twist. Where modules designed using classic module design patterns expose a public interface, that a developer can call directly in the code, Typester’s modules don’t expose anything. At least not directly.</p><p>Typester’s modules can’t be instantiated in isolation and then used via an exposed interface of public methods. Typester’s modular design works via a self contained ecosystem that leans heavily on nested layers of isolation and an hierarchy of mediators to facilitate interoperability.</p><p>There are three primary pieces to this:</p><ol><li>Containers</li><li>Mediators</li><li>Modules</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1NiYcBH2xwKE0RH-cZ9Ew.png" /></figure><h3>Containers</h3><p>The first part of this ecosystem is the Container. A container encapsulates, instantiates, and links modules using a mediator. Containers can do the same with other containers, offering container composition and nesting. These are created using a factory method that takes in a container definition and returns a constructor method of instantiating the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5UxkK4yN7P7S7D1MlgN5A.png" /></figure><p>The container offers the following benefits:</p><ol><li><strong>Domain scoping:</strong> where related modules are encapsulated and then linked via a shared mediator which allows for cross module communication to happen in the local scope.</li><li><strong>Inter-domain communication: </strong>where, when the local domain is unable to fulfill a request, the request is hoisted to the parent container which in turn checks with peer containers to see if any of them, or their modules, are capable of fulfilling the request. If none of the peers are capable off handling the request, it will be hoisted once again. This hoisting will continue until either the request is handled or the root container is reached. If the request hasn’t been handled by this point it will just fail silently.</li><li><strong>Module multi-instancing with isolation: </strong>by scoping and encapsulating the domains in containers, you are able to have multi-instanced modules existing in the same system, but used in different scopes. For example: in Typester there is a module that is responsible for handling selections, but we have two areas that require the module, the currently active editable node on the page as well as the canvas in which Typester does all the heavy lifting. By using containers to separate the editor and canvas domains, we are able to have the two instances of the selection module active without them cross interacting or fighting each other.</li></ol><p>The library currently has 4 containers:</p><ol><li><strong>AppContainer: </strong>This container holds modules responsible for handling the user’s interaction with the active editable container on the page. This is the only container that will have multiple instances, one for each editable container with Typester bound.</li><li><strong>UIContainer (Singleton): </strong>This container holds modules responsible for the display and interaction handling of the UI components such as the toolbar, the flyout that wraps and positions the toolbar, and a mouse handler.</li><li><strong>FormatterContainer (Singleton): </strong>This container holds all the formatter modules.</li><li><strong>CanvasContainer (Singleton): </strong>This container holds the modules related to the canvas and the handling of content into and out of the canvas.</li></ol><h3>Mediators</h3><p>The mediators are the glue that holds everything together in Typester and facilitates the interoperability of the system. Containers and modules register themselves with the mediators and then use the mediator to dispatch commands, do requests, and bind to system events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3rM7j5Qi1PO27q7HnyilQ.png" /></figure><p>The mediators can also be chained, parent to child, to allow for a hierarchy of mediators. This is useful for propagating mediator dispatches that cannot be fulfilled by the current mediator. Mediators also allow for hot swapping their parents, which is used by Typester to attach the editor instances to the singleton instances of the UI, Formatter, and Canvas containers on focus of an editable DOM element.</p><p>The mediators offer three modes of communication within the system:</p><ol><li><strong>Requests: </strong>Getting data or content from another part of the system.</li><li><strong>Commands: </strong>Triggering another part of the system to execute a method or routine.</li><li><strong>Events: </strong>Emit a system wide message to signal a noteworthy event.</li></ol><p>Some of the benefits of using a mediator for inter-system communication include:</p><ol><li><strong>Decoupling: </strong>Modules do not connect or interact with each other directly. All interaction is mediated by the mediator, so replacing a module or moving a handler to another module only requires declaring, or migrating, the correct handlers. So the rest of the system needs no changes. No need to grep the codebase and replace multiples of namespaced module method calls.</li><li><strong>Isolation: </strong>Modules are essentially blind to the inner workings of the rest of the system. They may assume that the system <em>can </em>do something, but have no knowledge of <em>how </em>or <em>where </em>the system will handle a request or execute a command.<em> </em>All they need to do is request something or issue a command. I need this done, and I don’t care who does it or how it gets done.</li><li><strong>Fault tolerance: </strong>Failures inside modules are not propagated to other parts of the system, and should not bring the entire system to a halt.</li></ol><p>Module, and container, definitions can include a handler: {} object that declares the mapping of requests, commands, and events to handler methods using arbitrary call strings as keys. In Typester we opted for colon separated call strings that are declarative, describing the expected command outcome or the result from a request. In the code sample above, the handler mapper for the Canvas module, you can see that mediator.get(&#39;canvas:document&#39;) will be mapped to a method called getCanvasDocument and you can expect to get the document node of the canvas iframe in response.</p><h3>Modules</h3><p>The next piece to the system, and the real workhorses of it all, are the Modules. These are created using a factory method that takes in a module definition and returns a constructor method of instantiating the module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-ZJ1FK8BSki1vjitgbHMQ.png" /></figure><p>As mentioned earlier, once instantiated, a module does not expose any kind of public interface. Instead, modules are passed a mediator to self-register to during setup.</p><p>The modules offer two hooks that are called when they are instantiated. A setup() hook and an init() hook, inside which relevant setup or post-init code can be placed.</p><p>Other than that the developer is free to populate the methods:{} object with all the methods they need. All the methods declared will be bound with the module context</p><h3>Contexts</h3><p>Used by modules and containers, contexts gave us a way of setting the this context of child methods to an extendable object. The system populates the context with references to the mediator, available methods from the module or container, the module props, and any declared DOM references.</p><h3>Fin</h3><p>For more info check out the technical docs for typester here: <a href="https://github.com/typecode/typester/tree/devel/docs">https://github.com/typecode/typester/tree/devel/docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc63affaef0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/typecode/the-typester-series-core-abc63affaef0">Unpacking Typester: A New Open Source Text Editor</a> was originally published in <a href="https://medium.com/typecode">Type/Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A strategy for handling multiple file uploads using JavaScript]]></title>
            <link>https://medium.com/typecode/a-strategy-for-handling-multiple-file-uploads-using-javascript-eb00a77e15f?source=rss-d1ddb7f4638e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb00a77e15f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[asset-management]]></category>
            <dc:creator><![CDATA[Fred Every]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 21:45:14 GMT</pubDate>
            <atom:updated>2017-08-07T21:45:14.197Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s a lot simpler than you might expect!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RssiVjqICzgWt8N8jQAjA.jpeg" /><figcaption>Icons made by <a href="https://www.flaticon.com/authors/madebyoliver">Madebyoliver</a> <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a></figcaption></figure><h3>Problem Definition</h3><p>So, you need to get files from your user’s browser to your server. Not just one file though. A whole bunch. A batch even. And each file needs to be able to have its own meta data sent with it, i.e. Title, Caption, Copyright, Tags, etc. And asking your user to send them one at a time is not an option.</p><p>You also want to be able to keep that slick single page application aesthetic you’ve work so gosh darn hard at. So you need to be able to send your payload without forcing the user to reload the page.</p><p>Easy-peezy, lemon-squeezy!</p><h3>The building blocks</h3><p>Our shopping list</p><ul><li>1 x Form</li><li>1 x File input</li><li>1 x Submit button</li><li>~41 x Lines of JavaScript</li></ul><h3>The [mutiple] attribute</h3><p>The first thing we need to make sure to do is set the <strong><em>mutiple </em></strong>attribute to the file input. This will signal to the browser that the input field is allowed to select more than one file at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*1DZd_4FOMSUSDk0MGQqApQ.png" /></figure><h3>Watching for changes and grabbing all them files</h3><p>Next up, we need to watch the file input for any changes. When we detect a change we then cache the file pointers in an array to be used when the form is submitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*NEO-ksAY07BumcrnMzu8HA.png" /><figcaption>Notice how the fileList array is reset inside the change handler. This is in case the user selects files more than once.</figcaption></figure><h3>Intercepting the form submit event</h3><p>So far, so good. Now we are going to hook into the form’s submit event to trigger our uploads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*MnFUKySTNPe1emWTdCR0RQ.png" /></figure><p>First we grab a reference to the form DOM element, here called <strong><em>“file-catcher”</em></strong>, and then we attach an event listener for the form’s <strong><em>“submit”</em></strong> event. Thereafter we prevent the form from actually submitting using the event’s <strong><em>preventDefault()</em></strong> method. Finally we iterate over the cached <strong><em>fileList</em></strong> array and send each file to the <strong><em>sendFile</em></strong><em> </em>method (see below).</p><h3>FormData and Ajax</h3><p>Ok, we’ve cached the files after the user has selected them. We’ve intercepted, and prevented, the form submission and piped the files through to the <strong><em>sendFile </em></strong>method. All we have to do now is actually write the <strong><em>sendFile </em></strong>method to accept the files and send them off to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Xqt7A3GmzmkcaRWxG6_EyQ.png" /></figure><p>This simple method does two things.</p><ol><li>Creates a <strong><em>formData </em></strong>instance and sets the file as a value on it</li><li>Creates a new <strong><em>XMLHttpRequest </em></strong>(<strong><em>Ajax</em></strong>), opens a connection to the server, and sends the <strong><em>formData </em></strong>instance</li></ol><p>And that’s it! We’ve sent multiple files, in parallel, to our server.</p><h3>Serial chunk vs. Parallel streams</h3><p>Now it should be noted that it isn’t necessary to unpack the files from the file input and send them off separately. You could skip the array iteration and multiple requests in favor of just sending the entire collection of files in a single request quite easily.</p><p>I, however, chose not to do that. One of the reasons was that our server was already setup to accept single file uploads (with metadata like Title, Caption, etc.) and to save our backend developer having the adapt the server code to accept multiple files, it made sense to update the UI codebase to send each file individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NSHJExZiZat3l42BCm7Fvw.jpeg" /></figure><p>Another reason was to fold the upload time over on itself, by leveraging the browser’s ability to handle multiple server connections simultaneously. Thereby allowing the files to stream in parallel.</p><p>And lastly, fault tolerance. By splitting the files into separate requests, this strategy allows for a file upload to fail in isolation. In other words, if the connection fails for the request, or the file is invalidated by the server, or any other reason, that file upload will fail by itself and should not necessarily affect any of the other uploads.</p><h3>Next steps</h3><p>This walkthrough of this strategy is intentionally simplistic in order to focus on the core mechanics and structures that make it work. It is in no way a fully fledged solution and would not be advisable to use it as is in a production environment.</p><p>What is missing here are things like:</p><ul><li>Form validation on submit to ensure that files have actually been selected</li><li>Request response handling to notify the user when a file is successfully upload, or if it fails</li><li>Initiate file uploads immediately after the user selects them. By doing this you could reduce the perceived upload time as the user spends time filling out any file related form fields.</li></ul><h3>The full example</h3><p>Here’s a JSFiddle that showcases this strategy as a whole. When running it I would suggest you have your browser tools open on the network tab, and inspect the request payload. You will see the file data in there!</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Ftr3aLa2r%2F5%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Ftr3aLa2r%2F5%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/268fe38858adc9285e9db6f4cccf6b86/href">https://medium.com/media/268fe38858adc9285e9db6f4cccf6b86/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb00a77e15f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/typecode/a-strategy-for-handling-multiple-file-uploads-using-javascript-eb00a77e15f">A strategy for handling multiple file uploads using JavaScript</a> was originally published in <a href="https://medium.com/typecode">Type/Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>