PropertyTable 생성

This commit is contained in:
현성필
2024-01-19 21:10:57 +09:00
parent dba414cb4a
commit 924196b629
33 changed files with 1067 additions and 368 deletions
+10
View File
@@ -9,6 +9,7 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@popperjs/core": "^2.11.8",
"drawflow": "^0.0.59",
"jqueryui": "^1.11.1",
"monaco-editor": "^0.45.0",
@@ -1796,6 +1797,15 @@
"node": ">=14"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@types/body-parser": {
"version": "1.19.5",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz",
+2 -1
View File
@@ -8,7 +8,7 @@
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1",
"clean": "rimraf ./dist",
"deploy": "cp ./dist/* ../src/main/resources/static/plugins/apitestmanager/"
"deploy": "cp -r ./dist/* ../src/main/resources/static/plugins/apitestmanager/"
},
"author": "",
"license": "ISC",
@@ -27,6 +27,7 @@
"webpack-dev-server": "^4.15.1"
},
"dependencies": {
"@popperjs/core": "^2.11.8",
"drawflow": "^0.0.59",
"jqueryui": "^1.11.1",
"monaco-editor": "^0.45.0",
+3 -10
View File
@@ -13,7 +13,6 @@ class APIScenario {
}
init() {
console.log('init');
this.loadScenarioList();
this.outputEditor = monaco.editor.create(document.getElementById('output'), {
value: '',
@@ -27,15 +26,9 @@ class APIScenario {
this.editor.reroute_fix_curvature = true;
this.editor.force_first_input = true;
this.editor.start();
this.editor.on('contextmenu', (event)=> {
console.log(event);
console.log('contextmenu');
//get class of target node
console.log(event.target.id);
let node = this.editor.getNodeFromId(event.target.id);
console.log(node);
})
// this.editor.on('contextmenu', (event) => {
// let node = this.editor.getNodeFromId(event.target.id);
// })
this.showOutput = true;
}
+5 -5
View File
@@ -65,7 +65,7 @@ class APIScenarioExecutor {
if (currentNode.class === 'api') {
let model = JSON.parse(JSON.stringify(this.apiTester.getApiRequestModel(currentNode.data.id)));
model.responseModel = {};
this.appendLog(`Executing API [${model.name}]`);
this.appendLog(`===============================================================\nExecuting API [${model.name}]`);
this.apiClient.sendAPIRequest(model, this.logHttpRequest.bind(this))
.then(response => {
this.isRunning = false;
@@ -84,7 +84,7 @@ class APIScenarioExecutor {
this.appendLog(error.message);
reject(error);
});
console.log(`Executing API request for node: ${currentNode.id} - ${currentNode.name}`);
console.log(`===============================================================\nExecuting API request for node: ${currentNode.id} - ${currentNode.name}`);
} else if (currentNode.class === 'start') {
this.appendLog('Starting API scenario\n');
nodeElement.classList.add('result-success');
@@ -102,7 +102,7 @@ class APIScenarioExecutor {
appendLog(text) {
var range = new monaco.Range(this.outputEditor.getModel().getLineCount(), 1, this.outputEditor.getModel().getLineCount(), 1);
var id = {major: 1, minor: 1};
var op = {identifier: id, range: range, text: text + '\n', forceMoveMarkers: true};
var op = {identifier: id, range: range, text: text + '\n\n', forceMoveMarkers: true};
this.outputEditor.executeEdits("my-source", [op]);
}
@@ -113,14 +113,14 @@ class APIScenarioExecutor {
}
logHttpResponse(response) {
let log = `[Response]\nHTTP/1.1 ${response.status}\n[Response Headers]\n${this.parseHeaders(response.headers)}\n[Response Body]\n${response.body}`;
let log = `[Response]\nHTTP/1.1 ${response.status}\n[Response Headers]\n${this.parseHeaders(response.headers)}\n[Response Body]\n${response.body}\n`;
this.appendLog(log);
}
parseRequestHeaders(headers) {
let parsedHeaders = '';
headers.forEach(header => {
if (header.enabled){
if (header.enabled) {
parsedHeaders += `${header.key}: ${header.value}\n`;
}
});
+110 -107
View File
@@ -1,6 +1,8 @@
import * as monaco from 'monaco-editor';
import APIClient from './APIClient';
import EditableInput from './components/EditableInput';
import {createPopper} from "@popperjs/core/lib/popper-lite";
import PropertyTable from "./components/PropertyTable";
class APITester {
@@ -20,7 +22,8 @@ class APITester {
this.postRequestEditors = [];
this.apiClient = new APIClient();
console.log('test');
this.popperContent = document.getElementById('popperContent');
this.popperInstance = null;
}
renderServers(selectedServer) {
@@ -67,7 +70,8 @@ class APITester {
<input type="text" name="basePath" class="form-control" style="width: 180px; border-radius: 0" value="${this.basePath(apiRequest.server)}" readonly>
<label class="must">기본 경로</label>
</div>
<div class="form-floating editableInput me-1">
<div class="form-floating editableInput me-1 path" data-name="path" data-label="Path">
<label>Path</label>
</div>
<button class="btn btn-primary send me-1">Send</button>
<button class="btn btn-primary save" data-index="${index}" style="height: 58px;">저장</button>
@@ -105,23 +109,9 @@ class APITester {
</li>
</ul>
<div class="tab-content border-bottom" style="min-height: 300px;">
<div class="tab-pane fade show request_param_tab" role="tabpanel" id="requestParamTab_${apiRequest.id}"
aria-labelledby="requestParams-tab">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">이름</th>
<th></th>
<th>
<button type="button" class="btn btn-secondary btn-sm btn_add_query">추가</button>
</th>
</tr>
</thead>
<tbody class="query_params">
${this.renderParams(apiRequest.queryParams)}
</tbody>
</table>
<div class="tab-pane fade show request_param_tab" role="tabpanel" id="requestParamTab_${apiRequest.id}" aria-labelledby="requestParams-tab">
<div class="query_params">
</div>
</div>
<div class="tab-pane fade request_header_tab" role="tabpanel" id="requestHeaderTab_${apiRequest.id}"
aria-labelledby="requestHeader-tab">
@@ -150,13 +140,22 @@ class APITester {
</select>
<div class="request_body mt-1" style="width:100%;height:250px;border:1px solid grey;"></div>
</div>
<div class="tab-pane fade pre_script_tab" role="tabpanel" id="preRequestTab_${apiRequest.id}"
aria-labelledby="preScrit-tab">
<div class="pre-request mt-1" style="width:100%;height:250px;border:1px solid grey;"></div>
<div class="tab-pane fade pre_script_tab" role="tabpanel" id="preRequestTab_${apiRequest.id}" aria-labelledby="preScrit-tab">
<div class="d-flex flex-row">
<div style="width:calc(100% - 200px);">
<div class="pre-request mt-1" style="height:300px;border:1px solid grey;"></div>
</div>
<div style="width: 200px;"></div>
</div>
</div>
<div class="tab-pane fade post_script_tab" role="tabpanel" id="postRequestTab_${apiRequest.id}"
aria-labelledby="postScrit-tab">
<div class="post-request mt-1" style="width:100%;height:250px;border:1px solid grey;"></div>
<div class="d-flex flex-row">
<div style="width:calc(100% - 200px);">
<div class="post-request mt-1" style="height:300px;border:1px solid grey;"></div>
</div>
<div style="width: 200px;"></div>
</div>
</div>
</div>
<div class="mt-1">
@@ -203,26 +202,6 @@ class APITester {
`;
}
queryParamTemplate(queryParam, index) {
return `
<tr data-index="${index}">
<td>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="queryParams[${index}].enabled" ${queryParam.enabled ? 'checked' : ''} />
</div>
</td>
<td>
<input class="form-control" type="text" name="queryParams[${index}].key" value="${queryParam.key}"/>
</td>
<td>
<input class="form-control" type="text" name="queryParams[${index}].value" value="${queryParam.value}"/>
</td>
<td>
<button type="button" class="btn btn-secondary btn-sm btn_remove_query">제거</button>
</td>
</tr>
`;
}
headerTemplate(header, index) {
return `
@@ -308,8 +287,6 @@ class APITester {
const events = [
{selector: '.btn_add_header', action: this.addHeader.bind(this)},
{selector: '.btn_remove_header', action: this.removeHeader.bind(this)},
{selector: '.btn_add_query', action: this.addQueryParam.bind(this)},
{selector: '.btn_remove_query', action: this.removeQueryParam.bind(this)},
{selector: '.send', action: this.handleSendAPIRequest.bind(this)},
{selector: '.save', action: this.saveAPIRequest.bind(this)},
{selector: '.save_collection', action: this.addCollection.bind(this)},
@@ -332,10 +309,6 @@ class APITester {
$(document).on('click', event.selector, event.action);
}
$(document).on('input', '.query_params input', this.handleUIUpdate.bind(this));
$(document).on('input', '.query_params input', this.buildPath.bind(this));
$(document).on('change', '.query_params input', this.handleUIUpdate.bind(this));
$(document).on('change', '.query_params input', this.buildPath.bind(this));
$(document).on('change', '.path', this.parseParam.bind(this));
$(document).on('change', '.request_headers input', this.handleUIUpdate.bind(this));
$(document).on('change', '.api_request_info select, .api_request_info input', this.handleUIUpdate.bind(this));
@@ -510,9 +483,6 @@ class APITester {
target.find('input[name="basePath"]').val(this.basePath(model.server));
}
renderParams(params) {
return params.map((param, index) => this.queryParamTemplate(param, index)).join('');
}
renderHeaders(headers) {
return headers.map((header, index) => this.headerTemplate(header, index)).join('');
@@ -532,6 +502,29 @@ class APITester {
}
}
showPopper(element) {
this.popperContent.style.display = 'block';
this.popperInstance = createPopper(element, popperContent, {
placement: 'bottom', // Popper below the element
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8], // Adjust the position if needed
},
},
],
});
}
hidePopper(element) {
if (this.popperInstance) {
this.popperInstance.destroy();
this.popperInstance = null;
}
this.popperContent.style.display = 'none';
}
renderTabContent(index) {
var me = this;
let apiRequestTabContent = $(this.apiTabContentTarget);
@@ -539,17 +532,40 @@ class APITester {
apiRequestTabContent.append(this.apiRequestTemplate(model, index));
apiRequestTabContent.find(`#api_request_${model.id}`).find('.editableInput').each(function () {
let editableInput = new EditableInput({
name: 'path',
value: model.path,
placeholder: 'Enter text here...',
label: 'Path'
});
console.log(this);
editableInput.init(this, (event) => {
me.parseParam(event);
let editableInput = new EditableInput({
name: 'path',
value: model.path,
});
let propertyTable = new PropertyTable({
propertyName: 'queryParams',
properties: model.queryParams
});
propertyTable.init(apiRequestTabContent.find('.query_params')[0], (properties) => {
model.queryParams = properties;
console.log(model.queryParams);
this.buildPath(model);
editableInput.setValue(model.path);
});
apiRequestTabContent.find(`#api_request_${model.id}`).find('.api_request_info').find('.path').each(function () {
editableInput.init(this, (value) => {
model.path = value;
model.queryParams = me.parseParam(model.path);
propertyTable.setProperties(model.queryParams);
});
$(this).append(`<label>Path</label>`);
$('span.variable').off('mouseover');
$('span.variable').off('mouseout');
});
document.querySelectorAll('.variable').forEach(element => {
element.addEventListener('mouseover', () => me.showPopper(element));
element.addEventListener('mouseout', () => me.hidePopper(element));
});
this.openTab(model.id);
@@ -560,6 +576,23 @@ class APITester {
language: 'json',
automaticLayout: true
});
requestBodyEditor.onMouseMove((e) => {
let position = e.target.position;
if (position) {
let model = requestBodyEditor.getModel();
let word = model.getWordAtPosition(position);
let lineContent = model.getLineContent(position.lineNumber);
if (word) {
if (lineContent.indexOf('{{' + word.word + '}}') > -1) {
me.showPopper(e.target.element);
}
} else {
me.hidePopper(e.target.element);
}
}
});
me.requestEditors.push(requestBodyEditor);
target.find(".request_body")[0].addEventListener('shown.bs.tab', () => {
me.requestEditors[index].layout();
@@ -577,13 +610,16 @@ class APITester {
let responseBodyEditor = monaco.editor.create(target.find(".response_body")[0], {
value: '',
language: 'json',
automaticLayout: true
automaticLayout: true,
quickSuggestions: false
});
me.responseEditors.push(responseBodyEditor);
let consoleEditor = monaco.editor.create(target.find(".console")[0], {
value: '',
automaticLayout: true
automaticLayout: true,
quickSuggestions: false
});
me.consoleEditors.push(consoleEditor);
@@ -591,7 +627,8 @@ class APITester {
let preRequestEditor = monaco.editor.create(target.find(".pre-request")[0], {
value: model.preRequestScript,
language: 'javascript',
automaticLayout: true
automaticLayout: true,
quickSuggestions: false
});
me.preRequestEditors.push(preRequestEditor);
target.find(".pre-request")[0].addEventListener('shown.bs.tab', () => {
@@ -605,7 +642,8 @@ class APITester {
let postRequestEditor = monaco.editor.create(target.find(".post-request")[0], {
value: model.postRequestScript,
language: 'javascript',
automaticLayout: true
automaticLayout: true,
quickSuggestions: false
});
me.postRequestEditors.push(postRequestEditor);
target.find(".post-request")[0].addEventListener('shown.bs.tab', () => {
@@ -730,58 +768,25 @@ class APITester {
}
addQueryParam(event) {
const tabIndex = $('#apiRequestTabContent').children().index($(event.currentTarget).closest('.api_request'));
let model = this.apiRequests[tabIndex];
model.queryParams.push({
enabled: true,
key: '',
value: ''
});
this.renderQueryParamsView(tabIndex);
}
removeQueryParam(event) {
const tabIndex = $('#apiRequestTabContent').children().index($(event.currentTarget).closest('.api_request'));
const index = $(event.currentTarget).closest('tr').data('index');
let model = this.apiRequests[tabIndex];
model.queryParams.splice(index, 1);
this.renderQueryParamsView(tabIndex);
}
renderQueryParamsView(tabIndex) {
let model = this.apiRequests[tabIndex];
let target = $('#api_request_' + model.id);
target.find('.query_params').empty();
target.find('.query_params').append(this.renderParams(model.queryParams));
}
parseParam(event) {
const tabIndex = $('#apiRequestTabContent').children().index($(event.currentTarget).closest('.api_request'));
let model = this.apiRequests[tabIndex];
model.path = $(event.currentTarget).siblings('input[type="hidden"]').val();
model.queryParams = [];
let queryString = model.path.split('?')[1];
parseParam(path) {
let queryParams = [];
let queryString = path.split('?')[1];
if (queryString) {
let queryParamArray = queryString.split('&');
for (let i = 0; i < queryParamArray.length; i++) {
let queryParam = queryParamArray[i].split('=');
model.queryParams.push({
queryParams.push({
enabled: true,
key: queryParam[0],
value: (queryParam[1] === undefined ? '' : queryParam[1])
});
}
this.renderQueryParamsView(tabIndex);
}
return queryParams;
}
buildPath(event) {
const tabIndex = $('#apiRequestTabContent').children().index($(event.currentTarget).closest('.api_request'));
let model = this.apiRequests[tabIndex];
buildPath(model) {
let queryString = model.path.split('?')[0];
if (model.queryParams.length > 0) {
queryString += '?';
@@ -796,8 +801,6 @@ class APITester {
}
}
model.path = queryString;
console.log(model.path);
$('#api_request_' + model.id).find('.editableInputContent').html(model.path);
}
showLoadingOverlay() {
+132 -67
View File
@@ -1,90 +1,59 @@
class EditableInput {
constructor(options = {}) {
this.value = options.value || '';
this.name = options.name || '';
this.id = options.id || '';
this.class = options.class || 'form-control';
this.placeholder = options.placeholder || '';
this.label = options.label || '';
class EditableInputModel {
constructor(value = '') {
this.value = value;
}
init(element, callback) {
this.element = element;
this.element.innerHTML = this.render();
this.attachEventListeners(callback);
setValue(newValue) {
this.value = newValue;
}
val(newValue) {
if (newValue !== undefined) {
this.value = newValue;
this.updateUI();
}
getValue() {
return this.value;
}
}
updateUI() {
const editableDiv = this.element.querySelector('.editableInputContent');
const hiddenInput = this.element.querySelector('input[type="hidden"]');
if (this.value) {
editableDiv.innerHTML = this.renderContent(this.parseContent(this.value));
} else {
editableDiv.innerHTML = '&#8203;'; // Insert a zero-width space
}
hiddenInput.value = this.value;
class EditableInputView {
constructor(model, editableInput) {
this.model = model;
this.editableInput = editableInput;
}
render() {
let contentHtml = this.value ? this.renderContent(this.parseContent(this.value)) : '&#8203;';
render(element) {
this.element = element;
this.element.innerHTML = this.generateInputHtml();
this.editableDiv = this.element.querySelector('.editableInputContent');
this.attachEventListeners();
}
generateInputHtml() {
let contentHtml = this.model.getValue() ? this.renderContent(this.parseContent(this.model.getValue())) : '&#8203;';
return `
<div contenteditable="true" class="editableInputContent ${this.class}" style="border-bottom-left-radius: 0; border-top-left-radius: 0;" placeholder="${this.placeholder}">
${contentHtml}
</div>
<input type="hidden" name="${this.name}" value="${this.value}" />
<label>${this.label}</label>
`;
<div contenteditable="true" class="editableInputContent form-control" data-value="${this.model.getValue()}">
${contentHtml}
</div>
`;
}
attachEventListeners(callback) {
const editableDiv = this.element.querySelector('.editableInputContent');
const hiddenInput = this.element.querySelector('input[type="hidden"]');
editableDiv.addEventListener('input', (event) => {
this.handleInput(event, editableDiv, hiddenInput);
if (callback)
callback(event);
attachEventListeners() {
this.editableDiv.addEventListener('input', (event) => {
this.editableInput.controller.handleInput(this.editableDiv);
if (this.editableInput.controller.additionalCallback) {
this.editableInput.controller.additionalCallback(this.model.getValue());
}
});
}
handleInput(event, editableDiv, hiddenInput) {
let cursor = this.getCurrentCursor(editableDiv);
let mergedString = Array.from(editableDiv.childNodes)
.filter(function(node) {
// Keep only SPAN elements and text nodes
return node.nodeName.toUpperCase() === 'SPAN' || node.nodeType === 3;
})
.map(node => {
return node.nodeType === 3 ? node.data.trim() : node.innerText.trim();
})
.join('');
let content = this.parseContent(mergedString);
this.value = content.join('');
hiddenInput.value = this.value;
if (!this.value) {
editableDiv.innerHTML = '&#8203;'; // Insert a zero-width space
cursor = 0;
updateUI() {
let content = this.model.getValue();
if (content) {
this.editableDiv.innerHTML = this.renderContent(this.parseContent(content));
} else {
editableDiv.innerHTML = this.renderContent(content);
this.editableDiv.innerHTML = '&#8203;'; // Insert a zero-width space
}
this.restoreCursor(editableDiv, cursor);
this.editableDiv.setAttribute('data-value', content);
}
renderContent(contentArray) {
let content = '';
contentArray.forEach((item) => {
@@ -122,6 +91,20 @@ class EditableInput {
return returnStringArray;
}
}
class EditableInputController {
constructor(model, view) {
this.model = model;
this.view = view;
}
init(element, callback) {
this.view.render(element);
this.additionalCallback = callback;
}
getCurrentCursor(element) {
const selection = window.getSelection();
@@ -134,6 +117,53 @@ class EditableInput {
return preCaretRange.toString().trim().length;
}
handleInput(editableDiv) {
let cursor = this.getCurrentCursor(editableDiv);
let mergedString = Array.from(editableDiv.childNodes)
.filter(function (node) {
// Keep only SPAN elements and text nodes
return node.nodeName.toUpperCase() === 'SPAN' || node.nodeType === 3;
})
.map(node => {
return node.nodeType === 3 ? node.data.trim() : node.innerText.trim();
})
.join('');
let content = this.parseContent(mergedString);
this.model.setValue(content.join(''));
// Optionally, update the view if needed
this.view.updateUI();
this.restoreCursor(editableDiv, cursor);
}
parseContent(inputString) {
let returnStringArray = [];
let regex = /{{.*?}}/g;
let lastIndex = 0;
inputString.replace(regex, (match, index) => {
// Add the string before the match
if (index > lastIndex) {
returnStringArray.push(inputString.slice(lastIndex, index));
}
// Add the matched string including the delimiters
returnStringArray.push(match);
// Update lastIndex for the next iteration
lastIndex = index + match.length;
});
// Add any remaining string after the last match
if (lastIndex < inputString.length) {
returnStringArray.push(inputString.slice(lastIndex));
}
return returnStringArray;
}
restoreCursor(element, position) {
const selection = window.getSelection();
const range = document.createRange();
@@ -167,7 +197,42 @@ class EditableInput {
selection.removeAllRanges();
selection.addRange(range);
}
}
class EditableInput {
constructor(options = {}) {
// Initialize the model with the value
this.model = new EditableInputModel(options.value || '');
// Create the view and controller, passing the model to them
this.view = new EditableInputView(this.model, this);
this.controller = new EditableInputController(this.model, this.view);
// Additional properties as required
this.name = options.name || '';
this.id = options.id || '';
this.class = options.class || 'form-control';
this.placeholder = options.placeholder || '';
}
init(element, callback) {
// Initialize the controller with the DOM element
this.controller.init(element, callback);
}
getValue() {
// Delegate to the model
return this.model.getValue();
}
setValue(newValue) {
// Delegate to the model and update the view
this.model.setValue(newValue);
this.view.updateUI();
}
// Any additional methods required for interaction with this component
}
export default EditableInput;
@@ -1,130 +0,0 @@
class EditableInput {
constructor(options = {}) {
this.value = options.value || '';
this.name = options.name || '';
this.id = options.id || '';
this.class = options.class || '';
this.placeholder = options.placeholder || '';
}
val(newValue) {
if (newValue !== undefined) {
this.value = newValue;
}
return this.value;
}
init(element, callback) {
const editableDiv = element.querySelector(`.editableInputContent`);
const hiddenInput = element.querySelector(`.editableInputTarget`);
editableDiv.innerHTML = this.renderContent(this.parseContent(hiddenInput.value)); // Set the initial content
editableDiv.addEventListener('input', (event) => {
let cursor = this.getCurrentCursor(editableDiv);
let mergedString = Array.from(editableDiv.children)
.map(span => span.textContent)
.join('');
let content = this.parseContent(mergedString);
editableDiv.innerHTML = this.renderContent(content); // Update the content
hiddenInput.value = content.join(''); // Update the hidden input value
this.value = content.join(''); // Update the value of the EditableInput object
this.restoreCursor(editableDiv, cursor);
if (callback)
callback(event);
});
}
renderContent(contentArray) {
let content = '';
contentArray.forEach((item) => {
if (item.startsWith('{{')) {
content += `<span class="variable">${item}</span>`;
} else {
content += `<span class="text">${item}</span>`;
}
});
return content;
}
parseContent(inputString) {
let returnStringArray = [];
let regex = /{{.*?}}/g;
let lastIndex = 0;
inputString.replace(regex, (match, index) => {
// Add the string before the match
if (index > lastIndex) {
returnStringArray.push(inputString.slice(lastIndex, index));
}
// Add the matched string including the delimiters
returnStringArray.push(match);
// Update lastIndex for the next iteration
lastIndex = index + match.length;
});
// Add any remaining string after the last match
if (lastIndex < inputString.length) {
returnStringArray.push(inputString.slice(lastIndex));
}
return returnStringArray;
}
getCurrentCursor(element) {
const selection = window.getSelection();
if (selection.rangeCount === 0) return null;
const range = selection.getRangeAt(0);
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
return preCaretRange.toString().length;
}
restoreCursor(element, position) {
const selection = window.getSelection();
const range = document.createRange();
range.setStart(element, 0);
range.collapse(true);
const nodeStack = [element];
let node, foundStart = false, stop = false;
let charIndex = 0;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType === 3) {
const nextCharIndex = charIndex + node.length;
if (!foundStart && position >= charIndex && position <= nextCharIndex) {
range.setStart(node, position - charIndex);
foundStart = true;
}
if (foundStart && position >= charIndex && position <= nextCharIndex) {
range.setEnd(node, position - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
let i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
selection.removeAllRanges();
selection.addRange(range);
}
}
export default EditableInput;
@@ -0,0 +1,226 @@
import EditableInput from './EditableInput.js';
class PropertyTableModel {
constructor(properties = []) {
this.properties = properties;
}
addProperty(property) {
this.properties.push(property);
}
removeProperty(index) {
this.properties.splice(index, 1);
}
getProperties() {
return this.properties;
}
setProperties(newProperties) {
this.properties = newProperties;
}
}
class PropertyTableView {
constructor(model, propertyTable) {
this.model = model;
this.propertyTable = propertyTable;
this.modelViewList = [];
}
render(element) {
this.element = element;
this.element.innerHTML = this.generateTableHtml();
this.attachEventListeners();
}
generateTableHtml() {
const properties = this.model.getProperties();
let rowsHtml = properties.map((property, index) => this.generateRowHtml(property, index)).join('');
return `<div class="prop-table">
<div class="prop-table-row prop-table-header">
<div class="prop-table-cell" style="width: 50px;">#</div>
<div class="prop-table-cell" style="flex: 1">이름</div>
<div class="prop-table-cell" style="flex: 1"></div>
<div class="prop-table-cell" style="width:100px;">
<button type="button" class="btn btn-secondary btn-sm add_property">추가</button>
</div>
</div>
${rowsHtml}
</div>`;
}
generateRowHtml(property, index) {
// Updated to include placeholders for EditableInput
return `
<div class="prop-table-row" data-index="${index}">
<div class="prop-table-cell" style="width: 50px;">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-name="enabled" ${property.enabled ? 'checked' : ''} />
</div>
</div>
<div class="prop-table-cell key" style="flex: 1">
<div class="editable" data-name="key" data-value="${property.key}"></div>
</div>
<div class="prop-table-cell value" style="flex: 1">
<div class="editable" data-name="value" data-value="${property.value}"></div>
</div>
<div class="prop-table-cell" style="width:100px;">
<button type="button" class="btn btn-secondary btn-sm remove-property" data-index="${index}"><i class="fa fa-sharp fa-minus"></i></button>
</div>
</div>
`;
}
updateUI() {
// Re-render the table with updated data
this.element.innerHTML = this.generateTableHtml();
// Instantiate EditableInput components for each editable cell
this.element.querySelectorAll('.prop-table-row:not(.prop-table-header)').forEach((row, index) => {
const checkbox = row.querySelector('.form-check-input');
if (checkbox) {
checkbox.addEventListener('change', (event) => {
const index = parseInt(event.target.parentElement.parentElement.parentElement.getAttribute('data-index'), 10);
this.propertyTable.controller.updateProperty(index, 'enabled', event.target.checked);
if (this.propertyTable.controller.additionalCallback) {
this.propertyTable.controller.additionalCallback(this.model.getProperties());
}
});
}
this.element.querySelectorAll('.editable').forEach(editableElement => {
const index = parseInt(editableElement.parentElement.parentElement.getAttribute('data-index'), 10);
const editableInput = new EditableInput({
name: editableElement.dataset.name,
value: editableElement.dataset.value
});
editableInput.init(editableElement, (value) => {
let model = this.model.getProperties()[index];
model[editableElement.dataset.name] = value;
if (this.propertyTable.controller.additionalCallback) {
this.propertyTable.controller.additionalCallback(this.model.getProperties());
}
});
});
});
this.attachEventListeners();
}
attachEventListeners() {
this.element.querySelectorAll('.remove-property').forEach(button => {
button.addEventListener('click', (event) => {
const index = parseInt(event.target.getAttribute('data-index'), 10);
console.log({index});
this.propertyTable.controller.removeProperty(index);
});
});
const addButton = this.element.querySelector('.add_property');
if (addButton) {
console.log('Add button found'); // Check if the button is found
addButton.addEventListener('click', (event) => {
console.log(event)
console.log(this)
console.log('Add button clicked'); // Check if this gets logged on click
this.propertyTable.controller.addProperty();
});
} else {
console.log('Add button not found'); // Check if the button is not found
}
}
}
class PropertyTableController {
constructor(model, view) {
this.model = model;
this.view = view;
}
init(element, callback) {
this.view.render(element);
this.additionalCallback = callback;
}
addProperty() {
console.log('addProperty');
// Add a new property to the model
this.model.addProperty({
key: '',
value: ''
});
// Update the view to reflect the model changes
this.view.updateUI();
}
removeProperty(index) {
// Remove the property from the model
this.model.removeProperty(index);
// Update the view to reflect the model changes
this.view.updateUI();
if (this.additionalCallback) {
this.additionalCallback(this.model.getProperties());
}
}
updateProperty(index, key, value) {
// Update a specific property in the model
let properties = this.model.getProperties();
if (properties[index]) {
properties[index][key] = value;
}
}
}
class PropertyTable {
constructor(options = {}) {
// Initialize the model with properties
this.model = new PropertyTableModel(options.properties || []);
// Create the view and controller, passing the model to them
this.view = new PropertyTableView(this.model, this);
this.controller = new PropertyTableController(this.model, this.view);
// Additional properties
this.propertyName = options.propertyName || '';
}
init(element, callback) {
// Initialize the controller with the DOM element
this.controller.init(element, callback);
this.setProperties(this.model.getProperties());
}
getProperties() {
// Delegate to the model
return this.model.getProperties();
}
setProperties(newProperties) {
// Update the model and refresh the view
this.model.setProperties(newProperties);
this.view.updateUI();
}
addProperty(property) {
// Delegate to the controller
this.controller.addProperty(property);
}
removeProperty(index) {
// Delegate to the controller
this.controller.removeProperty(index);
}
// Any additional methods as needed
}
export default PropertyTable;
+2 -6
View File
@@ -1,13 +1,10 @@
import APITester from './APITester';
import APIScenario from "./APIScenario";
// import { buildWorkerDefinition } from "monaco-editor-workers";
//
// buildWorkerDefinition('./node_modules/monaco-editor-workers/dist/workers', import.meta.url, false);
self.MonacoEnvironment = {
window.MonacoEnvironment = {
getWorkerUrl: function (moduleId, label) {
if (label === 'json') {
return '/plugins/apitestmanager/json.worker.js';
return '/plugins/apitestmanager/json.worker.bundle.js';
}
if (label === 'css' || label === 'scss' || label === 'less') {
return '/plugins/apitestmanager/css.worker.bundle.js';
@@ -29,7 +26,6 @@ export default class APITestManager {
this.apiTester.init(servers);
this.apiScenario = new APIScenario(this.apiTester);
this.apiScenario.init();
console.log("APITestManager initialized");
}
}
+22 -8
View File
@@ -1,14 +1,14 @@
const path = require('path');
// const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
'editor.worker': 'monaco-editor/esm/vs/editor/editor.worker.js',
'json.worker': 'monaco-editor/esm/vs/language/json/json.worker',
'css.worker': 'monaco-editor/esm/vs/language/css/css.worker',
'html.worker': 'monaco-editor/esm/vs/language/html/html.worker',
'ts.worker': 'monaco-editor/esm/vs/language/typescript/ts.worker'
// 'editor.worker': 'monaco-editor/esm/vs/editor/editor.worker.js',
// 'json.worker': 'monaco-editor/esm/vs/language/json/json.worker',
// 'css.worker': 'monaco-editor/esm/vs/language/css/css.worker',
// 'html.worker': 'monaco-editor/esm/vs/language/html/html.worker',
// 'ts.worker': 'monaco-editor/esm/vs/language/typescript/ts.worker'
},
module: {
rules: [
@@ -40,6 +40,7 @@ module.exports = {
}
]
},
plugins: [new MonacoWebpackPlugin()],
externals: {
jquery: 'jQuery',
bootstrap: 'bootstrap',
@@ -53,6 +54,7 @@ module.exports = {
export: 'default'
},
globalObject: `(typeof self !== 'undefined' ? self : this)`,
// globalObject: 'self',
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
},
@@ -64,6 +66,18 @@ module.exports = {
changeOrigin: true,
}
}
}
},
// optimization: {
// splitChunks: {
// chunks: 'all',
// automaticNameDelimiter: '-',
// cacheGroups: {
// vendor: {
// test: /[\\/]node_modules[\\/]/,
// name: 'vendors',
// chunks: 'all',
// }
// }
// }
// }
};