Class: Synthra::LivePreview

Inherits:
Object
  • Object
show all
Defined in:
lib/synthra/live_preview.rb

Overview

Live Preview Server with Web UI

Provides real-time schema preview with hot reload.

Examples:

CLI usage

$ synthra watch --live --port 4567

Ruby usage

Synthra::LivePreview.start(port: 4567, schema_dir: "schemas/")

Constant Summary collapse

DEFAULT_PORT =
4567

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema_dir:, port: DEFAULT_PORT) ⇒ LivePreview

Returns a new instance of LivePreview.



23
24
25
26
27
28
# File 'lib/synthra/live_preview.rb', line 23

def initialize(schema_dir:, port: DEFAULT_PORT)
  @schema_dir = schema_dir
  @port = port
  @registry = Registry.new
  @registry.load_dir(schema_dir)
end

Instance Attribute Details

#portObject (readonly)

Returns the value of attribute port.



21
22
23
# File 'lib/synthra/live_preview.rb', line 21

def port
  @port
end

#registryObject (readonly)

Returns the value of attribute registry.



21
22
23
# File 'lib/synthra/live_preview.rb', line 21

def registry
  @registry
end

#schema_dirObject (readonly)

Returns the value of attribute schema_dir.



21
22
23
# File 'lib/synthra/live_preview.rb', line 21

def schema_dir
  @schema_dir
end

#serverObject (readonly)

Returns the value of attribute server.



21
22
23
# File 'lib/synthra/live_preview.rb', line 21

def server
  @server
end

Class Method Details

.start(**options) ⇒ Object



513
514
515
# File 'lib/synthra/live_preview.rb', line 513

def start(**options)
  new(**options).start
end

Instance Method Details

#render_indexObject (private)



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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/synthra/live_preview.rb', line 142

