summaryrefslogtreecommitdiff
path: root/source/Felix/Render/Html/Export.hs
blob: a3f0e3993e17707c23811c5b93799036741dc52f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Prepare a complete HTML export from retained parsed presentation.
module Felix.Render.Html.Export
    ( HtmlPresentation
    , htmlPresentationFromParsedWorkspace
    , HtmlExportError(..)
    , renderHtmlExportError
    , prepareHtmlExport
    , prepareHtmlExportWithLayout
    , prepareHtmlExportWithLayoutFromRendererRoots
    ) where

import Base
import Felix.Parse
import Felix.Source
import Felix.Render.Html qualified as Html
import Felix.Render.Html.Context
import Felix.Render.Html.Layout
import Felix.Render.Html.Output
import Felix.Syntax.Abstract (Block)

import Control.Exception (Exception, IOException, displayException)
import Control.Exception qualified as Exception
import Data.Bifunctor (first)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TextEncoding
import Data.Text.Encoding.Error (UnicodeException)
import Data.Text.IO qualified as TextIO
import System.Directory (doesFileExist)
import System.FilePath.Posix ((</>))


-- | The strict, invocation-local subset of parsed presentation needed by the
-- renderer. Construction forces the complete module sequence and every page
-- shell, severing references to parser payloads, syntax interfaces, and
-- canonical cache payloads.
data HtmlPresentation = HtmlPresentation
    !(NonEmpty HtmlSourcePresentation)

data HtmlSourcePresentation = HtmlSourcePresentation
    !ResolvedSource
    ![Block]

htmlPresentationFromParsedWorkspace
    :: ParsedSourceWorkspace
    -> HtmlPresentation
htmlPresentationFromParsedWorkspace workspace =
    HtmlPresentation
        (strictMapNonEmpty project parsedModules)
  where
    parsedModules =
        parsedWorkspaceImportedBeforeImporter workspace
    project parsedModule =
        HtmlSourcePresentation
            (parsedModuleResolved parsedModule)
            (parsedModuleBlocks parsedModule)

strictMapNonEmpty :: (a -> b) -> NonEmpty a -> NonEmpty b
strictMapNonEmpty f (value :| values) =
    let !firstPage = f value
        !rest = strictMapList f values
    in firstPage :| rest

strictMapList :: (a -> b) -> [a] -> [b]
strictMapList _ [] =
    []
strictMapList f (value : values) =
    let !next = f value
        !rest = strictMapList f values
    in next : rest

data HtmlExportError
    = HtmlRendererDataNotFound !FilePath ![FilePath]
    | HtmlRendererDataLookupFailed !FilePath !Text
    | HtmlRendererDataReadFailed !FilePath !Text
    | HtmlExportLayoutError !HtmlLayoutError
    | HtmlExportContextError !HtmlRenderContextError
    deriving stock (Show)

instance Exception HtmlExportError

renderHtmlExportError :: HtmlExportError -> Text
renderHtmlExportError = \case
    HtmlRendererDataNotFound requested searched ->
        "renderer data " <> quotePath requested <> " was not found; searched "
            <> Text.intercalate ", " (quotePath <$> searched)
    HtmlRendererDataLookupFailed path reason ->
        "could not locate renderer data " <> quotePath path <> ": " <> reason
    HtmlRendererDataReadFailed path reason ->
        "could not read renderer data " <> quotePath path <> ": " <> reason
    HtmlExportLayoutError failure ->
        renderHtmlLayoutError failure
    HtmlExportContextError failure ->
        case failure of
            HtmlCurrentSourceNotRouted source ->
                "current source has no HTML route: " <> sourceLabel source
            HtmlReferencedSourceNotRouted source ->
                "referenced source has no HTML route: " <> sourceLabel source
  where
    sourceLabel source =
        sourceMountIdText (resolvedSourceMount source)
            <> ":"
            <> Text.pack
                (safeRelativePathFilePath
                    (resolvedSourceRelativePath source))

    quotePath = Text.pack . show

prepareHtmlExport
    :: [(SourceMountId, [Text])]
    -> HtmlPresentation
    -> Text
    -> Either HtmlExportError [PreparedHtmlArtifact]
prepareHtmlExport
        mountPrefixes
        (HtmlPresentation presentation)
        hints = do
    let sources =
            sourceOf <$> NonEmpty.toList presentation
    layout <-
        first
            HtmlExportLayoutError
            (layoutHtmlSources mountPrefixes sources)
    prepareRenderedExport hints layout presentation
  where
    sourceOf (HtmlSourcePresentation source _blocks) =
        source

