nitlight_aas: offer a low-level JSON service
authorJean Privat <jean@pryen.org>
Thu, 27 Apr 2017 13:00:24 +0000 (09:00 -0400)
committerJean Privat <jean@pryen.org>
Tue, 9 May 2017 18:29:14 +0000 (14:29 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

src/examples/nitlight_as_a_service.nit
src/highlight.nit

index 934bded..103a3c8 100644 (file)
@@ -22,6 +22,7 @@ import highlight
 import nitcorn
 import nitcorn::log
 import template
+import json::serialization_write
 
 # Nitcorn service to hightlight code
 #
@@ -39,6 +40,13 @@ class HighlightAction
                var hlcode = null
                if code != null then hlcode = hightlightcode(hl, code)
 
+               if http_request.post_args.get_or_null("json") == "true" and hlcode != null then
+                       var response = new HttpResponse(200)
+                       response.header["Content-Type"] = "text/json"
+                       response.body = hlcode.to_json
+                       return response
+               end
+
                if http_request.post_args.get_or_null("ajax") == "true" and hlcode != null then
                        page.add hlcode.code_mirror_update
                        page.add """
index 254e2d2..35d7d2e 100644 (file)
@@ -19,6 +19,7 @@ import frontend
 import html
 import pipeline
 import astutil
+import serialization
 
 # Fully process a content as a nit source file.
 fun hightlightcode(hl: HighlightVisitor, content: String): HLCode
@@ -65,6 +66,8 @@ end
 
 # A standalone highlighted piece of code
 class HLCode
+       super Serializable
+
        # The highlighter used
        var hl: HighlightVisitor
 
@@ -99,6 +102,19 @@ class HLCode
                res.add """});}"""
                return res
        end
+
+       redef fun core_serialize_to(v)
+       do
+               v.serialize_attribute("code", hl.html.write_to_string)
+               var msgs = new Array[Map[String, Serializable]]
+               for m in source.messages do
+                       var o = new Map[String, Serializable]
+                       msgs.add o
+                       o["line"] = m.location.line_start-1
+                       o["message"] = m.text
+               end
+               v.serialize_attribute("messages", msgs)
+       end
 end
 
 # Visitor used to produce a HTML tree based on a AST on a `Source`