def render_index
  <<~HTML
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Synthra Live Preview</title>
      <style>
        :root {
          --bg: #1a1b26;
          --surface: #24283b;
          --primary: #7aa2f7;
          --secondary: #bb9af7;
          --success: #9ece6a;
          --warning: #e0af68;
          --text: #c0caf5;
          --text-muted: #565f89;
          --border: #414868;
        }
        
        * { box-sizing: border-box; }
        
        body {
          font-family: 'JetBrains Mono', 'Fira Code', monospace;
          background: var(--bg);
          color: var(--text);
          margin: 0;
          padding: 0;
          min-height: 100vh;
        }
        
        .container {
          max-width: 1400px;
          margin: 0 auto;
          padding: 2rem;
        }
        
        header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 2rem;
          padding-bottom: 1rem;
          border-bottom: 1px solid var(--border);
        }
        
        h1 {
          margin: 0;
          font-size: 1.5rem;
          background: linear-gradient(135deg, var(--primary), var(--secondary));
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
        
        .status {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          color: var(--success);
        }
        
        .status-dot {
          width: 8px;
          height: 8px;
          background: var(--success);
          border-radius: 50%;
          animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
        
        .grid {
          display: grid;
          grid-template-columns: 300px 1fr;
          gap: 2rem;
        }
        
        .sidebar {
          background: var(--surface);
          border-radius: 8px;
          padding: 1rem;
          height: fit-content;
        }
        
        .sidebar h2 {
          font-size: 0.875rem;
          color: var(--text-muted);
          text-transform: uppercase;
          margin: 0 0 1rem;
        }
        
        .schema-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }
        
        .schema-item {
          padding: 0.75rem;
          border-radius: 4px;
          cursor: pointer;
          transition: background 0.2s;
        }
        
        .schema-item:hover {
          background: var(--bg);
        }
        
        .schema-item.active {
          background: var(--primary);
          color: var(--bg);
        }
        
        .main {
          display: flex;
          flex-direction: column;
          gap: 1rem;
        }
        
        .controls {
          display: flex;
          gap: 1rem;
          align-items: center;
          flex-wrap: wrap;
        }
        
        .control-group {
          display: flex;
          align-items: center;
          gap: 0.5rem;
        }
        
        label {
          font-size: 0.75rem;
          color: var(--text-muted);
          text-transform: uppercase;
        }
        
        input, select, button {
          font-family: inherit;
          font-size: 0.875rem;
          padding: 0.5rem 1rem;
          border: 1px solid var(--border);
          border-radius: 4px;
          background: var(--surface);
          color: var(--text);
        }
        
        input:focus, select:focus {
          outline: none;
          border-color: var(--primary);
        }
        
        button {
          cursor: pointer;
          background: var(--primary);
          color: var(--bg);
          border: none;
          font-weight: 600;
          transition: transform 0.1s, box-shadow 0.2s;
        }
        
        button:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(122, 162, 247, 0.3);
        }
        
        button:active {
          transform: translateY(0);
        }
        
        .output {
          background: var(--surface);
          border-radius: 8px;
          overflow: hidden;
          flex: 1;
        }
        
        .output-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 1rem;
          border-bottom: 1px solid var(--border);
        }
        
        .output-header h3 {
          margin: 0;
          font-size: 0.875rem;
        }
        
        .copy-btn {
          padding: 0.25rem 0.5rem;
          font-size: 0.75rem;
        }
        
        pre {
          margin: 0;
          padding: 1rem;
          overflow: auto;
          max-height: 600px;
          font-size: 0.875rem;
          line-height: 1.5;
        }
        
        .json-key { color: var(--primary); }
        .json-string { color: var(--success); }
        .json-number { color: var(--warning); }
        .json-boolean { color: var(--secondary); }
        .json-null { color: var(--text-muted); }
        
        footer {
          margin-top: 2rem;
          padding-top: 1rem;
          border-top: 1px solid var(--border);
          text-align: center;
          color: var(--text-muted);
          font-size: 0.75rem;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <header>
          <h1>🎲 Synthra Live Preview</h1>
          <div class="status">
            <span class="status-dot"></span>
            Watching for changes
          </div>
        </header>
        
        <div class="grid">
          <aside class="sidebar">
            <h2>Schemas</h2>
            <ul class="schema-list" id="schema-list">
              <li class="schema-item">Loading...</li>
            </ul>
          </aside>
          
          <main class="main">
            <div class="controls">
              <div class="control-group">
                <label>Count</label>
                <input type="number" id="count" value="5" min="1" max="100">
              </div>
              <div class="control-group">
                <label>Mode</label>
                <select id="mode">
                  <option value="random">Random</option>
                  <option value="edge">Edge Cases</option>
                  <option value="invalid">Invalid</option>
                  <option value="hostile">Hostile</option>
                </select>
              </div>
              <div class="control-group">
                <label>Seed</label>
                <input type="number" id="seed" placeholder="(optional)">
              </div>
              <button id="generate-btn">Generate</button>
              <button id="reload-btn" style="background: var(--secondary);">Reload Schemas</button>
            </div>
            
            <div class="output">
              <div class="output-header">
                <h3 id="output-title">Select a schema to start</h3>
                <button class="copy-btn" id="copy-btn">Copy JSON</button>
              </div>
              <pre id="output">// Generated data will appear here</pre>
            </div>
          </main>
        </div>
        
        <footer>
          Synthra &bull; Hot Reload Enabled &bull; Schemas: <span id="schema-count">0</span>
        </footer>
      </div>
      
      <script>
        let currentSchema = null;
        let lastData = null;
        
        async function loadSchemas() {
          const res = await fetch('/api/schemas');
          const data = await res.json();
          const list = document.getElementById('schema-list');
          document.getElementById('schema-count').textContent = data.schemas.length;
          
          list.innerHTML = data.schemas.map(name => 
            `<li class="schema-item" data-name="${name}">${name}</li>`
          ).join('');
          
          list.querySelectorAll('.schema-item').forEach(item => {
            item.addEventListener('click', () => selectSchema(item.dataset.name));
          });
        }
        
        function selectSchema(name) {
          currentSchema = name;
          document.querySelectorAll('.schema-item').forEach(item => {
            item.classList.toggle('active', item.dataset.name === name);
          });
          document.getElementById('output-title').textContent = `Generated ${name}`;
          generate();
        }
        
        async function generate() {
          if (!currentSchema) return;
          
          const count = document.getElementById('count').value;
          const mode = document.getElementById('mode').value;
          const seed = document.getElementById('seed').value;
          
          let url = `/api/generate?name=${currentSchema}&count=${count}&mode=${mode}`;
          if (seed) url += `&seed=${seed}`;
          
          const res = await fetch(url);
          const data = await res.json();
          lastData = data;
          
          document.getElementById('output').innerHTML = syntaxHighlight(JSON.stringify(data, null, 2));
        }
        
        async function reload() {
          await fetch('/api/reload');
          await loadSchemas();
          if (currentSchema) generate();
        }
        
        function syntaxHighlight(json) {
          return json.replace(/("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) {
            let cls = 'json-number';
            if (/^"/.test(match)) {
              if (/:$/.test(match)) {
                cls = 'json-key';
              } else {
                cls = 'json-string';
              }
            } else if (/true|false/.test(match)) {
              cls = 'json-boolean';
            } else if (/null/.test(match)) {
              cls = 'json-null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
          });
        }
        
        function copyToClipboard() {
          if (lastData) {
            navigator.clipboard.writeText(JSON.stringify(lastData, null, 2));
          }
        }
        
        document.getElementById('generate-btn').addEventListener('click', generate);
        document.getElementById('reload-btn').addEventListener('click', reload);
        document.getElementById('copy-btn').addEventListener('click', copyToClipboard);
        document.getElementById('count').addEventListener('change', generate);
        document.getElementById('mode').addEventListener('change', generate);
        document.getElementById('seed').addEventListener('change', generate);
        
        loadSchemas();
      </script>
    </body>
    </html>
  HTML
end

#setup_file_watcherObject (private)



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/synthra/live_preview.rb', line 124

def setup_file_watcher
  Thread.new do
    last_mtime = Dir.glob("#{@schema_dir}/**/*.dsl").map { |f| File.mtime(f) }.max
    
    loop do
      sleep 1
      current_mtime = Dir.glob("#{@schema_dir}/**/*.dsl").map { |f| File.mtime(f) }.max rescue nil
      
      if current_mtime && last_mtime && current_mtime > last_mtime
        puts "♻️  Detected schema changes, reloading..."
        @registry.clear
        @registry.load_dir(@schema_dir)
        last_mtime = current_mtime
      end
    end
  end
end

#setup_routesObject (private)



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
# File 'lib/synthra/live_preview.rb', line 52

def setup_routes
  # Main page
  @server.mount_proc "/" do |req, res|
    if req.path == "/" || req.path == "/index.html"
      res["Content-Type"] = "text/html"
      res.body = render_index
    else
      res.status = 404
    end
  end

  # API: List schemas
  @server.mount_proc "/api/schemas" do |_, res|
    res["Content-Type"] = "application/json"
    res.body = JSON.pretty_generate(
      schemas: @registry.names.sort
    )
  end

  # API: Get schema details
  @server.mount_proc "/api/schema" do |req, res|
    name = req.query["name"]
    res["Content-Type"] = "application/json"

    if name && @registry.schema?(name)
      schema = @registry.schema(name)
      res.body = JSON.pretty_generate(
        name: name,
        fields: schema.fields.map { |f| { name: f.name, type: f.type_name, optional: f.optional } },
        sample: schema.generate(seed: 42)
      )
    else
      res.status = 404
      res.body = JSON.generate(error: "Schema not found")
    end
  end

  # API: Generate data
  @server.mount_proc "/api/generate" do |req, res|
    name = req.query["name"]
    count = (req.query["count"] || "1").to_i
    mode = (req.query["mode"] || "random").to_sym
    seed = req.query["seed"]&.to_i

    res["Content-Type"] = "application/json"

    if name && @registry.schema?(name)
      schema = @registry.schema(name)
      data = if count > 1
               count.times.map { schema.generate(seed: seed, mode: mode) }
             else
               schema.generate(seed: seed, mode: mode)
             end
      res.body = JSON.pretty_generate(data)
    else
      res.status = 404
      res.body = JSON.generate(error: "Schema not found")
    end
  end

  # API: Reload schemas
  @server.mount_proc "/api/reload" do |_, res|
    @registry.clear
    @registry.load_dir(@schema_dir)
    res["Content-Type"] = "application/json"
    res.body = JSON.generate(
      reloaded: true,
      schemas: @registry.names.count
    )
  end
end

#startObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/synthra/live_preview.rb', line 30

def start
  puts "🚀 Starting Synthra Live Preview Server..."
  puts "   Schema directory: #{@schema_dir}"
  puts "   URL: http://localhost:#{@port}"
  puts ""
  puts "   Press Ctrl+C to stop"

  @server = WEBrick::HTTPServer.new(
    Port: @port,
    Logger: WEBrick::Log.new("/dev/null"),
    AccessLog: []
  )

  setup_routes
  setup_file_watcher

  trap("INT") { @server.shutdown }
  @server.start
end