<?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 André Marques on Medium]]></title>
        <description><![CDATA[Stories by André Marques on Medium]]></description>
        <link>https://medium.com/@almarques?source=rss-4cbd5bf2a14f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PtqKRZc2AknikWJIamudjw.png</url>
            <title>Stories by André Marques on Medium</title>
            <link>https://medium.com/@almarques?source=rss-4cbd5bf2a14f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:48:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@almarques/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[Create TinyMCE Plugins with React, TypeScript, and Jest]]></title>
            <link>https://levelup.gitconnected.com/create-tinymce-plugins-with-react-typescript-jest-and-webpack-6edd19ac378f?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6edd19ac378f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[tinymce]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[editor]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 16:31:34 GMT</pubDate>
            <atom:updated>2026-11-21T16:36:58.310Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go beyond TinyMCE’s built-in UI components by rendering your own React app inside the editor.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekdpQI2sfaNTvf-XdxZW1Q.jpeg" /></figure><p><a href="https://www.tiny.cloud/">TinyMCE</a> is a WYSIWYG HTML editor you can add to personal and commercial websites for free. Its documentation is clear, and getting the editor into your app is easy.</p><p>Most of TinyMCE’s power comes from plugins. Some are built by the TinyMCE team and others by the community, and they come in two flavours: free and premium.</p><p>Plugins are great until you hit a wall: the free ones don’t quite do what you need, and the premium ones cost money you’d rather not spend. You want more complex logic in your editor and full control over how it looks. How do you get there?</p><h3>Starting point: the Yeoman generator</h3><p>TinyMCE provides a <a href="https://www.tiny.cloud/docs/advanced/yeoman-generator/">Yeoman generator</a> that scaffolds a new plugin project in a few seconds. Follow the docs and you’ll end up with a working template plugin.</p><p>The catch is that the generated plugin uses TinyMCE’s pre-built <a href="https://www.tiny.cloud/docs/ui-components">UI components</a>, so you’re limited to whatever TinyMCE offers. That’s rarely enough.</p><p>In this article I’ll show you how to render your own React components inside the plugin, with TypeScript for types and Jest for tests.</p><h3>How the pieces fit together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tON_fXZZeLdWJoquefWm5Q.png" /><figcaption>The plugin registers itself with TinyMCE and boots a React app once the editor loads.</figcaption></figure><p>The plugin entry point is Main.ts. It calls a function from Plugin.ts, which holds all the logic for the plugin. The generator has already registered the plugin with TinyMCE for you:</p><pre>tinymce.PluginManager.add(&#39;plugin-name&#39;, setup);</pre><p>The setup function is where you would normally wire up TinyMCE&#39;s built-in UI components. We won&#39;t do that. Instead, let&#39;s tweak the folder structure to make room for React. Under src, add an application folder:</p><pre>src<br>├── application<br>│   ├── components<br>│   └── App.tsx<br>├── Main.ts<br>└── Plugin.ts</pre><p>The application folder holds all of our React code, and App.tsx is where the magic happens.</p><h3>Rendering React inside the editor</h3><p>First, install React and its type definitions:</p><pre>yarn add react react-dom<br>yarn add -D @types/react @types/react-dom</pre><blockquote><em>If you want a custom TypeScript configuration, add a </em><em>tsconfig.json to the root of your project.</em></blockquote><p>Now create a setupReactApp function in App.tsx:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;react-dom&#39;;<br>import { Dropdown } from &#39;./components/dropdown&#39;;<br> <br>export const setupReactApp = (element: Element) =&gt; {<br>  render(<br>    &lt;Dropdown /&gt;,<br>    element.insertAdjacentElement(&#39;beforeend&#39;, document.createElement(&#39;div&#39;)),<br>  );<br>};</pre><p>It receives an HTML element and renders a React component inside it. Here the component is a simple dropdown, but it could be anything. The element can be any part of the editor.</p><blockquote><strong><em>Using React 18 or later?</em></strong><em> </em><em>render has been replaced by </em><em>createRoot: </em><em>createRoot(container).render(&lt;Dropdown /&gt;).</em></blockquote><p>Back in Plugin.ts, listen for the editor&#39;s load event. Once it fires, find the menu bar and mount the React app there:</p><pre>editor.on(&#39;load&#39;, () =&gt; {<br>  const menu = document.querySelector(&#39;.tox-menubar&#39;);<br>  setupReactApp(menu);<br>});</pre><p>And that’s it! You now have custom React components running inside TinyMCE. How easy is that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4RYR8aTNojvO0DmUHjZeQ.png" /><figcaption>A React dropdown rendered inside TinyMCE’s menu bar.</figcaption></figure><h3>Adding tests with Jest</h3><p>I’m a big fan of Jest: it’s simple to set up and fast to run. Install it along with ts-jest, which lets Jest understand TypeScript:</p><pre>yarn add -D jest ts-jest</pre><p>Then create a jest.config.js at the root of your project:</p><pre>module.exports = {<br>  roots: [&#39;&lt;rootDir&gt;/src&#39;],<br>  transform: {<br>    &#39;^.+\\.tsx?$&#39;: &#39;ts-jest&#39;,<br>  },<br>  testRegex: &#39;(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$&#39;,<br>  moduleFileExtensions: [&#39;ts&#39;, &#39;tsx&#39;, &#39;js&#39;, &#39;jsx&#39;, &#39;json&#39;, &#39;node&#39;],<br>};</pre><p>You can now add test files with a .spec or .test suffix, for example dropdown.spec.tsx.</p><h3>Bonus: replace Grunt with Webpack</h3><p>If you want more control over how your plugin and its modules are built, you can remove the logic from the generated Grunt file and bundle the project with Webpack instead, using a separate configuration for each environment.</p><h3>Try it yourself</h3><p>This article focused on setting up the project rather than on the component itself. If you want a complete working example, I’ve published a template on GitHub: <a href="https://github.com/thealmarques/tinymce-react-plugin">tinymce-react-plugin</a>.</p><p>To run it:</p><pre>yarn<br>yarn start</pre><p>Then open /demo/html/index.html with a local server, such as VS Code&#39;s Live Server extension.</p><p>Thanks for reading, and see you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6edd19ac378f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/create-tinymce-plugins-with-react-typescript-jest-and-webpack-6edd19ac378f">Create TinyMCE Plugins with React, TypeScript, and Jest</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement SVG Sprites in React]]></title>
            <link>https://medium.com/geekculture/how-to-implement-svg-sprites-in-react-14db2ca39595?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/14db2ca39595</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[sprite]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 14:25:14 GMT</pubDate>
            <atom:updated>2026-11-21T16:21:48.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop firing one HTTP request per icon. Put them all in a single sprite and render them with a tiny component.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7jlERVx_UYdhfWkKxloBA.jpeg" /></figure><p>You’ve probably written something like this more times than you can count:</p><pre>&lt;img src=&quot;@assets/cool-icon.svg&quot; /&gt;</pre><p>It’s simple and everyone does it. So what’s wrong with it?</p><p>Open the <strong>Network</strong> tab in your browser’s developer tools and you’ll see that every &lt;img&gt; tag sends its own HTTP request to fetch the image. Now picture a component that renders conditionally, makes a few calls to your backend, and contains a handful of icons. Every time it renders, each icon adds another request to the queue, and they&#39;re just icons.</p><p>I’m not saying you should stop using &lt;img&gt; tags. Just think twice about performance when your app loads a lot of icons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HhobXG6DY-5Li2Ev2jqcw.png" /><figcaption>Six &lt;img&gt; tags mean six requests. A sprite needs only one.</figcaption></figure><h3>What are inline SVGs?</h3><p>An inline SVG is an &lt;svg&gt; element placed directly in your markup, so it renders along with the page:</p><pre>&lt;svg width=&quot;100&quot; height=&quot;100&quot;&gt;<br>  &lt;circle cx=&quot;50&quot; cy=&quot;50&quot; r=&quot;40&quot; stroke=&quot;green&quot; stroke-width=&quot;4&quot; fill=&quot;yellow&quot; /&gt;<br>&lt;/svg&gt;</pre><p>You can also reference a shape defined in another file with the &lt;use&gt; element. Point it at the file and at the id of the shape you want:</p><pre>&lt;svg width=&quot;20&quot; viewBox=&quot;0 0 1000 500&quot; fill=&quot;white&quot;&gt;<br>  &lt;use href=&quot;/assets/icon.svg#icon&quot; /&gt;<br>&lt;/svg&gt;</pre><blockquote><strong><em>Note:</em></strong><em> most browsers need the </em><em>#id fragment, and the SVG file must be served from the same origin as your page.</em></blockquote><p>That’s already an improvement. But if you have 30 icons, do you really want to repeat this 30 times across your codebase? We can do better.</p><h3>Building an SVG sprite</h3><p>An SVG sprite is a single file that contains all of your icons. Each icon is wrapped in a &lt;symbol&gt; with a unique id:</p><pre>&lt;!-- icons.svg --&gt;<br>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; style=&quot;display: none;&quot;&gt;<br>  &lt;symbol id=&quot;icon-username&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>    &lt;path d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br> <br>  &lt;symbol id=&quot;icon-password&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>    &lt;path d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br>&lt;/svg&gt;</pre><p>The browser downloads this file once, caches it, and every icon on the page reads from it.</p><h3>A reusable Icon component</h3><p>Now create a React component that picks an icon from the sprite by its symbol id:</p><pre>import sprite from &#39;./assets/icons.svg&#39;;<br> <br>export const Icon = ({ name, color = &#39;currentColor&#39;, size = 24 }) =&gt; (<br>  &lt;svg width={size} height={size} fill={color} aria-hidden=&quot;true&quot;&gt;<br>    &lt;use href={`${sprite}#${name}`} /&gt;<br>  &lt;/svg&gt;<br>);</pre><p>Using it looks like this:</p><pre>&lt;Icon name=&quot;icon-username&quot; size={20} color=&quot;#2f4cf5&quot; /&gt;</pre><p>The component takes the icon’s id, a colour and a size, and renders the icon inline. All your icons now come from a single file that the browser downloads once. Simple and clean as it can be.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14db2ca39595" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-implement-svg-sprites-in-react-14db2ca39595">How to Implement SVG Sprites in React</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an Image Distortion Effect with Three.js, React, and GSAP]]></title>
            <link>https://levelup.gitconnected.com/create-distortion-effect-in-images-using-threejs-react-gsap-97ca92959351?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ca92959351</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Fri, 28 May 2021 09:27:28 GMT</pubDate>
            <atom:updated>2026-11-21T16:39:39.018Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step walkthrough of a shader-based image transition, with all the code included.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uhy7Xlsx3Bp5MR5bi4o4g.jpeg" /></figure><p>This was a tough article to write because I’m not an expert in this area. I still think it’s worth writing. Most of the Three.js image effects I find online never show the code, and they rarely mention that you need a bit of GLSL (the OpenGL Shading Language) to build them.</p><p>To be upfront: this project is an adaptation of an existing <a href="https://codepen.io/ashthornton/pen/KRQbMO">CodePen by Ash Thornton</a>, which I integrated into a React application. I’ll walk you through every step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*CKrbbqhWyZ35JFh4AiD1kw.gif" /><figcaption>The finished effect.</figcaption></figure><h3>App structure</h3><p>The React application has three components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjf1-aH5okN7fAxPRdL4NQ.png" /><figcaption>The app has three components. The Slider tells the Landing component which image to show.</figcaption></figure><ul><li>Header renders the header elements, and for this project that&#39;s all it does.</li><li>Slider receives the number of items to show, plus a callback that updates the selected image index in the parent.</li><li>Landing renders the Three.js scene. It turns every image into a texture and animates to the selected one whenever the Slider changes.</li></ul><p>This article is about Three.js and image animation, so I’ll focus on the Landing component. You can find the other components in the full source code.</p><h3>How the effect works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVaUZCTxXd420hKTAuAgKA.png" /><figcaption>Images become textures, a ShaderMaterial blends two of them, and GSAP animates the blend.</figcaption></figure><h4>Step 1: Collect the images</h4><p>Once the images are rendered (only one is visible at a time), we grab them from the DOM and pass them to our effect module. I’m using React hooks, so this happens in a useEffect:</p><pre>useEffect(() =&gt; {<br>  const parent = document.querySelector(&#39;.landing&#39;) as HTMLElement;<br>  const images = document.querySelectorAll(&#39;.landing__image&#39;);<br> <br>  if (parent &amp;&amp; images.length) {<br>    const effects = SliderEffect({<br>      parent,<br>      images: Array.from(images),<br>    });<br>    setEffects(effects);<br>  }<br>}, []);</pre><h4>Step 2: The effect module</h4><p>Here is the signature of SliderEffect. I&#39;ve written the types out in full to make it easier to follow:</p><pre>export const SliderEffect = (opts: {<br>  parent: HTMLElement;<br>  images: Element[];<br>}): {<br>  material: ShaderMaterial;<br>  images: Texture[];<br>} =&gt; { /* ... */ };</pre><p>It receives the parent element that will hold the Three.js canvas, along with the list of image elements. It returns a shader material and an array of textures, which the Landing component uses to run the animation.</p><h4>Step 3: Shaders</h4><p>The first thing SliderEffect does is define a vertex shader and a fragment shader for a ShaderMaterial.</p><p>A ShaderMaterial is a material rendered with your own shaders, written in GLSL (<a href="https://www.khronos.org/files/opengles_shading_language.pdf">reference manual</a>):</p><ul><li>The <strong>vertex shader</strong> positions and sizes the image.</li><li>The <strong>fragment shader</strong> creates the effect itself: the blurred distortion between two images.</li></ul><p>On the GPU, the fragment shader always runs after the vertex shader.</p><h4>Step 4: The renderer</h4><p>Next we create the canvas. Its size is the larger of the window and the image, so the full image is always visible. Then we create a WebGL renderer, set its background colour and size, and add its canvas to the DOM:</p><pre>const renderer = new THREE.WebGLRenderer({ antialias: false });<br> <br>renderer.setClearColor(0x23272a, 1.0);<br>renderer.setSize(renderWidth, renderHeight);<br>parent.appendChild(renderer.domElement);</pre><h4>Step 5: Textures</h4><p>Every image becomes a texture:</p><pre>const loader = new THREE.TextureLoader();<br>const sliderImages: Texture[] = [];<br> <br>images.forEach((img) =&gt; {<br>  const texture = loader.load(img.getAttribute(&#39;src&#39;) + &#39;?v=&#39; + Date.now());<br>  texture.magFilter = texture.minFilter = THREE.LinearFilter;<br>  texture.anisotropy = renderer.capabilities.getMaxAnisotropy();<br>  sliderImages.push(texture);<br>});</pre><p>LinearFilter controls how the texture&#39;s pixels are sampled when the texture is scaled or distorted, which keeps the effect smooth.</p><h4>Step 6: Scene, camera, and material</h4><p>Finally, we create the scene, an orthographic camera, and the shader material. The material receives the current image, the next image, and a dispFactor uniform that controls how far the transition has progressed:</p><pre>const scene = new THREE.Scene();<br>scene.background = new THREE.Color(0x23272a);<br> <br>const camera = new THREE.OrthographicCamera(<br>  renderWidth / -2,<br>  renderWidth / 2,<br>  renderHeight / 2,<br>  renderHeight / -2,<br>  1,<br>  1000,<br>);<br>camera.position.z = 2;<br> <br>const material = new THREE.ShaderMaterial({<br>  uniforms: {<br>    dispFactor: { value: 0.0 },<br>    currentImage: { value: sliderImages[0] },<br>    nextImage: { value: sliderImages[1] },<br>  },<br>  vertexShader: vertex,<br>  fragmentShader: fragment,<br>  transparent: true,<br>  opacity: 1.0,<br>});<br> <br>const geometry = new THREE.PlaneGeometry(parent.offsetWidth, parent.offsetHeight, 1);<br>const mesh = new THREE.Mesh(geometry, material);<br>mesh.position.set(0, 0, 0);<br>scene.add(mesh);</pre><blockquote><em>In older versions of Three.js this was called </em><em>PlaneBufferGeometry. It has since been renamed to </em><em>PlaneGeometry.</em></blockquote><h3>Animating the transition</h3><p>Back in the Landing component, another useEffect watches the selected item. When the user clicks the slider, we set the next image and use GSAP to animate dispFactor from 0 to 1. When the animation finishes, the new image becomes the current one and dispFactor resets to 0:</p><pre>effects.material.uniforms.nextImage.value = effects.images[item];<br> <br>gsap.to(effects.material.uniforms.dispFactor, {<br>  value: 1,<br>  duration: 1,<br>  ease: &#39;expo.out&#39;,<br>  onComplete: () =&gt; {<br>    effects.material.uniforms.currentImage.value = effects.images[item];<br>    effects.material.uniforms.dispFactor.value = 0.0;<br>  },<br>});</pre><p>As dispFactor moves from 0 to 1, the fragment shader blends from the current image to the next one, creating the distortion you see in the demo.</p><blockquote><em>The original project used </em><em>TweenLite, which is now part of the main </em><em>gsap package as </em><em>gsap.to.</em></blockquote><p>I also added a CSS keyframe animation to the text elements. The original CodePen used TweenLite for this.</p><h3>Source code</h3><p>The full project is on GitHub: <a href="https://github.com/thealmarques/react-threejs-distorion-effect">react-threejs-distortion-effect</a>.</p><p>I hope you enjoyed it. See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ca92959351" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/create-distortion-effect-in-images-using-threejs-react-gsap-97ca92959351">Create an Image Distortion Effect with Three.js, React, and GSAP</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure HTTPS on AWS EC2 for Free Using Cloudflare]]></title>
            <link>https://medium.com/geekculture/configure-https-on-aws-ec2-for-free-using-cloudflare-e7120e9a6856?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7120e9a6856</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 03:03:58 GMT</pubDate>
            <atom:updated>2026-11-21T16:24:06.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Set Up Free HTTPS on AWS EC2 with Cloudflare</h3><h4>Put your EC2 backend behind Cloudflare and NGINX to get a free SSL certificate in a few minutes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF-V7RlOMbPv_O4uPGi1Zg.jpeg" /></figure><p>In this article I’ll show you how to serve an application hosted on AWS EC2 (or any other server) over HTTPS, for free.</p><h3>The problem</h3><p>I once built a web app with a React frontend and a Go backend. When it was time to deploy, I put the React app on Netlify, which is a great tool. To my surprise, it came with an SSL certificate out of the box.</p><p>For the Go backend, I tried the AWS EC2 free tier. What I hadn’t thought through was that my EC2 machine had no SSL certificate. A page loaded over HTTPS can’t make requests to an insecure HTTP server, because browsers block that as mixed content. So my frontend couldn’t reach my backend.</p><p>A quick search points you to Let’s Encrypt, a great certificate authority that issues certificates for free. There’s a catch, though. Let’s Encrypt won’t issue certificates for the default *.amazonaws.com hostnames that EC2 gives you, so you need your own domain either way.</p><h3>The solution at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILYMTGidHRWqMw9oIAtxjg.png" /><figcaption>Cloudflare handles the public certificate. NGINX on EC2 receives the traffic and forwards it to your app.</figcaption></figure><p>You need three things:</p><ol><li>A domain name.</li><li>A free Cloudflare account.</li><li>NGINX installed on your EC2 machine.</li></ol><h3>Part 1: Cloudflare</h3><p>Cloudflare offers a free SSL certificate and DDoS protection. You might wonder why they give it away. The more traffic flows through their network, the better they get at telling good traffic from bad, so everybody wins.</p><p>First, get a domain. Back when I wrote this I used a free .tk domain from Freenom, but Freenom no longer offers free domains, so you&#39;ll need a cheap one from any registrar.</p><p>Next, create a Cloudflare account and add your domain. You’ll land on the DNS screen, where you map your domain to your EC2 instance’s public hostname (or IP address). Make sure the record is <strong>proxied</strong> (orange cloud), so traffic goes through Cloudflare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbe1la2mcWZL6NdItV7NGQ.png" /><figcaption>A proxied CNAME record pointing to your EC2 instance.</figcaption></figure><p>Then, in your registrar’s dashboard, replace your domain’s name servers with the two that Cloudflare assigns you. They look like this:</p><pre>kinsley.ns.cloudflare.com<br>matteo.ns.cloudflare.com</pre><p>Name server changes can take up to 24 hours to propagate.</p><p>From now on, every request to your domain goes through Cloudflare and gets a free HTTPS certificate automatically. Requests then reach your EC2 machine, but nothing answers yet because there’s no web server listening. Let’s fix that.</p><h3>Part 2: NGINX</h3><p>The installation steps depend on the Amazon Machine Image (AMI) you picked. Log in to your EC2 instance and check which Linux distribution it runs:</p><pre>cat /etc/os-release</pre><p>In my case it was CentOS. The <a href="https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/">NGINX documentation</a> has instructions for every distribution. These are the commands I used:</p><pre># Add the official NGINX repository<br>sudo vi /etc/yum.repos.d/nginx.repo</pre><pre>[nginx]<br>name=nginx repo<br>baseurl=https://nginx.org/packages/mainline/&lt;OS&gt;/&lt;OSRELEASE&gt;/$basearch/<br>gpgcheck=0<br>enabled=1</pre><pre>sudo yum update<br>sudo yum install nginx<br>sudo service nginx start</pre><p>If you now open your domain over HTTP, you’ll see the default NGINX welcome page. We want HTTPS, though, so let’s configure it.</p><h4>Create a certificate for NGINX</h4><p>Cloudflare needs to talk to your server over HTTPS too. For that connection, a self-signed certificate is enough. Create one with OpenSSL:</p><pre>sudo mkdir -p /etc/ssl/private<br>sudo chmod 700 /etc/ssl/private<br>sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \<br>  -keyout /etc/ssl/private/nginx-selfsigned.key \<br>  -out /etc/ssl/certs/nginx-selfsigned.crt</pre><p>OpenSSL will ask you a few questions. You can press Enter to accept the defaults.</p><blockquote><strong><em>Tip:</em></strong><em> Cloudflare can also generate a free </em><strong><em>Origin Certificate</em></strong><em> for you (SSL/TLS → Origin Server). It’s valid for up to 15 years and works with the stricter “Full (strict)” mode.</em></blockquote><h4>Configure the reverse proxy</h4><p>Edit the NGINX configuration:</p><pre>sudo vi /etc/nginx/conf.d/default.conf</pre><p>And add:</p><pre>upstream backend {<br>  server 127.0.0.1:9000;<br>}<br> <br>server {<br>  listen 443 ssl default_server;<br>  listen [::]:443 ssl default_server;<br> <br>  server_name your-domain.com;<br> <br>  ssl_certificate     /etc/ssl/certs/nginx-selfsigned.crt;<br>  ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;<br> <br>  location / {<br>    proxy_pass http://backend;<br> <br>    # Needed if your app uses WebSockets<br>    proxy_http_version 1.1;<br>    proxy_set_header Upgrade $http_upgrade;<br>    proxy_set_header Connection &quot;upgrade&quot;;<br> <br>    proxy_set_header Host            $host;<br>    proxy_set_header X-Real-IP       $remote_addr;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br> <br>    # Keeps long-lived WebSocket connections open<br>    proxy_read_timeout 600s;<br>  }<br>}</pre><p>NGINX now accepts requests on port 443 and forwards them to your app on port 9000, which is where my Go server was listening. Reload NGINX to apply the changes:</p><pre>sudo nginx -t &amp;&amp; sudo service nginx reload</pre><h4>Set Cloudflare’s SSL mode</h4><p>In the Cloudflare dashboard, go to <strong>SSL/TLS</strong> and set the encryption mode to <strong>Full</strong>. This tells Cloudflare to connect to your server over HTTPS and to accept the self-signed certificate. If you’re using a Cloudflare Origin Certificate, choose <strong>Full (strict)</strong> instead.</p><p>Also make sure your EC2 security group allows inbound traffic on port 443.</p><h3>Done</h3><p>Open your domain over HTTPS and your requests will reach your backend on port 9000. Simple and secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7120e9a6856" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/configure-https-on-aws-ec2-for-free-using-cloudflare-e7120e9a6856">Configure HTTPS on AWS EC2 for Free Using Cloudflare</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Concurrency in Gorilla Web Sockets]]></title>
            <link>https://medium.com/swlh/handle-concurrency-in-gorilla-web-sockets-ade4d06acd9c?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade4d06acd9c</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gorilla]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 08:12:51 GMT</pubDate>
            <atom:updated>2026-11-21T16:26:19.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handle Concurrent Writes in Gorilla WebSocket</h3><h4>Gorilla connections allow only one writer at a time, and a small mutex wrapper keeps your Go server from panicking.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0Fzb5d5cAH_VKCKQ7Q7sA.jpeg" /></figure><p>When people want WebSockets up and running quickly, they usually reach for Socket.IO. But there are other options. In this post I’ll talk about one I came across during a personal project: <a href="https://github.com/gorilla/websocket">Gorilla WebSocket</a> for Go.</p><h3>Why Gorilla?</h3><p>I was building a web application and needed WebSockets in my infrastructure. It was a personal project and I had some time, so I wanted to learn something new instead of using Socket.IO again. I was learning Go at the time, so it was the perfect moment to try WebSockets with it. Gorilla handled everything I needed: managing connections and broadcasting messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Rjf-0Rja-FncJaw_nR7iQ.png" /><figcaption>Clients connect to the server over WebSockets, and the server broadcasts messages to all of them.</figcaption></figure><h3>Accepting connections</h3><p>If you use an HTTP framework, start by exposing a WebSocket endpoint and pointing it at a handler. I was using <a href="https://github.com/gin-gonic/gin">Gin</a>:</p><pre>router.GET(&quot;/ws&quot;, func(c *gin.Context) {<br>	wshandler(c.Writer, c.Request)<br>})</pre><p>The handler upgrades the HTTP request to a WebSocket and stores the connection so we can send messages to it later. Each connection is keyed by an ID, usually the user’s ID, and a map is the natural structure for that:</p><pre>var sockets = make(map[string]*Connection)</pre><p>The handler looks like this:</p><pre>var upgrader = websocket.Upgrader{<br>	// Accepts every origin. Restrict this in production.<br>	CheckOrigin: func(r *http.Request) bool { return true },<br>}<br> <br>func wshandler(w http.ResponseWriter, r *http.Request) {<br>	conn, err := upgrader.Upgrade(w, r, nil)<br>	if err != nil {<br>		return<br>	}<br>	defer conn.Close()<br> <br>	var message Message<br>	if err := conn.ReadJSON(&amp;message); err != nil {<br>		return<br>	}<br> <br>	if sockets[message.UserID] == nil {<br>		sockets[message.UserID] = &amp;Connection{Socket: conn}<br>	}<br> <br>	// Keep reading until the client disconnects; returning closes the connection.<br>	for {<br>		if err := conn.ReadJSON(&amp;message); err != nil {<br>			delete(sockets, message.UserID)<br>			return<br>		}<br>		// handle the incoming message...<br>	}<br>}</pre><h3>The problem: concurrent writes</h3><p>Gorilla’s <a href="https://pkg.go.dev/github.com/gorilla/websocket#hdr-Concurrency">documentation</a> is very clear about this: a connection supports <strong>one concurrent reader and one concurrent writer</strong>. If two goroutines call WriteJSON on the same connection at the same time, your server will panic with concurrent write to websocket connection.</p><p>In a real app this happens all the time, because one broadcast is often still running when another event triggers the next.</p><h3>The fix: wrap the connection with a mutex</h3><p>Instead of storing the raw *websocket.Conn, store a small struct that pairs it with a sync.Mutex. Every write locks the mutex first, so only one goroutine can write at a time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHz_TAp39JFXpta8kmNL9g.png" /><figcaption>Every goroutine goes through Send(), and the mutex lets one write through at a time.</figcaption></figure><pre>// Connection wraps a WebSocket connection so it can be written to safely.<br>type Connection struct {<br>	Socket *websocket.Conn<br>	mu     sync.Mutex<br>}<br> <br>// Send writes a message, waiting for any in-flight write to finish first.<br>func (c *Connection) Send(message Message) error {<br>	c.mu.Lock()<br>	defer c.mu.Unlock()<br>	return c.Socket.WriteJSON(message)<br>}</pre><p>From now on, never call WriteJSON directly. Always go through Send:</p><pre>for id, connection := range sockets {<br>	if err := connection.Send(message); err != nil {<br>		delete(sockets, id)<br>	}<br>}</pre><h3>One more thing: protect the map too</h3><p>The sockets map has the same problem. Go maps aren&#39;t safe for concurrent use, and different handlers read and write it at the same time. Guard it with a sync.RWMutex, or use sync.Map:</p><pre>var (<br>	sockets   = make(map[string]*Connection)<br>	socketsMu sync.RWMutex<br>)<br> <br>// When adding or removing a connection<br>socketsMu.Lock()<br>sockets[id] = conn<br>socketsMu.Unlock()<br> <br>// When broadcasting<br>socketsMu.RLock()<br>for _, c := range sockets {<br>	c.Send(message)<br>}<br>socketsMu.RUnlock()</pre><p>And that’s it. Your Gorilla server now handles concurrent writes safely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade4d06acd9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/handle-concurrency-in-gorilla-web-sockets-ade4d06acd9c">Handle Concurrency in Gorilla Web Sockets</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Dynamic Multi-Peer Connections in WebRTC]]></title>
            <link>https://medium.com/swlh/manage-dynamic-multi-peer-connections-in-webrtc-3ff4e10f75b7?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff4e10f75b7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[video-chat]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Mon, 26 Oct 2020 11:10:41 GMT</pubDate>
            <atom:updated>2026-11-21T16:35:10.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most WebRTC examples connect exactly two people. This one works for any number of users joining and leaving.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gT8TNBvP7MQ08q0EgVABdw.jpeg" /></figure><p>If you’re reading this, you’re probably building a video conferencing or chat app. Welcome to the club! I’ve been there too. When I started looking at examples, I noticed that most of them only supported a fixed number of peers, usually two. In this post I’ll show you how to handle a dynamic number of peers with WebRTC.</p><h3>What is WebRTC?</h3><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API">MDN</a>:</p><blockquote><strong><em>WebRTC</em></strong><em> (Web Real-Time Communication) is a technology that enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary.</em></blockquote><p>That last part, <em>“without requiring an intermediary”</em>, is only half true, and most tutorials skip over it. The media can flow directly between browsers, but to get there you need help from a few servers.</p><h3>STUN, TURN, and NAT</h3><p>Most devices sit behind a NAT or a firewall, so they don’t know their own public address. Before two browsers can talk directly, each one has to find out how the outside world sees it. That’s what a <strong>STUN server</strong> is for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlPXDbQiF8nt1NwOVp-Gnw.png" /><figcaption>A STUN server tells the browser what its public IP address and port look like from the outside.</figcaption></figure><p>There are plenty of free public STUN servers (<a href="https://gist.github.com/zziuni/3741933">here’s a list</a>).</p><p>Sometimes a direct connection simply isn’t possible, for example when both peers are behind strict (symmetric) NATs. In that case the media has to be relayed through a <strong>TURN</strong> server (Traversal Using Relays around NAT). TURN servers aren’t free to run, because all the traffic passes through them, but they make sure the call works on any network.</p><h3>How a WebRTC connection is set up</h3><p>The connection process works like this:</p><ul><li>Each peer describes its media (audio and video codecs, formats, and so on) using the <strong>Session Description Protocol (SDP)</strong>.</li><li>One peer sends an <strong>offer</strong>, and the other replies with an <strong>answer</strong>.</li><li>Both peers then exchange network candidates, meaning the addresses where they might be reachable, using the <a href="https://datatracker.ietf.org/doc/html/rfc8445">ICE protocol</a>.</li></ul><p>WebRTC doesn’t say how offers, answers, and candidates should travel between peers. That’s your job, and the channel you use for it is called <strong>signaling</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yA3G-KwSDJVJGSu1fbyLfA.png" /><figcaption>The full exchange: STUN and TURN lookups, then offer, answer, and ICE candidates through the signaling server.</figcaption></figure><h3>Building it</h3><p>Because a demo is worth a thousand words, let’s build a working example where every user shares audio and video with everyone else.</p><p>We need two things: WebRTC, and a messaging service for signaling. Signaling messages represent what each user wants to do: join, call, offer, answer.</p><h4>Signaling</h4><p>The messaging service can be anything: Socket.IO, Gorilla WebSocket, Firebase, and so on. I’ll wrap it in a small SocketCommunication class (its implementation doesn&#39;t matter for this post).</p><pre>const socket = new SocketCommunication(&#39;wss://your-signaling-server&#39;);</pre><h4>Local media</h4><p>When a user joins, the browser asks for permission to use the camera and microphone. The result is a MediaStream containing one track for audio and one for video:</p><pre>const localStream = await navigator.mediaDevices.getUserMedia({<br>  audio: true,<br>  video: true,<br>});</pre><h4>Joining the room</h4><p>Imagine three users joining, each with a unique ID.</p><p>The first user sends a connect event and the signaling server replies with session_joined. The user then sends start_call, but nobody receives it because they&#39;re alone in the room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB3EgscyO6whEQU7cs2n7w.png" /><figcaption>The first user joins and announces that they want to start a call.</figcaption></figure><h4>Making the offer</h4><p>Now the second user joins and also sends start_call. This time the first user receives it.</p><p>The first user creates an RTCPeerConnection dedicated to the second user and adds their local tracks to it:</p><pre>const peerConnection = new RTCPeerConnection({<br>  iceServers: [{ urls: &#39;stun:stun.l.google.com:19302&#39; }],<br>});<br> <br>localStream.getTracks().forEach((track) =&gt; {<br>  peerConnection.addTrack(track, localStream);<br>});</pre><p>Then they create an offer, set it as their local description, and send it to the second user through the signaling server:</p><pre>const offer = await peerConnection.createOffer();<br>await peerConnection.setLocalDescription(offer);<br>socket.send(&#39;offer&#39;, offer, fromUserId, toUserId);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Su-AqI0AbLjpNm-sfE2Wiw.png" /><figcaption>start_call triggers an offer, and the offer is answered, all through the signaling server.</figcaption></figure><h4>Answering</h4><p>When the second user receives the offer, they do the same thing: create an RTCPeerConnection for the first user and add their local tracks. Then they set the offer as the <strong>remote</strong> description, create an answer, set it as the <strong>local</strong> description, and send it back:</p><pre>await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));<br> <br>const answer = await peerConnection.createAnswer();<br>await peerConnection.setLocalDescription(answer);<br>socket.send(&#39;answer&#39;, answer, fromUserId, toUserId);</pre><p>When the first user receives the answer, they set it as the remote description:</p><pre>await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));</pre><h4>Exchanging ICE candidates and receiving media</h4><p>Both sides also need to share their ICE candidates and listen for the other person’s tracks:</p><pre>peerConnection.onicecandidate = ({ candidate }) =&gt; {<br>  if (candidate) socket.send(&#39;candidate&#39;, candidate, fromUserId, toUserId);<br>};<br> <br>// When a candidate arrives from the other peer<br>await peerConnection.addIceCandidate(candidate);<br> <br>peerConnection.ontrack = ({ streams }) =&gt; {<br>  remoteVideoElement.srcObject = streams[0];<br>};</pre><h3>Scaling to any number of users</h3><p>What makes this work for any number of people is that each user keeps one RTCPeerConnection per remote user, stored in a map keyed by user ID. Nothing in the logic above assumes there are only two people.</p><p>When a third user joins and sends start_call, the two users already in the room each send them an offer. The new user answers both. A fourth user gets three offers, and so on. When someone leaves, close their connection and remove it from the map.</p><blockquote><em>This “full mesh” setup works well for small groups. Every user uploads their stream once for each other user, so beyond 5 or 6 people you’ll want a media server (an SFU) instead.</em></blockquote><h3>Muting audio or video</h3><p>Since every peer connection shares the same local tracks, toggling a track updates every connection at once:</p><pre>localStream.getTracks().forEach((track) =&gt; {<br>  if (track.kind === &#39;video&#39;) {<br>    track.enabled = !track.enabled;<br>  }<br>});</pre><p>Disabling a track makes it send black frames (for video) or silence (for audio) to everyone, with no renegotiation needed.</p><p>And that’s it! I hope this was helpful for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff4e10f75b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/manage-dynamic-multi-peer-connections-in-webrtc-3ff4e10f75b7">Manage Dynamic Multi-Peer Connections in WebRTC</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a real-time collaborative plugin in TinyMCE]]></title>
            <link>https://almarques.medium.com/how-to-build-a-real-time-collaborative-plugin-in-tinymce-8e748e10a87a?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e748e10a87a</guid>
            <category><![CDATA[tinymce]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 20:05:14 GMT</pubDate>
            <atom:updated>2026-11-21T16:28:20.678Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Real-Time Collaborative Plugin for TinyMCE</h3><h4>How I built a free alternative to TinyMCE’s paid collaboration plugin with Socket.IO.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QlgA9NBGdzf8puhxGD4eg.jpeg" /></figure><h3>Introduction</h3><p>Like many developers, I had a project idea I wanted to build. When I finally found the time to research the technology, I hit a problem: I needed a good-looking text editor that let several people edit at the same time.</p><p>I quickly found <a href="https://www.tiny.cloud/">TinyMCE</a>. To be honest, it was the first result, but it’s popular for good reason. This WYSIWYG editor has plenty of free plugins, but none of them supported collaborative editing. The one I did find cost more than $10 a month.</p><p>So I had a new project idea: build a free collaborative plugin for TinyMCE.</p><h3>Creating a plugin</h3><p>TinyMCE’s documentation is good, though a bit confusing in places, and getting a sample plugin running is quick. The Yeoman generator creates a project that you can start testing and publishing right away:</p><pre>npm install --global yo generator-tinymce<br>yo tinymce</pre><p>Then start the project:</p><pre>npm start</pre><p>I recommend opening the demo HTML file with VS Code’s Live Server extension, so your changes reload automatically.</p><h3>The big picture</h3><p>Now for the fun part: what does it take to build a collaborative plugin?</p><p>We need to connect several clients, each running its own TinyMCE editor, to a server. Every client sends events to the server when something happens:</p><ul><li>A client opens the editor.</li><li>A client moves the cursor.</li><li>A client selects text.</li><li>A client types something.</li></ul><p>The server then broadcasts each event to every other connected client.</p><p>Some of you are already thinking of Socket.IO, and you’re right, that’s what I used. Alternatives such as SignalR, SocketCluster, or Firebase would work too.</p><h3>The client: the TinyMCE plugin</h3><p>With the sample plugin in place, let’s add our own logic. In demo.js, add a configuration object for the plugin to the TinyMCE init call. Let&#39;s call our plugin <strong>budwriter</strong>:</p><pre>tinymce.init({<br>  selector: &#39;textarea.tinymce_1&#39;,<br>  plugins: &#39;code budwriter&#39;,<br>  toolbar: &#39;budwriter&#39;,<br>  height: 600,<br>  branding: false,<br>  budwriter: {<br>    name: &#39;André&#39;,<br>    photoUrl: &#39;https://example.com/avatar.png&#39;,<br>    key: &#39;free4all&#39;,<br>    socketUrl: &#39;http://localhost:3000&#39;,<br>  },<br>});</pre><p>The most important property is socketUrl, the address of our Socket.IO server. The others describe the current user.</p><p>Now create a file in the core folder for our collaboration class. It connects to the Socket.IO server and listens for these events:</p><ul><li>update_clients: another client has connected.</li><li>update_cursor: a client moved their cursor.</li><li>update_selection: a client changed their selection.</li><li>update_content: a client changed the content.</li><li>delete_client: a client disconnected, so remove their cursor from the editor.</li></ul><pre>io: SocketIOClientStatic;<br>ioClient: SocketIOClient.Socket;<br> <br>this.ioClient = this.io.connect(user.socketUrl, {<br>  query: `name=${user.name}&amp;photoUrl=${user.photoUrl}`,<br>});<br> <br>this.ioClient.on(&#39;update_clients&#39;, (users: User[]) =&gt; { /* ... */ });<br>this.ioClient.on(&#39;delete_client&#39;, (user: User) =&gt; { /* ... */ });<br>this.ioClient.on(&#39;update_cursor&#39;, (data: string) =&gt; { /* ... */ });<br>this.ioClient.on(&#39;update_selection&#39;, (data: string) =&gt; { /* ... */ });<br>this.ioClient.on(&#39;update_content&#39;, (content: string) =&gt; { /* ... */ });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfZv_qMwcBILKDfH78UKvw.png" /><figcaption>Every client reports what it’s doing to the server.</figcaption></figure><p>Each client sends events whenever its editor changes. Drawing the other users’ cursors and selections is mostly about the browser’s Range and Selection APIs, which I covered in <a href="https://medium.com/@almarques/cursors-and-selections-how-do-they-work-in-modern-browsers-5c132029b044">a separate article</a>.</p><blockquote><strong><em>Note:</em></strong><em> the Socket.IO client is distributed as a Node.js module that relies on </em><em>require. To use it in the browser, I added a </em><a href="https://browserify.org/"><em>Browserify</em></a><em> step to the Grunt build to bundle it.</em></blockquote><h3>The server</h3><p>The server is a small Node.js project with Socket.IO installed. It listens for events from the clients and passes them on to everyone else:</p><pre>io.on(&#39;connection&#39;, (socket: Socket) =&gt; {<br>  io.emit(&#39;update_clients&#39;, listOfUsers);<br> <br>  socket.on(&#39;disconnect&#39;, () =&gt; {<br>    io.emit(&#39;delete_client&#39;, deletedClient);<br>  });<br> <br>  // TinyMCE client events<br>  socket.on(&#39;set_cursor&#39;, (message: string) =&gt; {<br>    socket.broadcast.emit(&#39;update_cursor&#39;, message);<br>  });<br> <br>  socket.on(&#39;set_selection&#39;, (message: string) =&gt; {<br>    socket.broadcast.emit(&#39;update_selection&#39;, message);<br>  });<br> <br>  socket.on(&#39;set_content&#39;, (message: string) =&gt; {<br>    socket.broadcast.emit(&#39;update_content&#39;, message);<br>  });<br>});</pre><p>socket.broadcast.emit sends the event to every client except the one that sent it, so nobody receives their own changes back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2oa8U49LObWQrGuQfpUmQ.png" /><figcaption>The server broadcasts each change, so every editor stays in sync.</figcaption></figure><h3>Limitations</h3><p>This approach sends the whole document on every change, and the last write wins. It works well for a handful of users. If you need real conflict resolution, look at CRDT libraries such as <a href="https://yjs.dev/">Yjs</a>.</p><h3>Demo and code</h3><p>You can try it on <a href="https://codepen.io/thealmarques/pen/YzqOrWV">CodePen</a>, and the source code is on GitHub: <a href="https://github.com/thealmarques/tinymce-collaborative-editing-plugin">tinymce-collaborative-editing-plugin</a>.</p><p>Hope you enjoyed it, and see you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e748e10a87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cursors and selections. How do they work in modern Browsers?]]></title>
            <link>https://almarques.medium.com/cursors-and-selections-how-do-they-work-in-modern-browsers-5c132029b044?source=rss-4cbd5bf2a14f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c132029b044</guid>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[highlights]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[André Marques]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 11:32:27 GMT</pubDate>
            <atom:updated>2026-11-21T16:20:07.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Cursors and Selections Work in the Browser</h3><h4>A short guide to the Selection and Range APIs, and how to find exactly where the cursor is on screen.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCmUdhZDaERt_z9SgvXODw.jpeg" /></figure><h3>Introduction</h3><p>If you found this post, you probably want to work with cursor positions or text selections. Maybe you want to draw an extra cursor, or highlight text after the user selects it. The possibilities are endless (well, almost).</p><p>Every modern browser supports these APIs, so compatibility isn’t something you need to worry about.</p><h3>Selection vs. Range</h3><p>The cursor is the small blinking bar you see when typing in a text field. To the browser, though, that cursor is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Selection">Selection</a>. Everything is a selection, even a single blinking caret.</p><p>A selection is either a Caret or a Range. A caret is a collapsed selection: its start and end are the same point, so all you see is the blinking cursor. A range spans some content, so its start and end are different.</p><p>The start of a selection is called the <strong>anchor</strong> (where the user started selecting) and the end is called the <strong>focus</strong> (where they stopped).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Kswaw_r4Sdhtybi0C-5HA.png" /><figcaption>A caret is a collapsed selection. A range has its anchor and focus at different positions.</figcaption></figure><p>Each selection contains a list of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Range">Range</a> objects. In practice there’s only ever one, except in Firefox, which supports multiple ranges.</p><h3>Reading the current selection</h3><p>You can get the selection from either window or document:</p><pre>const selection = document.getSelection();</pre><p>The returned object tells you the selection’s type, its anchorNode and focusNode, their offsets, and how many ranges it contains (rangeCount).</p><h3>Finding the cursor’s position on screen</h3><p>Say the user is editing some text and you want to know exactly where the caret or selection is on screen. For example, you might want to show a tooltip next to it. Get the first range of the selection and ask for its bounding box:</p><pre>const selection = document.getSelection();<br> <br>if (selection &amp;&amp; selection.rangeCount &gt; 0) {<br>  const range = selection.getRangeAt(0);<br>  const rect = range.getBoundingClientRect();<br> <br>  console.log(rect.top, rect.left, rect.width, rect.height);<br>}</pre><p>For a caret, rect.width is 0 and rect.left is the cursor&#39;s horizontal position. From there you can position anything you like relative to it.</p><h3>Creating your own range</h3><p>You can also build a range yourself. That’s handy for highlighting part of a text node, or for measuring where a given character sits on screen:</p><pre>const textNode = element.firstChild;<br> <br>const range = document.createRange();<br>range.setStart(textNode, 10); // start offset<br>range.setEnd(textNode, 15);   // end offset<br> <br>const rect = range.getBoundingClientRect();</pre><p>To make it the user’s actual selection:</p><pre>const selection = document.getSelection();<br>selection.removeAllRanges();<br>selection.addRange(range);</pre><blockquote><strong><em>Inputs and textareas are different.</em></strong><em> Their text isn’t part of the DOM tree, so ranges can’t reach inside them. Use </em><em>input.selectionStart and </em><em>input.selectionEnd to read the cursor position, and </em><em>input.setSelectionRange(start, end) to change it.</em></blockquote><h3>Bonus: selections that span several elements</h3><p>What if the user selects across several HTML elements, like the end of one paragraph and the start of the next? The selection’s type is now Range, and a single bounding box isn&#39;t very precise because it covers everything in between.</p><p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Range/getClientRects">Range.getClientRects()</a> instead. It returns one rectangle per line box, which is exactly what you need to draw a custom highlight:</p><pre>const rects = document.getSelection().getRangeAt(0).getClientRects();<br> <br>for (const rect of rects) {<br>  // draw a highlight for each line<br>}</pre><p>And that’s it. Hope you enjoyed it, and see you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c132029b044" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>