<?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 AlexF on Medium]]></title>
        <description><![CDATA[Stories by AlexF on Medium]]></description>
        <link>https://medium.com/@fraiha26?source=rss-f63694777701------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EyzlkYTLfi2IGinDmBkkAg.jpeg</url>
            <title>Stories by AlexF on Medium</title>
            <link>https://medium.com/@fraiha26?source=rss-f63694777701------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:52:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fraiha26/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[Creating custom Tab Bars with LiveView Native and Swift]]></title>
            <link>https://medium.com/@fraiha26/creating-custom-tab-bars-with-liveview-native-and-swift-e90dcff14da1?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90dcff14da1</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 22:32:10 GMT</pubDate>
            <atom:updated>2025-06-06T22:32:10.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1GcDcz0jm72XvpLlHAwKw.png" /></figure><p>In this article, I’ll share my approach to creating a custom tab bar leveraging out-of-the-box LiveView Native (LVN) components and custom Swift Views.</p><p>We are going to turn the LVN TabBar core component into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*GLBfy0906qa89GknApINaQ.png" /></figure><p>In LVN, you’re provided a stock Tab Bar component that you can customize using inline Swift classes. Though, I needed a fully customizable tab bar that I could pass data to populate a user’s avatar image or add badges for activity notifications, for example.</p><p><strong>Let’s get started:</strong></p><ul><li>First, I created a wrapper around the stock Tab Bar component and passed it the arguments needed:</li></ul><pre>//<br>//  TabBarCoordinator.swift<br>//<br><br>import SwiftUI<br>import LiveViewNative // Imports LiveViewNative for integrating with Phoenix LiveView.<br>import LiveViewNativeCore // Imports core components for LiveViewNative.<br>// MARK: - TabItem Enum<br>// This enum defines the different tabs in the application.<br>enum TabItem: Int, CaseIterable {<br>    case home = 0<br>    case search = 1<br>    case add = 2<br>    case favorites = 3<br>    case profile = 4<br>    // Returns the appropriate SF Symbol or custom image name based on the tab and its selection state.<br>    func iconName(isSelected: Bool) -&gt; String {<br>        switch self {<br>        case .home:<br>            return isSelected ? &quot;house-fill-custom&quot; : &quot;house-custom&quot; // Custom icons for home.<br>        case .search:<br>            return isSelected ? &quot;magnifyingglass&quot; : &quot;magnifyingglass&quot; // SF Symbol for search.<br>        case .add:<br>            return &quot;plus&quot; // SF Symbol for add (always &quot;plus&quot; as it&#39;s a static icon).<br>        case .favorites:<br>            return isSelected ? &quot;heart.fill&quot; : &quot;heart&quot; // SF Symbol for favorites.<br>        case .profile:<br>            return isSelected ? &quot;person.fill&quot; : &quot;person&quot; // SF Symbol for profile.<br>        }<br>    }<br>    // Indicates if the tab uses a custom image from the asset catalog instead of an SF Symbol.<br>    var isCustomIcon: Bool {<br>        switch self {<br>        case .home: return true // Home uses a custom icon.<br>        default: return false // Other tabs use SF Symbols by default.<br>        }<br>    }<br>    // Provides a title for each tab (currently empty, but can be expanded).<br>    var title: String {<br>        switch self {<br>        case .home: return &quot;&quot;<br>        case .search: return &quot;&quot;<br>        case .add: return &quot;&quot;<br>        case .favorites: return &quot;&quot;<br>        case .profile: return &quot;&quot;<br>        }<br>    }<br>    // Converts the raw value of the enum to a 1-based string, which is used for communication with LiveView.<br>    // LiveView often expects 1-based indexing for things like tab selections.<br>    var tabValue: String {<br>        return String(self.rawValue + 1) // Convert to 1-based for LiveView<br>    }<br>}<br>// MARK: - Tab Bar Coordinator<br>// This class manages the state and logic for the tab bar, acting as a bridge between SwiftUI and LiveView.<br>@Observable // Makes this class observable, allowing SwiftUI views to react to its changes.<br>final class TabBarCoordinator&lt;Root: RootRegistry&gt; {<br>    var selection: String = &quot;1&quot; // The currently selected tab, initialized to &quot;1&quot; (the first tab). This value is synced with LiveView.<br>    var liveContext: LiveContext&lt;Root&gt;? = nil // Holds the context for interacting with the LiveView server, allowing events to be sent.<br>    var profileAvatarURL: URL? = nil // Stores the URL for the user\&#39;s profile avatar, received from LiveView.<br>    // Selects a new tab based on the provided string value.<br>    func selectTab(_ value: String) {<br>        selection = value // Updates the selection, which can trigger UI updates.<br>    }<br>    // Checks if a given tab is currently selected.<br>    func isSelected(_ tab: String) -&gt; Bool {<br>        return selection == tab<br>    }<br>    // Sets the profile avatar URL. It validates the URL string before assigning it.<br>    // This function receives the avatar URL from a LiveView attribute.<br>    func setProfileAvatar(_ urlString: String?) {<br>        // Clear the URL if it\&#39;s nil, empty, or just whitespace<br>        guard let urlString = urlString,<br>              !urlString.isEmpty,<br>              !urlString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,<br>              let url = URL(string: urlString) else {<br>            profileAvatarURL = nil // If invalid, clear the avatar URL.<br>            return<br>        }<br>        profileAvatarURL = url // Sets the valid avatar URL.<br>    }<br>}<br>// MARK: - Custom Tab Bar<br>// This struct defines the SwiftUI view for the custom tab bar.<br>@LiveElement // Marks this struct as a LiveView Native element, making it usable in LiveView templates.<br>struct CustomTabBar&lt;Root: RootRegistry&gt;: View {<br>    // @ChangeTracked connects this SwiftUI state to a LiveView attribute named &quot;selection&quot;.<br>    // This allows LiveView to read and update the selected tab.<br>    @ChangeTracked(attribute: &quot;selection&quot;) private var selection: String? = nil<br>    // @LiveAttribute reads the &quot;selection&quot; attribute from the LiveView element.<br>    @LiveAttribute(.init(name: &quot;selection&quot;)) var selectionAttribute: String?<br>    // @LiveAttribute reads the &quot;avatar_url&quot; attribute from the LiveView element.<br>    @LiveAttribute(.init(name: &quot;avatar_url&quot;)) var avatarURL: String?<br>    // @LiveElementIgnored indicates that this state should not be directly synced with LiveView.<br>    // It manages the internal state of the tab bar coordinator.<br>    @LiveElementIgnored<br>    @State private var coordinator = TabBarCoordinator&lt;Root&gt;() // The coordinator managing tab bar state.<br>    var body: some View {<br>        ZStack(alignment: .bottom) { // Arranges views in a ZStack, with the tab bar at the bottom.<br>            $liveElement.children() // Renders the content of the LiveView element (e.g., the current tab\&#39;s content).<br>                .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                .padding(.bottom, 80) // Adds padding to prevent content from being hidden by the tab bar.<br>                .edgesIgnoringSafeArea(.bottom) // Extends content into the safe area at the bottom.<br>                .onAppear {<br>                    UITabBar.appearance().isHidden = true // Hides the default iOS tab bar to use the custom one.<br>                }<br>            HStack(spacing: 0) { // Arranges tab items horizontally.<br>                ForEach(TabItem.allCases, id: \.rawValue) { item in // Iterates through all defined tab items.<br>                    Button {<br>                        updateSelection(item.tabValue) // Calls updateSelection when a tab button is tapped.<br>                    } label: {<br>                        customTabItem(<br>                            item: item,<br>                            isActive: coordinator.isSelected(item.tabValue) // Determines if the current tab is active.<br>                        )<br>                    }<br>                }<br>            }<br>            .padding(.top, 20)<br>            .frame(height: 60)<br>            .background(.black) // Sets the background color of the tab bar.<br>            .edgesIgnoringSafeArea(.bottom) // Extends the tab bar background into the safe area.<br>        }<br>        .onAppear {<br>            coordinator.liveContext = $liveElement.context // Provides the LiveView context to the coordinator.<br>            if let avatarURL = avatarURL {<br>                coordinator.setProfileAvatar(avatarURL) // Sets the profile avatar if available from LiveView.<br>            }<br>            if let selectionAttribute = selectionAttribute {<br>                updateSelection(selectionAttribute) // Sets the initial selection if provided by LiveView.<br>            }<br>        }<br>        // Reacts to changes in the `selectionAttribute` received from LiveView.<br>        .onChange(of: selectionAttribute) { _, newValue in<br>            if let newValue = newValue {<br>                updateSelection(newValue) // Updates the selection when LiveView sends a change.<br>            }<br>        }<br>        // Reacts to changes in the `avatarURL` received from LiveView.<br>        .onChange(of: avatarURL) { _, newValue in<br>            coordinator.setProfileAvatar(newValue) // Updates the profile avatar when LiveView sends a new URL.<br>        }<br>    }<br>    // Updates the tab selection and sends an event to LiveView.<br>    private func updateSelection(_ value: String) {<br>        if coordinator.selection == value {<br>            print(&quot;Tab \(value) already selected, skipping update&quot;) // Avoids redundant updates.<br>            return<br>        }<br>        selection = value // Updates the local SwiftUI selection.<br>        coordinator.selectTab(value) // Notifies the coordinator of the new selection.<br>        // Sends a &quot;phx-change&quot; event with &quot;tab-changed&quot; as the event name to the LiveView server.<br>        // The `value` dictionary contains the new selection, allowing LiveView to react.<br>        Task { // Uses a Task to perform asynchronous work (sending the event).<br>            do {<br>                try await coordinator.liveContext?.coordinator.pushEvent(<br>                    type: &quot;phx-change&quot;,<br>                    event: &quot;tab-changed&quot;,<br>                    value: [&quot;selection&quot;: value] // Sends the new selection value to LiveView.<br>                )<br>            } catch {<br>                print(&quot;Error sending tab selection event: \(error)&quot;) // Handles potential errors during event sending.<br>            }<br>        }<br>    }<br>    // Creates the visual representation of a single tab item.<br>    private func customTabItem(item: TabItem, isActive: Bool) -&gt; some View {<br>        VStack(spacing: 4) {<br>            Spacer().frame(height: 8) // Adds space at the top of the tab item.<br>            Group { // Groups conditional views for better readability.<br>                if item == .add { // Special styling for the &quot;Add&quot; tab.<br>                    ZStack {<br>                        RoundedRectangle(cornerRadius: 12)<br>                            .fill(Color.gray.opacity(0.2))<br>                            .frame(width: 48, height: 40)<br>                        Image(systemName: item.iconName(isSelected: isActive))<br>                            .font(.system(size: 19))<br>                            .foregroundColor(.white)<br>                    }<br>                } else if item == .profile &amp;&amp; coordinator.profileAvatarURL != nil { // Shows profile avatar if available.<br>                    ZStack {<br>                        Circle()<br>                            .fill(Color.gray.opacity(0.2))<br>                            .frame(width: 36, height: 36)<br>                        AsyncImage(url: coordinator.profileAvatarURL) { phase in // Loads avatar asynchronously.<br>                            if let image = phase.image {<br>                                image<br>                                    .resizable()<br>                                    .scaledToFill()<br>                            } else { // Placeholder if image fails to load.<br>                                Image(systemName: &quot;person.fill&quot;)<br>                                    .font(.system(size: 20))<br>                                    .foregroundColor(.white)<br>                            }<br>                        }<br>                        .frame(width: 36, height: 36)<br>                        .clipShape(Circle()) // Clips the avatar to a circle.<br>                        Circle()<br>                            .strokeBorder(Color.white, lineWidth: 2) // Adds a white border to the avatar.<br>                            .frame(width: 36, height: 36)<br>                    }<br>                } else if item == .profile { // Default profile icon if no avatar URL.<br>                    Image(systemName: item.iconName(isSelected: isActive))<br>                        .font(.system(size: 27))<br>                } else { // Handles other tab items.<br>                    if item.isCustomIcon { // Uses named image for custom icons.<br>                        Image(item.iconName(isSelected: isActive))<br>                            .resizable()<br>                            .scaledToFit()<br>                            .frame(width: 40, height: 40)<br>                    } else { // Uses SF Symbol for system icons.<br>                        Image(systemName: item.iconName(isSelected: isActive))<br>                            .font(.system(size: 27))<br>                    }<br>                }<br>            }<br>            Spacer() // Pushes content to the top.<br>        }<br>        .foregroundColor(isActive ? .white : .gray) // Changes icon color based on active state.<br>        .frame(maxWidth: .infinity) // Makes the tab item take full available width.<br>    }<br>}<br><br>// MARK: - Addon Registration<br>// This extension registers the CustomTabBar as a LiveView Native Addon.<br>extension Addons {<br>    @Addon // Marks this struct as a LiveView Native Addon.<br>    struct CustomTabBarAddon&lt;Root: RootRegistry&gt; {<br>        // Defines the tag name used in LiveView templates for this component.<br>        enum TagName: String {<br>            case customTabBar = &quot;CustomTabBar&quot; // The LiveView tag will be &lt;CustomTabBar&gt;.<br>        }<br>        // This function maps the LiveView tag name to the corresponding SwiftUI view.<br>        // When LiveViewNative encounters a &lt;CustomTabBar&gt; tag, it will render CustomTabBar&lt;Root&gt;().<br>        @ViewBuilder<br>        public static func lookup(_ name: TagName, element: ElementNode) -&gt; some View {<br>            switch name {<br>            case .customTabBar:<br>                CustomTabBar&lt;Root&gt;() // Returns an instance of the CustomTabBar SwiftUI view.<br>            }<br>        }<br>    }<br>}<br><br></pre><ul><li>Then, I added it to my ContentView under Add-ons:</li></ul><pre>//<br>//  ContentView.swift<br>//  To use local phone: development: URL(string: &quot;http://local_ip:port&quot;)!,<br><br>import SwiftUI<br>import LiveViewNative<br>import LiveViewNativeLiveForm<br>import LiveViewNativePhotoKit<br>import LiveViewNativeAVKit<br>struct ContentView: View {<br>    var body: some View {<br>        NavigationView {<br>            #LiveView(<br>                .automatic(<br>                    development: devURL,<br>                    production: stagingOrProductionURL<br>                ),<br>                configuration: LiveSessionConfiguration(transition: .opacity,<br>                addons: [<br>                   .liveForm,<br>                   .photoKit,<br>                   .avKit,<br>                   .customTabBarAddon, // add new component here<br>                ]<br>            ) {<br>                ConnectingView()<br>            } disconnected: {<br>                DisconnectedView()<br>            } reconnecting: { content, isReconnecting in<br>                ReconnectingView(isReconnecting: isReconnecting) {<br>                    content<br>                }<br>            } error: { error in<br>                ErrorView(error: error)<br>            }<br>        }<br>    }<br>}</pre><ul><li>Then, I simply wrapped the TabView core component with my CustomTabBar component in my LVN template and passed the correct arguments. In this example, we are passing in the URL for the current user’s avatar, but you can pass any data needed using this pattern.</li></ul><pre>def render(assigns, _interface) do<br>    ~LVN&quot;&quot;&quot;<br>      &lt;CustomTabBar<br>        :if={@current_user}<br>        selection={@tab}<br>        avatar_url={@current_user.avatar}<br>      &gt;<br>        &lt;TabView selection={@tab} phx-change=&quot;tab-changed&quot; style=&quot;tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)); toolbar(.hidden, for: .tabBar)&quot;&gt;<br>          &lt;Tab value=&quot;1&quot; title=&quot;&quot;&gt;<br>            &lt;.home tab={@tab} current_user={@current_user} /&gt;<br>          &lt;/Tab&gt;<br>          &lt;Tab value=&quot;2&quot; title=&quot;&quot;&gt;<br>            &lt;.search tab={@tab} /&gt;<br>          &lt;/Tab&gt;<br>          &lt;Tab value=&quot;3&quot; title=&quot;&quot;&gt;<br>            &lt;.add tab={@tab} /&gt;<br>          &lt;/Tab&gt;<br>          &lt;Tab value=&quot;4&quot; title=&quot;&quot;&gt;<br>            &lt;.activity tab={@tab} /&gt;<br>          &lt;/Tab&gt;<br>          &lt;Tab value=&quot;5&quot; title=&quot;&quot;&gt;<br>            &lt;.profile tab={@tab} /&gt;<br>          &lt;/Tab&gt;<br>        &lt;/TabView&gt;<br>      &lt;/CustomTabBar&gt;<br>    &quot;&quot;&quot;<br>  end</pre><p>Finally, these are the handle_events used within LVN to pass assigns to the templates:</p><pre>def handle_event(&quot;tab-changed&quot;, %{&quot;selection&quot; =&gt; tab}, socket) do<br>  if socket.assigns.tab == String.to_integer(tab) do<br>    {:noreply, socket}<br>  else<br>    set_tab_assigns(socket.assigns.current_user, tab, socket)<br>  end<br>end</pre><p>This should provide you a way to add in any icon, image, animation etc. to your Tab Bar using LVN and Swift. Thanks so much for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90dcff14da1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Receiving events in Swift from LiveView Native]]></title>
            <link>https://medium.com/@fraiha26/receiving-events-in-swift-from-liveview-native-96dbbd8964af?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/96dbbd8964af</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Tue, 20 May 2025 13:40:50 GMT</pubDate>
            <atom:updated>2025-05-20T13:41:25.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaVuIi8E2grIURieAsxXhA.png" /></figure><p><a href="https://medium.com/@fraiha26/building-custom-swiftui-components-for-liveview-native-e628940168c7"><em>Be sure to check out my first article on LiveView Native (LVN) and Swift, which shares a bit about LiveView Native itself, the relationship between Swift and LVN and how to leverage Swift Views as components in LiveView Native.</em></a></p><p><a href="https://medium.com/@fraiha26/sending-events-between-swift-and-liveview-native-c40282822ec3">In my last article, I shared how to send events from a Swift View to LiveView Native. </a>In this example, we’ll review how to receive events in Swift from LVN. We’ll create a simple demo whereby through a button click within an LVN template, we are receiving an event within the Swift View.</p><p>Let’s get started:</p><ol><li>First create a Swift View that can receive events. In this example, we’ll create a Swift View that receives “ticks” and displays that tick count in your template. We will also send a simple message “ticks received” as the payload.</li></ol><pre>import SwiftUI<br>import LiveViewNative<br><br>// Define the expected payload structure<br>struct TickPayload: Decodable {<br>    let message: String<br>}<br><br>@LiveElement<br>struct TickReceiver&lt;Root: RootRegistry&gt;: View {<br>    @State private var tickCount = 0<br>    @State private var lastMessage = &quot;&quot;<br><br>    var body: some View {<br>        VStack(spacing: 12) {<br>            Text(&quot;Ticks Received: \(tickCount)&quot;)<br>                .font(.title)<br>            if !lastMessage.isEmpty {<br>                Text(&quot;Last Message: \(lastMessage)&quot;)<br>                    .font(.subheadline)<br>                    .foregroundColor(.gray)<br>            }<br>        }<br>        .padding()<br>        // This is where you set up your onReceive<br>        .onReceive($liveElement.context.coordinator.receiveEvent(&quot;ticks&quot;)) { (payload: TickPayload) in<br>            tickCount += 1<br>            lastMessage = payload.message<br>        }<br>    }<br>}<br><br>// MARK: - Addon Registration<br>extension Addons {<br>    @Addon<br>    struct TickReceiverAddon&lt;Root: RootRegistry&gt; {<br>        enum TagName: String {<br>            case tickReceiver = &quot;TickReceiver&quot;<br>        }<br><br>        @ViewBuilder<br>        public static func lookup(_ name: TagName, element: ElementNode) -&gt; some View {<br>            switch name {<br>            case .tickReceiver:<br>                TickReceiver&lt;Root&gt;()<br>            }<br>        }<br>    }<br>}</pre><p>2. Add this view to your list of Addons in your ContentView.swift.</p><pre>//<br>//  ContentView.swift<br>//<br><br>import SwiftUI<br>import LiveViewNative<br>import LiveViewNativeLiveForm<br>import LiveViewNativePhotoKit<br>import LiveViewNativeAVKit<br><br>struct ContentView: View {<br>    init() {}<br>    <br>    var body: some View {<br>        NavigationView {<br>            #LiveView(<br>                .automatic(<br>                    development: developmentURL,<br>                    production: productionURL<br>                ),<br>                configuration: LiveSessionConfiguration(transition: .opacity,<br>                addons: [<br>                   .liveForm,<br>                   .photoKit,<br>                   .avKit,<br>                   .TickReceiverAddon // this is where you add the new view<br>                ]<br>            ) {<br><br>// rest of ContentView file</pre><p>3. Create a handle_event in your LiveView Native application to both receive and send an event like so:</p><pre>def handle_event(&quot;send_tick&quot;, _params, socket) do<br>  # Push an event to the Swift view<br>  push_event(socket, &quot;ticks&quot;, %{message: &quot;tick received&quot;})<br>  {:noreply, socket}<br>end</pre><p>4. And finally, add the View and other components to your template:</p><pre>&lt;div class=&quot;container mx-auto p-4&quot;&gt;<br>  &lt;h1 class=&quot;text-2xl font-bold mb-4&quot;&gt;Event Sender Demo&lt;/h1&gt;<br>  &lt;div class=&quot;bg-white shadow rounded-lg p-6&quot;&gt;<br>    &lt;div class=&quot;mb-4 space-x-2&quot;&gt;<br><br>      &lt;button<br>        phx-click=&quot;send_tick&quot;<br>        class=&quot;px-4 py-2 rounded-lg text-white font-semibold bg-green-600 hover:bg-green-700&quot;<br>      &gt;<br>        Send Tick to Swift View<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- This is your Swift View --&gt;<br>    &lt;TickReceiver /&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Using the <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#push_event/3">push_event function</a>, you can easily send events back to the client (Swift View) leveraging the .onReceive method.</p><p>What kind of data are you passing between Swift and LVN?</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96dbbd8964af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending events from Swift to LiveView Native]]></title>
            <link>https://medium.com/@fraiha26/sending-events-between-swift-and-liveview-native-c40282822ec3?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/c40282822ec3</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Fri, 02 May 2025 16:13:28 GMT</pubDate>
            <atom:updated>2025-06-04T00:09:30.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*W9wsorpuEjLdLY8576hVqA.png" /></figure><p><a href="https://medium.com/@fraiha26/building-custom-swiftui-components-for-liveview-native-e628940168c7"><em>Be sure to check out my first article on LiveView Native (LVN) and Swift, which shares a bit about LiveView Native itself, the relationship between Swift and LVN and how to leverage Swift Views as components in LiveView Native.</em></a></p><p>In this article, we’ll review how to pass events from Swift to LiveView Native using the handle_event function commonly found in Phoenix/LiveView apps.</p><p>In this example, we’ll send an event every 5 seconds from the Client-side (Swift) to the server-side (LVN). I’ve also added functionality to turn this timer on / off sending an attribute to the Swift View.</p><p>Let’s get started:<br>_</p><ol><li>First create a Swift View that can send events:</li></ol><pre>import SwiftUI<br>import LiveViewNative<br><br>@LiveElement<br>struct EventSender&lt;Root: RootRegistry&gt;: View {<br>    var is_running: Bool = false<br>    <br>    @LiveElementIgnored<br>    @State private var timer: Timer?<br>    @LiveElementIgnored<br>    @State private var counter: Int = 0<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Event Counter: \(counter)&quot;)<br>                .font(.title)<br>                .padding()<br>            <br>            Text(is_running ? &quot;Sending events every 5 seconds&quot; : &quot;Timer stopped&quot;)<br>                .font(.subheadline)<br>                .foregroundColor(is_running ? .green : .gray)<br>        }<br>        .onChange(of: is_running) { _, newValue in<br>            if newValue {<br>                startTimer()<br>            } else {<br>                stopTimer()<br>            }<br>        }<br>        .onAppear {<br>            if is_running {<br>                startTimer()<br>            }<br>        }<br>        .onDisappear {<br>            stopTimer()<br>        }<br>    }<br>    <br>    private func startTimer() {<br>        // Ensure we don&#39;t create multiple timers<br>        stopTimer()<br>        <br>        // Create a timer that fires every 5 seconds<br>        timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in<br>            sendEvent()<br>        }<br>    }<br>    <br>    private func stopTimer() {<br>        timer?.invalidate()<br>        timer = nil<br>    }<br>    <br>    private func sendEvent() {<br>        counter += 1<br>        <br>        Task {<br>            do {<br>                try await $liveElement.context.coordinator.pushEvent(<br>                    // You can change &quot;phx&quot; to &quot;click&quot; or any other phx type.<br>                    // &quot;phx&quot; is used to send an event when there is no user <br>                    // interaction but some other environment change (in this<br>                    // case, a timer that auto-fires every 5 seconds)<br>                    type: &quot;phx&quot;,<br>                    event: &quot;timer_tick&quot;,<br>                    value: [<br>                        &quot;counter&quot;: counter,<br>                        &quot;timestamp&quot;: Date().timeIntervalSince1970<br>                    ]<br>                )<br>            } catch {<br>                print(&quot;Error sending timer_tick event: \(error)&quot;)<br>            }<br>        }<br>    }<br>}<br><br>// MARK: - Addon Registration<br>extension Addons {<br>    @Addon<br>    struct EventSenderAddon&lt;Root: RootRegistry&gt; {<br>        enum TagName: String {<br>            case eventSender = &quot;EventSender&quot;<br>        }<br>        <br>        @ViewBuilder<br>        public static func lookup(_ name: TagName, element: ElementNode) -&gt; some View {<br>            switch name {<br>            case .eventSender:<br>                EventSender&lt;Root&gt;()<br>            }<br>        }<br>    }<br>}</pre><p>2. Add this view to your list of Addons in your ContentView.swift.</p><pre>//<br>//  ContentView.swift<br>//<br><br>import SwiftUI<br>import LiveViewNative<br>import LiveViewNativeLiveForm<br>import LiveViewNativePhotoKit<br>import LiveViewNativeAVKit<br><br>struct ContentView: View {<br>    init() {}<br>    <br>    var body: some View {<br>        NavigationView {<br>            #LiveView(<br>                .automatic(<br>                    development: developmentURL,<br>                    production: productionURL<br>                ),<br>                configuration: LiveSessionConfiguration(transition: .opacity,<br>                addons: [<br>                   .liveForm,<br>                   .photoKit,<br>                   .avKit,<br>                   .eventSenderAddon // this is where you add the new view<br>                ]<br>            ) {<br><br>// rest of ContentView file</pre><p>3. Create a handle_event in your LiveView Native application to receive the event like so:</p><pre>def handle_event(&quot;toggle_timer&quot;, _params, socket) do<br>  {:noreply, assign(socket, is_running: !socket.assigns.is_running)}<br>end<br><br>def handle_event(&quot;timer_tick&quot;, %{&quot;counter&quot; =&gt; counter, &quot;timestamp&quot; =&gt; timestamp}, socket) do<br>  last_tick = DateTime.from_unix!(timestamp)<br>  {:noreply, assign(socket, counter: counter, last_tick: last_tick)}<br>end</pre><p>4. And finally, add the View and other components to your template:</p><pre>&lt;div class=&quot;container mx-auto p-4&quot;&gt;<br>  &lt;h1 class=&quot;text-2xl font-bold mb-4&quot;&gt;Event Sender Demo&lt;/h1&gt;<br>  <br>  &lt;div class=&quot;bg-white shadow rounded-lg p-6&quot;&gt;<br>    &lt;div class=&quot;mb-4&quot;&gt;<br>      &lt;h2 class=&quot;text-lg font-semibold&quot;&gt;Counter from Swift:&lt;/h2&gt;<br>      &lt;p class=&quot;text-3xl font-bold text-blue-600&quot;&gt; {@counter}&lt;/p&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;mb-4&quot;&gt;<br>      &lt;h2 class=&quot;text-lg font-semibold&quot;&gt;Last Event Time:&lt;/h2&gt;<br>      &lt;p :if={@last_trick} class=&quot;text-gray-600&quot;&gt;<br>         { Calendar.strftime(@last_tick, &quot;%Y-%m-%d %H:%M:%S&quot;) }<br>      &lt;/p&gt;<br>      &lt;p :if={!@last_trick} class=&quot;text-gray-600&quot;&gt;<br>        No events received<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;mb-4&quot;&gt;<br>      &lt;button<br>        phx-click=&quot;toggle_timer&quot;<br>        class=&quot;px-4 py-2 rounded-lg text-white font-semibold&quot;<br>      &gt;<br>        { if @is_running, do: &quot;Stop&quot;, else: &quot;Start&quot; }<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;!-- This is your Swift View --&gt;<br>    &lt;EventSender is_running={@is_running} /&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>And that’s it! It’s as easy as that to send events from Swift to LiveView Native.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c40282822ec3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing arguments from LiveView Native Components to Swift]]></title>
            <link>https://medium.com/@fraiha26/passing-arguments-from-liveview-native-components-to-swift-4be34908c527?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be34908c527</guid>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 12:53:00 GMT</pubDate>
            <atom:updated>2025-04-24T12:53:00.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*W9wsorpuEjLdLY8576hVqA.png" /></figure><p><a href="https://medium.com/@fraiha26/building-custom-swiftui-components-for-liveview-native-e628940168c7"><em>Be sure to check out my first article on LiveView Native (LVN) and Swift, which shares a bit about LiveView Native itself, the relationship between Swift and LVN and how to leverage Swift Views as components in LiveView Native.</em></a></p><p>In this article, I’ll share my approach to passing arguments from LVN to Swift. As an example, we will create a basic video feed in Swift where we are passing in a url of a video from LVN to be auto-played when viewed.</p><p>This is a contrived example because you can create this component all within LVN, never having to touch Swift. I’ll share an article on how to do that soon. Though, if you need to pass an argument from LVN to Swift, this is one approach you can use.</p><p>Let’s get started:</p><p>_</p><ol><li>Create a basic video player in Swift that accepts one argument (URL) as a string and shows standard playback controls and plays automatically on appear.</li></ol><pre>// native/swiftui/Echo/SimpleVideoPlayer.swift<br><br>import SwiftUI<br>import AVKit<br>import LiveViewNative<br><br>/// A SwiftUI View that displays a video from a given URL using AVPlayerViewController.<br>/// It shows standard playback controls and plays automatically on appear.<br>@LiveElement<br>struct SimpleVideoPlayer&lt;Root: RootRegistry&gt;: View {<br><br><br>  var videoURL: String?<br><br>    // State variable to hold the AVPlayer instance.<br>    // AVPlayer manages the playback of the video asset.<br>  @LiveElementIgnored<br>  @State <br>  var player: AVPlayer?<br><br>  var body: some View {<br>      Group {<br>          if let player = player {<br>              // If the player is initialized, show the representable view.<br>               AVPlayerControllerRepresentable(player: player)<br>          } else {<br>               // Display a placeholder view while the URL is invalid or the player is initializing.<br>               Rectangle()<br>                   .fill(.black)<br>                   .overlay(<br>                       VStack {<br>                           ProgressView().tint(.white)<br>                           Text(&quot;Loading Video...&quot;)<br>                               .foregroundColor(.white)<br>                               .padding(.top, 8)<br>                       }<br>                   )<br>          }<br>      }<br>      .onAppear(perform: setupPlayer) // Call setupPlayer when the view appears.<br>      .onDisappear(perform: cleanupPlayer) // Call cleanupPlayer when the view disappears.<br>      // Update the player if the videoURL attribute changes while the view is visible.<br>      .onChange(of: videoURL) { _ in setupPlayer() }<br><br>  }<br><br>  /// Initializes or updates the AVPlayer instance based on the `videoURL`.<br>  private func setupPlayer() {<br>      // Ensure we have a valid URL.<br>      guard let url = videoURL else {<br>          print(&quot;❌ SimpleVideoPlayer: Video URL is nil.&quot;)<br>          player?.pause() // Pause existing player if URL becomes nil<br>          player = nil    // Set player to nil<br>          return<br>      }<br><br>      // Check if the player already exists and has the same URL.<br>      // Avoids recreating the player unnecessarily if the URL hasn&#39;t changed.<br>      if let existingPlayer = player,<br>         let currentItem = existingPlayer.currentItem as? AVPlayerItem,<br>         let currentURL = currentItem.asset as? AVURLAsset,<br>         currentURL.url == url {<br>          print(&quot;ℹ️ SimpleVideoPlayer: Player already exists for URL: \(url). Ensuring playback.&quot;)<br>          existingPlayer.play()<br>          return<br>      }<br><br>      // Create a new AVPlayer instance with the URL.<br>      print(&quot;✨ SimpleVideoPlayer: Setting up new player for URL: \(url)&quot;)<br>      player = AVPlayer(url: url)<br>      // Start playback automatically. Sound will be on by default.<br>      player?.play()<br>      print(&quot;▶️ SimpleVideoPlayer: Playback started.&quot;)<br>  }<br><br>  /// Pauses the player when the view is no longer visible.<br>  private func cleanupPlayer() {<br>      player?.pause()<br>      print(&quot;⏸️ SimpleVideoPlayer: Playback paused on disappear.&quot;)<br>      // Optionally set player = nil to release resources immediately,<br>      // but onAppear logic should handle recreation correctly.<br>      // player = nil<br>  }<br>}<br><br>/// A UIViewControllerRepresentable struct that wraps AVPlayerViewController.<br>/// This allows embedding the standard UIKit video player controls within a SwiftUI view.<br>struct AVPlayerControllerRepresentable: UIViewControllerRepresentable {<br>  // The AVPlayer instance that controls the video playback.<br>  let player: AVPlayer<br><br>  /// Creates the initial AVPlayerViewController.<br>  func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>      let controller = AVPlayerViewController()<br>      controller.player = player<br>      // Use standard aspect ratio fitting for the video.<br>      controller.videoGravity = .resizeAspect<br>      // Show the default system playback controls (play/pause, seek, volume, etc.).<br>      controller.showsPlaybackControls = true<br>      print(&quot;AVPlayerControllerRepresentable: Created AVPlayerViewController.&quot;)<br>      return controller<br>  }<br><br>  /// Updates the existing AVPlayerViewController when SwiftUI state changes.<br>  /// This ensures the controller always uses the correct AVPlayer instance.<br>  func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {<br>      // If the player instance provided to the representable changes, update the controller&#39;s player.<br>      if uiViewController.player !== player {<br>           uiViewController.player = player<br>           print(&quot;AVPlayerControllerRepresentable: Updated AVPlayer instance in controller.&quot;)<br>      }<br>  }<br>}<br><br>extension Addons {<br>  @Addon<br>  struct SimpleVideoPlayerView&lt;Root: RootRegistry&gt; { // Keep original Addon name for now<br>      enum TagName: String {<br>          case simpleVideoPlayerView = &quot;SimpleVideoPlayerView&quot; // Keep original tag name for now<br>      }<br><br>      @ViewBuilder<br>      public static func lookup(_ name: TagName, element: ElementNode) -&gt; some View {<br>          switch name {<br>          case .simpleVideoPlayerView:<br>              // Instantiate the simplified player view<br>              SimpleVideoPlayer&lt;Root&gt;()<br>          }<br>      }<br>  }<br>}</pre><p>2. Add the video player view to your list of Addons in your ContentView.swift.</p><pre>//<br>//  ContentView.swift<br>//<br><br>import SwiftUI<br>import LiveViewNative<br>import LiveViewNativeLiveForm<br>import LiveViewNativePhotoKit<br>import LiveViewNativeAVKit<br><br>struct ContentView: View {<br>    init() {}<br>    <br>    var body: some View {<br>        NavigationView {<br>            #LiveView(<br>                .automatic(<br>                    development: developmentURL,<br>                    production: productionURL<br>                ),<br>                configuration: LiveSessionConfiguration(transition: .opacity,<br>                addons: [<br>                   .liveForm,<br>                   .photoKit,<br>                   .avKit,<br>                   .simpleVideoPlayerView // this is where you add the new view<br>                ]<br>            ) {<br><br>// rest of ContentView file</pre><p>3. Add the video player component to your LVN template.</p><pre>~LVN&quot;&quot;&quot;<br>    &lt;ZStack&gt;<br>      &lt;SimpleVideoFeed videoURL={&quot;https://videos.com/video.mp4&quot;}&gt;  <br>    &lt;/ZStack&gt;<br>    &quot;&quot;&quot;</pre><p>And that’s it! You should now have a functioning video player that auto-plays the URL passed to it. You can pass multiple arguments and treat them the same way as long as they are basic types (strings, integers, booleans etc.).</p><p>For more complex types (lists, maps etc.), you can use the following pattern to pass in many urls, for instance. In this example, I am passing in a list of unique urls and a separate list of unique ids.</p><pre>  <br>~LVN&quot;&quot;&quot;<br>    &lt;ZStack&gt;<br>        &lt;SimpleVideoFeed<br>          urls={Enum.uniq_by(@videos, &amp; &amp;1.url) |&gt; Enum.map(&amp; &amp;1.url)}<br>          ids={Enum.uniq_by(@videos, &amp; &amp;1.url) |&gt; Enum.map(&amp; &amp;1.id)}<br>        &gt;<br>    &lt;/ZStack&gt;<br>    &quot;&quot;&quot;</pre><pre>// native/swiftui/Echo/SimpleVideoPlayer.swift<br><br>import SwiftUI<br>import AVKit<br>import LiveViewNative<br><br>/// A SwiftUI View that displays a video from a given URL using AVPlayerViewController.<br>/// It shows standard playback controls and plays automatically on appear.<br>@LiveElement<br>struct SimpleVideoPlayer&lt;Root: RootRegistry&gt;: View {<br><br>    var urls: [String] = []<br>    var ids: [Int] = []<br><br>    // State variable to hold the AVPlayer instance.<br>    // AVPlayer manages the playback of the video asset.<br>   @LiveElementIgnored<br>   @State <br>   var player: AVPlayer?<br><br>// Rest of SimpleVideoPlayer file</pre><p>In order for this to work, you’d need to change a good bit of the SimpleVideoPlayer to handle a list of URLs but leveraging these patterns, you should be able to pass in whatever you’d like from LVN to Swift.</p><p>Feel free to leave comments and thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be34908c527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom SwiftUI Components for LiveView Native]]></title>
            <link>https://medium.com/@fraiha26/building-custom-swiftui-components-for-liveview-native-e628940168c7?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/e628940168c7</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[liveview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 00:24:47 GMT</pubDate>
            <atom:updated>2025-04-02T00:48:43.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*HvmXvwAtznvTLjvqLgfFnA.jpeg" /></figure><p>Lately at work, I’ve been all in on LiveView Native (LVN) from the wonderful folks at <a href="https://dockyard.com/">DockYard</a>. <a href="https://dockyard.com/blog/2024/09/09/liveview-native-is-here">Before we get started, here’s a crash course if you’re unfamiliar w/ LVN.</a></p><p>So far, it’s been nice to develop mobile apps using mostly Elixir / Phoenix / LiveView Native w/ a bit of Swift when needed. If you’re familiar w/ Phoenix / LiveView, then developing in LVN should come naturally. The learning curve for me was figuring out how to do things that LVN couldn’t do just yet.</p><p>In Phoenix / LiveView, when you can’t do something with the tools provided out-of-the-box, you can leverage JS Hooks. In LVN, you turn to Swift Views.</p><p>Let’s build a simple blinking dot animation in Swift, then use it in our LVN template. In this particular example, if you didn’t want to use Swift, you could write this all within LVN. I’ll write a follow-up about how to do that soon. <strong>However, if you come across something you can’t yet do in LVN, you can use the following pattern to bring Swift code into your LVN templates.</strong><br>_</p><p>Let’s start:</p><ul><li>First, find an image of a dot w/ a transparent background and add<a href="https://developer.apple.com/documentation/xcode/adding-images-to-your-xcode-project"> it to your assets folder in Xcode,</a> the IDE used for developing iOS apps.</li><li>Create a BlinkingDot.swift file within the main directory of your project in Xcode.</li><li>Within the newly created BlinkingDot.swift file, add the following View (I tried to include comments around anything that is LVN-specific).</li></ul><pre>import SwiftUI<br>import LiveViewNative<br><br>// @LiveElement is a LiveView Native decorator that marks this struct as a custom element<br>// that can be used in LiveView Native templates. This makes the component available to be used<br>// in your LiveView Native templates.<br>@LiveElement<br>struct BlinkingDot&lt;Root: RootRegistry&gt;: View {<br>    @State private var isPulsing = false<br>    <br>    var body: some View {<br>        HStack(alignment: .top, spacing: 0) {<br>            if let dotImage = UIImage(named: &quot;Dot&quot;) {<br>                Image(uiImage: dotImage)<br>                    .resizable()<br>                    .aspectRatio(contentMode: .fit)<br>                    .frame(width: 12, height: 12)<br>                    .opacity(isPulsing ? 0.3 : 1.0)<br>                    .animation(<br>                        Animation.easeInOut(duration: 1.0)<br>                            .repeatForever(autoreverses: true),<br>                        value: isPulsing<br>                    )<br>                    .padding(.top, 20)<br>                    .onAppear {<br>                        isPulsing = true<br>                    }<br>            } else {<br>                EmptyView()<br>            }<br>        }<br>    }<br>}<br><br>// The Addons namespace is used by LiveView Native to register custom components<br>extension Addons {<br>    // @Addon decorator marks this struct as a custom addon for LiveView Native<br>    // Addons allow you to extend LVN with custom native components<br>    @Addon<br>    struct BlinkingDotView&lt;Root: RootRegistry&gt; {<br>        // TagName enum defines the HTML/HEEx tag names that will be mapped to Swift views<br>        // These tags can be used directly in your LVN templates<br>        enum TagName: String {<br>            case blinkingDot = &quot;BlinkingDot&quot;<br>        }<br><br>        // The lookup method is required for all addons<br>        // It maps tag names to their corresponding SwiftUI views<br>        // This is how LiveView Native knows which Swift view to render for a given tag<br>        @ViewBuilder<br>        public static func lookup(_ name: TagName, element: ElementNode) -&gt; some View {<br>            switch name {<br>            case .blinkingDot:<br>                // ElementNode contains the attributes and children of the LVN element<br>                // It can be used to extract properties passed from the server<br>                BlinkingDot&lt;Root&gt;()<br>            }<br>        }<br>    }<br>}<br><br>// Important: The LiveElement name (BlinkingDot) and the Addon name (BlinkingDotView) must be different</pre><ul><li>Add the Addon (BlinkingDotView) to the file named ContentView.swift</li></ul><pre>//  ContentView.swift<br>//  To use local phone: development: URL(string: &quot;http://local_ip:port&quot;)!,<br><br>import SwiftUI<br>import LiveViewNative<br>import LiveViewNativeLiveForm<br>import LiveViewNativePhotoKit<br>import LiveViewNativeAVKit<br><br>struct ContentView: View {<br>    var body: some View {<br>        #LiveView(<br>            .automatic(<br>                development: .localhost(path: &quot;/&quot;),<br>                production: URL(string: &quot;https://prod_url.com/&quot;)!<br>            ),<br>            configuration: LiveSessionConfiguration(transition: .opacity),<br>            addons: [<br>               .liveForm,<br>               .photoKit,<br>               .avKit,<br>               //  Note that everything in this list is camelCased<br>               .blinkingDotView,<br>            ]<br>        ) {<br>            ConnectingView()<br>        } disconnected: {<br>            DisconnectedView()<br>        } reconnecting: { content, isReconnecting in<br>            ReconnectingView(isReconnecting: isReconnecting) {<br>                content<br>            }<br>        } error: { error in<br>            ErrorView(error: error)<br>        }<br>    }<br>}</pre><ul><li>Now, after compiling in Xcode, you should now have access to your Swift View in your LVN template.</li></ul><pre>// Added the VStack element to center the blinking app within the view<br><br>  &lt;VStack style={~s[frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)]}&gt;<br>    &lt;BlinkingDot&gt;<br>    &lt;/BlinkingDot&gt;<br>  &lt;/VStack&gt;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FyKvMboxE3AmvEuMP6X%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FyKvMboxE3AmvEuMP6X&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZDA0eHJlbjB2b3Aza2tleGVvZG53bXU0d3V0dndwMWx5cDcyaGtmayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FyKvMboxE3AmvEuMP6X%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c4173eadb8184b564cd16934248774/href">https://medium.com/media/26c4173eadb8184b564cd16934248774/href</a></iframe><p>And that’s it! You should see a blinking dot within your mobile app.</p><p>Obviously, this is a contrived example, especially because you can build a blinking dot animation all within LVN with a few lines of code, but I hope this highlights how simple it is to bring Swift Views into LVN templates.</p><p>The next article on LVN will focus on passing arguments from your LVN template to the Swift View for processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e628940168c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up SMTP with Gmail in Elixir/Phoenix]]></title>
            <link>https://medium.com/@fraiha26/setting-up-smtp-with-gmail-in-elixir-phoenix-fcceae02e43f?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcceae02e43f</guid>
            <category><![CDATA[smtp]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[gmail]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 01:07:15 GMT</pubDate>
            <atom:updated>2025-04-04T11:32:56.578Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to set up an email service for a personal project such that I received an email after a form was submitted. Gmail accounts can send up to 500 emails per day, and I would be sending less than 50 emails on a busy day, so this worked for me.</p><p>_</p><ol><li>Add {:gen_smtp, “~&gt; 1.2”} to your mix.exs file. <em>Skip this step if you’ve already run “mix phx.gen.auth,” as you’ll already have this dependency.</em></li></ol><p>The gen_smtp library is an Erlang-based library that provides functionality for sending and receiving emails using the Simple Mail Transfer Protocol (SMTP).</p><p>Don’t forget to run mix deps.get after adding it.</p><p>2. Create a gmail account and turn on two-step verification, which is necessary to expose the App Password section within your account settings.</p><p>An App Password from Google is a 16-digit passcode. It’s used when an app or device doesn’t support two-step verification, and this is what we will set as our GMAIL_PASSWORD when setting up environment variables.</p><p>When copying the App Password, it is copied with white spaces, so please remember to remove them before adding them to your app.</p><p>3. Now, in runtime.exs (or dev.exs), add the following:</p><pre>config :app, App.Mailer,<br>  adapter: Swoosh.Adapters.SMTP,<br>  relay: &quot;smtp.gmail.com&quot;,<br>  port: 587,<br>  username: System.get_env(&quot;GMAIL_USERNAME&quot;), // the gmail account<br>  password: System.get_env(&quot;GMAIL_PASSWORD&quot;), // the App Password<br>  ssl: false,<br>  tls: :always,<br>  tls_options: [verify: :verify_none],<br>  auth: :always</pre><p>I<a href="https://elixirforum.com/t/help-setup-email-verification-in-phoenix/62665/4">t was thanks to this great thread on the Elixir forums that helped resolve the tls issues I experienced setting this up the first time.</a></p><p>4. Finally, set up the notification in Phoenix / LiveView. I’ll provide an example:</p><pre>defmodule App.UserNotifier do<br>  import Swoosh.Email<br>  alias App.Mailer<br>  require Logger<br><br>  def notification(notification_attrs) do<br>    deliver(&quot;email_recipient@gmail.com&quot;, &quot;Subject Line&quot;, &quot;&quot;&quot;<br>  <br>    Content including notification attrs<br>  <br>    &quot;&quot;&quot;)<br>  end<br>  <br>  <br>  defp deliver(recipient, subject, body) do<br>    email =<br>      new()<br>      |&gt; to(recipient)<br>      |&gt; from({&quot;Name of Sender&quot;, &quot;email_sender@gmail.com&quot;})<br>      |&gt; subject(subject)<br>      |&gt; text_body(body)<br>  <br>    case Mailer.deliver(email) do<br>      {:ok, _metadata} -&gt;<br>        {:ok, email}<br>      error -&gt;<br>        Logger.warning(&quot;Email delivery failed&quot;)<br>        Logger.warning(error)<br>        error<br>    end<br>  end<br>end</pre><p>Now, when notification() is invoked, the email_recipient should immediately receive an email.</p><p>_<br>And that’s it! You should now have a simple, working SMTP-supported email service for your app.</p><p>Thanks for reading and let me know how you’ve approached setting something like this up in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcceae02e43f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pushing events to LiveComponents from JS hooks w/ Phoenix / Elixir]]></title>
            <link>https://medium.com/@fraiha26/pushing-events-to-livecomponents-from-js-hooks-w-phoenix-elixir-d5544d4c3dfa?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5544d4c3dfa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[phoenix-liveview]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 13:03:25 GMT</pubDate>
            <atom:updated>2024-02-28T13:03:25.168Z</atom:updated>
            <content:encoded><![CDATA[<p>While in the process of adding a “mentions” feature to a SAAS app, I needed to use <a href="https://dev.to/postelxpro/getting-started-using-hooks-with-phoenix-and-liveview-f18">a js hook</a>, but didn’t have a way to pass data / trigger handle_events from the hook directly to/in my LiveComponent.</p><p>I’ve been using the <a href="https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks">pushEvent method</a> to push events from hooks to parent LiveViews, but what I didn’t know is there is a similar method called <strong>pushEventTo</strong>, and this is exactly what I was looking for, <strong>as it allows you to push events directly to LiveComponents</strong>.</p><p>Let’s get into a quick code example.</p><p>Sample code found within a JS hook:</p><pre>let handleEventCode = debounce((_e) =&gt; {  <br>  el.pushEventTo(&quot;#text_with_mentions&quot;, &quot;save_text&quot;, {id: text_id, description: div.innerHTML})<br>  }, 500);</pre><p>Sample code found within a heex template of a LiveComponent:</p><pre>   &lt;div id=&quot;text_with_mentions&quot; phx-hook=&quot;TextWithMention&quot;&gt;<br>      &lt;%= raw(@text_description) %&gt;<br>   &lt;/div&gt;</pre><p>Sample handle_event found within a LiveComponent:</p><pre>def handle_event(&quot;save_text&quot;, %{&quot;id&quot; =&gt; id, &quot;description&quot; =&gt; description}, socket) do<br>   # do anything with the data you need to<br>   {:noreply, socket}<br>end</pre><p>In the first code block, I am pushing an event (“save_text”) to the LiveComponent using the id “text_with_mentions” in the second code block, which will trigger the handle_event in the third code block.</p><p><a href="https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks">The Elixir / Phoenix / LiveView documentation is incredible, and this is where I stumbled onto this method and definition:</a></p><pre><strong>pushEventTo(selectorOrTarget, event, payload, (reply, ref) =&gt; ...) - </strong><br>method to push targeted events from the client to LiveViews and LiveComponents. <br>It sends the event to the LiveComponent or LiveView the selectorOrTarget is <br>defined in, where its value can be either a query selector or an actual DOM <br>element. If the query selector returns more than one element it will send the <br>event to all of them, even if all the elements are in the same LiveComponent <br>or LiveView.</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5544d4c3dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Calendar API Integration w/ Elixir + Phoenix]]></title>
            <link>https://medium.com/@fraiha26/google-calendar-api-integration-w-elixir-phoenix-d1ddbb162dfc?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1ddbb162dfc</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[inspire]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 11:49:35 GMT</pubDate>
            <atom:updated>2023-07-25T13:02:29.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Elixir &amp; Phoenix Logos" src="https://cdn-images-1.medium.com/max/259/1*z903sbGTkLT2DUgYBIpcag.png" /></figure><p>A (relatively) quick how-to.</p><p>Recently, at <a href="https://inspirehq.team/">InspireHQ</a>, I was tasked with integrating the Google Calendar API into our existing application using Elixir / Phoenix / Surface UI. As I could not find any comprehensive guides for how to accomplish this, I decided to write an article in the hopes of helping other folks tasked with something similar. For our particular use case, we wanted to make it so that users on our platform had access to the next three days of their calendar events, as well as the ability to see other user’s calendars.</p><p>Versions:</p><pre>      {:phoenix, &quot;~&gt; 1.6.6&quot;},      <br>      {:surface, &quot;~&gt; 0.7.1&quot;},<br>      {:ueberauth_google, &quot;~&gt; 0.10&quot;},<br>      {:oauth2, &quot;~&gt; 2.0&quot;}</pre><p>We are using version 1.6.6 of Phoenix and version 0.7.1 of Surface UI. In order to setup the Google Calendar API, I had to also setup the Google authentication process. For this, I used a combination of two libraries: <a href="https://github.com/ueberauth/ueberauth_google">ueberauth_google (v0.10)</a> and <a href="https://github.com/ueberauth/oauth2">oauth2 (v2.0)</a>. One thing I’ll probably do in the future is switch out ueberauth_google to use oauth2 for everything. What I didn’t know (and maybe this is incorrect, but I could not figure out how to do this) is that ueberauth_google does not provide a way to refresh authentication tokens out-of-the-box, which is why I brought in oauth2 (more on this later).</p><p>After setting up the correct dependencies, we need to add all of the associated boilerplate code for ueberauth_google / oauth2. Let’s do that now.</p><p><strong>Step 1: </strong>Add dependencies to your mix.exs file (see above for versions).</p><p><strong>Step 2: </strong>Add the following to your config.exs file:</p><pre>config :ueberauth, Ueberauth,<br>  providers: [<br>    google: {Ueberauth.Strategy.Google, [<br>    default_scope: &quot;profile email https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.settings.readonly&quot;,<br>    client_id: GOOGLE_ID,<br>    client_secret: GOOGLE_SECRET_KEY,<br>    access_type: &quot;offline&quot;,<br>    prompt: &quot;consent&quot;<br>    ]}<br>  ]</pre><p>Be sure to replace the GOOGLE_ID and GOOGLE_SECRET_KEY with the information you receive from <a href="https://console.cloud.google.com/">the Google Developer’s Console</a>. You’ll need to register your app through Google’s Developer’s Console. This is where you’ll obtain the scopes cited above, as well as setup some additional configuration related to redirect URLs. After your application is ready to deploy, you’ll also have to go through the <a href="https://sjinnovation.com/4-easy-steps-to-preparing-your-app-for-google-authentication">Google verification process</a> if you are using sensitive or restricted scopes (two of the scopes above are sensitive), which is pretty involved so maybe I’ll write another article about that one day.</p><p>Everything in the code above is important but the access_type: “offline” and prompt: “consent” are what enable you to receive refresh_tokens every time a user within your application moves through the Google authentication process. Also, depending on how your environments are set up, you may need to add the following to your runtime.exs file:</p><pre>  config :ueberauth, Ueberauth.Strategy.Google.OAuth,<br>    client_id: System.get_env(&quot;GOOGLE_CLIENT_ID&quot;),<br>    client_secret: System.get_env(&quot;GOOGLE_CLIENT_SECRET&quot;)</pre><p><strong>Step 3: </strong>Create a controller for the Google authentication process. You can do this by adding a file like google_auth_controller.ex in your controllers folder:</p><pre>defmodule AppWeb.GoogleAuthController do<br>  use AppWeb, :controller<br>  plug Ueberauth<br><br>  alias Ueberauth.Strategy.Helpers<br>  <br>  def request(conn, _params) do<br>    render(conn, &quot;request.html&quot;, callback_url: Helpers.callback_url(https://medium.com/conn))  <br>  end<br>  <br>  def callback(%{assigns: %{ueberauth_failure: _fails}} = conn, _params) do<br>    conn<br>    |&gt; put_flash(:error, &quot;Failed to authenticate.&quot;)<br>    |&gt; redirect(to: &quot;/&quot;)<br>  end<br><br>  def callback(%{assigns: %{ueberauth_auth: nil}} = conn, _params) do   <br>    conn<br>    |&gt; put_flash(:error, &quot;Failed to authenticate.&quot;)        <br>    |&gt; redirect(to: &quot;ADD_UNSUCCESSFUL_REDIRECT_LINK&quot;) <br>    end<br>  end<br>  <br>  def callback(%{assigns: %{ueberauth_auth: auth}} = conn, _params) do   <br>    conn<br>    |&gt; put_flash(:info, &quot;You&#39;ve Successfully Logged in to your Google Account&quot;)<br>    |&gt; redirect(to: &quot;ADD_SUCCESSFUL_REDIRECT_LINK&quot;)<br>  end<br>end</pre><p>Eventually, there will be a lot more added to this controller but for now, this is the boilerplate needed to get the basic authentication process up and running (and remember, we haven’t even begun talking about integrating Google Calendar yet).</p><p><strong>Step 4: </strong>Add the required routes in your router.ex file:</p><pre>  get &quot;/auth/google&quot;, GoogleAuthController, :request<br>  get &quot;/auth/google/callback&quot;, GoogleAuthController, :callback</pre><p>These routes match up with the request and callback functions in the controller you just created.</p><p><strong>Step 5: </strong>Create a component or module containing a link to start the Google authentication process (I created a component that I’ve added to a module. In this instance, I’ll share the component):</p><pre>defmodule AppWeb.Components.ScheduleSignIn do<br>  use Surface.Component<br><br>  prop current_user, :map, default: nil<br>  prop user, :map, default: nil<br><br>  def render(assigns) do<br>    ~F&quot;&quot;&quot;<br>    &lt;div&gt;<br>      &lt;a href={google_auth_url()}&gt;<br>        &lt;img src=&quot;/images/btn_google_signin_dark_normal_web@2x.png&quot; alt=&quot;Sign in with Google&quot;/&gt;<br>      &lt;/a&gt;<br>    &lt;/div&gt;<br>    &quot;&quot;&quot;<br>  end<br>  <br>  def google_auth_url() do<br>    &quot;/auth/google/&quot;<br>  end<br>end</pre><p>This is a simple component that displays the Google Sign-In button. Clicking the button will initiate the authentication process, calling the functions in the Google auth controller in the process.</p><p><em>Note: I am not sharing the component used to display the actual calendar data as that will be unique to every application. However, this guide will hopefully put you in a position to receive the data from Google you need, so that you can display it however you’d like.</em></p><p><strong>Step 6: </strong>Prepare your database to receive data from Google. As most use cases will vary, I’m going to share what fields we included across several tables. However, you can include all of these fields in a single table if it fits your needs:</p><ul><li>user_id (in our case, this is an integer)</li><li>google_calendar_access_token (string)</li><li>google_calendar_refresh_token (string)</li><li>google_calendar_access_token_expiration (datetime)</li><li>google_calendar_subscription_id (string)</li><li>google_calendar_subscription_expiration (datetime)</li><li>google_calendar_event_list (map)</li><li>google_calendar_event_list_last_updated (datetime)</li></ul><p>Obviously, feel free to change any of these fields to whatever is appropriate for your application.</p><p><strong>Step 7: </strong>Begin to add code to make successful API calls to Google, obtaining a user’s Google calendar event list:</p><pre>def gcal_api_call(token, user_id) do<br>  case is_token_fresh(token, user_id) do <br>    {:ok, token} -&gt; <br>      headers = [<br>        Authorization: &quot;Bearer #{token}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>      ]<br>      <br>      # Get primary calendar<br>      {:ok, primary_calendar} =<br>        HTTPoison.get(&quot;https://www.googleapis.com/calendar/v3/calendars/primary&quot;, headers)<br>        |&gt; parse_body_response()<br><br>      start_cal = Timex.now(&quot;America/New_York&quot;)<br>      end_cal = Timex.shift(start_cal, days: 2)<br><br>      # Get events of primary (default) calendar<br>      params = %{<br>        timeMin: start_cal |&gt; Timex.format!(&quot;{RFC3339}&quot;),<br>        timeMax: end_cal |&gt; Timex.end_of_day() |&gt; Timex.format!(&quot;{RFC3339}&quot;),<br>        singleEvents: true,<br>        orderBy: &quot;startTime&quot;<br>      }<br><br>      {:ok, event_list, last_updated} =<br>        HTTPoison.get(<br>          &quot;https://www.googleapis.com/calendar/v3/calendars/#{primary_calendar.id}/events&quot;,<br>          headers,<br>          params: params<br>        )<br>        |&gt; parse_body_response()<br>        |&gt; update_user_with_gcal(user_id)<br><br>      {reshape_gcal_data(event_list), last_updated}<br><br>      _ -&gt;<br>      {nil, nil}<br>  end<br>end</pre><p>Feel free to create a utils folder and a file within that folder titled google_calendar_helper.ex. This file will contain all the helper functions we’ll need to not only retrieve the data we need, but also refresh tokens (and a few other things we’ll see momentarily).</p><p>There is a lot going on in the code above so let’s break it down:</p><ul><li>First, given our use case, I am passing in the user.id and a token and I immediately check to see if that token is fresh (will share more on this process shortly).</li><li>Second, if the token is fresh and not expired, make the first API call gaining access to a user’s calendars. As all data received from Google is JSON data, we’ll need to parse it in order to be able to better work with it in Elixir. Here is a simple parsing function:</li></ul><pre>  defp parse_body_response({:error, err}), do: {:error, err}<br>  defp parse_body_response({:ok, response}) do<br>    body = Map.get(response, :body)<br><br>    if body == nil do<br>      {:error, :no_body}<br>    else<br>      {:ok, str_key_map} = Jason.decode(body)<br>      atom_key_map = for {key, val} &lt;- str_key_map, into: %{}, do: {String.to_atom(key), val}<br>      {:ok, atom_key_map}<br>    end<br>  end</pre><p>Without going too deep into an explanation, the functions above turn a JSON object into an Elixir map, allowing us to more easily re-shape the data.</p><ul><li>Third, given our specific use case, I only want a user’s calendar data for the next three days, so I utilized <a href="https://hexdocs.pm/timex/Timex.html">the Timex library</a>. I also setup specific parameters to pass to Google for my second API call, which gets me the relevant user calendar data I required.</li><li>Fourth, after receiving the data, I once again send it through my parsing function then I call a function (update_user_with_gcal) that saves what was received from Google to our database. We’ll talk more about this function in a bit.</li><li>Finally, I return the event_list and last_updated, and while doing so, I also re-shape the event_list so it is easier for me to use on the front end. Google sends back a lot of data that I don’t need, so I used the following function to create a data structure that contains only the relevant information I need to display to the user. Here is that function:</li></ul><pre>def reshape_gcal_data(event_list) do<br>  formatted_map =<br>    for event &lt;- event_list do<br>      <br>      [meeting_date, start_time, end_time] = <br>      if Map.get(event, &quot;start&quot;, %{})[&quot;dateTime&quot;] != nil do<br>         [meeting_date, _] = String.split(event[&quot;start&quot;][&quot;dateTime&quot;], &quot;T&quot;)<br>         start_time = event[&quot;start&quot;][&quot;dateTime&quot;]<br>         end_time = event[&quot;end&quot;][&quot;dateTime&quot;]<br>         <br>         [meeting_date, start_time, end_time]<br>      else<br>         meeting_date = event[&quot;start&quot;][&quot;date&quot;]<br>         start_time = &quot;All Day&quot;<br>         end_time = &quot;All Day&quot;<br>         <br>         [meeting_date, start_time, end_time]<br>      end<br><br>      attendees =<br>        case event[&quot;attendees&quot;] do<br>          nil -&gt; []<br>          _ -&gt; event[&quot;attendees&quot;] |&gt; Enum.map(fn att -&gt; att[&quot;email&quot;] end)<br>        end<br><br>      summary = event[&quot;summary&quot;]<br><br>      %{<br>        &quot;Date&quot; =&gt; meeting_date,<br>        &quot;Details&quot; =&gt; %{<br>          &quot;attendees&quot; =&gt; attendees,<br>          &quot;summary&quot; =&gt; summary,<br>          &quot;start&quot; =&gt; start_time,<br>          &quot;end&quot; =&gt; end_time<br>        }<br>      }<br>    end<br><br>  grouped_map = Enum.group_by(formatted_map, &amp; &amp;1[&quot;Date&quot;])<br><br>  reformatted_map =<br>    Enum.map(grouped_map, fn {meeting_date, events} -&gt;<br>      %{<br>        &quot;Date&quot; =&gt; meeting_date,<br>        &quot;Events&quot; =&gt; Enum.map(events, &amp; &amp;1[&quot;Details&quot;])<br>      }<br>    end)<br><br>  reformatted_map<br>end</pre><p>The function above accounts for all_day events and returns a map that breaks down and organizes the data by date (when Google returns the event_list, it is broken down by event, and NOT by date, which is what we needed). This makes it much simpler to display the data to look like a traditional calendar, where all events are listed under a specific date.</p><p><strong>Step 8: </strong>Now that we’ve received the data we want, we need to subscribe to the calendar so that we receive updates when the calendar changes. Going back to our controller, I’ve added the following lines of code to the second callback function listed:</p><pre>def callback(%{assigns: %{ueberauth_auth: auth}} = conn, _params) do    <br>  case update(auth, user.user_id) do<br>    {:ok, _user} -&gt; <br>      conn<br>      |&gt; put_flash(:info, &quot;You&#39;ve Successfully Logged in to your Google Account&quot;)<br>      |&gt; redirect(to: &quot;ADD_SUCCESSFUL_REDIRECT_LINK&quot;)<br>    {:error, _reason} -&gt;<br>      conn<br>      |&gt; put_flash(:error, &quot;Failed to authenticate.&quot;)        <br>      |&gt; redirect(to: &quot;ADD_UNSUCCESSFUL_REDIRECT_LINK&quot;)    <br>    nil -&gt; nil<br>end</pre><p>In our particular use case, I needed to set up an update function, passing the auth code and the user.id. I’ve seen in a few cases where folks would create a create_or_update function, basically creating a new auth user in the database or updating one that exists. Because users went through a separate authentication process to sign into our app, I do not need to include this extra step. For our use case, all I need to do is update their information in our database with the new information from Google. Here is our version of the update function:</p><pre>  defp update(auth, user_id) do<br>    subscription = GoogleCalHelper.create_subscription(auth.credentials.token, auth.info.email)<br>    <br>    {access_token_exp, subscription_exp} = calculate_expiration_datetimes(auth.credentials.expires_at, subscription[&quot;expiration&quot;])<br>    <br>    gcal_params = %{<br>      &quot;access_token_gcal&quot; =&gt; auth.credentials.token,<br>      &quot;refresh_token_gcal&quot; =&gt; auth.credentials.refresh_token,<br>      &quot;access_token_exp&quot; =&gt; access_token_exp,<br>      &quot;subscription_id&quot; =&gt; subscription[&quot;resourceId&quot;],<br>      &quot;subscription_exp&quot; =&gt; subscription_exp,<br>      &quot;pending&quot; =&gt; false<br>    }<br><br>    GcalUpdate.call(user_id, context_id, gcal_params)<br>  end<br><br>  defp calculate_expiration_datetimes(_expires_at, _expiration), do: {nil, nil}<br>  defp calculate_expiration_datetimes(expires_at, expiration) when is_integer(expires_at) and is_binary(expiration) do<br>    {:ok, access_token_exp} = DateTime.from_unix(expires_at)<br>    exp_ms = String.to_integer(expiration)<br>    exp_s = div(exp_ms, 1000)<br>    {:ok, subscription_exp} = DateTime.from_unix(exp_s)<br><br>    {access_token_exp, subscription_exp}<br>  end<br></pre><p>Skipping over the create_subscription function for a moment, we are manipulating the expiration dates received for both the access_token and subscription, so that they can be received by our database. Then we are saving all of the relevant information we need to our database for that user.</p><p>Going back to the create_subscription function:</p><pre>def create_subscription(token, primary_calendar) do<br>  notification_id = UUID.uuid1()<br>  calendar_id = primary_calendar<br>  <br>  headers = [<br>    {&quot;Authorization&quot;, &quot;Bearer #{token}&quot;},<br>    {&quot;Content-Type&quot;, &quot;application/json&quot;},<br>  ]<br>  <br>  domain = Application.get_env(:app, :web_url)<br>      <br>  body = %{<br>    &quot;id&quot; =&gt; notification_id,<br>    &quot;type&quot; =&gt; &quot;web_hook&quot;,<br>    # to set up for localhost, use a tool like ngrok: https://dashboard.ngrok.com/get-started/setup <br>    # if using ngrok, set address to the forwarding address (example: &quot;https://d331-24-228-150-250.ngrok.io/notifications&quot;)<br>    &quot;address&quot; =&gt; &quot;#{domain}/google_cal_notifications&quot;<br>    }<br>  <br>  case HTTPoison.post(&quot;https://www.googleapis.com/calendar/v3/calendars/#{calendar_id}/events/watch&quot;, Jason.encode!(body), headers) do<br>    {:ok, %{status_code: 200, body: body}} -&gt;<br>      IO.inspect(&quot;Subscription successful!&quot;)<br>      Jason.decode!(body)<br>      <br>    {:ok, %{status_code: status_code, body: body}} -&gt;<br>      IO.inspect(&quot;Failed to create subscription: #{status_code} - #{inspect(body)}&quot;)<br>    {:error, reason} -&gt;<br>      IO.inspect(&quot;Failed: #{reason}&quot;)<br>  end<br> end</pre><p>The function above sets up a subscription to a specific user’s calendar, so that whenever it changes, our app will be notified. We’ll explore handling those notifications in a moment. I used <a href="https://dashboard.ngrok.com/get-started/setup">ngrok</a> to set up a local forwarding address to test this set up locally and it worked like a charm. I also used an <a href="https://github.com/zyro/elixir-uuid">UUID library</a> to create custom notification ids.</p><p><strong>Step 9: </strong>Next is to set up a way to handle notifications from Google (when a calendar changes for instance). To accomplish this, we’ll need to setup a <a href="https://www.redhat.com/en/topics/automation/what-is-a-webhook">webhook</a>:</p><pre> def handle_notifications(conn, _params) do<br>    case Plug.Conn.read_body(conn) do<br>      {:ok, _body, conn} -&gt;<br>         subscription_id = <br>           conn.req_headers<br>            |&gt; Enum.find(fn {key, _} -&gt; key == &quot;x-goog-resource-id&quot; end)<br>            |&gt; elem(1)<br>            <br>         tokens = GoogleCalHelper.get_subscription(subscription_id)<br>     <br>         case is_nil(token) do<br>          true -&gt; nil<br>          false -&gt; GoogleCalHelper.gcal_api_call(token.access_token_gcal, token.user_id)<br>         end<br>    <br>        send_resp(conn, 200, &quot;Notification received successfully&quot;)<br>      {:error, reason} -&gt;<br>        send_resp(conn, 400, &quot;Failed to read notification body: #{reason}&quot;)<br>    end<br>  end</pre><p>I placed the function above in the google auth controller file. I used a helper function to grab the correct user information from our database using the subscription_id (the UUID) we set up in the last step. Once received, I use the same gcal_api_call function we used a few steps back to make another API call on behalf of the user whose calendar changed. In addition to this function, we’ll also have to add a webhook route to our router.ex file:</p><pre>  pipeline :api do<br>    plug :accepts, [&quot;json&quot;]<br><br>    #Webhooks<br>    scope &quot;/&quot;, AppWeb do<br>      post &quot;/google_cal_notifications&quot;, GoogleAuthController, :handle_notifications<br>    end<br>  end</pre><p>Once that’s setup, let’s take a closer look at one of the functions we skipped over in a previous step:</p><pre>defp update_user_context_with_gcal({:ok, events} = _event_list, user_id) do<br>  case UserUpdate.call(user_id, %{<br>         &quot;google_cal_events&quot; =&gt; events,<br>         &quot;google_cal_events_last_updated&quot; =&gt; DateTime.utc_now()<br>       }) do<br>    {:ok, _new_user_context} -&gt; nil<br>    {:error, error_message} -&gt; IO.inspect(error_message)<br>  end<br><br>  event_list_from_db = <br>    case UserGet.call(%{&quot;user_id&quot; =&gt; user_id}) do<br>      {:error, reason} -&gt; IO.inspect(reason)<br>      event_list_from_db -&gt; event_list_from_db<br>    end<br>    <br>  broadcast_google_events(event_list_from_db.google_cal_events[&quot;items&quot;], event_list_from_db.google_cal_events_last_updated)<br>  <br>  {:ok, event_list_from_db.google_cal_events[&quot;items&quot;],<br>   event_list_from_db.google_cal_events_last_updated}<br> end</pre><p>This function is at the tail end of the gcal_api_call function and is meant to update the database with a user’s event_list information. The important piece for us is the broadcast_google_events function, which is utilizing the <a href="https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html">Phoenix PubSub library</a> to broadcast a message to another module:</p><pre>defp broadcast_google_events(events, last_updated) do<br>  PubSub.broadcast(App.PubSub, &quot;calendar_updates&quot;, {:calendar_updates, events, last_updated})<br>end</pre><p>Now, in the main module displaying a user’s calendar, which I haven’t shared because it will look totally different depending on your specific needs, but whatever that is for you, you can add the following in your mount function:</p><pre>  if connected?(socket), do: PubSub.subscribe(App.PubSub, &quot;calendar_updates&quot;)</pre><p>Now, this module is listening for changes when a user’s calendar is updated. We are “subscribed” to the calendar_updates topic. The final piece of this is to create a handle_info function like this:</p><pre> def handle_info({:calendar_updates, events, last_updated}, socket) do       <br>   updated_events = GoogleCalHelper.reshape_gcal_data(events)<br>      <br>   {:noreply, assign(socket, event_list: updated_events, last_updated: last_updated)}<br> end</pre><p>This function receives the updated_events list, re-shapes the data using our helper function I shared a few steps back, then updates the socket with the new list.</p><p>I’ll leave it to you to figure out how to display the list.</p><p><strong>Step 10: </strong>Now that we’re all hooked up and ready to receive updates from Google, let’s resolve the last step of refreshing our access tokens when they expire:</p><pre>def is_token_fresh(nil, _user_id), do: nil<br>  def is_token_fresh(token, user_id) do    <br>    token_info = case GcalGet.call(%{&quot;access_token_gcal&quot; =&gt; token}) do<br>      {:error, reason} -&gt; IO.inspect(reason)<br>      token -&gt; token<br>  end<br>  <br>  case DateTime.compare(token_info.access_token_exp, Timex.now()) do<br>    :gt -&gt; {:ok, token}<br>    :lt -&gt; new_token(token_info.refresh_token_gcal, user_id, context_id)<br>    :eq -&gt; {:ok, token}<br>  end<br>end<br><br>defp new_token(nil, user_id) do<br>  Logger.warn(&quot;No refresh token found for gCal on user_id #{user_id}&quot;)<br>  {:error, &quot;#{user_id} did not return a refresh token&quot;}<br>end<br>defp new_token(refresh_token, user_id) do<br>  <br>  refresh_client = OAuth2.Client.new([<br>    strategy: OAuth2.Strategy.Refresh,<br>    client_id: &quot;CLIENT_ID&quot;,<br>    client_secret: &quot;CLIENT_SECRET&quot;,<br>    site: &quot;https://accounts.google.com&quot;,<br>    token_url: &quot;https://oauth2.googleapis.com/token&quot;, <br>    params: %{&quot;refresh_token&quot; =&gt; refresh_token}<br>  ]) <br>    <br>  refreshed_client = OAuth2.Client.get_token!(refresh_client)<br>  <br>  {:ok, decode_token} = Jason.decode(refreshed_client.token.access_token)    <br>  <br>  current_time = Timex.now()<br>  expiration_time = Timex.shift(current_time, seconds: decode_token[&quot;expires_in&quot;])<br>  <br>  case GcalUpdate.call(user_id, %{<br>    &quot;access_token_gcal&quot; =&gt; decode_token[&quot;access_token&quot;],<br>    &quot;access_token_exp&quot; =&gt; expiration_time,<br>  }) do<br>    {:ok, _new_gcal_tokens} -&gt; nil<br>    {:error, error_message} -&gt; Logger.warn(error_message)<br>  end<br>  <br>  {:ok, decode_token[&quot;access_token&quot;]}<br>end</pre><p>In the original gcal_api_call function, we first check to see if a token is fresh, and the is_token_fresh function does exactly that. To do this, I am using the compare function from the <a href="https://hexdocs.pm/elixir/1.13/DateTime.html">DateTime library.</a> Also, this is where the oauth2 library finally comes into play. If the token is expired, we call the new_token function. Within this function, we set up our refresh_client, make the call to get a new access_token, then store that new token in our database, sending the newly minted access token to make another API call.</p><p>—</p><p>And that’s one way to integrate Google Calendar into your Elixir application. However, you might be asking, “but Alex, you didn’t refresh the calendar subscriptions! What happens when they expire?!” That will be the next article I write, as that process is a bit more involved, and this is already a long article. Our goal is to set up background workers using <a href="https://hexdocs.pm/oban/Oban.html">Oban</a> to not only re-subscribe to expired calendars, but also handle notifications from Google. More on that soon.</p><p>Hopefully, this article helps you along your journey of integrating Google Calendar (I know I could have used it when I first started this project!).</p><p>And please don’t hesitate to reach out with questions or comments.</p><p>Thank for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ddbb162dfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding read-only sections in the Monaco Editor in React Part 2]]></title>
            <link>https://medium.com/@fraiha26/adding-read-only-sections-in-the-monaco-editor-in-react-part-2-b693cf5a7c92?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/b693cf5a7c92</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[monaco]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 12:45:39 GMT</pubDate>
            <atom:updated>2023-04-20T12:45:39.474Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll share how to add a reset button in the same component as your Monaco Editor while using the <a href="https://constrained-editor-plugin.vercel.app/docs/Usage/creating-an-instance">constrained editor plugin</a>.</p><p>In the last article, I shared how to set up the constrained editor plugin within a React component to be used with the <a href="https://www.npmjs.com/package/@monaco-editor/react">Monaco Editor for React</a>. This allowed for the creation of read only sections within the editor. Here is the final code from Part 1:</p><pre>import { constrainedEditor } from &quot;constrained-editor-plugin&quot;;<br><br>// Within React Component<br><br>let restrictions = [];<br><br>function handleEditorDidMount(editor, monaco) {<br>    monacoRef.current = editor;<br><br>    const constrainedInstance = constrainedEditor(monaco);<br>    const model = editor.getModel();<br>    constrainedInstance.initializeIn(editor);<br>    restrictions.push({<br>      range: [2, 1, 4, 1],<br>      allowMultiline: true<br>    });<br><br>    constrainedInstance.addRestrictionsTo(model, restrictions);<br>  }<br>};</pre><p>Now, let’s figure out how to add a reset button to our component so that the user can reset the code in the editor to a default value.</p><p>To begin, let’s take the code above and build it out a bit, adding the code for a functional React component:</p><pre>import React, { useState, useRef } from &#39;react&#39;;<br>import MonacoEditor from &#39;react-monaco-editor&#39;;<br>import { constrainedEditor } from &quot;constrained-editor-plugin&quot;;<br><br>function MyEditor() {<br>  const [code, setCode] = useState(&#39;&#39;);<br>  const monacoRef = useRef(null);<br>  const constrainedInstanceRef = useRef(null);<br>  const restrictions = [];<br><br>  const handleEditorDidMount = (editor, monaco) =&gt; {<br>    monacoRef.current = editor;<br>    const constrainedInstance = constrainedEditor(monaco);<br>    const model = editor.getModel();<br><br>    constrainedInstance.initializeIn(editor);<br>    restrictions.push({<br>      range: [1, 1, 1, 1],<br>      allowMultiline: true,<br>    });<br><br>    constrainedInstance.addRestrictionsTo(model, restrictions);<br>    constrainedInstanceRef.current = constrainedInstance;<br>  };<br><br>  const handleResetCode = () =&gt; {<br>    setCode(&#39;Hello, World!&#39;);<br>  };<br><br>  const handleUnmount = () =&gt; {<br>    if (constrainedInstanceRef.current) {<br>      constrainedInstanceRef.current.dispose();<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleResetCode}&gt;Reset Code&lt;/button&gt;<br>      &lt;MonacoEditor<br>        language=&quot;javascript&quot;<br>        editorDidMount={handleEditorDidMount}<br>        onChange={(newValue) =&gt; setCode(newValue)}<br>        onUnmount={handleUnmount}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyEditor;</pre><p>In the code above, I’ve set up a simple React component that returns both the Monaco Editor and a button to handle resetting the code within the editor. If a user clicks on the button, the code in the editor should reset to a default value. In this case, that default value is a string: ‘Hello, World!’.</p><p>Let’s review some of the new code in the file above, starting from the top.</p><pre>const monacoRef = useRef(null);<br>const constrainedInstanceRef = useRef(null);</pre><p>I added the monacoRef and constrainedInstanceRef variables as useRef hooks to store references to the editor and constrainedInstance objects, respectively. This will give us access to the instance of the editor with which we’re working.</p><p>I won’t review the handleEditorDidMount function, but <a href="https://medium.com/@fraiha26/adding-read-only-sections-in-the-monaco-editor-in-react-ae64c6f2fac5">feel free to review part 1 for more information on this.</a></p><p>Skipping over the handleResetCode function for a moment, let’s discuss the handleUnmount function.</p><pre>const handleUnmount = () =&gt; {<br>    if (constrainedInstanceRef.current) {<br>      constrainedInstanceRef.current.dispose();<br>    }<br>  };</pre><p>The handleUnmount function utilizes the built-in dispose method found within the Constrained Editor library to use on the constrainedInstance object when the component unmounts. We are using the reference we created (constrainedInstanceRef) to access the current instance of the constrained editor. For the current editor instance, the dispose method removes the event listeners and other resources associated with it. The onUnmount prop within the code editor in the return statement is set to the handleUnmount function, which calls the dispose() method.</p><p>Next, let’s discuss the code for the reset button:</p><pre>const [code, setCode] = useState(&#39;&#39;);<br><br>const handleResetCode = () =&gt; {<br>    setCode(&#39;Hello, World!&#39;);<br>  };<br><br>&lt;button onClick={handleResetCode}&gt;Reset Code&lt;/button&gt;ed</pre><p>In the code above, I’ve set up a simple onClick event handler where when a user clicks the Reset Code button, the code in the editor should change to the default code we’ve set within the handleResetCode function, which, in this case, is ‘Hello, World!’.</p><p>If you were to try to use the complete code above, you might find that there is a pretty serious issue. If you were to try adding random code to the code editor to test the reset button, you might find that the code only resets back to your most recent change, basically mimicking what it’s like to click the undo button in a text editor once. This is not what we want though. We want all of the code in the code editor to be replaced with our default code.</p><p>So, how do we resolve this issue? By adding the following lines of code to the handleResetCode funtion:</p><pre>const handleResetCode = () =&gt; {<br>  const defaultCode = &#39;console.log(&quot;Hello, world!&quot;);&#39;;<br>  const model = monacoRef.current.getModel();<br>  model.setValue(defaultCode);<br>  setCode(defaultCode);<br>};</pre><p>In this updated function, we first define a variable defaultCode with the default code that we want to set. Then, we get the editor&#39;s model using the getModel() method of the editor object, and set its value to defaultCode using the setValue() method. Finally, we update the state of the code variable to match the default code.</p><p>This update will reset all of the code in the editor to the default value.</p><p>The final code looks like this:</p><pre>import React, { useState, useRef } from &#39;react&#39;;<br>import MonacoEditor from &#39;react-monaco-editor&#39;;<br>import { constrainedEditor } from &quot;constrained-editor-plugin&quot;;<br><br>function MyEditor() {<br>  const [code, setCode] = useState(&#39;&#39;);<br>  const monacoRef = useRef(null);<br>  const constrainedInstanceRef = useRef(null);<br>  const restrictions = [];<br><br>  const handleEditorDidMount = (editor, monaco) =&gt; {<br>    monacoRef.current = editor;<br>    const constrainedInstance = constrainedEditor(monaco);<br>    const model = editor.getModel();<br><br>    constrainedInstance.initializeIn(editor);<br>    restrictions.push({<br>      range: [1, 1, 1, 1],<br>      allowMultiline: true,<br>    });<br><br>    constrainedInstance.addRestrictionsTo(model, restrictions);<br>    constrainedInstanceRef.current = constrainedInstance;<br>  };<br><br>  const handleResetCode = () =&gt; {<br>    const defaultCode = &#39;console.log(&quot;Hello, world!&quot;);&#39;;<br>    const model = monacoRef.current.getModel();<br>    model.setValue(defaultCode);<br>    setCode(defaultCode);<br>};<br><br>  const handleUnmount = () =&gt; {<br>    if (constrainedInstanceRef.current) {<br>      constrainedInstanceRef.current.dispose();<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleResetCode}&gt;Reset Code&lt;/button&gt;<br>      &lt;MonacoEditor<br>        language=&quot;javascript&quot;<br>        editorDidMount={handleEditorDidMount}<br>        onChange={(newValue) =&gt; setCode(newValue)}<br>        onUnmount={handleUnmount}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyEditor;</pre><p>With the code above, you not only can create read only sections within your editor, but a user can now reset the code in the editor to a default value you have set.</p><p>Hopefully, this is helpful to some of you out there. Please feel free to reach out with any questions or comments. Thanks so much for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b693cf5a7c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding read-only sections in the Monaco Editor in React Part 1]]></title>
            <link>https://medium.com/@fraiha26/adding-read-only-sections-in-the-monaco-editor-in-react-ae64c6f2fac5?source=rss-f63694777701------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae64c6f2fac5</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[code-editor]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[monaco]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[AlexF]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 14:14:03 GMT</pubDate>
            <atom:updated>2023-04-20T11:58:43.705Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll review how to add read-only sections to an instance of your Monaco Editor in React.</p><p>For context, I am working with a small team to create an algorithm competition website, which utilizes <a href="https://microsoft.github.io/monaco-editor/">the Monaco editor</a>, a free-to-use and full-featured code editor created by Microsoft. We chose Monaco over <a href="https://codemirror.net/">CodeMirror</a> and <a href="https://ace.c9.io/">Ace</a> (two other popular code editors) because of it’s ease-of-use, extensive documentation and our team’s familiarity with Monaco.</p><p>For our particular use case, we wanted to limit a user’s ability to edit specific lines of text within the code editor. Unfortunately, this is not a built-in feature but luckily, <a href="https://github.com/Pranomvignesh">Vignesh Prakash</a> created a simple but powerful plug-in for the Monaco editor called <a href="https://github.com/Pranomvignesh/constrained-editor-plugin">Constrained Editor Plug-in</a>.</p><p>Here is an example of the code to which we wanted to apply read-only limitations:</p><pre>function findSpecificNumber(root) {<br>  // write your code here<br>}<br><br>// example of the binary-tree class - do not edit<br>class binaryTree {<br>  constructor(number, sherman = false) {<br>    this.number = number;<br>    this.specificNumber = specificNumber;<br>    this.left = null;<br>    this.right = null; <br>  }<br>}<br><br>runSubmission()</pre><p>In this example, we only want users to be able to type within the findSpecificNumber function (or where you see “// write your code here”). The reasoning for this is that if a user deletes anything below the “do not edit” line, our code execution engine might fail as it relies on the execution of the rubSubmission function on the last line.</p><p><strong>So, how did we use the npm package </strong><a href="https://www.npmjs.com/package/constrained-editor-plugin"><strong>Constrained Editor Plug-In</strong></a><strong> to accomplish this using Monaco editor and React?</strong></p><ol><li>First, install the Constrained Editor Plug-in package.</li></ol><pre>npm i constrained-editor-plugin</pre><p>2. Second, import the package into your React project. This should live in the same component as your code editor.</p><pre>import { constrainedEditor } from &quot;constrained-editor-plugin&quot;;</pre><p>3. I am assuming that you are here because you already have a working instance of the Monaco editor within your React project. If this is the case, to begin the process of utilizing the Constrained Editor Plug-in, assign an empty array to the restrictions variable in your code editor component:</p><pre>  let restrictions = [];</pre><p>More on this in a bit.</p><p>4. Now, let’s create the instance of the constrained editor. The great thing about this plug-in is that you only need a few other lines of code to get things working. If you are working with the Monaco editor in React, you are probably utilizing the handleEditorDidMount function to create an instance of your editor. If you are not currently utilizing the handleEditorDidMount function, I believe you will need to to correctly get this package to work in React(though, there are probably many other ways to accomplish this). Below is the rest of the code you will need to add to your project:</p><pre>  function handleEditorDidMount(editor, monaco) {<br>    monacoRef.current = editor;<br><br>    const constrainedInstance = constrainedEditor(monaco);<br>    const model = editor.getModel();<br>    constrainedInstance.initializeIn(editor);<br>    restrictions.push({<br>      range: [2, 1, 4, 1],<br>      allowMultiline: true<br>    });<br><br>    constrainedInstance.addRestrictionsTo(model, restrictions);<br>  }</pre><p>I removed all extraneous code from this function that didn’t pertain to limiting a user’s ability to edit specific lines of code.</p><p><strong>Let’s break this block of code down line by line.</strong></p><p>The first line of the function (monacoRef.current = editor) creates a reference to the current instance of the editor. Then, we pass the monaco argument to the constrainedEditor function, creating a new instance of a constrained editor.</p><pre>monacoRef.current = editor;<br><br>const constrainedInstance = constrainedEditor(monaco);</pre><p>Next, we want to assign the actual document that is being shown in the Monaco editor to the model variable.</p><pre>const model = editor.getModel();</pre><p>Then, we want the constrained editor to add the necessary functions into the editor instance. This is accomplished by passing the current instance of the editor into the built-in method initializeIn.</p><pre> constrainedInstance.initializeIn(editor);</pre><p>Next, we want to create the restrictions that we’ll apply to the editor.</p><pre>restrictions.push({<br>      range: [2, 1, 4, 1],<br>      allowMultiline: true<br>    });</pre><p>This is also why we had created the empty array and assigned it to the restrictions variable outside of the handleEditorDidMount function.</p><p>The range refers to: [ startLine, startColumn, endLine, endColumn ]</p><p>Finally, we need to apply these restrictions to the current model, passing the model and restrictions arguments to the addRestrictions built-in method.</p><pre>constrainedInstance.addRestrictionsTo(model, restrictions);</pre><p>And that should do it. Now, your code editor will limit a user’s ability to only write and/or edit text within findSpecificNumber function above, or whatever range you used. Feel free to push as many restrictions as you’d like to the restrictions array. For example, if you want to allow two or more editable blocks, simply add:</p><pre>    <br>    restrictions.push({<br>      range: [2, 1, 4, 1],<br>      allowMultiline: true<br>    });<br><br>    restrictions.push({<br>      range: [5, 1, 7, 1],<br>      allowMultiline: true<br>    });</pre><p>The final code (or lines of code you would need in your React component for this feature to work) would look something like this:</p><pre>import { constrainedEditor } from &quot;constrained-editor-plugin&quot;;<br><br>// Within React Component<br><br>let restrictions = [];<br><br>function handleEditorDidMount(editor, monaco) {<br>    monacoRef.current = editor;<br><br>    const constrainedInstance = constrainedEditor(monaco);<br>    const model = editor.getModel();<br>    constrainedInstance.initializeIn(editor);<br>    restrictions.push({<br>      range: [2, 1, 4, 1],<br>      allowMultiline: true<br>    });<br><br>    constrainedInstance.addRestrictionsTo(model, restrictions);<br>  }<br>};<br></pre><p>Thanks for reading and I hope this helps anyone else that is struggling with implementing read-only text in the Monaco editor in React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae64c6f2fac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>