okf-core-0.14.0.0: src/Okf/Graph.hs
-- | Markdown link extraction and concept graph construction.
module Okf.Graph
( Edge (..),
Graph (..),
Node (..),
buildGraph,
buildGraphWith,
danglingBodyPaths,
extractConceptLinks,
danglingReferences,
duplicateConceptIds,
)
where
import CMarkGFM qualified
import Data.Aeson (ToJSON (..), object, (.=))
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Okf.Bundle
import Okf.ConceptId
import Okf.Document (body)
import Okf.Index (VersionDeclaration (..), frontmatterReferenceContext)
import Okf.Markdown (parseMarkdown)
import Okf.Path (PathReference (..), PathResolution (..), ReferenceContext (..), classifyFileReference, resolveFileReference)
import Okf.Prelude hiding ((.=))
import System.FilePath qualified as FilePath
-- | A graph node for one concept.
data Node = Node
{ id :: !ConceptId,
label :: !Text,
type_ :: !Text,
description :: !(Maybe Text),
resource :: !(Maybe Text),
tags :: ![Text]
}
deriving stock (Generic, Eq, Show)
-- | A directed concept-to-concept link.
data Edge = Edge
{ source :: !ConceptId,
target :: !ConceptId
}
deriving stock (Generic, Eq, Ord, Show)
-- | Bundle graph data with presentation-free nodes and edges.
data Graph = Graph
{ nodes :: ![Node],
edges :: ![Edge]
}
deriving stock (Generic, Eq, Show)
instance ToJSON Node where
toJSON Node {id = nodeId, label = nodeLabel, type_ = nodeType, description = nodeDescription, resource = nodeResource, tags = nodeTags} =
object
[ "id" .= nodeId,
"label" .= nodeLabel,
"type" .= nodeType,
"description" .= nodeDescription,
"resource" .= nodeResource,
"tags" .= nodeTags
]
instance ToJSON Edge where
toJSON Edge {source, target} =
object
[ "source" .= source,
"target" .= target
]
instance ToJSON Graph where
toJSON Graph {nodes, edges} =
object
[ "nodes" .= nodes,
"edges" .= edges
]
-- | Build a graph from in-memory concepts using the undeclared version policy.
buildGraph :: [Concept] -> Graph
buildGraph concepts =
buildGraphWith VersionUndeclared (bundleInventoryOfConcepts concepts) concepts
-- | Connect body and frontmatter references that resolve to indexed concepts.
buildGraphWith :: VersionDeclaration -> BundleInventory -> [Concept] -> Graph
buildGraphWith declaration inventory concepts =
Graph
{ nodes = conceptNode <$> List.sortOn (renderConceptId . conceptIdOf) concepts,
edges = Set.toAscList edgesById
}
where
conceptsByPath = Map.fromList [(conceptSourcePath concept, conceptIdOf concept) | concept <- concepts]
exists = flip bundleInventoryContainsPath inventory
edgesById =
Set.fromList
[ Edge (conceptIdOf concept) target
| concept <- concepts,
let sourcePath = conceptSourcePath concept,
let references =
[(BodyReference, raw) | raw <- conceptBodyLinks concept]
<> [(frontmatterReferenceContext declaration, raw) | (_, raw) <- conceptPathFields concept],
(context, raw) <- references,
ResolvedInBundle resolved <- [resolveFileReference exists context sourcePath raw],
Just target <- [Map.lookup resolved conceptsByPath]
]
-- | Extract OKF concept links from a concept body.
extractConceptLinks :: Concept -> [ConceptId]
extractConceptLinks concept =
[ conceptId
| raw <- conceptBodyLinks concept,
BundlePath resolved <- [classifyFileReference (conceptSourcePath concept) raw],
FilePath.takeExtension resolved == ".md",
Right conceptId <- [conceptIdFromFilePath resolved]
]
-- | Find unresolved Markdown links using the available bundle inventory.
danglingBodyPaths :: BundleInventory -> [Concept] -> [(ConceptId, FilePath)]
danglingBodyPaths inventory concepts =
[ (conceptIdOf concept, target)
| concept <- concepts,
raw <- conceptBodyLinks concept,
DanglingInBundle target <- [resolveFileReference (flip bundleInventoryContainsPath inventory) BodyReference (conceptSourcePath concept) raw]
]
-- | Compatibility projection for callers only interested in missing .md paths.
danglingReferences :: [Concept] -> [(ConceptId, ConceptId)]
danglingReferences concepts =
[ (source, target)
| (source, path) <- danglingBodyPaths (bundleInventoryOfConcepts concepts) concepts,
FilePath.takeExtension path == ".md",
Right target <- [conceptIdFromFilePath path]
]
conceptBodyLinks :: Concept -> [Text]
conceptBodyLinks = extractMarkdownLinks . body . conceptDocument
-- | Concept IDs that appear more than once in a concept list. Always empty for
-- a bundle read from disk (paths are unique) but possible for an in-memory
-- producer assembling concepts before writing.
duplicateConceptIds :: [Concept] -> [ConceptId]
duplicateConceptIds concepts =
[ conceptId
| (conceptId, count) <- Map.toList counts,
count > (1 :: Int)
]
where
counts = Map.fromListWith (+) [(conceptIdOf concept, 1) | concept <- concepts]
conceptNode :: Concept -> Node
conceptNode concept =
Node
{ id = conceptIdOf concept,
label = fromMaybe (renderConceptId (conceptIdOf concept)) (conceptTitle concept),
type_ = conceptType concept,
description = conceptDescription concept,
resource = conceptResource concept,
tags = conceptTags concept
}
extractMarkdownLinks :: Text -> [Text]
extractMarkdownLinks markdown =
walk (parseMarkdown markdown)
where
walk (CMarkGFM.Node _ nodeType childNodes) =
case nodeType of
CMarkGFM.LINK url _title -> [url]
_ -> foldMap walk childNodes