fact
string
type
string
library
string
imports
list
filename
string
symbolic_name
string
docstring
string
Html where /-- An `element "tag" attrs children` represents `<tag {...attrs}>{...children}</tag>`. -/ | element : String → Array (String × Json) → Array Html → Html /-- Raw HTML text. -/ | text : String → Html /-- A `component h e props children` represents `<Foo {...props}>{...children}</Foo>`, where `Foo : Component Props` is some component such that `h = hash Foo.javascript`, `e = Foo.«export»`, and `props` will produce a JSON-encoded value of type `Props`. -/ | component : UInt64 → String → LazyEncodable Json → Array Html → Html deriving Inhabited, RpcEncodable
inductive
ProofWidgets
[]
ProofWidgets/Data/Html.lean
Html
/-- A HTML tree which may contain widget components. -/
Html.ofComponent [RpcEncodable Props] (c : Component Props) (props : Props) (children : Array Html) : Html := .component (hash c.javascript) c.export (rpcEncode props) children /-- See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow). -/
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
Html.ofComponent
/-- A `component h e props children` represents `<Foo {...props}>{...children}</Foo>`, where `Foo : Component Props` is some component such that `h = hash Foo.javascript`, `e = Foo.«export»`, and `props` will produce a JSON-encoded value of type `Props`. -/
LayoutKind where | block | inline namespace Jsx open Parser PrettyPrinter declare_syntax_cat jsxElement declare_syntax_cat jsxChild declare_syntax_cat jsxAttr declare_syntax_cat jsxAttrVal scoped syntax str : jsxAttrVal /-- Interpolates an expression into a JSX attribute literal. -/ scoped syntax group("{" term "}") : jsxAttrVal scoped syntax ident "=" jsxAttrVal : jsxAttr /-- Interpolates a collection into a JSX attribute literal. For HTML tags, this should have type `Array (String × Json)`. For `ProofWidgets.Component`s, it can be any structure `$t` whatsoever: it is interpolated into the component's props using `{ $t with ... }` notation. -/ scoped syntax group(" {..." term "}") : jsxAttr /-- Characters not allowed inside JSX plain text. -/
inductive
ProofWidgets
[]
ProofWidgets/Data/Html.lean
LayoutKind
/-- See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow). -/
jsxTextForbidden : String := "{<>}$" /-- A plain text literal for JSX (notation for `Html.text`). -/
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
jsxTextForbidden
/-- Characters not allowed inside JSX plain text. -/
jsxText : Parser := withAntiquot (mkAntiquot "jsxText" `ProofWidgets.Jsx.jsxText) { fn := fun c s => let startPos := s.pos let s := takeWhile1Fn (not ∘ (fun c => jsxTextForbidden.contains c)) "expected JSX text" c s mkNodeToken `ProofWidgets.Jsx.jsxText startPos true c s }
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
jsxText
/-- A plain text literal for JSX (notation for `Html.text`). -/
getJsxText : TSyntax ``jsxText → String | stx => stx.raw[0].getAtomVal @[combinator_formatter ProofWidgets.Jsx.jsxText]
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
getJsxText
/-- A plain text literal for JSX (notation for `Html.text`). -/
jsxText.formatter : Formatter := Formatter.visitAtom ``jsxText @[combinator_parenthesizer ProofWidgets.Jsx.jsxText]
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
jsxText.formatter
/-- A plain text literal for JSX (notation for `Html.text`). -/
jsxText.parenthesizer : Parenthesizer := Parenthesizer.visitToken scoped syntax "<" ident jsxAttr* "/>" : jsxElement scoped syntax "<" ident jsxAttr* ">" jsxChild* "</" ident ">" : jsxElement scoped syntax jsxText : jsxChild /-- Interpolates an array of elements into a JSX literal -/ scoped syntax "{..." term "}" : jsxChild /-- Interpolates an expression into a JSX literal -/ scoped syntax "{" term "}" : jsxChild scoped syntax jsxElement : jsxChild scoped syntax:max jsxElement : term
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
jsxText.parenthesizer
null
transformTag (tk : Syntax) (n m : Ident) (vs : Array (TSyntax `jsxAttr)) (cs : Array (TSyntax `jsxChild)) : MacroM Term := do let nId := n.getId.eraseMacroScopes let mId := m.getId.eraseMacroScopes if nId != mId then Macro.throwErrorAt m s!"expected </{nId}>" let trailingWs (stx : Syntax) := if let .original _ _ trailing _ := stx.getTailInfo then trailing.toString else "" -- Whitespace appearing before the current child. let mut wsBefore := trailingWs tk -- This loop transforms (for example) `` `(jsxChild*| {a} text {...cs} {d})`` -- into ``children ← `(term| #[a, Html.text " text "] ++ cs ++ #[d])``. let mut csArrs := #[] let mut csArr := #[] for c in cs do match c with | `(jsxChild| $t:jsxText) => csArr ← csArr.push <$> `(Html.text $(quote <| wsBefore ++ getJsxText t)) wsBefore := "" | `(jsxChild| { $t }%$tk) => csArr := csArr.push t wsBefore := trailingWs tk | `(jsxChild| $e:jsxElement) => csArr ← csArr.push <$> `(term| $e:jsxElement) wsBefore := trailingWs e | `(jsxChild| {... $t }%$tk) => if !csArr.isEmpty then csArrs ← csArrs.push <$> `(term| #[$csArr,*]) csArr := #[] csArrs := csArrs.push t wsBefore := trailingWs tk | stx => Macro.throwErrorAt stx "unknown syntax" if !csArr.isEmpty then csArrs ← csArrs.push <$> `(term| #[$csArr,*]) let children ← joinArrays csArrs let vs : Array ((Ident × Term) ⊕ Term) ← vs.mapM fun | `(jsxAttr| $attr:ident = $s:str) => Sum.inl <$> pure (attr, s) | `(jsxAttr| $attr:ident = { $t:term }) => Sum.inl <$> pure (attr, t) | `(jsxAttr| {... $t:term }) => Sum.inr <$> pure t | stx => Macro.throwErrorAt stx "unknown syntax" let tag := toString nId -- Uppercase tags are parsed as components if String.Pos.Raw.get? tag 0 |>.filter (·.isUpper) |>.isSome then let withs : Array Term ← vs.filterMapM fun | .inr e => return some e | .inl _ => return none let vs ← vs.filterMapM fun | .inl (attr, val) => return some <| ← `(Term.structInstField| $attr:ident := $val) | .inr _ => return none let props ← match withs, vs with | #[w], #[] => pure w | _, _ => `({ $withs,* with $vs:structInstField,* }) `(Html.ofComponent $n $props $children) -- Lowercase tags are parsed as standard HTML else let vs ← joinArrays <| ← foldInlsM vs (fun vs' => do let vs' ← vs'.mapM (fun (k, v) => `(term| ($(quote <| toString k.getId), ($v : Json)))) `(term| #[$vs',*])) `(Html.element $(quote tag) $vs $children) /-- Support for writing HTML trees directly, using XML-like angle bracket syntax. It works very similarly to [JSX](https://react.dev/learn/writing-markup-with-jsx) in JavaScript. The syntax is enabled using `open scoped ProofWidgets.Jsx`. Lowercase tags are interpreted as standard HTML whereas uppercase ones are expected to be `ProofWidgets.Component`s. -/ macro_rules | `(<$n:ident $[$attrs:jsxAttr]* />%$tk) => transformTag tk n n attrs #[] | `(<$n:ident $[$attrs:jsxAttr]* >%$tk $cs*</$m>) => transformTag tk n m attrs cs section delaborator open Lean Delaborator SubExpr /-! First delaborate into our non-term `TSyntax`. Note this means we can't call `delab`, so we have to add the term annotations ourselves. -/
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
transformTag
/-- Interpolates an expression into a JSX literal -/
delabHtmlText : DelabM (TSyntax ``jsxText) := do let_expr Html.text e := ← getExpr | failure let .lit (.strVal s) := e | failure if s.any (fun (c : Char) => jsxTextForbidden.contains c) then failure annotateTermLikeInfo <| mkNode ``jsxText #[mkAtom s] mutual
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabHtmlText
null
delabHtmlElement' : DelabM (TSyntax `jsxElement) := do let_expr Html.element tag _attrs _children := ← getExpr | failure let .lit (.strVal s) := tag | failure let tag ← withNaryArg 0 <| annotateTermLikeInfo <| mkIdent <| .mkSimple s let attrs ← withNaryArg 1 <| try delabArrayLiteral <| withAnnotateTermLikeInfo do let_expr Prod.mk _ _ a _ := ← getExpr | failure let .lit (.strVal a) := a | failure let attr ← withNaryArg 2 <| annotateTermLikeInfo <| mkIdent <| .mkSimple a withNaryArg 3 do let v ← getExpr -- If the attribute's value is a string literal, -- use `attr="val"` syntax. -- TODO: also do this for `.ofComponent`. -- WN: not sure if matching a string literal is possible with `let_expr`. match v with | .app (.const ``Json.str _) (.lit (.strVal v)) => -- TODO: this annotation doesn't seem to work in infoview let val ← annotateTermLikeInfo <| Syntax.mkStrLit v `(jsxAttr| $attr:ident=$val:str) | _ => let val ← delab `(jsxAttr| $attr:ident={ $val }) catch _ => let vs ← delab return #[← `(jsxAttr| {... $vs })] let children ← withAppArg delabJsxChildren if children.isEmpty then `(jsxElement| < $tag $[$attrs]* />) else `(jsxElement| < $tag $[$attrs]* > $[$children]* </ $tag >)
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabHtmlElement'
null
delabHtmlOfComponent' : DelabM (TSyntax `jsxElement) := do let_expr Html.ofComponent _Props _inst _c _props _children := ← getExpr | failure let c ← withNaryArg 2 delab unless c.raw.isIdent do failure let tag : Ident := ⟨c.raw⟩ -- TODO: handle `Props` that do not delaborate to `{ }`, such as `Prod`, by parsing the `Expr` -- instead. let attrDelab ← withNaryArg 3 delab let attrs : Array (TSyntax `jsxAttr) ← do let `(term| { $[$ns:ident := $vs],* } ) := attrDelab | pure #[← `(jsxAttr| {...$attrDelab})] ns.zip vs |>.mapM fun (n, v) => do `(jsxAttr| $n:ident={ $v }) let children ← withNaryArg 4 delabJsxChildren if children.isEmpty then `(jsxElement| < $tag $[$attrs]* />) else `(jsxElement| < $tag $[$attrs]* > $[$children]* </ $tag >)
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabHtmlOfComponent'
null
delabJsxChildren : DelabM (Array (TSyntax `jsxChild)) := do try delabArrayLiteral (withAnnotateTermLikeInfo do try match_expr ← getExpr with | Html.text _ => let html ← delabHtmlText return ← `(jsxChild| $html:jsxText) | Html.element _ _ _ => let html ← delabHtmlElement' return ← `(jsxChild| $html:jsxElement) | Html.ofComponent _ _ _ _ _ => let comp ← delabHtmlOfComponent' return ← `(jsxChild| $comp:jsxElement) | _ => failure catch _ => let fallback ← delab return ← `(jsxChild| { $fallback })) catch _ => let vs ← delab return #[← `(jsxChild| {... $vs })]
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabJsxChildren
null
delabHtmlElement : Delab := do let t ← delabHtmlElement' `(term| $t:jsxElement) @[delab app.ProofWidgets.Html.ofComponent]
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabHtmlElement
null
delabHtmlOfComponent : Delab := do let t ← delabHtmlOfComponent' `(term| $t:jsxElement)
def
ProofWidgets
[]
ProofWidgets/Data/Html.lean
delabHtmlOfComponent
null
_root_.Float.toInt (x : Float) : Int := if x >= 0 then x.toUInt64.toNat else -((-x).toUInt64.toNat)
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
_root_.Float.toInt
null
_root_.Int.toFloat (i : Int) : Float := if i >= 0 then i.toNat.toFloat else -((-i).toNat.toFloat) namespace Svg
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
_root_.Int.toFloat
null
Frame where (xmin ymin : Float) (xSize : Float) (width height : Nat) deriving ToJson, FromJson
structure
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Frame
null
Frame.ySize (frame : Frame) : Float := frame.height.toFloat * (frame.xSize / frame.width.toFloat)
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Frame.ySize
null
Frame.xmax (frame : Frame) : Float := frame.xmin + frame.xSize
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Frame.xmax
null
Frame.ymax (frame : Frame) : Float := frame.ymin + frame.ySize
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Frame.ymax
null
Frame.pixelSize (frame : Frame) : Float := frame.xSize / frame.width.toFloat
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Frame.pixelSize
null
Color where (r := 0.0) (g := 0.0) (b := 0.0) deriving ToJson, FromJson
structure
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Color
null
Color.toStringRGB (c : Color) : String := s!"rgb({255*c.r}, {255*c.g}, {255*c.b})"
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Color.toStringRGB
/-- Returns string "rgb(r, g, b)" with `r,g,b ∈ [0,...,256)` -/
Point (f : Frame) where | px (i j : Int) | abs (x y : Float) deriving Inhabited, ToJson, FromJson
inductive
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Point
/-- Returns string "rgb(r, g, b)" with `r,g,b ∈ [0,...,256)` -/
Point.toPixels {f : Frame} (p : Point f) : Int × Int := match p with | .px x y => (x,y) | .abs x y => let Δx := f.pixelSize let i := ((x - f.xmin) / Δx).floor.toInt let j := ((f.ymax - y) / Δx).floor.toInt (i, j)
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Point.toPixels
/-- Returns string "rgb(r, g, b)" with `r,g,b ∈ [0,...,256)` -/
Point.toAbsolute {f : Frame} (p : Point f) : Float × Float := match p with | .abs x y => (x,y) | .px i j => let Δx := f.pixelSize let x := f.xmin + (i.toFloat + 0.5) * Δx let y := f.ymax - (j.toFloat + 0.5) * Δx (x,y)
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Point.toAbsolute
null
Size (f : Frame) where | px (size : Nat) : Size f | abs (size : Float) : Size f deriving ToJson, FromJson
inductive
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Size
null
Size.toPixels {f : Frame} (s : Size f) : Nat := match s with | .px x => x | .abs x => (x / f.pixelSize).ceil.toUInt64.toNat -- inductive PolylineType
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Size.toPixels
null
Shape (f : Frame) where | line (src trg : Point f) | circle (center : Point f) (radius : Size f) | polyline (points : Array (Point f)) -- (type : PolylineType) | polygon (points : Array (Point f)) | path (d : String) | ellipse (center : Point f) (rx ry : Size f) | rect (corner : Point f) (width height : Size f) | text (pos : Point f) (content : String) (size : Size f) deriving ToJson, FromJson
inductive
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Shape
null
Shape.toHtmlData {f : Frame} : Shape f → String × Array (String × Json) | .line src trg => let (x1,y1) := src.toPixels let (x2,y2) := trg.toPixels ("line", #[("x1", x1), ("y1", y1), ("x2", x2), ("y2", y2)]) | .circle center radius => let (cx,cy) := center.toPixels let r := radius.toPixels ("circle", #[("cx", cx), ("cy", cy), ("r", r)]) | .polyline points => let pts := points |>.map (λ p => let (x,y) := p.toPixels; s!"{x},{y}") |>.foldl (init := "") (λ s p => s ++ " " ++ p) ("polyline", #[("points", pts)]) | .polygon points => let pts := points |>.map (λ p => let (x,y) := p.toPixels; s!"{x},{y}") |>.foldl (init := "") (λ s p => s ++ " " ++ p) ("polygon", #[("fillRule", "nonzero"), ("points", pts)]) | .path d => ("path", #[("d", d)]) | .ellipse center rx ry => let (cx,cy) := center.toPixels let rX := rx.toPixels let rY := ry.toPixels ("ellipse", #[("cx", cx), ("cy", cy), ("rx", rX), ("ry", rY)]) | .rect corner width height => let (x,y) := corner.toPixels let w := width.toPixels let h := height.toPixels ("rect", #[("x", x), ("y", y), ("width", w), ("height", h)]) | .text pos content size => let (x,y) := pos.toPixels let fontSize := size.toPixels ("text", #[("x", x), ("y", y), ("font-size", fontSize), ("text", content)])
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Shape.toHtmlData
null
Element (f : Frame) where shape : Shape f strokeColor := (none : Option Color) strokeWidth := (none : Option (Size f)) fillColor := (none : Option Color) id := (none : Option String) data := (none : Option Json) deriving ToJson, FromJson
structure
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element
null
Element.setStroke {f} (elem : Element f) (color : Color) (width : Size f) := { elem with strokeColor := some color, strokeWidth := some width }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element.setStroke
null
Element.setFill {f} (elem : Element f) (color : Color) := { elem with fillColor := some color }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element.setFill
null
Element.setId {f} (elem : Element f) (id : String) := { elem with id := some id }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element.setId
null
Element.setData {α : Type} {f} (elem : Element f) (a : α) [ToJson α] := { elem with data := some (toJson a) }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element.setData
null
Element.toHtml {f : Frame} (e : Element f) : Html := Id.run do let mut (tag, args) := e.shape.toHtmlData let mut children := #[] if let .text _ content _ := e.shape then children := #[.text content] -- adding children <text> if let .some color := e.strokeColor then args := args.push ("stroke", color.toStringRGB) if let .some width := e.strokeWidth then args := args.push ("strokeWidth", width.toPixels) if let .some color := e.fillColor then args := args.push ("fill", color.toStringRGB) else args := args.push ("fill", "none") if let .some id := e.id then args := args.push ("id", id) if let .some data := e.data then args := args.push ("data", data) return .element tag args children
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Element.toHtml
null
line {f} (p q : Point f) : Element f := { shape := .line p q }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
line
null
circle {f} (c : Point f) (r : Size f) : Element f := { shape := .circle c r }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
circle
null
polyline {f} (pts : Array (Point f)) : Element f := { shape := .polyline pts }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
polyline
null
polygon {f} (pts : Array (Point f)) : Element f := { shape := .polygon pts }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
polygon
null
path {f} (d : String) : Element f := { shape := .path d }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
path
null
ellipse {f} (center : Point f) (rx ry : Size f) : Element f := { shape := .ellipse center rx ry }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
ellipse
null
rect {f} (corner : Point f) (width height : Size f) : Element f := { shape := .rect corner width height }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
rect
null
text {f} (pos : Point f) (content : String) (size : Size f) : Element f := { shape := .text pos content size }
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
text
null
mkIdToIdx {f} (elements : Array (Svg.Element f)) : Std.HashMap String (Fin elements.size) := let idToIdx := elements |>.mapFinIdx (λ idx el h => (⟨idx, h⟩, el)) -- zip with `Fin` index |>.filterMap (λ (idx,el) => el.id.map (λ id => (id, idx))) -- keep only elements with specified id |>.toList |> Std.HashMap.ofList idToIdx
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
mkIdToIdx
null
Svg (f : Svg.Frame) where elements : Array (Svg.Element f) idToIdx := mkIdToIdx elements namespace Svg open scoped ProofWidgets.Jsx
structure
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
Svg
null
toHtml {f : Frame} (svg : Svg f) : Html := <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width={f.width} height={f.height}> {... svg.elements.map (·.toHtml)} </svg>
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
toHtml
null
idToDataList {f} (svg : Svg f) : List (String × Json) := svg.elements.foldr (init := []) (λ e l => match e.id, e.data with | some id, some data => (id,data)::l | _, _ => l)
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
idToDataList
null
idToData {f} (svg : Svg f) : Std.HashMap String Json := HashMap.ofList svg.idToDataList
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
idToData
null
getData {f} (svg : Svg f) (id : String) : Option Json := match svg[id] with | none => none | some elem => elem.data
def
ProofWidgets
[]
ProofWidgets/Data/Svg.lean
getData
null
List.product : List α → List β → List (α × β) | [], _ => [] | a::as, bs => bs.map ((a, ·)) ++ as.product bs @[expose] def Matrix (n m α : Type) := n → m → α namespace Matrix open ProofWidgets open scoped Jsx variable {n : Nat} (A : Matrix (Fin n) (Fin n) Int)
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
List.product
null
nat_index (i j : Nat) : Int := if h : i < n ∧ j < n then A ⟨i, h.1⟩ ⟨j, h.2⟩ else 999 /-- TODO Delete me once `get_node_pos` smart enough to infer layout from values in `A`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
nat_index
null
get_node_pos_E : Nat → Nat × Nat | 0 => ⟨0, 0⟩ | 1 => ⟨2, 1⟩ | (i+1) => ⟨i, 0⟩ /-- TODO Use `A` to infer sensible layout. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_node_pos_E
/-- TODO Delete me once `get_node_pos` smart enough to infer layout from values in `A`. -/
get_node_pos (n : Nat) : Nat → Nat × Nat := if n < 6 then ((·, 0)) else get_node_pos_E
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_node_pos
/-- TODO Use `A` to infer sensible layout. -/
get_node_cx (n i : Nat) : Int := 20 + (get_node_pos n i).1 * 40
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_node_cx
/-- TODO Use `A` to infer sensible layout. -/
get_node_cy (n i : Nat) : Int := 20 + (get_node_pos n i).2 * 40
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_node_cy
/-- TODO Use `A` to infer sensible layout. -/
get_node_html (n i : Nat) : Html := <circle cx={toString <| get_node_cx n i} cy={toString <| get_node_cy n i} r="10" fill="white" stroke="black" /> /-- TODO * Error if `j ≤ i` * Error if `(A i j, A j i) ∉ [((0 : Int), (0 : Int)), (-1, -1), (-1, -2), (-2, -1), (-1, -3), (-3, -1)]` * Render `(A i j) * (A j i)` edges * Render arrow on double or triple edge with direction decided by `A i j < A j i` -/
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_node_html
/-- TODO Use `A` to infer sensible layout. -/
get_edge_html : Nat × Nat → List Html | (i, j) => if A.nat_index i j = 0 then [] else [<line x1={toString <| get_node_cx n i} y1={toString <| get_node_cy n i} x2={toString <| get_node_cx n j} y2={toString <| get_node_cy n j} fill="black" stroke="black" />]
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_edge_html
/-- TODO * Error if `j ≤ i` * Error if `(A i j, A j i) ∉ [((0 : Int), (0 : Int)), (-1, -1), (-1, -2), (-2, -1), (-1, -3), (-3, -1)]` * Render `(A i j) * (A j i)` edges * Render arrow on double or triple edge with direction decided by `A i j < A j i` -/
get_nodes_html (n : Nat) : List Html := (List.range n).map (get_node_html n)
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_nodes_html
null
get_edges_html : List Html := Id.run do let mut out := [] for j in [:n] do for i in [:j] do out := A.get_edge_html (i, j) ++ out return out
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
get_edges_html
null
toHtml (M : Matrix (Fin n) (Fin n) Int) : Html := <div style={json% { height: "100px", width: "300px", background: "grey" }}> {Html.element "svg" #[] (M.get_edges_html ++ Matrix.get_nodes_html n).toArray} </div>
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
toHtml
null
cartanMatrix.E₈ : Matrix (Fin 8) (Fin 8) Int := fun i j => [[ 2, 0, -1, 0, 0, 0, 0, 0], [ 0, 2, 0, -1, 0, 0, 0, 0], [-1, 0, 2, -1, 0, 0, 0, 0], [ 0, -1, -1, 2, -1, 0, 0, 0], [ 0, 0, 0, -1, 2, -1, 0, 0], [ 0, 0, 0, 0, -1, 2, -1, 0], [ 0, 0, 0, 0, 0, -1, 2, -1], [ 0, 0, 0, 0, 0, 0, -1, 2]][i]![j]! -- Place your cursor here #html cartanMatrix.E₈.toHtml
def
ProofWidgets
[]
ProofWidgets/Demos/Dynkin.lean
cartanMatrix.E₈
null
IncidenceGeometry where Point : Type u₁ Line : Type u₂ Circle : Type u₃ between : Point → Point → Point → Prop -- implies colinearity onLine : Point → Line → Prop onCircle : Point → Circle → Prop inCircle : Point → Circle → Prop centerCircle : Point → Circle → Prop circlesInter : Circle → Circle → Prop ne_23_of_between : ∀ {a b c : Point}, between a b c → b ≠ c line_unique_of_pts : ∀ {a b : Point}, ∀ {L M : Line}, a ≠ b → onLine a L → onLine b L → onLine a M → onLine b M → L = M onLine_2_of_between : ∀ {a b c : Point}, ∀ {L : Line}, between a b c → onLine a L → onLine c L → onLine b L line_of_pts : ∀ a b, ∃ L, onLine a L ∧ onLine b L circle_of_ne : ∀ a b, a ≠ b → ∃ C, centerCircle a C ∧ onCircle b C circlesInter_of_onCircle_inCircle : ∀ {a b α β}, onCircle b α → onCircle a β → inCircle a α → inCircle b β → circlesInter α β pts_of_circlesInter : ∀ {α β}, circlesInter α β → ∃ a b, a ≠ b ∧ onCircle a α ∧ onCircle a β ∧ onCircle b α ∧ onCircle b β inCircle_of_centerCircle : ∀ {a α}, centerCircle a α → inCircle a α open IncidenceGeometry /-! # Metaprogramming utilities to break down expressions -/ /-- If `e == between a b c` return `some (a, b, c)`, otherwise `none`. -/
class
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
IncidenceGeometry
null
isBetweenPred ? (e : Expr) : Option (Expr × Expr × Expr) := do let some (_, a, b, c) := e.app4? ``between | none return (a, b, c) /-- If `e == onLine a L` return `some (a, L)`, otherwise `none`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isBetweenPred
/-- If `e == between a b c` return `some (a, b, c)`, otherwise `none`. -/
isOnLinePred ? (e : Expr) : Option (Expr × Expr) := do let some (_, a, L) := e.app3? ``onLine | none return (a, L) /-- If `e == onCircle a C` return `some (a, C)`, otherwise `none`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isOnLinePred
/-- If `e == onLine a L` return `some (a, L)`, otherwise `none`. -/
isOnCirclePred ? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``onCircle | none return (a, C) /-- If `e == inCircle a C` return `some (a, C)`, otherwise `none`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isOnCirclePred
/-- If `e == onCircle a C` return `some (a, C)`, otherwise `none`. -/
isInCirclePred ? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``inCircle | none return (a, C) /-- If `e == centerCircle a C` return `some (a, C)`, otherwise `none`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isInCirclePred
/-- If `e == inCircle a C` return `some (a, C)`, otherwise `none`. -/
isCenterCirclePred ? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``centerCircle | none return (a, C) /-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isCenterCirclePred
/-- If `e == centerCircle a C` return `some (a, C)`, otherwise `none`. -/
isCirclesInterPred ? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``circlesInter | none return (a, C)
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isCirclesInterPred
/-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/
isPoint ? (e : Expr) : Bool := e.isAppOf ``Point
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isPoint
/-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/
isLine ? (e : Expr) : Bool := e.isAppOf ``Line /-! # Utilities for constructing diagrams -/ open DiagramBuilderM in
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
isLine
/-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/
addHypotheses (hyps : Array LocalDecl) : DiagramBuilderM Unit := do for h in hyps do let tp ← instantiateMVars h.type if isPoint? tp then discard $ addExpr "Point" h.toExpr if isLine? tp then discard $ addExpr "Line" h.toExpr if let some (a, b, c) := isBetweenPred? tp then let sa ← addExpr "Point" a let sb ← addExpr "Point" b let sc ← addExpr "Point" c addInstruction s!"Between({sa}, {sb}, {sc})" if let some (a, L) := isOnLinePred? tp then let sa ← addExpr "Point" a let sL ← addExpr "Line" L addInstruction s!"OnLine({sa}, {sL})" if let some (a, C) := isOnCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"OnCircle({sa}, {sC})" if let some (a, C) := isInCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"InCircle({sa}, {sC})" if let some (a, C) := isCenterCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"CenterCircle({sa}, {sC})" if let some (C, D) := isCirclesInterPred? tp then let sC ← addExpr "Circle" C let sD ← addExpr "Circle" D addInstruction s!"CirclesInter({sC}, {sD})" /-! # Implementation of the widget -/
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
addHypotheses
/-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/
EuclideanDisplay.dsl := include_str ".."/".."/"widget"/"penrose"/"euclidean.dsl"
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanDisplay.dsl
null
EuclideanDisplay.sty := include_str ".."/".."/"widget"/"penrose"/"euclidean.sty" open scoped Jsx in @[server_rpc_method]
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanDisplay.sty
null
EuclideanDisplay.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let inner : Html ← (do -- Are there any goals unsolved? If so, pick the first one. if props.goals.isEmpty then return <span>No goals.</span> let some g := props.goals[0]? | unreachable! -- Execute the next part using the metavariable context and local context of the goal. g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do -- Which hypotheses have been selected in the UI, -- meaning they should *not* be shown in the display. let mut hiddenLocs : Std.HashSet FVarId := .emptyWithCapacity props.selectedLocations.size for l in props.selectedLocations do match l with | ⟨mv, .hyp fv⟩ | ⟨mv, .hypType fv _⟩ => if mv == g.mvarId then hiddenLocs := hiddenLocs.insert fv | _ => continue -- Filter local declarations by whether they are not in `hiddenLocs`. let locs := (← getLCtx).decls.toArray.filterMap (fun d? => if let some d := d? then if !hiddenLocs.contains d.fvarId then some d else none else none) -- Produce the diagram. DiagramBuilderM.run do addHypotheses locs match ← DiagramBuilderM.buildDiagram dsl sty with | some html => return html | none => return <span>No Euclidean goal.</span>) return <details «open»={true}> <summary className="mv2 pointer">Euclidean diagram</summary> <div className="ml1">{inner}</div> </details> @[widget_module]
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanDisplay.rpc
null
EuclideanDisplay : Component PanelWidgetProps := mk_rpc_widget% EuclideanDisplay.rpc /-! # Example usage -/ variable [i : IncidenceGeometry]
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanDisplay
null
constructLines (hyps : Array LocalDecl) (docMeta : Server.DocumentMeta) (cursorPos : Lsp.Position) : DiagramBuilderM Unit := do -- Identify objects and hypotheses from which constructions can be made. let mut points : Array LocalDecl := {} let mut circleInters : Array (LocalDecl × LocalDecl × LocalDecl) := {} for h in hyps do let tp ← instantiateMVars h.type if isPoint? tp then points := points.push h if let some (.fvar C, .fvar D) := isCirclesInterPred? tp then circleInters := circleInters.push (h, ← C.getDecl, ← D.getDecl) -- Add a plausible construction, labelled with a link that makes the text edit. let addConstruction (nm tp ctr : String) : DiagramBuilderM Unit := do addEmbed nm tp ( <span> <b>{.text nm}</b> ({ .ofComponent MakeEditLink (MakeEditLinkProps.ofReplaceRange docMeta ⟨cursorPos, cursorPos⟩ ctr) #[.text "insert"] }) </span>) addInstruction s!"Emphasize({nm})" -- Construct every possible line and circle. for hi : i in [0:points.size] do let p := points[i] let sp ← addExpr "Point" p.toExpr for hj : j in [i+1:points.size] do let q := points[j] let sq ← addExpr "Point" q.toExpr -- Add the line. let nm := s!"{sp}{sq}" addConstruction nm "Line" s!"let ⟨{nm}, _, _⟩ := line_of_pts {sp} {sq}" addInstruction s!"OnLine({sp}, {nm})" addInstruction s!"OnLine({sq}, {nm})" -- Add two possible circles. let nm := s!"C{sp}{sq}" addConstruction nm "Circle" s!"let ⟨{nm}, _, _⟩ := circle_of_ne {sp} {sq} (by assumption)" addInstruction s!"CenterCircle({sp}, {nm})" addInstruction s!"OnCircle({sq}, {nm})" let nm := s!"C{sq}{sp}" addConstruction nm "Circle" s!"let ⟨{nm}, _, _⟩ := circle_of_ne {sq} {sp} (by assumption)" addInstruction s!"CenterCircle({sq}, {nm})" addInstruction s!"OnCircle({sp}, {nm})" -- Construct every possible circle intersection. for hi : i in [0:circleInters.size] do let (h, C, D) := circleInters[i] let sC ← addExpr "Circle" C.toExpr let sD ← addExpr "Circle" D.toExpr let nm := s!"{sC}{sD}" let nm' := s!"{sD}{sC}" addConstruction nm "Point" s!"let ⟨{nm}, {nm'}, _, _, _, _, _⟩ := pts_of_circlesInter {h.userName}" addEmbed nm' "Point" <b>{.text nm'}</b> addInstruction s!"OnCircle({nm'}, {sC})" addInstruction s!"OnCircle({nm}, {sD})" addInstruction s!"OnCircle({nm}, {sC})" addInstruction s!"OnCircle({nm'}, {sD})" open scoped Jsx in @[server_rpc_method]
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
constructLines
/-- Add every possible line between any two points in `hyps` to the diagram. Lines are labelled with links to insert them into the proof script. -/
EuclideanConstructions.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let inner : Html ← (do -- Are there any goals unsolved? If so, pick the first one. if props.goals.isEmpty then return <span>No goals.</span> let some g := props.goals[0]? | unreachable! -- Execute the next part using the metavariable context and local context of the goal. g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do -- Grab all hypotheses from the local context. let allHyps := (← getLCtx).decls.toArray.filterMap id -- Find which hypotheses are selected. let selectedHyps ← props.selectedLocations.filterMapM fun | ⟨mv, .hyp fv⟩ | ⟨mv, .hypType fv _⟩ => if mv == g.mvarId then return some (← fv.getDecl) else return none | _ => return none -- Produce the diagram. DiagramBuilderM.run do addHypotheses allHyps constructLines selectedHyps doc.meta props.pos match ← DiagramBuilderM.buildDiagram EuclideanDisplay.dsl EuclideanDisplay.sty 1500 with | some html => return html | none => return <span>No Euclidean goal.</span>) -- Return a collapsible `<details>` block around our widget. return <details «open»={true}> <summary className="mv2 pointer">Euclidean constructions</summary> <div className="ml1">{inner}</div> </details> @[widget_module]
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanConstructions.rpc
null
EuclideanConstructions : Component PanelWidgetProps := mk_rpc_widget% EuclideanConstructions.rpc
def
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
EuclideanConstructions
null
test_sorry {α} : α show_panel_widgets [local EuclideanConstructions] /-! # Example construction -/ /- Try constructing an equilateral triangle abc with line segment ab as the base. Place your cursor in the proof below. To make a construction involving objects `x, y, z`, shift-click their names in 'Tactic state' in order to select them. Due to a limitation of the widget, you can only click-to-select in 'Tactic state', and not in the diagram. - To construct a line on two points, select `a` and `b` in `a b : Point`. - To construct a circle with center `a` passing through `b`, select `a` and `b` in `a b : Point`. You may have to prove that `a ≠ b`. - To construct an intersection point of two circles `C` and `D`, you first have to provide a local proof of `have h : circlesInter C D := ...` (i.e., show that the circles intersect) using the axioms of `IncidenceGeometry` above. Then select `h` in `h : circlesInter C D`. -/
axiom
ProofWidgets
[]
ProofWidgets/Demos/Euclidean.lean
test_sorry
null
presenter : ExprPresenter where userName := "With octopodes" layoutKind := .inline present e := return <span> {.text "🐙 "}<InteractiveCode fmt={← Lean.Widget.ppExprTagged e} />{.text " 🐙"} </span>
def
ProofWidgets
[]
ProofWidgets/Demos/ExprPresentation.lean
presenter
null
State := Array (Float × Float)
abbrev
ProofWidgets
[]
ProofWidgets/Demos/InteractiveSvg.lean
State
null
isvg : InteractiveSvg State where init := #[(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)] frame := { xmin := -1 ymin := -1 xSize := 2 width := 400 height := 400 } update _time _Δt _action _mouseStart mouseEnd _selected getData state := match getData Nat, mouseEnd with | some id, some p => state.set! id p.toAbsolute | _, _ => state render _time mouseStart mouseEnd state := { elements := let mousePointer := match mouseStart, mouseEnd with | some s, some e => #[ Svg.circle e (.px 5) |>.setFill (1.,1.,1.), Svg.line s e |>.setStroke (1.,1.,1.) (.px 2) ] | _, _ => #[] let circles := (state.mapIdx fun idx (p : Float × Float) => Svg.circle p (.abs 0.2) |>.setFill (0.7,0.7,0.7) |>.setId s!"circle{idx}" |>.setData idx ) mousePointer.append circles } open Server RequestM in @[server_rpc_method]
def
ProofWidgets
[]
ProofWidgets/Demos/InteractiveSvg.lean
isvg
null
updateSvg (params : UpdateParams State) : RequestM (RequestTask (UpdateResult State)) := isvg.serverRpcMethod params @[widget_module]
def
ProofWidgets
[]
ProofWidgets/Demos/InteractiveSvg.lean
updateSvg
null
SvgWidget : Component (UpdateResult State) where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "interactiveSvg.js"
def
ProofWidgets
[]
ProofWidgets/Demos/InteractiveSvg.lean
SvgWidget
null
init : UpdateResult State := { html := <div>Init!!!</div>, state := { state := isvg.init time := 0 selected := none mousePos := none idToData := isvg.render 0 none none isvg.init |>.idToDataList} } #html <SvgWidget html={init.html} state={init.state}/>
def
ProofWidgets
[]
ProofWidgets/Demos/InteractiveSvg.lean
init
null
htmlLetters : Array ProofWidgets.Html := #[ <span style={json% {color: "red"}}>H</span>, <span style={json% {color: "yellow"}}>T</span>, <span style={json% {color: "green"}}>M</span>, <span style={json% {color: "blue"}}>L</span> ] -- HTML children can be interpolated with `{ }` (single node) and `{... }` (multiple nodes)
def
ProofWidgets
[]
ProofWidgets/Demos/Jsx.lean
htmlLetters
null
x := <b>You can use {...htmlLetters} in Lean {.text s!"{1 + 3}"}! <hr/> </b> #html x -- Use `MarkdownDisplay` to render Markdown open ProofWidgets in #html <MarkdownDisplay contents={" ## Hello, Markdown We have **bold text**, _italic text_, `example : True := by trivial`, and $3×19 = \\int\\limits_0^{57}1~dx$. "} /> -- HTML trees can also be produced by metaprograms open ProofWidgets Lean Server Elab in #html (do let e ← Term.elabTerm (← ``(1 + 3)) (mkConst ``Nat) Term.synthesizeSyntheticMVarsNoPostponing let e ← instantiateMVars e return <InteractiveExpr expr={← WithRpcRef.mk (← ExprWithCtx.save e)} /> : Term.TermElabM Html)
def
ProofWidgets
[]
ProofWidgets/Demos/Jsx.lean
x
null
MetaMStringCont where ci : Elab.ContextInfo lctx : LocalContext -- We can only derive `TypeName` for type constants, so this must be monomorphic. k : MetaM String deriving TypeName
structure
ProofWidgets
[]
ProofWidgets/Demos/LazyComputation.lean
MetaMStringCont
/-- A `MetaM String` continuation, containing both the computation and all monad state. -/
RunnerWidgetProps where /-- A continuation to run and print the results of when the button is clicked. -/ k : WithRpcRef MetaMStringCont -- Make it possible for widgets to receive `RunnerWidgetProps`. Uses the `TypeName` instance. deriving RpcEncodable @[server_rpc_method]
structure
ProofWidgets
[]
ProofWidgets/Demos/LazyComputation.lean
RunnerWidgetProps
/-- A `MetaM String` continuation, containing both the computation and all monad state. -/
runMetaMStringCont : RunnerWidgetProps → RequestM (RequestTask String) | {k := ref} => RequestM.asTask do let {ci, lctx, k} := ref.val ci.runMetaM lctx k @[widget_module]
def
ProofWidgets
[]
ProofWidgets/Demos/LazyComputation.lean
runMetaMStringCont
/-- A continuation to run and print the results of when the button is clicked. -/
runnerWidget : Component RunnerWidgetProps where javascript := " import { RpcContext, mapRpcError } from '@leanprover/infoview' import * as React from 'react'; const e = React.createElement; export default function(props) { const [contents, setContents] = React.useState('Run!') const rs = React.useContext(RpcContext) return e('button', { onClick: () => { setContents('Running..') rs.call('runMetaMStringCont', props) .then(setContents) .catch(e => { setContents(mapRpcError(e).message) }) }}, contents) } " syntax (name := makeRunnerTac) "make_runner" : tactic @[tactic makeRunnerTac] def makeRunner : Tactic | `(tactic| make_runner%$tk) => do let x : MetaM String := do return "Hello, world!" -- Store the continuation and monad context. let props : RunnerWidgetProps := { k := ← WithRpcRef.mk { ci := { ← CommandContextInfo.save with } lctx := (← getLCtx) k := x } } -- Save a widget together with a pointer to `props`. Widget.savePanelWidgetInfo runnerWidget.javascriptHash (rpcEncode props) tk | _ => throwUnsupportedSyntax
def
ProofWidgets
[]
ProofWidgets/Demos/LazyComputation.lean
runnerWidget
/-- A continuation to run and print the results of when the button is clicked. -/
Lean.SourceInfo.mkCanonical : SourceInfo → SourceInfo | .synthetic s e _ => .synthetic s e true | si => si
def
ProofWidgets
[]
ProofWidgets/Demos/Macro.lean
Lean.SourceInfo.mkCanonical
null
Lean.Syntax.mkInfoCanonical : Syntax → Syntax | .missing => .missing | .node i k a => .node i.mkCanonical k a | .atom i v => .atom i.mkCanonical v | .ident i r v p => .ident i.mkCanonical r v p
def
ProofWidgets
[]
ProofWidgets/Demos/Macro.lean
Lean.Syntax.mkInfoCanonical
null
Lean.TSyntax.mkInfoCanonical : TSyntax k → TSyntax k := (.mk ·.raw.mkInfoCanonical) macro "#browse " src:term : command => Lean.TSyntax.mkInfoCanonical <$> `(#html <iframe src={$src} width="100%" height="600px" />) #browse "https://leanprover-community.github.io/" -- Do you like recursion? #browse "https://lean.math.hhu.de"
def
ProofWidgets
[]
ProofWidgets/Demos/Macro.lean
Lean.TSyntax.mkInfoCanonical
null
fn (t : Float) (x : Float): Float := 50 * (x - 0.25) * (x - 0.5) * (x - 0.7) + 0.1 * (x * 40 - t * 2 * 3.141).sin open scoped ProofWidgets.Jsx in
def
ProofWidgets
[]
ProofWidgets/Demos/Plot.lean
fn
null
Plot (fn : Float → Float) (steps := 100) : Html := let jsonData : Array Json := Array.range (steps + 1) |> Array.map (fun (x : Nat) => let x : Float := x.toFloat / steps.toFloat; (x, fn x)) |> Array.map (fun (x,y) => json% {x: $(toJson x) , y: $(toJson y)}); <LineChart width={400} height={400} data={jsonData}> <XAxis domain?={#[toJson 0, toJson 1]} dataKey?="x" /> <YAxis domain?={#[toJson (-1), toJson 1]} allowDataOverflow={Bool.false} /> <Line type={.monotone} dataKey="y" stroke="#8884d8" dot?={Bool.false} /> </LineChart> #html Plot (fn 0) #html Plot (fn 0.2) #html Plot (fn 0.4) #html Plot (fn 0.6) /-! # Bonus demo: animated plots! -/
def
ProofWidgets
[]
ProofWidgets/Demos/Plot.lean
Plot
null
mkFrames (fn : Float → Float → Float) (steps := 100) : Array Html:= List.range (steps + 1) |>.toArray |>.map (fun t => Plot (fn (t.toFloat / steps.toFloat)))
def
ProofWidgets
[]
ProofWidgets/Demos/Plot.lean
mkFrames
null
AnimatedHtmlProps where frames : Array Html framesPerSecond? : Option Nat := none deriving Server.RpcEncodable @[widget_module]
structure
ProofWidgets
[]
ProofWidgets/Demos/Plot.lean
AnimatedHtmlProps
null