Commit 0dad5196 authored by jan.koester's avatar jan.koester
Browse files

editor widgets ported to nodejs

parent 57003dde
Loading
Loading
Loading
Loading
+12 −0
Changes for editor/CMakeLists.txt: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -29,6 +29,9 @@ endif()

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)

option(WEBEDIT_ENABLE_EMBEDDED_NODE "Install an embedded Node.js binary for editor widgets" OFF)
set(WEBEDIT_EMBEDDED_NODE_BINARY "" CACHE FILEPATH "Path to Node.js binary used for embedded runtime")

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}/../src
    ${CMAKE_CURRENT_BINARY_DIR}
@@ -76,4 +79,13 @@ add_subdirectory(widgets)

install(TARGETS blogi-editor DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY html/ DESTINATION ${CMAKE_INSTALL_DATADIR}/blogi-editor/html)
install(DIRECTORY node/ DESTINATION ${CMAKE_INSTALL_DATADIR}/blogi-editor/node)
install(FILES config.yaml DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/blogi-editor)

if(WEBEDIT_ENABLE_EMBEDDED_NODE)
    if(EXISTS "${WEBEDIT_EMBEDDED_NODE_BINARY}")
        install(PROGRAMS "${WEBEDIT_EMBEDDED_NODE_BINARY}" DESTINATION ${CMAKE_INSTALL_LIBDIR}/blogi-editor/node/bin RENAME node)
    else()
        message(FATAL_ERROR "WEBEDIT_ENABLE_EMBEDDED_NODE is ON but WEBEDIT_EMBEDDED_NODE_BINARY does not exist")
    endif()
endif()
+3 −0
Changes for editor/config.yaml: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -16,6 +16,9 @@ WEBEDIT:
  HTMLDIR: "/usr/share/blogi-editor/html"
  PREFIX: ""
  LANGUAGE: "DE"
  NODE:
    BINARY: "/usr/lib/blogi-editor/node/bin/node"
    RUNNER: "/usr/share/blogi-editor/node/node_widget_runner.js"
  AUTHDB:
    - URL: "https://localhost:8443"
      CLIENTNAME: "blogi-editor"
+90 −0
Changes for editor/node/node_widget_runner.js: 90 added lines, 0 removed lines.
Original line number Diff line number Diff line
'use strict';

const fs = require('fs');
const path = require('path');

async function main() {
  const [, , requestFile, responseFile] = process.argv;
  if (!requestFile || !responseFile) {
    throw new Error('Usage: node node_widget_runner.js <request.json> <response.json>');
  }

  const reqRaw = fs.readFileSync(requestFile, 'utf8');
  const req = JSON.parse(reqRaw);
  const hook = typeof req.hook === 'string' && req.hook ? req.hook : 'render';

  if (!req.script_path) {
    throw new Error('request.script_path is required');
  }

  const scriptPath = path.resolve(req.script_path);
  const mod = require(scriptPath);
  const fn = resolveHook(mod, hook);

  if (!fn) {
    fs.writeFileSync(
      responseFile,
      JSON.stringify({ status: 'success', missing_hook: true, result: null }),
      'utf8'
    );
    return;
  }

  const result = await Promise.resolve(fn(req));

  if (hook === 'render') {
    let html = '';
    if (typeof result === 'string') {
      html = result;
    } else if (result && typeof result === 'object' && typeof result.html === 'string') {
      html = result.html;
    } else {
      throw new Error('render() must return a string or { html: string }');
    }

    fs.writeFileSync(
      responseFile,
      JSON.stringify({ status: 'success', html, result: { html } }),
      'utf8'
    );
    return;
  }

  fs.writeFileSync(
    responseFile,
    JSON.stringify({ status: 'success', missing_hook: false, result }),
    'utf8'
  );
}

function resolveHook(mod, hook) {
  if (hook === 'render') {
    if (typeof mod === 'function') return mod;
    if (typeof mod.render === 'function') return mod.render;
    return null;
  }

  if (typeof mod[hook] === 'function') return mod[hook];
  if (mod.hooks && typeof mod.hooks[hook] === 'function') return mod.hooks[hook];
  return null;
}

