|
| 1 | +//go:build js && wasm |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "syscall/js" |
| 8 | + |
| 9 | + ast "github.com/tinybluerobots/jsonforms-parser" |
| 10 | + "github.com/tinybluerobots/jsonforms-html/renderer" |
| 11 | +) |
| 12 | + |
| 13 | +func renderHTML(this js.Value, args []js.Value) interface{} { |
| 14 | + if len(args) != 1 { |
| 15 | + return map[string]interface{}{ |
| 16 | + "error": "renderHTML expects 1 argument: JSON string with schema and uischema", |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + jsonString := args[0].String() |
| 21 | + |
| 22 | + // Parse the input JSON |
| 23 | + var input struct { |
| 24 | + Schema json.RawMessage `json:"schema"` |
| 25 | + UISchema json.RawMessage `json:"uischema"` |
| 26 | + } |
| 27 | + |
| 28 | + if err := json.Unmarshal([]byte(jsonString), &input); err != nil { |
| 29 | + return map[string]interface{}{ |
| 30 | + "error": "Invalid JSON: " + err.Error(), |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Validate we have both schema and uischema |
| 35 | + if len(input.Schema) == 0 || len(input.UISchema) == 0 { |
| 36 | + return map[string]interface{}{ |
| 37 | + "error": "JSON must contain both 'schema' and 'uischema' properties", |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Parse using jsonforms-parser |
| 42 | + tree, err := ast.Parse(input.UISchema, input.Schema) |
| 43 | + if err != nil { |
| 44 | + return map[string]interface{}{ |
| 45 | + "error": "Failed to parse schemas: " + err.Error(), |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + // Render to HTML |
| 50 | + html, err := renderer.Render(tree, nil) |
| 51 | + if err != nil { |
| 52 | + return map[string]interface{}{ |
| 53 | + "error": "Failed to render HTML: " + err.Error(), |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return map[string]interface{}{ |
| 58 | + "html": html, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func main() { |
| 63 | + // Make the Go function available to JavaScript |
| 64 | + js.Global().Set("renderHTML", js.FuncOf(renderHTML)) |
| 65 | + |
| 66 | + // Keep the program running |
| 67 | + select {} |
| 68 | +} |
0 commit comments