You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
1.2 KiB

import {Server} from "socket.io";
import fs from "fs/promises";
import {getBlockName, handlebarLayoutsPath} from "../helpers.js";
import path from "path";
export class ViewSync {
constructor(httpServer) {
this.sessions = {};
this.init(httpServer);
}
addSession(session, blockName) {
if (!this.sessions[blockName]) {
this.sessions[blockName] = [];
}
this.sessions[blockName].push(session);
}
init(httpServer) {
const io = new Server(httpServer);
io.on('connection', async (socket) => {
const blockName = socket.handshake.query.block;
if (!blockName) {
return;
}
this.addSession(socket, blockName);
await this.syncTemplate(blockName);
});
// return httpServer;
}
async syncTemplate(blockName, updateType = 'templateUpdate') {
const block = getBlockName(blockName);
const projectPath = path.join('blocks', '@' + block.project, block.name);
const hbsTemplate = await fs.readFile(handlebarLayoutsPath(projectPath, 'src', `${block.name}.template.hbs`), 'utf8');
if (!this.sessions[blockName]) {
return;
}
this.sessions[blockName].forEach(session => {
session.emit(updateType, {block: blockName, template: hbsTemplate});
});
}
}