main().catch((err) => {
  const [, , , responseFile] = process.argv;
  const payload = JSON.stringify({
    status: 'error',
    message: err && err.message ? err.message : 'Unknown Node runner error'
  });

  if (responseFile) {
    try {
      fs.writeFileSync(responseFile, payload, 'utf8');
    } catch (_) {
      process.stderr.write(payload + '\n');
    }
  } else {
    process.stderr.write(payload + '\n');
  }

  process.exitCode = 1;
});
+61 −0
Changes for editor/node/sample_widget.js: 61 added lines, 0 removed lines.
Original line number Diff line number Diff line
'use strict';

exports.metadata = function metadata() {
  return {
    name: 'Node Sample Widget',
    author: 'blogi',
    version: '1.0',
    can_have_children: false
  };
};

exports.settings = function settings(ctx) {
  const p = (ctx && ctx.properties) || {};
  const title = typeof p.title === 'string' ? p.title : '';
  const text = typeof p.text === 'string' ? p.text : '';
  return {
    html: `
<label>Title: </label><input type="text" name="title" value="${escapeHtml(title)}" />
<label>Text: </label><textarea name="text" rows="5" cols="80">${escapeHtml(text)}</textarea>`
  };
};

exports.json_api = function jsonApi(ctx) {
  const req = (ctx && ctx.payload && ctx.payload.request) || {};
  if (req.action === 'ping') {
    return { pong: true, message: 'hello from node widget' };
  }
  return {};
};

exports.render = function render(ctx) {
  const p = (ctx && ctx.properties) || {};
  const title = typeof p.title === 'string' ? p.title : 'Node Widget';
  const text = typeof p.text === 'string' ? p.text : 'Rendered by embedded Node.js';
  const color = typeof p.color === 'string' ? p.color : '#0f766e';

  return `
<section style="border:1px solid ${color};padding:12px;border-radius:8px;">
  <h3 style="margin:0 0 8px 0;color:${color};">${escapeHtml(title)}</h3>
  <p style="margin:0;">${escapeHtml(text)}</p>
</section>`;
};

exports.have_childs = function haveChilds(ctx) {
  const current = !!(ctx && ctx.payload && ctx.payload.have_childs);
  return { have_childs: current };
};

exports.set_child = function setChild() { return {}; };
exports.unset_child = function unsetChild() { return {}; };
exports.add_next = function addNext() { return {}; };
exports.remove_next = function removeNext() { return {}; };

function escapeHtml(input) {
  return String(input)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
+76 −0
Changes for editor/node/widgets/_base_widget.js: 76 added lines, 0 removed lines.
Original line number Diff line number Diff line
'use strict';

exports.makeWidget = function makeWidget(meta) {
  const defaults = {
    name: 'NodeWidget',
    author: 'Jan Koester',
    version: '1.0',
    canHaveChildren: false,
    className: 'we-node-widget'
  };
  const cfg = Object.assign({}, defaults, meta || {});

  return {
    metadata() {
      return {
        name: cfg.name,
        author: cfg.author,
        version: cfg.version,
        can_have_children: !!cfg.canHaveChildren
      };
    },

    settings(ctx) {
      const p = (ctx && ctx.properties) || {};
      const title = toStr(p.title);
      const text = toStr(p.text);
      const cssClass = toStr(p.css_class || cfg.className);
      return {
        html: `
<label>Title: </label><input type="text" name="title" value="${escapeHtml(title)}" />
<label>Text: </label><textarea name="text" rows="5" cols="80">${escapeHtml(text)}</textarea>
<label>CSS Class: </label><input type="text" name="css_class" value="${escapeHtml(cssClass)}" />`
      };
    },

    json_api(ctx) {
      const req = (ctx && ctx.payload && ctx.payload.request) || {};
      if (req.action === 'ping') {
        return { pong: true, widget: cfg.name };
      }
      return {};
    },

    render(ctx) {
      const p = (ctx && ctx.properties) || {};
      const title = toStr(p.title || cfg.name);
      const text = toStr(p.text || 'Node.js widget render');
      const cssClass = toStr(p.css_class || cfg.className);
      return {
        html: `<section class="${escapeHtml(cssClass)}"><h3>${escapeHtml(title)}</h3><p>${escapeHtml(text)}</p></section>`
      };
    },

    have_childs(ctx) {
      return { have_childs: !!(ctx && ctx.payload && ctx.payload.have_childs) };
    },

    set_child() { return {}; },
    unset_child() { return {}; },
    add_next() { return {}; },
    remove_next() { return {}; }
  };
};

function toStr(v) {
  return typeof v === 'string' ? v : '';
}

function escapeHtml(input) {
  return String(input)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
Loading