fsm-designer/js/export.js

66 lines
2.3 KiB
JavaScript
Raw Normal View History

function exportToJson() {
const _states = JSON.parse(JSON.stringify(states));
const _connections = JSON.parse(JSON.stringify(connections)).map((conn, index) => {
conn.type = connections[index].constructor.name;
return conn;
});
const data = {
states: _states,
connections: _connections.filter(conn => conn.type === 'Connection').map(conn => {
conn.stateA = conn.stateA.id;
conn.stateB = conn.stateB.id;
return conn;
}),
startConnections: _connections.filter(conn => conn.type === 'StartConnection').map(conn => {
conn.state = conn.state.id;
return conn;
}),
selfConnections: _connections.filter(conn => conn.type === 'SelfConnection').map(conn => {
conn.state = conn.state.id;
return conn;
}),
settings,
};
return JSON.stringify(data);
}
function importFromJson(json) {
const data = JSON.parse(json);
states.push(...data.states.map(state => Object.setPrototypeOf(state, State.prototype)));
connections.push(...data.connections.map(conn => Object.setPrototypeOf(conn, Connection.prototype)).map(conn => {
conn.stateA = states.find(state => state.id === conn.stateA);
conn.stateB = states.find(state => state.id === conn.stateB);
return conn;
}));
connections.push(...data.startConnections.map(conn => Object.setPrototypeOf(conn, StartConnection.prototype)).map(conn => {
conn.state = states.find(state => state.id === conn.state);
return conn;
}));
connections.push(...data.selfConnections.map(conn => Object.setPrototypeOf(conn, SelfConnection.prototype)).map(conn => {
conn.state = states.find(state => state.id === conn.state);
return conn;
}));
}
function exportToFile() {
const name = 'placeholder.fsm';
const json = exportToJson();
console.log(json);
downloadFile(name, json, 'application/json');
}
function downloadFile(name, content, type) {
const element = document.createElement('a');
element.setAttribute('href', `data:${type},charset=utf-8,${content}`);
element.setAttribute('download', name);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}