0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-02-10 09:08:31 -05:00

🎉 Add cache for font fetching on embedd ns.

This commit is contained in:
Andrey Antukh 2021-04-15 17:33:52 +02:00 committed by Andrés Moya
parent a777e8e42a
commit 2b35dce037
2 changed files with 40 additions and 15 deletions

View file

@ -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}]

View file

@ -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))]
(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)
(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))))
(http/as-promise)))
(defn embed-font
"Given a font-id and font-variant-id, retrieves the CSS for it and