<?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 Henok T on Medium]]></title>
        <description><![CDATA[Stories by Henok T on Medium]]></description>
        <link>https://medium.com/@hegystyle?source=rss-84cfcfba8548------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DjGAVr0roWeqLR7hbKST4w.jpeg</url>
            <title>Stories by Henok T on Medium</title>
            <link>https://medium.com/@hegystyle?source=rss-84cfcfba8548------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:16:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hegystyle/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[Enhance Your Web Browsing Experience with Our Chrome Extension: PageChat]]></title>
            <link>https://medium.com/mission-data-journal/enhance-your-web-browsing-experience-with-pagechat-our-chrome-extension-and-how-we-built-it-c1cb4a31d24c?source=rss-84cfcfba8548------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1cb4a31d24c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Henok T]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 18:55:08 GMT</pubDate>
            <atom:updated>2023-06-05T20:19:50.814Z</atom:updated>
            <content:encoded><![CDATA[<h4>See how we built “PageChat”, a Chrome extension allowing users to access ChatGPT and ask questions about and summarize web pages.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GBof_FreIKS-Jox9.jpg" /></figure><p>As a developer, I use ChatGPT throughout the day to help with my work, and often find myself wanting to ask questions about the topic I am reading on a webpage. So, I decided to write a <a href="https://github.com/HenokT/PageChat">Chrome extension</a> that lets you do just that. This extension allows you to access ChatGPT from any webpage, as well as ask questions about the page you are on or summarize it. The extension also remembers your chat history so you can continue your conversation later.</p><p>Before I get into the details of how I wrote this extension, for those who are not familiar with Chrome extension development, I encourage you to read the <a href="https://developer.chrome.com/docs/extensions/mv3/architecture-overview/">architecture overview</a> in the official Chrome extensions documentation.</p><h3>Tech Stack</h3><p>Being a fan of <a href="https://react.dev/">React</a>, I decided to use it to build out the UI. I am also a fan of the <a href="https://vitejs.dev/">Vite</a> bundler as it provides fast reloads during development and requires minimal configuration. However, I couldn’t just use the <a href="https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts">Vite</a> template for react projects as is. There are differences in entry points between a Chrome extension and a typical React app. The entry point for an extension is a manifest.json file, not an HTML page. This file contains the metadata for the extension as well as paths to content and background scripts and popup and options pages. Luckily, I found a Vite plugin <a href="https://crxjs.dev/vite-plugin/">CRXJS</a> that was created to address this specific problem. This plugin parses the manifest.json file and generates the appropriate Vite config, ensuring the manifest.json and files referenced in it are compiled and exported to the output directory dist. This also means things like <strong>Hot Module Replacement(HMR)</strong> and <strong>static asset imports</strong> we are used to when developing React apps will work as expected.</p><h3>The Popup</h3><p>The <a href="https://github.com/HenokT/PageChat/blob/main/src/popup/Popup.tsx">Popup</a> component is the main UI for the extension. It’s what the user sees when they click on the extension icon in the browser toolbar. It’s mounted by src/popup.tsx script into the popup.html page that&#39;s referenced in manifest.json.</p><p>The first time the user opens the popup, the <a href="https://github.com/HenokT/PageChat/blob/main/src/options/Options.tsx">Options</a> component is rendered where they are asked to supply an <a href="https://platform.openai.com/account/api-keys">OpenAI API key</a>. This key is stored in the extensions’s <a href="https://developer.chrome.com/docs/extensions/reference/storage/">local</a> storage via the <a href="https://github.com/HenokT/PageChat/blob/main/src/utils/useSettingsStore.tsx">useSettingStorage</a> custom hook that uses the <a href="https://github.com/HenokT/PageChat/blob/main/src/common/SettingsStoreProvider.tsx">SettingsStoreContext</a> under the hood:</p><pre>export default function Popup(){<br>  const { loading, settings } = useSettingsStore();<br>  /* ... */<br>  if (loading || !settings.openAIApiKey) {<br>    return &lt;Options /&gt;;<br>  }<br>  /* ... */<br>}<br><br>export default function Options() {<br>  const { loading, settings, setSettings } = useSettingsStore();<br>  const [openAIApiKeyInputText, setOpenAIApiKeyInputText] = useState(&quot;&quot;);<br>  /* ... */<br>  const saveOptions = useCallback(<br>    (event: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>      event.preventDefault();<br>      try {<br>        setSettings({<br>          ...settings,<br>          openAIApiKey: openAIApiKeyInputText,<br>        });<br>        /* ... */<br>      } catch (error) {<br>        /* ... */<br>      }<br>    },<br>    [openAIApiKeyInputText, setSettings, settings, /* ... */]<br>  );<br><br>  return (<br>    &lt;div&gt;<br>      &lt;form onSubmit={saveOptions} &gt;<br>        { /* ... */}<br>          &lt;button type=&quot;submit&quot;&gt;<br>            Save<br>          &lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Note:</strong> Users also have the option to change the API key later by right clicking on the extension icon and selecting the “Options” from the context menu. This opens the <a href="https://github.com/HenokT/PageChat/blob/main/src/options/Options.tsx">Options</a> component in the chrome extension management page as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*bG662rwFzZY5BuN7.png" /></figure><p>Once the OpenAI API key is set, the <a href="https://github.com/HenokT/PageChat/blob/main/src/popup/Chatbot.tsx">Chatbot</a> and <a href="https://github.com/HenokT/PageChat/blob/main/src/popup/PageSummary.tsx">PageSummary</a> component are rendered as tabs</p><h3>The Chatbot</h3><p>The <a href="https://github.com/HenokT/PageChat/blob/main/src/popup/Chatbot.tsx">Chatbot</a> component is where the user interacts with ChatGPT. It has two modes: <strong>Chat with GPT</strong> and <strong>Chat with page</strong>. The first mode is the default mode, and it allows the user to chat with GPT directly. The second mode allows the user to ask questions about the page they are on. The user can switch between the two modes by selecting the corresponding option from the dropdown menu at the top of the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*na8KiKqVKJmuagia.png" /></figure><p>In either mode, I am using <a href="https://js.langchain.com/docs/">LangChain</a> to interface with the OpenAI API. LangChain is an awesome library that lets you interface with a number of large language models (LLMs) including OpenAI’s GPT and Embeddings models. It also provides many utilities for pre and post processing of text data that you have to do when working with LLMs.</p><h4>Chatbot with GPT Mode</h4><p>When Chatbot is mounted and mode is <strong>Chatbot with GPT</strong>, it loads stored settings and existing chat history from <a href="https://developer.chrome.com/docs/extensions/reference/storage/#storage-areas">local storage</a> using the <a href="https://github.com/HenokT/PageChat/blob/main/src/utils/useChatHistory.ts">useChatHistory</a> custom hook that I wrote.</p><pre>const { settings, setSettings } = useSettingsStore();<br>const { openAIApiKey, chatMode = &quot;with-llm&quot; } = settings;<br>const [, history, setHistory] = useChatHistory([], chatMode);</pre><p>Under the hood, useChatHistory uses a generic <a href="https://github.com/HenokT/PageChat/blob/main/src/utils/useStoredState.ts">useStoredState</a> hook to load and save chat history from and to local storage.</p><p>It then initializes a <a href="https://js.langchain.com/docs/getting-started/guide-chat#memory-add-state-to-chains-and-agents">ConversationChain</a> instance as follows:</p><pre>const chain = useMemo(() =&gt; {<br>  const llm = new ChatOpenAI({<br>    openAIApiKey: openAIApiKey,<br>    // temperature: 0,<br>    streaming: true,<br>    verbose: true,<br>    callbacks: [<br>      {<br>        handleLLMNewToken(token: string) {<br>          setResponseStream((streamingText) =&gt; streamingText + token);<br>        },<br>        handleLLMEnd() {<br>          setResponseStream(&quot;&quot;);<br>        },<br>      },<br>    ],<br>  });<br><br>  /* ... */<br><br>  return new ConversationChain({<br>    memory: new BufferMemory({<br>      returnMessages: true,<br>      inputKey: &quot;input&quot;,<br>      memoryKey: &quot;history&quot;,<br>      chatHistory: {<br>        async getMessages() {<br>          return history;<br>        },<br>        async addUserMessage(message) {<br>          setHistory((history) =&gt; [...history, new HumanChatMessage(message)]);<br>        },<br>        async addAIChatMessage(message) {<br>          setHistory((history) =&gt; [...history, new AIChatMessage(message)]);<br>        },<br>        async clear() {<br>          setHistory([]);<br>        },<br>      },<br>    }),<br>    llm: llm,<br>    prompt: ChatPromptTemplate.fromPromptMessages([<br>      new MessagesPlaceholder(&quot;history&quot;),<br>      HumanMessagePromptTemplate.fromTemplate(&quot;{input}&quot;),<br>    ]),<br>  });<br>}, [openAIApiKey, chatMode, history, setHistory /* ... */]);</pre><p>ConversationChain is a class provided by LangChain. A chain in LangChain is a wrapper around primitives like LLM instances, memory or other chains that you can use to create complex interactions with LLM and other systems. Here, we are using the ConversationChain because it wraps an LLM instance and memory and ensures that our prompts to the LLM and the responses are stored in memory transparently.</p><p>The memory type the chain is configured with is a <a href="https://js.langchain.com/docs/modules/memory/examples/buffer_memory">BufferMemory</a> that lets you decide how the chat history is stored by passing an object that implements the following methods:</p><pre>async getMessages() {}<br>async addUserMessage(message){}<br>async addAIChatMessage(message){}<br>async clear() {}</pre><p>My implementation of these methods are just delegate calls to the accessors returned by the useChatHistory hook above.</p><p>You will also notice that the prompt template has a placeholder new MessagesPlaceholder(&quot;history&quot;) that the chain will replace with the chat history stored in memory when it&#39;s invoked. This is how we ensure that the chat history is included in the prompt to the LLM.</p><p>The LLM instance is initialized with the OpenAI API key and two callbacks. The first one is called when the LLM streams tokens as they are generated which are then appended to the responseStream state. The second one is called when the LLM is done processing the prompt. In this case we clear the responseStream state. In my experience, without this streaming capability, the LLMs I had access to feel too slow to be used as a chatbot.</p><p>The initialized ConversationChain is memoized and doesn&#39;t need to be reinitialized when the component re-renders unless states that it depends on have changed.</p><p>When the user types a message and hits enter, the sendUserMessage handler is called:</p><pre>const sendUserMessage = useCallback(<br>  async (event: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    /* ... */<br><br>    try {<br>      abortControllerRef.current = new AbortController();<br><br>      setUserInputAwaitingResponse(userInput);<br>      setUserInput(&quot;&quot;);<br><br>      if (chain instanceof ConversationChain) {<br>        const response = await chain.call({<br>          input: userInput,<br>          signal: abortControllerRef.current?.signal,<br>        });<br>      } else if (chain instanceof ConversationalRetrievalQAChain) {<br>        /* ... */<br>      }<br>    } catch (error) {<br>      /* ... */<br>    } finally {<br>      /* ... */<br>    }<br>  },<br>  [chain, history, setHistory, userInput]<br>);</pre><p>Here, we invoke the chain with the user input. Under the hood, the chain will build a prompt using the prompt template it was initialized with and call the LLM with the prompt. The LLM will start streaming the response back to the handleLLMNewToken callback. When streaming is done, the handleLLMEnd callback is invoked. Before the chain invocation returns, the user message and the LLM response are added to the chat history transparently.</p><p>Here is how I present the chat history to the user — accounting for the different states the chatbot might be in:</p><pre>function ChatMessageRow({ message }: { message: BaseChatMessage }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;span&gt;{message instanceof HumanChatMessage ? &quot;You: &quot; : &quot;Bot: &quot;}&lt;/span&gt;<br>      &lt;div&gt;<br>        &lt;ReactMarkdown children={message.text} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>function Chatbot{<br>  /* ... */<br>  return (<br>    &lt;div&gt;<br>      {/* ... */}<br>      {(history.length &gt; 0 ||<br>        userInputAwaitingResponse ||<br>        responseStream ||<br>        error) &amp;&amp; (<br>        &lt;div&gt;<br>          {history.map((message, index) =&gt; {<br>            return &lt;ChatMessageRow key={index} message={message} /&gt;;<br>          })}<br>          {userInputAwaitingResponse &amp;&amp; (<br>            &lt;ChatMessageRow<br>              message={new HumanChatMessage(userInputAwaitingResponse)}<br>            /&gt;<br>          )}<br>          {responseStream &amp;&amp; (<br>            &lt;ChatMessageRow message={new AIChatMessage(responseStream)} /&gt;<br>          )}<br>          {error &amp;&amp; (<br>            &lt;ChatMessageRow message={new AIChatMessage(`Error: ${error}`)} /&gt;<br>          )}<br>        &lt;/div&gt;<br>      )}<br>      {/* ... */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>As a side note, the chat history in this mode is accessible from any page and across browser sessions until the user clears it.</p><h4>Chatbot with Page Mode</h4><p>This mode is intended to answer questions about the page the user is on. Conceptually, we can accomplish this by including the page content as <em>context</em> in the prompt to the LLM as follows:</p><pre>`Use the following pieces of context to answer the question at the end. If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>{context}<br><br>Question: {question}<br>Helpful Answer:`</pre><p>This will work for small pages but LLMs have a limit on the length of the prompt they can process. For ChatGPT-3.5-turbo it’s 4,096 tokens (1 token is approximately 4 characters or ¾ words for English text). GPT-4 comes in flavors that have max token limits of 8,192 tokens and 32,768 tokens. To get around this limit, we have to split the page content into chunks and only include relevant chunks to the question as context in the prompt.</p><p>A state of the art tool that’s suited for the aforementioned task is a <a href="https://js.langchain.com/docs/modules/indexes/vector_stores/">vector store</a>. A vector store is a database that stores documents and their <a href="https://platform.openai.com/docs/guides/embeddings/what-are-embeddings">embeddings</a> for efficient retrieval of relevant documents based on similarity to a query’s embedding.</p><p>To keep things simple, I am loading the page content into a <a href="https://js.langchain.com/docs/modules/vector_store/memory_vector_store">MemoryVectorStore</a> instance in a useEffect callback as follows:</p><pre>async function getCurrentPageContent() {<br>  const [tab] = await chrome.tabs.query({<br>    active: true,<br>    currentWindow: true,<br>  });<br><br>  if (!tab.id) return;<br><br>  try {<br>    return await chrome.tabs.sendMessage&lt;<br>      GetPageContentRequest,<br>      GetPageContentResponse<br>    &gt;(tab.id, {<br>      action: &quot;getPageContent&quot;,<br>    });<br>  } catch (error) {<br>    console.error(error);<br>    throw new Error(&quot;Unable to get page content&quot;);<br>  }<br>}<br><br>useEffect(() =&gt; {<br>  let ignore = false;<br><br>  async function loadPageIntoVectorStore() {<br>    try {<br>      const pageContent = await getCurrentPageContent();<br>      if (!pageContent?.pageContent) return;<br><br>      const textSplitter = new RecursiveCharacterTextSplitter({<br>        chunkSize: 4000,<br>        chunkOverlap: 200,<br>      });<br><br>      const docs = await textSplitter.createDocuments([<br>        pageContent.pageContent,<br>      ]);<br><br>      const vectorStore = await MemoryVectorStore.fromDocuments(<br>        docs,<br>        new OpenAIEmbeddings({ openAIApiKey })<br>      );<br><br>      if (ignore) return;<br><br>      setPageContentVectorStore(vectorStore);<br>    } catch (error) {<br>      console.error(error);<br>      setError(`Error: ${error}`);<br>    }<br>  }<br><br>  if (chatMode === &quot;with-page&quot;) {<br>    loadPageIntoVectorStore();<br>  }<br><br>  return () =&gt; {<br>    ignore = true;<br>  };<br>}, [chatMode, openAIApiKey]);</pre><p>There is a lot going on in the above code snippet so let’s break it down.</p><p>To get the page content, I first query Chrome for the information about the current tab. I then send an async message with the payload {action: &quot;getPageContent&quot;} to a <a href="https://github.com/HenokT/PageChat/blob/main/src/content-script.tsx">content-script</a> that I wrote and is injected by the extension into the current tab. <a href="https://developer.chrome.com/docs/extensions/mv3/content_scripts/">Content scripts</a> are the only component of an extension that has access to the DOM of the current page, also known as the host page. Other extension components like the popup and background scripts that need information about the DOM have to send messages to the content script to get it.</p><p>As shown below, the content script responds with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText">innerText</a> of the primary content element of the page:</p><pre>chrome.runtime.onMessage.addListener(function (<br>  request: GetPageContentRequest,<br>  _sender,<br>  sendResponse<br>) {<br>  if (request.action === &quot;getPageContent&quot;) {<br>    const primaryContentElement =<br>      document.body.querySelector(&quot;article&quot;) ??<br>      document.body.querySelector(&quot;main&quot;) ??<br>      document.body;<br><br>    sendResponse({<br>      pageContent: primaryContentElement.innerText,<br>    } as GetPageContentResponse);<br>  }<br>});</pre><p>I then use the <a href="https://js.langchain.com/docs/modules/indexes/text_splitters/examples/recursive_character">RecursiveCharacterTextSplitter</a> to split the page content into chunks of 4,000 characters (approximately 1000 tokens) long. With 200 characters overlap between chunks.</p><p>Finally, I initialize the MemoryVectorStore with the chunks and an instance of the <a href="https://js.langchain.com/docs/modules/models/embeddings/">OpenAIEmbeddings</a> model that it can use to generate embeddings for each chunk. The initialized vector store is saved in a state variable.</p><p>Next, I initialize a <a href="https://js.langchain.com/docs/modules/chains/index_related_chains/conversational_retrieval">ConversationalRetrievalQAChain</a> instance as follows:</p><pre>if (chatMode === &quot;with-page&quot;) {<br>  if (!pageContentVectorStore) return undefined;<br><br>  return ConversationalRetrievalQAChain.fromLLM(<br>    llm,<br>    pageContentVectorStore.asRetriever()<br>  );<br>}</pre><p>ConversationalRetrievalQAChain is another chain provided by LangChain and is designed to retrieve relevant chunks of a document from a vector store based on a question and include them in a prompt to the LLM. Also, as we will see later, it supports chat history so that the user can ask follow up questions.</p><p>Similar to the ConversationChain we saw before, the initialized ConversationalRetrievalQAChain is memoized and doesn&#39;t need to be reinitialized when the component re-renders.</p><p>When the user types a question about the page and hits enter, the sendUserMessage handler is called:</p><pre>const sendUserMessage = useCallback(<br>  async (event: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    /* ... */<br><br>    try {<br>      abortControllerRef.current = new AbortController();<br><br>      setUserInputAwaitingResponse(userInput);<br>      setUserInput(&quot;&quot;);<br><br>      if (chain instanceof ConversationChain) {<br>        /* ... */<br>      } else if (chain instanceof ConversationalRetrievalQAChain) {<br>        const response = await chain.call({<br>          question: userInput,<br>          chat_history: history.map((message) =&gt; message.text),<br>          signal: abortControllerRef.current?.signal,<br>        });<br><br>        setHistory((history) =&gt; [<br>          ...history,<br>          new HumanChatMessage(userInput),<br>          new AIChatMessage(response.text),<br>        ]);<br><br>    } catch (error) {<br>      /* ... */<br>    } finally {<br>      /* ... */<br>  },<br>  [chain, history, setHistory, userInput]<br>);</pre><p>This time, I invoke the ConversationalRetrievalQAChain with the user input. I also have to pass the chat history manually because that chain doesn&#39;t have a memory component. The way the response is streamed back from the LLM is the same as before but when the call ends, the user message and the LLM response are added to the chat history manually.</p><p>Internally, when there is an existing chat history, the ConversationalRetrievalQAChain will break the task of answering the question into two steps. First, it will send the following prompt to the LLM asking it to rephrase the user&#39;s question to account for the chat history.</p><pre>`Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.<br><br>Chat History:<br>{chat_history}<br>Follow Up Input: {question}<br>Standalone question:`</pre><p>Then, it uses the new question to retrieve relevant chunks from its vector store and send the following prompt to the LLM to answer the question.</p><pre>`Use the following pieces of context to answer the question at the end. If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>{context}<br><br>Question: {question}<br>Helpful Answer:`</pre><p>The following chat with the <a href="https://developer.chrome.com/docs/extensions/mv3/messaging/">message passing</a> page of the extensions documentation illustrates how this works:</p><blockquote><em>First question: what’s this page about?</em></blockquote><blockquote><strong><em>First response:</em></strong><em> This page is about message passing in Chrome extensions, including communication between content scripts and other parts of the extension using one-time requests and long-lived connections, cross-extension messaging, and messaging between web pages and extensions. It also covers security considerations and best practices for avoiding cross-site scripting and validating input. Finally, it includes information on how to send messages to native applications using the native messaging feature.</em></blockquote><blockquote><strong><em>Second question:</em></strong><em> how do I ensure security?</em></blockquote><blockquote><strong><em>Rephrased question:</em></strong><em> What are the security considerations and best practices for avoiding cross-site scripting and validating input in Chrome extensions?</em></blockquote><blockquote><strong><em>Second response: </em></strong><em>To avoid cross-site scripting and validate input in Chrome extensions, developers should be aware of the security considerations of content scripts, which are less trustworthy than the extension service worker. Messages from content scripts might have been crafted by an attacker, so all input should be validated and sanitized. Also, dangerous APIs such as eval() and innerHTML should be avoided, and instead, safer APIs like JSON.parse() and innerText should be used. Best practices also include using promises instead of callbacks, using long-lived connections for conversations that last longer than a single request and response, and setting up proper port lifetime management. Additionally, developers can use externally_connectable in their manifest.json to specify which websites they want to communicate with and listen for messages from web pages via the runtime.onMessageExternal or runtime.onConnectExternal APIs.</em></blockquote><h3>Page Summarization</h3><p>Page summarization is an interesting task to tackle with LLMs, given their limits in the length of prompt they can process. While we can work around this constraint for question answering tasks through the use of a vector store, summarization requires the LLM to process the entire document. Thankfully, LangChain has a <a href="https://js.langchain.com/docs/api/chains/classes/MapReduceDocumentsChain">MapReduceDocumentsChain</a> available to handle such problems.</p><p>When the user switches to the <strong>Page Summary</strong> tab, the <a href="https://github.com/HenokT/PageChat/blob/main/src/popup/PageSummary.tsx">PageSummary</a> component is mounted and I try to load a previously generated summary from session storage using the useStoredState hook:</p><pre>const [loading, summary, setSummary] = useStoredState&lt;StoredSummary&gt;({<br>  storageKey: StorageKeys.PAGE_SUMMARY,<br>  defaultValue: INITIAL_SUMMARY,<br>  storageArea: &#39;session&#39;,<br>  scope: &#39;page&#39;<br>});</pre><p>If there is no previously generated summary, I initialize a summarization chain instance and invoke it passing the page content as chunks as follows:</p><pre>useEffect(() =&gt; {<br>  /* ... */<br>  async function summarizeCurrentPage() {<br>    if (loading || summary.content) return;<br><br>    /* ... */<br>    try {<br>      const pageContent = await getCurrentPageContent();<br><br>      if (!pageContent) return;<br><br>      const llm = new ChatOpenAI({<br>        openAIApiKey: openAIApiKey,<br>      });<br><br>      const textSplitter = new RecursiveCharacterTextSplitter({<br>        chunkSize: 4000,<br>      });<br><br>      const docs = await textSplitter.createDocuments([<br>        pageContent.pageContent,<br>      ]);<br><br>      const template = SUPPORTED_SUMMARY_TYPES.find(<br>        (type) =&gt; type.type === summary.type<br>      )?.template;<br><br>      if (!template) return;<br><br>      const prompt = new PromptTemplate({<br>        template: template,<br>        inputVariables: [&quot;text&quot;],<br>      });<br><br>      const chain = loadSummarizationChain(llm, {<br>        type: &quot;map_reduce&quot;,<br>        combineMapPrompt: prompt,<br>        combinePrompt: prompt,<br>      });<br>      const response = await chain.call({<br>        input_documents: docs,<br>      });<br><br>      /* ... */<br><br>      setSummary({<br>        ...summary,<br>        content: response.text,<br>      });<br>    } catch (error) {<br>      /* ... */<br>    } finally {<br>      /* ... */<br>    }<br>  }<br>  summarizeCurrentPage();<br><br> /* ... */<br><br>}, [loading, openAIApiKey, setSummary, summary]);</pre><p>loadSummarizationChain is just a helper function, when its type parameter is map_reduce, returns an instance of MapReduceDocumentsChain configured with a summarization prompt:</p><pre>export const loadSummarizationChain = (llm, params = { type: &quot;map_reduce&quot; }) =&gt; {<br>     /* ... */<br>    if (params.type === &quot;map_reduce&quot;) {<br>        const { combineMapPrompt = DEFAULT_PROMPT, combinePrompt = DEFAULT_PROMPT, returnIntermediateSteps, } = params;<br>        const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose });<br>        const combineLLMChain = new LLMChain({<br>            prompt: combinePrompt,<br>            llm,<br>            verbose,<br>        });<br>        const combineDocumentChain = new StuffDocumentsChain({<br>            llmChain: combineLLMChain,<br>            documentVariableName: &quot;text&quot;,<br>            verbose,<br>        });<br>        const chain = new MapReduceDocumentsChain({<br>            llmChain,<br>            combineDocumentChain,<br>            documentVariableName: &quot;text&quot;,<br>            returnIntermediateSteps,<br>            verbose,<br>        });<br>        return chain;<br>    }<br>     /* ... */<br>};</pre><p>This chain works by summarizing each chunk of the document separately and then combining the summaries into a single input that’s then fed to the LLM to generate a final summary. If the combined summary is too long for the LLM to process, it will be split into chunks and the process will be repeated until the combined summary + instruction length is under the LLM’s max tokens limit.</p><p>The chain also allows you to provide different prompts for summarizing the individual chunks (the map phase) and the combined summaries (the reduce phase). I chose to use the same prompt for both phases but it varies based on the type of summary the user selects. For the default summary type, <strong>Concise</strong>, the following prompt is used:</p><pre>`Write a concise summary of the following in markdown format:<br><br><br>&quot;{text}&quot;<br><br><br>CONCISE SUMMARY:`</pre><p>Here are sample summaries that are generated for a <a href="https://developer.chrome.com/docs/extensions/mv3/content_scripts/">page</a> that covers content scripts in depth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*Lo_zcIE5gv102Ftz.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*rSuJ_truFjRS6NQz.png" /></figure><p>The MapReduceDocumentsChain tries to be efficient by executing the summarization of chunks in parallel. However, because of the recursive nature of the reduce phase, which ensures the combined summary is short enough, it can be slow for large pages.</p><p>On the upside, the MapReduceDocumentsChain is implemented in a way that if it&#39;s configured with an LLM that has a higher max tokens limit, it can combine chunks transparently before sending them. This means that if I have access to the high-end GPT-4 model, I can reduce the summarization time by an order of magnitude just by switching the model passed to the chain. This is without taking into account other improvements in the new model.</p><h3>Conclusion</h3><p>Highlights of some improvements that can be made to this extension:</p><ul><li>The <strong>Chat with GPT</strong> history is currently stored in local storage which has a max size of 5MB. An option can be added that allows the user to offload this responsibility to a cloud storage like Firebase or S3. This could also make it practical to store <strong>Chat with Page</strong> history permanently.</li><li>It could support maintaining multiple chat histories and allow switching between them — similar to how the ChatGPT site does.</li><li>It could support chatting with multiple LLMs at the same time. This could be a killer feature of this extension.</li><li>It could also support ChatGPT plugins via LangChain’s <a href="https://js.langchain.com/docs/modules/agents/tools/">tools</a> abstraction.</li><li>Page summarization currently is slow on large pages and could be canceled if the user closes the popup or switches to another tab. A <a href="https://developer.chrome.com/docs/extensions/mv3/service_workers/basics/">Service Worker</a> can be used to run the summarization in the background, store the result and send the message to the popup when it’s done.</li></ul><p>I hope this post was a helpful overview of how one can develop a Chrome extension with React and Vite. I also hope it was an inspiration on how to use LangChain to interface with LLMs to accomplish complex tasks. The way I see it, the possibilities are endless. I encourage you to play with libraries like LangChain to get a feel for what’s possible.</p><p>You can find the source code for this extension on <a href="https://github.com/HenokT/PageChat">Github</a>.</p><h3>About Mission Data</h3><p>We’re designers, engineers, and strategists building innovative digital products that transform the way companies do business. Learn more: <a href="https://www.missiondata.com/">https://www.missiondata.com</a>.</p><p><em>Originally published at </em><a href="https://blog.missiondata.com/enhance-your-web-browsing-experience-with-pagechat-our-chrome-extension-and-how-we-built-it/"><em>https://blog.missiondata.com</em></a><em> on June 5, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1cb4a31d24c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mission-data-journal/enhance-your-web-browsing-experience-with-pagechat-our-chrome-extension-and-how-we-built-it-c1cb4a31d24c">Enhance Your Web Browsing Experience with Our Chrome Extension: PageChat</a> was originally published in <a href="https://medium.com/mission-data-journal">Mission Data Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lab Notes: An Introduction to Android Jetpack Compose]]></title>
            <link>https://medium.com/mission-data-journal/lab-notes-an-introduction-to-android-jetpack-compose-cc1bd730e2e9?source=rss-84cfcfba8548------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc1bd730e2e9</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Henok T]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 18:02:06 GMT</pubDate>
            <atom:updated>2022-10-31T15:59:28.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*fDCRiBFvRUCu7UOCxA60OA.png" /></figure><p><a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> is a fairly new UI toolkit for Android that is declarative and represents a departure from the legacy view-based imperative library. It’s an adaptation of UI development concepts first made popular by the web UI library <a href="https://reactjs.org/">React</a>. If you are already familiar with React, you will have an easier time learning Compose. However, in this article, I don’t assume the reader has prior knowledge of any declarative UI frameworks.</p><h3>Basics</h3><p>Compose is a fundamental rethinking of how Android UI is authored. As such many of the concepts that we used to associate with Android UI development such as XML layout files, view/data binding, list adapters, and the use of imperative APIs to interact with views are no longer a thing. With Compose, all of your UI layout and logic is written as Kotlin functions annotated with the <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/Composable">@Composable</a> annotation. This means you have the full power of the Kotlin language at your fingertips to write composable functions that emit different UI trees based on their arguments and local state variables.</p><p>Let’s look at a composable function that emits different post headers based on the type of post it’s given as a parameter:</p><pre>@Composable<br>private fun PostHeader(post: Post) {<br>    Column(<br>        Modifier.padding(horizontal = 10.dp),<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(<br>            text = post.title,<br>            style = MaterialTheme.typography.h6,<br>            modifier = Modifier.padding(bottom = 8.dp)<br>        )<br>        if (post.postType == PostType.Promoted) {<br>            Text(<br>                text = &quot;Promoted Post&quot;,<br>                style = MaterialTheme.typography.subtitle1,<br>            )<br>        } else {<br>            Text(<br>                text = &quot;Shared by ${post.author}&quot;,<br>                style = MaterialTheme.typography.subtitle2,<br>            )<br>        }<br>    }<br>}</pre><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#Column(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.ui.Alignment.Horizontal,kotlin.Function1)">Column</a> is a layout composable function from the foundation package that places its children in a vertical sequence. It’s analogous to using the &lt;LinearLayout android:orientation=&quot;vertical&quot;/&gt; tag in the legacy layout system and is part of a layout system that includes two other common layout composables: <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#Row(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.Arrangement.Horizontal,androidx.compose.ui.Alignment.Vertical,kotlin.Function1)">Row</a> and <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#Box(androidx.compose.ui.Modifier)">Box</a>, which are analogous to &lt;LinearLayout android:orientation=&quot;horizontal&quot;/&gt; and &lt;FrameLayout/&gt; respectively.</p><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#Text(kotlin.String,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.font.FontStyle,androidx.compose.ui.text.font.FontWeight,androidx.compose.ui.text.font.FontFamily,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextDecoration,androidx.compose.ui.text.style.TextAlign,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextOverflow,kotlin.Boolean,kotlin.Int,kotlin.Function1,androidx.compose.ui.text.TextStyle)">Text</a> is another composable function from the material package that displays text using a given style, font size, color, etc.</p><p>The basic idea is simple. You describe your UI tree based on the data passed to your composable functions as arguments and local state variables. When the arguments or local state variables change, Compose re-executes your composable with the new data in a process called recomposition and a new UI tree is emitted.</p><p>One way to trigger a recomposition is by updating a state observed by your composables. Let’s look at a PostCard composable function that wraps the PostHeader composable from above and reacts to post title clicks by toggling the visibility of the post content based on a state variable.</p><pre>@Composable<br>private fun PostCard(<br>    post: Post,<br>    modifier: Modifier = Modifier<br>) {</pre><pre>    var isExpanded by remember { mutableStateOf(false) }</pre><pre>    Column(modifier = modifier) {<br>        PostHeader(<br>            post,<br>            onTitleClick = {<br>                isExpanded = !isExpanded<br>            },<br>            isExpanded = isExpanded<br>        )<br>        if (isExpanded) {<br>            Text(<br>                text = post.content,<br>                style = MaterialTheme.typography.body1,<br>                modifier = Modifier.padding(top = 8.dp)<br>            )<br>        }</pre><pre>    }<br>}</pre><pre>@Composable<br>private fun PostHeader(<br>    post: Post,<br>    onTitleClick: () -&gt; Unit = {}<br>    isExpanded: Boolean,<br>) {<br>    Column(<br>        modifier = Modifier<br>            .padding(horizontal = 10.dp)<br>            .let {<br>                if (isExpanded) it.border(width = 1.dp, color = Color.Red) else it<br>            },<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(<br>            text = post.title,<br>            style = MaterialTheme.typography.h6,<br>            modifier = Modifier<br>                .padding(bottom = 8.dp)<br>                .clickable { onTitleClick() },<br>        )<br>        <em>/*...*/</em><br>    }<br>}</pre><p>The first thing you will notice is that we are declaring a state variable isExpanded using this syntax:</p><pre>var isExpanded by remember { mutableStateOf(false) }</pre><p>There is a lot to unpack here so let’s go through it one by one:</p><ul><li><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#mutableStateOf(kotlin.Any,androidx.compose.runtime.SnapshotMutationPolicy)">mutableStateOf</a> returns a <a href="https://developer.android.com/jetpack/compose/state#state-in-composables">MutableState</a> object initialized with the passed in value. A MutableState object is a single value holder whose reads and writes are observed by the Compose runtime. When the value is changed, it triggers a recomposition of the composables that read from it and any composables that they call.</li><li><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#remember(kotlin.Function0)">remember</a> is a Compose specific function that ensures that the value returned by its lambda parameter is remembered across recompositions. Without it, our state object will be reinitialized on every recomposition.</li><li>by is a kotlin keyword for declaring a <a href="https://kotlinlang.org/docs/delegated-properties.html#local-delegated-properties">delegated property</a> - syntactic sugar that lets us read and write a value stored in an object (returned by the right side) as if it&#39;s a local variable.</li></ul><p>To react to the post title click, we are passing in an event handler callback to the PostHeader composable which in turn forwards it to the Text composable that displays the title. Inside the callback, we update the value of isExpanded state, which triggers a recomposition of the PostCard and PostHeader composables and causes a new UI tree to be emitted.</p><h3>Integration with Activity and Fragment lifecycle</h3><p>In a 100% Compose application, you typically will have one activity as an entry point where the root of the compose UI tree is set as the content of the activity in an onCreate lifecycle callback as follows. You can then nest other composables under the root of the UI tree (MyApp) to describe the UI for the entire app.</p><pre>class MainActivity : AppCompatActivity(){  <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MyApp()<br>        }<br>    }<br>}</pre><pre>@Composable<br>fun MyApp() {<br>    var currentRoute by remember {<br>        mutableStateOf(NavRoutes.POST_FEED)<br>    }</pre><pre>    when (currentRoute) {<br>        NavRoutes.POST_FEED -&gt; {<br>            val postFeedViewModel = viewModel&lt;PostFeedViewModel&gt;()<br>            PostFeed(<br>                postFeedViewModel = postFeedViewModel,<br>                navigateTo = {<br>                    currentRoute = it<br>                }<br>            )<br>        }<br>        NavRoutes.SETTINGS -&gt; {<br>            val settingsViewModel = viewModel&lt;SettingsViewModel&gt;()<br>            UserSettings(settingsViewModel = settingsViewModel,<br>                navigateTo = {<br>                    currentRoute = it<br>                }<br>            )<br>        }<br>    }<br>}</pre><pre>object NavRoutes {<br>    const val POST_FEED = &quot;post-feed&quot;<br>    const val SETTINGS = &quot;settings&quot;<br>}<br></pre><pre>@Composable<br>fun PostFeed(postFeedViewModel: PostFeedViewModel, navigateTo: (route: String) -&gt; Unit) {<br>    val posts by postFeedViewModel.posts.collectAsState()<br>    LazyColumn {<br>        items(items = posts) { post -&gt;<br>            PostCard(post = post)<br>        }<br>    }<br>}</pre><pre>@Composable<br>fun UserSettings(settingsViewModel: SettingsViewModel, navigateTo: (route: String) -&gt; Unit) {<br>     <em>/*...*/</em><br>}</pre><p>The navigation scheme we are using above is straightforward and works for simple apps but Compose also provides deep integration with Jetpack <a href="https://developer.android.com/jetpack/compose/navigation">Navigation</a> that can be employed for complex apps.</p><p>The example also demonstrates how we can obtain an instance of a <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/ViewModel">ViewModel</a> that’s scoped to the lifecycle of the activity by using the built-in <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/viewmodel/compose/package-summary#viewModel(androidx.lifecycle.ViewModelStoreOwner,kotlin.String,androidx.lifecycle.ViewModelProvider.Factory)">viewModel&lt;T : ViewModel&gt;()</a> function.</p><p>You can also progressively adopt Compose by implementing some parts of your UI with it. We don’t go into that here but the official guide has a <a href="https://developer.android.com/jetpack/compose/interop/adding">section</a> dedicated to this use case.</p><h3>Modifiers</h3><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier">Modifiers</a> in compose allow you to decorate a composable and affect its size, layout, appearance, interactivity, etc.</p><p>In the following example, we use modifiers to specify the layout constraints for the Column layout and set a background and padding for its contents. We also use modifiers to specify the aspect ratio of the Image composable and make it clickable by passing a click event handler lambda.</p><pre>@Composable<br>fun PostCard(post: Post, onImageClick: () -&gt; Unit) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .height(200.dp)<br>            .background(color = Color.Gray)<br>            .padding(vertical = 8.dp, horizontal = 12.dp)<br>    ) {<br>        Image(<br>            painter = rememberImagePainter(post.image.url),<br>            contentDescription = &quot;&quot;,<br>            modifier = Modifier<br>                .aspectRatio(16/9f)<br>                .clickable { onImageClick() }<br>        )<br>        Text(<em>/*...*/</em>)<br>    }<br>}</pre><p>Modifiers are also type-safe, in that you will only have access to modifiers that are allowed in the scope the composable you are modifying is in. For example, you can use the weight modifier to have composables with flexible sizes inside a Row or Column layout. However, the weight modifier is not available within a Box layout.</p><p>One thing to be mindful about when using modifiers is that the order in which they are applied matters. Consider the following example of a custom button implemented with a Text composable centered within a Box layout.</p><pre>@Composable<br>private fun CustomButton(text: String){<br>    Box(<br>        modifier = Modifier<br>            .padding(5.dp)<br>            .background(Color.Red)<br>            .clickable { <em>/*...*/</em> }<br>    ) {<br>       Text(text = text, modifier = Modifier.align(Alignment.Center))<br>    }<br>}</pre><p>The padding modifier is applied to the Box composable before the background and clickable modifiers. This means the background color won&#39;t be applied to the padding area and the clickable surface won&#39;t include the padding.</p><p>On the other hand, if we apply the padding modifier after the background and clickable modifiers, as shown below, both modifiers apply to the padding area.</p><pre>@Composable<br>private fun CustomButton(text: String){<br>    Box(<br>        modifier = Modifier<br>            .background(Color.Red)<br>            .clickable { <em>/*...*/</em> }<br>            .padding(5.dp)<br>    ) {<br>       Text(text = text, modifier = Modifier.align(Alignment.Center))<br>    }<br>}</pre><p>You can also apply the same modifier multiple times. Below, we are applying the padding and background modifiers twice to give the button surface a layered appearance.</p><pre>@Composable<br>private fun FancyButton(text: String){<br>    Box(<br>        modifier = Modifier<br>            .clickable { <em>/*...*/</em> }<br>            .background(Color.Red)<br>            .padding(5.dp)<br>            .background(Color.Yellow)<br>            .padding(5.dp)<br>    ) {<br>        Text(text = text, modifier = Modifier.align(Alignment.Center))<br>    }<br>}</pre><h3>CompositionLocal</h3><p>In Compose, you will have values that are frequently and widely used in your composables and passing those values as arguments to all composables that rely on them isn’t practical. Examples of these types of values are the context object and theming values like color and typography styles. Compose addresses this concern by providing a way to pass data down the composition tree implicitly via what’s called <a href="https://developer.android.com/jetpack/compose/compositionlocal">CompositionLocal</a>. And if you are familiar with React, it’s analogous to <a href="https://reactjs.org/docs/context.html">React.Context</a>.</p><p>You can find the use of this feature in the built-in stringResource composable function that loads string resources by resource id.</p><pre>@Composable<br>fun stringResource(@StringRes  id: Int): String {<br>    <em>// simplified for clarity</em><br>    val context = LocalContext.current<br>    return context.resources.getString(id)<br>}</pre><p>As you can see above, the context object is obtained by simply accessing the current property of a top-level property object LocalContext of type CompositionLocal.</p><p>You can think of a CompositionLocal instance as a key to a value in an internally managed map. When you access its current property, it returns a value associated with it somewhere higher up in the composition tree. This becomes clearer when you want to provide your own values via CompositionLocal. Here is an example in which we initialize and provide a GoogleSignInClient instance that is needed by composables throughout our app.</p><p>We first declare a CompositionLocal&lt;GoogleSignInClient?&gt; instance as a top-level property associated with a default value of null:</p><pre>val LocalGoogleSignInClient = staticCompositionLocalOf&lt;GoogleSignInClient?&gt; { null }</pre><p>Then, inside the root of our Compose tree (MyApp), we initialize a GoogleSignInClient instance and wrap the contents of the app with the CompositionLocalProvider composable while providing the mapping of the LocalGoogleSignInClient CompositionLocal to the initialized client as its argument:</p><pre>@Composable<br>fun MyApp() {</pre><pre>    val context = LocalContext.current<br>    <br>    val gso = GoogleSignInOptions<br>        .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)<br>        .requestIdToken(context.getString(R.string.google_sign_in_server_client_id))<br>        .requestEmail()<br>        .requestId()<br>        .build()<br>    <br>    val googleSignInClient = GoogleSignIn.getClient(context, gso)</pre><pre>    CompositionLocalProvider(<br>        LocalGoogleSignInClient provides googleSignInClient<br>    ){<br>        var currentRoute by remember {<br>            mutableStateOf(NavRoutes.POST_FEED)<br>        }</pre><pre>        when (currentRoute) {<br>            NavRoutes.POST_FEED -&gt; {<br>                <em>/*...*/</em><br>            }<br>            NavRoutes.SETTINGS -&gt; {<br>                val settingsViewModel = viewModel&lt;SettingsViewModel&gt;()<br>                UserSettings(settingsViewModel = settingsViewModel,<br>                    navigateTo = {<br>                        currentRoute = it<br>                    }<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>Now, any composable in our app that needs to access the initialized GoogleSignInClient can do so as follows:</p><pre>@Composable<br>fun UserSettings(settingsViewModel: SettingsViewModel, navigateTo: (route: String) -&gt; Unit) {<br>    val googleSignInClient = LocalGoogleSignInClient.current<br>    <em>/*...*/</em><br>}</pre><p>Keep in mind that CompositionLocal is a powerful feature but it has the potential to make your composables context-dependent and less testable. It’s only intended to be used when it is not practical to pass values to composables via arguments.</p><h3>Side Effects</h3><p>Although composables, in general, should be side-effect free, there are cases that require us to launch side-effects from composables. Below is an example where we launch an effect to increment the view count of the PostFeed when it enters composition.</p><pre>@Composable<br>fun PostFeed(postFeedViewModel: PostFeedViewModel, navigateTo: (route: String) -&gt; Unit) {<br>    LaunchedEffect(postFeedViewModel) {<br>        <em>// this block is executed in a coroutine scope and </em><br>        <em>// can call suspend functions that make API/db calls,  </em><br>        <em>// provided that those suspend functions are implemented </em><br>        <em>// to run with a dispatcher other than Dispatchers.Main</em><br>        postFeedViewModel.incrementViews()<br>    }<br>    <em>/*...*/</em><br>}</pre><p>There are other ways to launch a side effect depending on your requirements and are documented in detail in the <a href="https://developer.android.com/jetpack/compose/side-effects">side-effect</a> section of the official guide.</p><h3>Preview</h3><p>Previews are one of my favorite features of Compose; they allow you to preview your composables with different arguments and system configurations during development from within Android Studio. As an example, if you have the following previews of the PostCard composable from above defined in Android Studio, when you switch to the design view of the file containing those previews, you will see two instances of the composable rendered - one in light mode (default) and one in dark mode.</p><pre>@Preview(&quot;PostCard (light)&quot;)<br>@Preview(&quot;PostCard (dark)&quot;, uiMode = Configuration.UI_MODE_NIGHT_YES)<br>@Composable<br>fun PreviewPostCard() {<br>    MaterialTheme {<br>        PostCard(<br>            post = samplePosts[0],<br>            onImageClick = {}<br>        )<br>    }<br>}</pre><h3>Conclusion</h3><p>In my opinion, Jetpack Compose is a game-changer in Android UI development. Implementation of UI layout and behavior that used to span multiple files and formats can now be expressed as a tree of composable functions where you have all of Kotlin at your disposal. And with previews, you can quickly iterate through the design of your composables until you get something you are happy with.</p><p>There are topics that I haven’t covered such as Theming, Navigation, Lists, Animation, Gestures, etc but are covered in detail in the <a href="https://developer.android.com/jetpack/compose/documentation">official guide</a>.</p><figure><a href="https://cta-redirect.hubspot.com/cta/redirect/2399711/2c85370d-6a82-4f11-aee4-b5d3a2964e61"><img alt="Teaser graphic with text that states “Turn your visions into real digital solutions.”" src="https://cdn-images-1.medium.com/max/1024/1*v7WvulucBnqVwh-vF6reLQ.jpeg" /></a></figure><p><strong>About Mission Data:</strong><br>We’re designers, engineers, and strategists building innovative digital products that transform the way companies do business. Learn more: <a href="https://www.missiondata.com/">https://www.missiondata.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc1bd730e2e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mission-data-journal/lab-notes-an-introduction-to-android-jetpack-compose-cc1bd730e2e9">Lab Notes: An Introduction to Android Jetpack Compose</a> was originally published in <a href="https://medium.com/mission-data-journal">Mission Data Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remembering the previous value of a prop or a state while using React Hooks]]></title>
            <link>https://medium.com/@hegystyle/remembering-the-previous-value-of-a-prop-or-a-state-while-using-react-hooks-6f57686aa0a6?source=rss-84cfcfba8548------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f57686aa0a6</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Henok T]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 16:56:35 GMT</pubDate>
            <atom:updated>2019-06-15T17:44:28.494Z</atom:updated>
            <content:encoded><![CDATA[<p>Prior to the introduction of hooks, if you want to know the previous value of a React component’s prop or state, you’d have to implement the life cycle method componentDidUpdate(prevProps, prevState){..}. However, with hooks, you can’t use class components and life-cycle methods and there is no built-in mechanism of accessing the previous value of a prop or state from your function components. Fortunately, you can write a custom hook that relies on useRef and useEffect to remember previous values of any value it’s provided.</p><pre>import React, { useRef, useEffect, useState } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;</pre><pre>const usePreviousValue = value =&gt; {<br>  const ref = useRef();<br>  useEffect(() =&gt; {<br>    ref.current = value;<br>  });<br>  return ref.current;<br>};</pre><pre>function App() {<br>  const [value, setValue] =  useState(&quot;&quot;)<br>  const prevValue = usePreviousValue(value)<br>  return (<br>    &lt;div className=&quot;App container mt-5&quot;&gt;<br>      &lt;input<br>        className=&quot;form-control&quot;<br>        placeholder=&quot;Type something here&quot;<br>        value={value}<br>        onChange={e =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;div className=&quot;text-left mt-2&quot;&gt;<br>        Curr Value: {value}<br>      &lt;/div&gt;<br>      &lt;div className=&quot;text-left&quot;&gt;<br>        Prev Value: {prevValue}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You can even combine it with useState to create another custom hook that returns both the previous and current value of a state in one call</p><pre>const useTraceableState = initialValue =&gt; {<br>  const [value, setValue] = useState(initialValue);<br>  const prevValue = usePreviousValue(value);<br>  return [prevValue, value, setValue];<br>};</pre><p>That’s it. You got to love the composability of hooks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f57686aa0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>