From 2b35dce0372ea8eab4e034a00f38fe114a503566 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Thu, 15 Apr 2021 17:33:52 +0200 Subject: [PATCH] :tada: Add cache for font fetching on embedd ns. --- frontend/src/app/main/repo.cljs | 9 ++-- .../src/app/main/ui/shapes/text/embed.cljs | 46 ++++++++++++++----- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/frontend/src/app/main/repo.cljs b/frontend/src/app/main/repo.cljs index ef9050268..3d2a167a7 100644 --- a/frontend/src/app/main/repo.cljs +++ b/frontend/src/app/main/repo.cljs @@ -7,12 +7,13 @@ (ns app.main.repo (:require [app.common.data :as d] - [beicon.core :as rx] - [lambdaisland.uri :as u] - [cuerdas.core :as str] [app.config :as cfg] + [app.util.http :as http] + [app.util.time :as dt] [app.util.transit :as t] - [app.util.http :as http])) + [beicon.core :as rx] + [cuerdas.core :as str] + [lambdaisland.uri :as u])) (defn- handle-response [{:keys [status body] :as response}] diff --git a/frontend/src/app/main/ui/shapes/text/embed.cljs b/frontend/src/app/main/ui/shapes/text/embed.cljs index 4e8030497..1b1475a60 100644 --- a/frontend/src/app/main/ui/shapes/text/embed.cljs +++ b/frontend/src/app/main/ui/shapes/text/embed.cljs @@ -11,6 +11,7 @@ [app.common.text :as txt] [app.main.fonts :as fonts] [app.util.http :as http] + [app.util.time :as dt] [app.util.webapi :as wapi] [app.util.object :as obj] [clojure.set :as set] @@ -19,6 +20,23 @@ [beicon.core :as rx] [rumext.alpha :as mf])) + +(defonce cache (atom {})) + +(defn with-cache + [{:keys [key max-age]} observable] + (let [entry (get @cache key) + age (when entry + (dt/diff (dt/now) + (:created-at entry)))] + (if (and (some? entry) + (< age max-age)) + (rx/of (:data entry)) + (->> observable + (rx/tap (fn [data] + (let [entry {:created-at (dt/now) :data data}] + (swap! cache assoc key entry)))))))) + (def font-face-template " /* latin */ @font-face { @@ -63,20 +81,26 @@ (->> (rx/take 1 observable) (rx/subs resolve reject))))) -(defn get-font-data +(defn fetch-font-data "Parses the CSS and retrieves the font data as DataURI." [^string css] (let [uris (->> (re-seq #"url\(([^)]+)\)" css) - (map second))] - (->> (rx/from (seq uris)) - (rx/mapcat (fn [uri] - (http/send! {:method :get - :uri uri - :response-type :blob}))) - (rx/map :body) - (rx/mapcat wapi/read-file-as-data-url) - (rx/reduce conj []) - (http/as-promise)))) + (mapv second))] + (with-cache {:key uris :max-age (dt/duration {:hours 4})} + (->> (rx/from (seq uris)) + (rx/mapcat (fn [uri] + (http/send! {:method :get + :uri uri + :response-type :blob}))) + (rx/map :body))))) + +(defn get-font-data + "Parses the CSS and retrieves the font data as DataURI." + [^string css] + (->> (fetch-font-data css) + (rx/mapcat wapi/read-file-as-data-url) + (rx/reduce conj []) + (http/as-promise))) (defn embed-font "Given a font-id and font-variant-id, retrieves the CSS for it and