prepareHtmlExportWithLayout
    :: HtmlLayout
    -> HtmlPresentation
    -> Text
    -> Either HtmlExportError [PreparedHtmlArtifact]
prepareHtmlExportWithLayout
        layout
        (HtmlPresentation presentation)
        hints =
    prepareRenderedExport hints layout presentation

prepareHtmlExportWithLayoutFromRendererRoots
    :: [FilePath]
    -> HtmlLayout
    -> HtmlPresentation
    -> IO (Either HtmlExportError [PreparedHtmlArtifact])
prepareHtmlExportWithLayoutFromRendererRoots roots layout presentation = do
    hintsResult <- findAndReadRendererFile roots "lexicon.tsv"
    pure do
        hints <- hintsResult
        prepareHtmlExportWithLayout layout presentation hints

-- Renderer data follows the established current-directory,
-- configured-library, and debug-directory lookup policy.
findAndReadRendererFile
    :: [FilePath]
    -> FilePath
    -> IO (Either HtmlExportError Text)
findAndReadRendererFile roots path =
    selectRendererData path ((</> path) <$> roots) >>= \case
        Left failure -> pure (Left failure)
        Right selectedPath -> do
            readResult <- tryRendererRead (TextIO.readFile selectedPath)
            pure case readResult of
                Left reason ->
                    Left (HtmlRendererDataReadFailed selectedPath reason)
                Right contents -> Right contents

selectRendererData
    :: FilePath
    -> [FilePath]
    -> IO (Either HtmlExportError FilePath)
selectRendererData requested candidates = go candidates
  where
    go = \case
        [] -> pure (Left (HtmlRendererDataNotFound requested candidates))
        candidate : remaining ->
            tryRendererIO (doesFileExist candidate) >>= \case
                Left failure ->
                    pure
                        (Left
                            (HtmlRendererDataLookupFailed
                                candidate
                                (Text.pack (displayException failure))))
                Right True -> pure (Right candidate)
                Right False -> go remaining

tryRendererIO :: IO value -> IO (Either IOException value)
tryRendererIO = Exception.try

tryRendererRead :: IO value -> IO (Either Text value)
tryRendererRead action =
    Exception.catch
        (Exception.catch (Right <$> action) renderIOException)
        renderUnicodeException
  where
    renderIOException :: IOException -> IO (Either Text value)
    renderIOException = pure . Left . Text.pack . displayException

    renderUnicodeException
        :: UnicodeException
        -> IO (Either Text value)
    renderUnicodeException = pure . Left . Text.pack . displayException

prepareRenderedExport
    :: Text
    -> HtmlLayout
    -> NonEmpty HtmlSourcePresentation
    -> Either HtmlExportError [PreparedHtmlArtifact]
prepareRenderedExport hints layout presentation = do
    let sourceBlocks =
            (\(HtmlSourcePresentation source blocks) ->
                (source, blocks))
                <$> presentation
        (unforcedRenderIndex, pages) =
            Html.buildRenderIndex sourceBlocks
        !renderIndex = unforcedRenderIndex
        renderEnvironment =
            htmlRenderEnvironment layout
    pageArtifacts <-
        traverse
            (prepareSourceArtifact
                renderEnvironment
                layout
                hints
                renderIndex)
            pages
    let supportRoute =
            htmlSupportScriptRoute layout
        supportArtifact =
            preparedHtmlArtifact
                (routeDestination supportRoute)
                (Right
                    (TextEncoding.encodeUtf8
                        Html.supportScriptAssetContents))
        -- Page artifacts retain imported-before-importer source order.  The
        -- singleton support asset is published deterministically afterward.
    Right (NonEmpty.toList pageArtifacts <> [supportArtifact])

prepareSourceArtifact
    :: HtmlRenderEnvironment
    -> HtmlLayout
    -> Text
    -> Html.HtmlRenderIndex
    -> Html.HtmlPagePresentation
    -> Either
        HtmlExportError
        PreparedHtmlArtifact
prepareSourceArtifact renderEnvironment layout hints renderIndex page = do
    let source = Html.htmlPagePresentationSource page
    context <-
        first
            HtmlExportContextError
            (htmlRenderContextFromEnvironment
                renderEnvironment
                source)
    route <-
        maybe
            (Left
                (HtmlExportContextError
                    (HtmlCurrentSourceNotRouted source)))
            Right
            (htmlPageRoute layout source)
    Right
        (preparedHtmlArtifact
            (routeDestination route)
            (first renderHtmlExportError
                (TextEncoding.encodeUtf8
                    <$> first
                        HtmlExportContextError
                        (Html.renderDocument
                            context
                            hints
                            renderIndex
                            page))))