3758 lines
158 KiB
HTML
3758 lines
158 KiB
HTML
<!doctype html>
|
||
<html lang="fa" dir="rtl">
|
||
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
<title>XFramework Backend SDK Manager</title>
|
||
<style>
|
||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
||
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&display=swap');
|
||
|
||
:root {
|
||
--primary: #1a365d;
|
||
--primary-light: #2c5282;
|
||
--primary-dark: #0f2341;
|
||
--accent: #c9a961;
|
||
--accent-dark: #a8893f;
|
||
--accent-light: #e0c789;
|
||
--bg: #f5f7fa;
|
||
--board-bg: #e2e8f0;
|
||
--card-bg: #ffffff;
|
||
--column-bg: #edf2f7;
|
||
--panel-bg: #ffffff;
|
||
--text: #1a202c;
|
||
--text-muted: #4a5568;
|
||
--text-light: #718096;
|
||
--border: #cbd5e0;
|
||
--border-light: #e2e8f0;
|
||
--success: #38a169;
|
||
--danger: #e53e3e;
|
||
--warning: #dd6b20;
|
||
--info: #3182ce;
|
||
--shadow: 0 4px 6px rgba(0, 0, 0, 0.08), 0 10px 20px rgba(26, 54, 93, 0.1);
|
||
--shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.06);
|
||
--shadow-lg: 0 10px 30px rgba(0, 0, 0, 0.15);
|
||
--radius: 10px;
|
||
--radius-sm: 6px;
|
||
--sidebar-width: 300px;
|
||
--header-height: 64px;
|
||
--footer-height: 36px;
|
||
}
|
||
|
||
[data-theme='dark'] {
|
||
--primary: #2c5282;
|
||
--primary-light: #3b6fb5;
|
||
--primary-dark: #1a365d;
|
||
--accent: #e0c789;
|
||
--accent-dark: #c9a961;
|
||
--accent-light: #f0d9a0;
|
||
--bg: #1a202c;
|
||
--board-bg: #2d3748;
|
||
--card-bg: #2d3748;
|
||
--column-bg: #374151;
|
||
--panel-bg: #1f2937;
|
||
--text: #e2e8f0;
|
||
--text-muted: #cbd5e0;
|
||
--text-light: #a0aec0;
|
||
--border: #4a5568;
|
||
--border-light: #374151;
|
||
}
|
||
|
||
* {
|
||
box-sizing: border-box;
|
||
margin: 0;
|
||
padding: 0;
|
||
}
|
||
|
||
body {
|
||
font-family: 'Vazirmatn', Tahoma, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
height: 100vh;
|
||
overflow: hidden;
|
||
font-size: 14px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
transition: background 0.3s, color 0.3s;
|
||
}
|
||
|
||
.app-header {
|
||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
|
||
color: white;
|
||
padding: 0 20px;
|
||
height: var(--header-height);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
box-shadow: var(--shadow);
|
||
z-index: 100;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.app-brand {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 14px;
|
||
}
|
||
|
||
.app-logo {
|
||
width: 44px;
|
||
height: 44px;
|
||
background: var(--accent);
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 22px;
|
||
font-weight: 800;
|
||
color: var(--primary-dark);
|
||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.app-brand-text {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 2px;
|
||
}
|
||
|
||
.app-title {
|
||
font-size: 16px;
|
||
font-weight: 800;
|
||
color: white;
|
||
}
|
||
|
||
.app-subtitle {
|
||
font-size: 11px;
|
||
opacity: 0.85;
|
||
color: rgba(255, 255, 255, 0.9);
|
||
}
|
||
|
||
.header-actions {
|
||
display: flex;
|
||
gap: 10px;
|
||
align-items: center;
|
||
}
|
||
|
||
.btn {
|
||
background: linear-gradient(135deg, var(--primary-light), var(--primary));
|
||
color: white;
|
||
border: none;
|
||
padding: 8px 14px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
transition: all 0.2s;
|
||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.btn:hover {
|
||
transform: translateY(-1px);
|
||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
|
||
filter: brightness(1.1);
|
||
}
|
||
|
||
.btn:active {
|
||
transform: translateY(0);
|
||
}
|
||
|
||
.btn:disabled {
|
||
opacity: 0.5;
|
||
cursor: not-allowed;
|
||
}
|
||
|
||
.btn-accent {
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
font-weight: 700;
|
||
}
|
||
|
||
.btn-ghost {
|
||
background: rgba(255, 255, 255, 0.1);
|
||
border: 1px solid rgba(255, 255, 255, 0.25);
|
||
color: white;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.btn-ghost:hover {
|
||
background: rgba(255, 255, 255, 0.2);
|
||
}
|
||
|
||
.btn-success {
|
||
background: linear-gradient(135deg, #48bb78, var(--success));
|
||
}
|
||
|
||
.btn-danger {
|
||
background: linear-gradient(135deg, #f56565, var(--danger));
|
||
}
|
||
|
||
.btn-warning {
|
||
background: linear-gradient(135deg, #f6ad55, var(--warning));
|
||
color: white;
|
||
}
|
||
|
||
.btn-info {
|
||
background: linear-gradient(135deg, #63b3ed, var(--info));
|
||
}
|
||
|
||
.btn-sm {
|
||
padding: 6px 10px;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.btn-xs {
|
||
padding: 4px 8px;
|
||
font-size: 11px;
|
||
}
|
||
|
||
.app-main {
|
||
flex: 1;
|
||
display: flex;
|
||
overflow: hidden;
|
||
flex-direction: row;
|
||
}
|
||
|
||
.sidebar {
|
||
order: -1;
|
||
width: var(--sidebar-width);
|
||
background: var(--panel-bg);
|
||
border-right: 1px solid var(--border);
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: var(--shadow);
|
||
flex-shrink: 0;
|
||
z-index: 50;
|
||
}
|
||
|
||
.sidebar-header {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 12px;
|
||
border-bottom: 2px solid var(--accent);
|
||
min-height: 48px;
|
||
display: flex;
|
||
align-items: center;
|
||
}
|
||
|
||
.sidebar-title {
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
}
|
||
|
||
.sidebar-body {
|
||
flex: 1;
|
||
overflow-y: auto;
|
||
padding: 8px;
|
||
}
|
||
|
||
.search-input-wrapper {
|
||
position: relative;
|
||
margin-bottom: 8px;
|
||
}
|
||
|
||
.search-input {
|
||
width: 100%;
|
||
padding: 8px 12px 8px 32px;
|
||
border: 1px solid var(--border);
|
||
border-radius: var(--radius-sm);
|
||
font-family: inherit;
|
||
font-size: 12px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
}
|
||
|
||
.search-input:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
box-shadow: 0 0 0 3px rgba(201, 169, 97, 0.15);
|
||
}
|
||
|
||
.search-icon {
|
||
position: absolute;
|
||
left: 10px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
font-size: 14px;
|
||
opacity: 0.5;
|
||
pointer-events: none;
|
||
}
|
||
|
||
.search-clear {
|
||
position: absolute;
|
||
right: 8px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
display: none;
|
||
}
|
||
|
||
.search-clear.visible {
|
||
display: block;
|
||
}
|
||
|
||
.controller-item {
|
||
background: var(--card-bg);
|
||
border: 1px solid var(--border-light);
|
||
color: var(--text);
|
||
padding: 10px 12px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 500;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
transition: all 0.2s;
|
||
width: 100%;
|
||
margin-bottom: 4px;
|
||
}
|
||
|
||
.controller-item:hover {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
transform: translateX(-2px);
|
||
}
|
||
|
||
.controller-item.active {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-color: var(--accent);
|
||
}
|
||
|
||
.controller-item .ctrl-icon {
|
||
font-size: 18px;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.controller-item .ctrl-name {
|
||
flex: 1;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.controller-item .ctrl-badge {
|
||
font-size: 10px;
|
||
background: rgba(201, 169, 97, 0.2);
|
||
color: var(--accent-dark);
|
||
padding: 2px 7px;
|
||
border-radius: 10px;
|
||
font-weight: 700;
|
||
}
|
||
|
||
.controller-item.active .ctrl-badge {
|
||
background: rgba(255, 255, 255, 0.25);
|
||
color: white;
|
||
}
|
||
|
||
.board-area {
|
||
flex: 1;
|
||
overflow: auto;
|
||
padding: 20px;
|
||
background: var(--board-bg);
|
||
}
|
||
|
||
.upload-zone {
|
||
background: var(--card-bg);
|
||
border: 3px dashed var(--border);
|
||
border-radius: var(--radius);
|
||
padding: 60px 40px;
|
||
text-align: center;
|
||
cursor: pointer;
|
||
max-width: 700px;
|
||
margin: 40px auto;
|
||
}
|
||
|
||
.upload-zone:hover,
|
||
.upload-zone.dragover {
|
||
border-color: var(--accent);
|
||
transform: translateY(-2px);
|
||
}
|
||
|
||
.upload-zone-icon {
|
||
font-size: 70px;
|
||
margin-bottom: 20px;
|
||
opacity: 0.7;
|
||
}
|
||
|
||
.upload-zone h2 {
|
||
color: var(--primary);
|
||
font-size: 22px;
|
||
margin-bottom: 10px;
|
||
}
|
||
|
||
[data-theme='dark'] .upload-zone h2 {
|
||
color: var(--accent);
|
||
}
|
||
|
||
.upload-zone p {
|
||
color: var(--text-muted);
|
||
margin-bottom: 20px;
|
||
}
|
||
|
||
.controller-tabs {
|
||
display: flex;
|
||
gap: 4px;
|
||
background: var(--card-bg);
|
||
padding: 6px;
|
||
border-radius: var(--radius);
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.controller-tab {
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
padding: 10px 16px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
}
|
||
|
||
.controller-tab:hover {
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
}
|
||
|
||
.controller-tab.active {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
}
|
||
|
||
.content-section {
|
||
background: var(--card-bg);
|
||
border-radius: var(--radius);
|
||
padding: 24px;
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
|
||
.section-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
padding-bottom: 14px;
|
||
border-bottom: 2px solid var(--border-light);
|
||
margin-bottom: 18px;
|
||
}
|
||
|
||
.section-icon {
|
||
width: 44px;
|
||
height: 44px;
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 20px;
|
||
flex-shrink: 0;
|
||
box-shadow: 0 4px 10px rgba(26, 54, 93, 0.2);
|
||
}
|
||
|
||
.section-title {
|
||
flex: 1;
|
||
}
|
||
|
||
.section-title h3 {
|
||
font-size: 17px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
}
|
||
|
||
[data-theme='dark'] .section-title h3 {
|
||
color: var(--accent);
|
||
}
|
||
|
||
.section-title .subtitle {
|
||
font-size: 12px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.models-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||
gap: 12px;
|
||
}
|
||
|
||
.model-card {
|
||
background: var(--column-bg);
|
||
border: 2px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
position: relative;
|
||
}
|
||
|
||
.model-card:hover {
|
||
border-color: var(--accent);
|
||
transform: translateY(-2px);
|
||
}
|
||
|
||
.model-card-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
margin-bottom: 8px;
|
||
}
|
||
|
||
.model-card-icon {
|
||
width: 32px;
|
||
height: 32px;
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
border-radius: 8px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 14px;
|
||
font-weight: 800;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.model-card-name {
|
||
font-size: 14px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
flex: 1;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
[data-theme='dark'] .model-card-name {
|
||
color: var(--accent);
|
||
}
|
||
|
||
.model-card-meta {
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
display: flex;
|
||
gap: 10px;
|
||
margin-top: 6px;
|
||
}
|
||
|
||
.endpoints-table {
|
||
width: 100%;
|
||
border-collapse: collapse;
|
||
background: var(--card-bg);
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.endpoints-table thead {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
}
|
||
|
||
.endpoints-table th {
|
||
padding: 12px 14px;
|
||
text-align: right;
|
||
font-weight: 600;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.endpoints-table td {
|
||
padding: 11px 14px;
|
||
border-bottom: 1px solid var(--border-light);
|
||
font-size: 12px;
|
||
}
|
||
|
||
.endpoints-table tbody tr:nth-child(even) {
|
||
background: var(--column-bg);
|
||
}
|
||
|
||
.method-badge {
|
||
display: inline-block;
|
||
padding: 3px 10px;
|
||
border-radius: 4px;
|
||
font-size: 10px;
|
||
font-weight: 800;
|
||
color: white;
|
||
font-family: 'Fira Code', monospace;
|
||
}
|
||
|
||
.method-get {
|
||
background: var(--info);
|
||
}
|
||
|
||
.method-post {
|
||
background: var(--success);
|
||
}
|
||
|
||
.method-put {
|
||
background: var(--warning);
|
||
}
|
||
|
||
.method-delete {
|
||
background: var(--danger);
|
||
}
|
||
|
||
.method-patch {
|
||
background: #805ad5;
|
||
}
|
||
|
||
.endpoint-path {
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
|
||
.test-btn {
|
||
background: linear-gradient(135deg, var(--success), #2f855a);
|
||
color: white;
|
||
border: none;
|
||
padding: 5px 10px;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
}
|
||
|
||
.test-btn:hover {
|
||
transform: translateY(-1px);
|
||
box-shadow: 0 2px 6px rgba(56, 161, 105, 0.4);
|
||
}
|
||
|
||
.modal-overlay {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(26, 54, 93, 0.6);
|
||
backdrop-filter: blur(3px);
|
||
display: none;
|
||
align-items: center;
|
||
justify-content: center;
|
||
z-index: 1000;
|
||
padding: 20px;
|
||
}
|
||
|
||
.modal-overlay.active {
|
||
display: flex;
|
||
}
|
||
|
||
.modal {
|
||
background: var(--panel-bg);
|
||
color: var(--text);
|
||
border-radius: 12px;
|
||
width: 100%;
|
||
max-width: 1100px;
|
||
max-height: 90vh;
|
||
overflow: hidden;
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: var(--shadow-lg);
|
||
}
|
||
|
||
.modal-header {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 16px 20px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
}
|
||
|
||
.modal-title {
|
||
font-size: 16px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
}
|
||
|
||
.modal-close {
|
||
background: rgba(255, 255, 255, 0.15);
|
||
border: none;
|
||
color: white;
|
||
width: 30px;
|
||
height: 30px;
|
||
border-radius: 50%;
|
||
cursor: pointer;
|
||
font-size: 16px;
|
||
}
|
||
|
||
.modal-close:hover {
|
||
background: var(--danger);
|
||
}
|
||
|
||
.modal-body {
|
||
padding: 20px;
|
||
overflow-y: auto;
|
||
flex: 1;
|
||
}
|
||
|
||
.modal-footer {
|
||
padding: 14px 20px;
|
||
border-top: 1px solid var(--border);
|
||
display: flex;
|
||
gap: 8px;
|
||
background: var(--border-light);
|
||
}
|
||
|
||
.code-block {
|
||
background: #1e1e1e;
|
||
color: #d4d4d4;
|
||
border-radius: 8px;
|
||
padding: 16px;
|
||
font-family: 'Fira Code', 'Courier New', monospace;
|
||
font-size: 12px;
|
||
line-height: 1.7;
|
||
overflow-x: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
max-height: 600px;
|
||
overflow-y: auto;
|
||
white-space: pre;
|
||
}
|
||
|
||
.code-block-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
background: #2d2d2d;
|
||
padding: 8px 14px;
|
||
border-radius: 8px 8px 0 0;
|
||
color: #d4d4d4;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
}
|
||
|
||
.code-keyword {
|
||
color: #569cd6;
|
||
}
|
||
|
||
.code-type {
|
||
color: #4ec9b0;
|
||
}
|
||
|
||
.code-string {
|
||
color: #ce9178;
|
||
}
|
||
|
||
.code-comment {
|
||
color: #6a9955;
|
||
font-style: italic;
|
||
}
|
||
|
||
.code-number {
|
||
color: #b5cea8;
|
||
}
|
||
|
||
.toast-container {
|
||
position: fixed;
|
||
bottom: 20px;
|
||
left: 20px;
|
||
z-index: 2000;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 8px;
|
||
}
|
||
|
||
.toast {
|
||
background: var(--primary);
|
||
color: white;
|
||
padding: 12px 18px;
|
||
border-radius: 8px;
|
||
box-shadow: var(--shadow-lg);
|
||
font-size: 13px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
animation: slideInLeft 0.3s;
|
||
min-width: 250px;
|
||
}
|
||
|
||
.toast.success {
|
||
background: var(--success);
|
||
}
|
||
|
||
.toast.error {
|
||
background: var(--danger);
|
||
}
|
||
|
||
.toast.warning {
|
||
background: var(--warning);
|
||
}
|
||
|
||
@keyframes slideInLeft {
|
||
from {
|
||
opacity: 0;
|
||
transform: translateX(-30px);
|
||
}
|
||
|
||
to {
|
||
opacity: 1;
|
||
transform: translateX(0);
|
||
}
|
||
}
|
||
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||
gap: 14px;
|
||
margin-bottom: 20px;
|
||
}
|
||
|
||
.stat-card {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 18px;
|
||
border-radius: var(--radius);
|
||
text-align: center;
|
||
}
|
||
|
||
.stat-card .stat-value {
|
||
font-size: 28px;
|
||
font-weight: 800;
|
||
color: var(--accent);
|
||
}
|
||
|
||
.stat-card .stat-label {
|
||
font-size: 12px;
|
||
opacity: 0.9;
|
||
}
|
||
|
||
.app-footer {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 8px 20px;
|
||
font-size: 11px;
|
||
display: flex;
|
||
justify-content: space-between;
|
||
border-top: 2px solid var(--accent);
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.footer-brand {
|
||
color: var(--accent);
|
||
font-weight: 700;
|
||
}
|
||
|
||
.global-settings-panel {
|
||
background: linear-gradient(135deg, var(--primary-dark), var(--primary));
|
||
color: white;
|
||
padding: 10px 20px;
|
||
border-bottom: 2px solid var(--accent);
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 10px;
|
||
align-items: center;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.global-setting-item {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
background: rgba(255, 255, 255, 0.08);
|
||
padding: 5px 10px;
|
||
border-radius: 6px;
|
||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||
}
|
||
|
||
.global-setting-item label {
|
||
font-weight: 600;
|
||
color: var(--accent-light);
|
||
font-size: 11px;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.global-setting-item input {
|
||
background: rgba(255, 255, 255, 0.1);
|
||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||
color: white;
|
||
padding: 4px 8px;
|
||
border-radius: 4px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
width: 180px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
|
||
.global-setting-item input:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
}
|
||
|
||
.global-setting-item input.short {
|
||
width: 80px;
|
||
}
|
||
|
||
.global-setting-item input.medium {
|
||
width: 280px;
|
||
}
|
||
|
||
.auth-status {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
padding: 5px 12px;
|
||
border-radius: 6px;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
}
|
||
|
||
.auth-status.authenticated {
|
||
background: rgba(56, 161, 105, 0.2);
|
||
color: #9ae6b4;
|
||
border: 1px solid rgba(56, 161, 105, 0.4);
|
||
}
|
||
|
||
.auth-status.unauthenticated {
|
||
background: rgba(229, 62, 62, 0.2);
|
||
color: #feb2b2;
|
||
border: 1px solid rgba(229, 62, 62, 0.4);
|
||
}
|
||
|
||
.auth-status-dot {
|
||
width: 8px;
|
||
height: 8px;
|
||
border-radius: 50%;
|
||
background: currentColor;
|
||
animation: pulse 2s infinite;
|
||
}
|
||
|
||
@keyframes pulse {
|
||
|
||
0%,
|
||
100% {
|
||
opacity: 1;
|
||
}
|
||
|
||
50% {
|
||
opacity: 0.4;
|
||
}
|
||
}
|
||
|
||
.test-form {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 16px;
|
||
margin-bottom: 16px;
|
||
}
|
||
|
||
.test-form-section {
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
}
|
||
|
||
.test-form-section.full-width {
|
||
grid-column: 1 / -1;
|
||
}
|
||
|
||
.test-form-section-title {
|
||
font-size: 12px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 10px;
|
||
padding-bottom: 8px;
|
||
border-bottom: 1px solid var(--border-light);
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
}
|
||
|
||
[data-theme='dark'] .test-form-section-title {
|
||
color: var(--accent);
|
||
}
|
||
|
||
.test-field {
|
||
margin-bottom: 10px;
|
||
}
|
||
|
||
.test-field:last-child {
|
||
margin-bottom: 0;
|
||
}
|
||
|
||
.test-field label {
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
font-family: 'Fira Code', monospace;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
|
||
.test-field label .required {
|
||
color: var(--danger);
|
||
}
|
||
|
||
.test-field input,
|
||
.test-field textarea,
|
||
.test-field select {
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
|
||
.test-field textarea {
|
||
min-height: 100px;
|
||
resize: vertical;
|
||
line-height: 1.5;
|
||
}
|
||
|
||
.test-field input:focus,
|
||
.test-field textarea:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
}
|
||
|
||
.test-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
margin-bottom: 16px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.response-panel {
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
margin-top: 16px;
|
||
}
|
||
|
||
.response-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
margin-bottom: 12px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.response-status {
|
||
padding: 4px 12px;
|
||
border-radius: 4px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 12px;
|
||
font-weight: 700;
|
||
color: white;
|
||
}
|
||
|
||
.response-status.success {
|
||
background: var(--success);
|
||
}
|
||
|
||
.response-status.error {
|
||
background: var(--danger);
|
||
}
|
||
|
||
.response-status.redirect {
|
||
background: var(--warning);
|
||
}
|
||
|
||
.response-status.info {
|
||
background: var(--info);
|
||
}
|
||
|
||
.response-time,
|
||
.response-size {
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
font-family: 'Fira Code', monospace;
|
||
}
|
||
|
||
.response-tabs {
|
||
display: flex;
|
||
gap: 4px;
|
||
margin-bottom: 10px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.response-tab {
|
||
background: transparent;
|
||
border: 1px solid var(--border);
|
||
color: var(--text-muted);
|
||
padding: 5px 12px;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.response-tab.active {
|
||
background: var(--primary);
|
||
color: white;
|
||
border-color: var(--primary);
|
||
}
|
||
|
||
.response-body {
|
||
background: #1e1e1e;
|
||
color: #d4d4d4;
|
||
padding: 14px;
|
||
border-radius: 6px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
line-height: 1.6;
|
||
max-height: 400px;
|
||
overflow: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
white-space: pre-wrap;
|
||
word-break: break-word;
|
||
}
|
||
|
||
.json-key {
|
||
color: #9cdcfe;
|
||
}
|
||
|
||
.json-string {
|
||
color: #ce9178;
|
||
}
|
||
|
||
.json-number {
|
||
color: #b5cea8;
|
||
}
|
||
|
||
.json-boolean {
|
||
color: #569cd6;
|
||
}
|
||
|
||
.json-null {
|
||
color: #569cd6;
|
||
}
|
||
|
||
.debug-log {
|
||
background: #0d1117;
|
||
color: #c9d1d9;
|
||
border-radius: 6px;
|
||
padding: 12px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 10px;
|
||
line-height: 1.6;
|
||
max-height: 200px;
|
||
overflow: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
margin-top: 10px;
|
||
white-space: pre-wrap;
|
||
word-break: break-all;
|
||
}
|
||
|
||
.debug-log .log-request {
|
||
color: #79c0ff;
|
||
}
|
||
|
||
.debug-log .log-response {
|
||
color: #7ee787;
|
||
}
|
||
|
||
.debug-log .log-error {
|
||
color: #ff7b72;
|
||
}
|
||
|
||
.debug-log .log-info {
|
||
color: #d2a8ff;
|
||
}
|
||
|
||
.cors-info-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #f6e05e;
|
||
border-right: 4px solid var(--warning);
|
||
padding: 14px 18px;
|
||
border-radius: 8px;
|
||
margin-bottom: 16px;
|
||
font-size: 12px;
|
||
color: var(--text);
|
||
}
|
||
|
||
[data-theme='dark'] .cors-info-box {
|
||
background: rgba(221, 107, 32, 0.1);
|
||
border-color: rgba(221, 107, 32, 0.3);
|
||
}
|
||
|
||
.cors-info-box strong {
|
||
color: var(--warning);
|
||
}
|
||
|
||
.cors-info-box code {
|
||
background: rgba(0, 0, 0, 0.08);
|
||
padding: 2px 6px;
|
||
border-radius: 3px;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
display: inline-block;
|
||
}
|
||
|
||
.hidden-input {
|
||
display: none;
|
||
}
|
||
|
||
.empty-state {
|
||
text-align: center;
|
||
padding: 40px 20px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.empty-state-icon {
|
||
font-size: 60px;
|
||
opacity: 0.3;
|
||
margin-bottom: 14px;
|
||
}
|
||
|
||
.btn-reset {
|
||
background: linear-gradient(135deg, #e53e3e, #c53030);
|
||
color: white;
|
||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||
animation: resetPulse 2s infinite;
|
||
}
|
||
|
||
.btn-reset:hover {
|
||
background: linear-gradient(135deg, #f56565, #e53e3e);
|
||
transform: translateY(-1px);
|
||
box-shadow: 0 4px 12px rgba(229, 62, 62, 0.4);
|
||
}
|
||
|
||
@keyframes resetPulse {
|
||
|
||
0%,
|
||
100% {
|
||
box-shadow: 0 2px 4px rgba(229, 62, 62, 0.3);
|
||
}
|
||
|
||
50% {
|
||
box-shadow: 0 2px 8px rgba(229, 62, 62, 0.6);
|
||
}
|
||
}
|
||
|
||
/* ================= x-Form Builder ================= */
|
||
.fb-toolbar {
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 10px;
|
||
align-items: flex-end;
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 12px;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
.fb-toolbar .fb-tf {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 4px
|
||
}
|
||
|
||
.fb-toolbar label {
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted)
|
||
}
|
||
|
||
.fb-toolbar input,
|
||
.fb-toolbar select {
|
||
padding: 6px 9px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
min-width: 150px
|
||
}
|
||
|
||
.fb-layout {
|
||
display: grid;
|
||
grid-template-columns: 290px 1fr;
|
||
gap: 14px
|
||
}
|
||
|
||
.fb-col {
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 12px;
|
||
min-height: 420px
|
||
}
|
||
|
||
.fb-list {
|
||
max-height: 430px;
|
||
overflow: auto;
|
||
margin-top: 8px
|
||
}
|
||
|
||
.fb-item {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
background: var(--card-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: 6px;
|
||
padding: 6px 8px;
|
||
margin-bottom: 5px;
|
||
cursor: pointer
|
||
}
|
||
|
||
.fb-item:hover {
|
||
border-color: var(--accent)
|
||
}
|
||
|
||
.fb-item.active {
|
||
border-color: var(--accent);
|
||
box-shadow: 0 0 0 2px rgba(201, 169, 97, .2)
|
||
}
|
||
|
||
.fb-item.off {
|
||
opacity: .45
|
||
}
|
||
|
||
.fb-item .fb-nm {
|
||
flex: 1;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
direction: ltr;
|
||
text-align: left
|
||
}
|
||
|
||
.fb-item .fb-tp {
|
||
font-size: 9px;
|
||
background: rgba(201, 169, 97, .2);
|
||
color: var(--accent-dark);
|
||
padding: 2px 6px;
|
||
border-radius: 8px
|
||
}
|
||
|
||
.fb-mini {
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
cursor: pointer;
|
||
font-size: 11px;
|
||
padding: 0 2px
|
||
}
|
||
|
||
.fb-mini:hover {
|
||
color: var(--accent)
|
||
}
|
||
|
||
.fb-tabs {
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 4px;
|
||
margin-bottom: 10px
|
||
}
|
||
|
||
.fb-tab {
|
||
background: transparent;
|
||
border: 1px solid var(--border);
|
||
color: var(--text-muted);
|
||
padding: 5px 10px;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 11px;
|
||
font-weight: 600
|
||
}
|
||
|
||
.fb-tab.active {
|
||
background: var(--primary);
|
||
color: #fff;
|
||
border-color: var(--primary)
|
||
}
|
||
|
||
.fb-panel {
|
||
max-height: 430px;
|
||
overflow: auto;
|
||
padding-left: 4px
|
||
}
|
||
|
||
.fb-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 10px
|
||
}
|
||
|
||
.fb-field {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 4px
|
||
}
|
||
|
||
.fb-field.full {
|
||
grid-column: 1/-1
|
||
}
|
||
|
||
.fb-field>label {
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
font-family: 'Fira Code', monospace;
|
||
direction: ltr;
|
||
text-align: left
|
||
}
|
||
|
||
.fb-field input[type=text],
|
||
.fb-field input[type=number],
|
||
.fb-field select,
|
||
.fb-field textarea {
|
||
width: 100%;
|
||
padding: 6px 9px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
text-align: left
|
||
}
|
||
|
||
.fb-field textarea {
|
||
min-height: 110px;
|
||
resize: vertical;
|
||
line-height: 1.6
|
||
}
|
||
|
||
.fb-check {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
font-size: 12px;
|
||
cursor: pointer;
|
||
padding-top: 16px
|
||
}
|
||
|
||
.fb-hint {
|
||
font-size: 10px;
|
||
color: var(--text-light)
|
||
}
|
||
|
||
.fb-sec {
|
||
grid-column: 1/-1;
|
||
font-size: 12px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
border-bottom: 1px solid var(--border-light);
|
||
padding-bottom: 6px;
|
||
margin-top: 6px
|
||
}
|
||
|
||
[data-theme='dark'] .fb-sec {
|
||
color: var(--accent)
|
||
}
|
||
|
||
.fb-err-row {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr 30px;
|
||
gap: 6px;
|
||
margin-bottom: 6px
|
||
}
|
||
|
||
.fb-note {
|
||
grid-column: 1/-1;
|
||
background: rgba(49, 130, 206, .1);
|
||
border-right: 3px solid var(--info);
|
||
padding: 8px 10px;
|
||
border-radius: 4px;
|
||
font-size: 11px;
|
||
color: var(--text-muted)
|
||
}
|
||
|
||
.fb-card-btn {
|
||
position: absolute;
|
||
top: 6px;
|
||
left: 6px;
|
||
background: transparent;
|
||
border: none;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
opacity: .6;
|
||
z-index: 10
|
||
}
|
||
|
||
.fb-card-btn:hover {
|
||
opacity: 1
|
||
}
|
||
|
||
.model-card {
|
||
position: relative
|
||
}
|
||
|
||
@media (max-width:900px) {
|
||
.fb-layout {
|
||
grid-template-columns: 1fr
|
||
}
|
||
|
||
.fb-grid {
|
||
grid-template-columns: 1fr
|
||
}
|
||
}
|
||
|
||
@media (max-width: 768px) {
|
||
.sidebar {
|
||
position: absolute;
|
||
height: 100%;
|
||
z-index: 200;
|
||
}
|
||
|
||
.models-grid {
|
||
grid-template-columns: 1fr;
|
||
}
|
||
|
||
.stats-grid {
|
||
grid-template-columns: 1fr 1fr;
|
||
}
|
||
|
||
.test-form {
|
||
grid-template-columns: 1fr;
|
||
}
|
||
|
||
.global-settings-panel {
|
||
flex-direction: column;
|
||
align-items: stretch;
|
||
}
|
||
|
||
.global-setting-item input {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
</head>
|
||
|
||
<body>
|
||
<header class="app-header">
|
||
<div class="app-brand">
|
||
<div class="app-logo">⚡</div>
|
||
<div class="app-brand-text">
|
||
<div class="app-title">XFramework Backend SDK Manager</div>
|
||
<div class="app-subtitle">تولید سرویس های فراخوانی سرویس دهنده</div>
|
||
</div>
|
||
</div>
|
||
<div class="header-actions">
|
||
<button type="button" class="btn btn-ghost btn-sm" id="themeToggle" title="تغییر تم">
|
||
<span id="themeIcon">☀️</span>
|
||
</button>
|
||
<button type="button" class="btn btn-reset btn-sm" id="resetAppBtn"
|
||
title="پاکسازی کامل محتوای بارگذاری شده" style="display: none">
|
||
<span>🗑️</span><span>پاکسازی</span>
|
||
</button>
|
||
<button type="button" class="btn btn-accent btn-sm" id="loadFileBtn">
|
||
<span>📂</span><span>بارگذاری Swagger</span>
|
||
</button>
|
||
</div>
|
||
</header>
|
||
<div class="global-settings-panel" id="globalSettingsPanel">
|
||
<div class="global-setting-item">
|
||
<label>🌐 Base URL:</label>
|
||
<input type="text" id="gBaseUrl" value="https://localhost:5001" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>🔀 CORS Proxy:</label>
|
||
<input type="text" id="gCorsProxy" class="medium" placeholder="مثال: https://corsproxy.io/?" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>⚡ X-PoweredBy:</label>
|
||
<input type="text" id="gXPoweredBy" value="SaherElmITCenter" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>🗝️ X-Api-Key:</label>
|
||
<input type="text" id="gXApiKey" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>📌 Version:</label>
|
||
<input type="text" id="gVersion" class="short" value="1.0" />
|
||
</div>
|
||
<div class="global-setting-item" id="authStatusContainer">
|
||
<div class="auth-status unauthenticated" id="authStatus">
|
||
<span class="auth-status-dot"></span>
|
||
<span>غیرفعال</span>
|
||
</div>
|
||
</div>
|
||
<button type="button" class="btn btn-info btn-sm" id="openAuthBtn">
|
||
<span>🔐</span><span>احراز هویت</span>
|
||
</button>
|
||
</div>
|
||
<div class="app-main">
|
||
<aside class="sidebar" id="sidebar">
|
||
<div class="sidebar-header">
|
||
<div class="sidebar-title">🎛️ کنترلرها</div>
|
||
</div>
|
||
<div class="sidebar-body" id="controllersList">
|
||
<div class="empty-state">
|
||
<div class="empty-state-icon">📭</div>
|
||
<p>ابتدا فایل Swagger را بارگذاری کنید</p>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
<main class="board-area" id="boardArea">
|
||
<div id="uploadZone" class="upload-zone">
|
||
<div class="upload-zone-icon">📄</div>
|
||
<h2>فایل Swagger JSON را بارگذاری کنید</h2>
|
||
<p>فایل را اینجا بکشید و رها کنید یا روی این ناحیه کلیک کنید</p>
|
||
<button type="button" class="btn btn-accent">
|
||
<span>📁</span><span>انتخاب فایل</span>
|
||
</button>
|
||
</div>
|
||
<div id="loadedContent" style="display: none">
|
||
<div class="stats-grid" id="statsGrid"></div>
|
||
<div class="controller-tabs" id="controllerTabs"></div>
|
||
<div id="controllerContent"></div>
|
||
</div>
|
||
</main>
|
||
</div>
|
||
<footer class="app-footer">
|
||
<div>
|
||
<span class="footer-brand">طراح و توسعهدهنده:</span> هادی خزاعی اصل
|
||
<span style="margin: 0 10px">|</span>
|
||
<span class="footer-brand">شرکت:</span> فن آوران ساحر علم
|
||
</div>
|
||
<div><span class="footer-brand">نسخه:</span> 1.8.0</div>
|
||
</footer>
|
||
<!-- Model Modal -->
|
||
<div class="modal-overlay" id="modelModal">
|
||
<div class="modal">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>📦</span><span id="modelModalTitle">جزئیات مدل</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-modal>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="modelModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-accent" id="openFormBuilderBtn">
|
||
<span>🧩</span><span>تولید فرم x-form</span>
|
||
</button>
|
||
<button type="button" class="btn btn-success" id="downloadDtoBtn">
|
||
<span>💾</span><span>دانلود DTO</span>
|
||
</button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);"
|
||
id="copyCodeBtn">
|
||
<span>📋</span><span>کپی</span>
|
||
</button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);"
|
||
data-close-modal>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- Provider Modal -->
|
||
<div class="modal-overlay" id="providerModal">
|
||
<div class="modal" style="max-width: 1200px">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>🔌</span><span id="providerModalTitle">Service</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-provider>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="providerModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-success" id="downloadProviderBtn">
|
||
<span>💾</span><span>دانلود</span>
|
||
</button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);"
|
||
id="copyProviderCodeBtn">
|
||
<span>📋</span><span>کپی</span>
|
||
</button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);"
|
||
data-close-provider>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- x-Form Builder Modal -->
|
||
<div class="modal-overlay" id="formBuilderModal">
|
||
<div class="modal" style="max-width:1400px">
|
||
<div class="modal-header">
|
||
<div class="modal-title"><span>🧩</span><span id="fbTitle">تولید پیکربندی فرم (x-form)</span></div>
|
||
<button type="button" class="modal-close" data-close-fb>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="fbBody"></div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-success" id="fbDownloadBtn"><span>💾</span><span>دانلود فایل
|
||
فرم</span></button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background:var(--column-bg);color:var(--text);border:1px solid var(--border)"
|
||
id="fbCopyBtn"><span>📋</span><span>کپی کد</span></button>
|
||
<button type="button" class="btn btn-info" id="fbExportBtn"><span>📤</span><span>خروجی
|
||
JSON</span></button>
|
||
<button type="button" class="btn btn-info" id="fbImportBtn"><span>📥</span><span>ورود
|
||
JSON</span></button>
|
||
<button type="button" class="btn btn-danger"
|
||
id="fbResetBtn"><span>♻️</span><span>بازنشانی</span></button>
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background:var(--column-bg);color:var(--text);border:1px solid var(--border)"
|
||
data-close-fb>بستن</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<input type="file" id="fbImportInput" class="hidden-input" accept=".json,application/json" />
|
||
<!-- Auth Modal -->
|
||
<div class="modal-overlay" id="authModal">
|
||
<div class="modal" style="max-width: 700px">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>🔐</span><span>احراز هویت - /Account/Authenticate</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-auth>✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div
|
||
style="background: var(--column-bg); border: 1px solid var(--border-light); border-radius: var(--radius-sm); padding: 16px; margin-bottom: 16px">
|
||
<div
|
||
style="font-size: 13px; font-weight: 700; color: var(--primary); margin-bottom: 12px; display: flex; align-items: center; gap: 8px">
|
||
<span>🔑</span><span>ورود از طریق /Account/Authenticate</span>
|
||
</div>
|
||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px">
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">userSelectBy
|
||
(Username/Email/Mobile)</label>
|
||
<input type="text" id="loginUserSelectBy" placeholder="username or email"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">password</label>
|
||
<input type="password" id="loginPassword" placeholder="password"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
</div>
|
||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px">
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">language</label>
|
||
<input type="text" id="loginLanguage" value="fa-IR"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
<div style="display: flex; align-items: flex-end">
|
||
<button type="button" class="btn btn-success" id="doLoginBtn" style="width: 100%">
|
||
<span>🚀</span><span>ورود به سیستم</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="background: var(--column-bg); border: 1px solid var(--border-light); border-radius: var(--radius-sm); padding: 16px; margin-bottom: 16px">
|
||
<div
|
||
style="font-size: 13px; font-weight: 700; color: var(--primary); margin-bottom: 12px; display: flex; align-items: center; gap: 8px">
|
||
<span>📝</span><span>ثبت دستی توکنها</span>
|
||
</div>
|
||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px">
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">accessToken</label>
|
||
<input type="text" id="manualAccessToken"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">refreshToken</label>
|
||
<input type="text" id="manualRefreshToken"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
</div>
|
||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px">
|
||
<div>
|
||
<label
|
||
style="display: block; font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px">expiresAt
|
||
(Unix Timestamp)</label>
|
||
<input type="number" id="manualExpiresAt"
|
||
style="width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 11px; background: var(--card-bg); color: var(--text); direction: ltr; text-align: left" />
|
||
</div>
|
||
<div style="display: flex; align-items: flex-end">
|
||
<button type="button" class="btn btn-info" id="saveManualTokenBtn" style="width: 100%">
|
||
<span>💾</span><span>ذخیره دستی</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="background: var(--column-bg); border: 1px solid var(--border-light); border-radius: var(--radius-sm); padding: 16px; margin-bottom: 16px">
|
||
<div
|
||
style="font-size: 13px; font-weight: 700; color: var(--primary); margin-bottom: 12px; display: flex; align-items: center; gap: 8px">
|
||
<span>📊</span><span>وضعیت فعلی</span>
|
||
</div>
|
||
<div id="currentTokenInfo"
|
||
style="font-family: 'Fira Code', monospace; font-size: 11px; direction: ltr; text-align: left; color: var(--text-muted)">
|
||
</div>
|
||
<button type="button" class="btn btn-danger btn-sm" id="clearTokenBtn" style="margin-top: 10px">
|
||
<span>🗑️</span><span>پاک کردن توکنها</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-ghost"
|
||
style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border)"
|
||
data-close-auth>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<input type="file" id="fileInput" class="hidden-input" accept=".json,application/json" />
|
||
<div class="toast-container" id="toastContainer"></div>
|
||
<script>
|
||
/* =========================================================================
|
||
Global State
|
||
========================================================================= */
|
||
const AppState = {
|
||
swagger: null,
|
||
controllers: {},
|
||
allSchemas: {},
|
||
activeController: null,
|
||
selectedModel: null,
|
||
generatedCode: '',
|
||
generatedProviderCode: '',
|
||
generatedProviderFilename: '',
|
||
searchTerms: { controllers: '', models: '', endpoints: '' },
|
||
};
|
||
const GlobalSettings = {
|
||
baseUrl: 'https://localhost:5001',
|
||
corsProxy: '',
|
||
xPoweredBy: 'SaherElmITCenter',
|
||
xApiKey: '',
|
||
version: '1.0',
|
||
accessToken: '',
|
||
refreshToken: '',
|
||
expiresAt: 0,
|
||
load() {
|
||
try {
|
||
const saved = localStorage.getItem('xfw-sdk-settings-v2');
|
||
if (saved) Object.assign(this, JSON.parse(saved));
|
||
} catch (e) { }
|
||
},
|
||
save() {
|
||
try {
|
||
localStorage.setItem('xfw-sdk-settings-v2', JSON.stringify({
|
||
baseUrl: this.baseUrl,
|
||
corsProxy: this.corsProxy,
|
||
xPoweredBy: this.xPoweredBy,
|
||
xApiKey: this.xApiKey,
|
||
version: this.version,
|
||
accessToken: this.accessToken,
|
||
refreshToken: this.refreshToken,
|
||
expiresAt: this.expiresAt,
|
||
}));
|
||
} catch (e) { }
|
||
},
|
||
isAuthenticated() { return !!this.accessToken; },
|
||
isTokenExpired() {
|
||
if (!this.expiresAt) return false;
|
||
return Math.floor(Date.now() / 1000) >= this.expiresAt;
|
||
},
|
||
buildHeaders(extraHeaders = {}) {
|
||
const headers = {
|
||
Accept: 'application/json',
|
||
'X-PoweredBy': this.xPoweredBy || 'SaherElmITCenter',
|
||
};
|
||
if (this.xApiKey) headers['X-Api-Key'] = this.xApiKey;
|
||
if (this.isAuthenticated()) {
|
||
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
||
headers['refresh_token'] = this.refreshToken;
|
||
headers['expires_at'] = String(this.expiresAt);
|
||
}
|
||
return { ...headers, ...extraHeaders };
|
||
},
|
||
buildUrl(url) {
|
||
if (this.corsProxy && this.corsProxy.trim()) {
|
||
let proxy = this.corsProxy.trim();
|
||
if (!proxy.endsWith('/') && !proxy.endsWith('?') && !proxy.endsWith('=')) proxy += '/';
|
||
return proxy + url;
|
||
}
|
||
return url;
|
||
},
|
||
};
|
||
/* =========================================================================
|
||
Utility Functions
|
||
========================================================================= */
|
||
function showToast(message, type = 'info', duration = 3000) {
|
||
const container = document.getElementById('toastContainer');
|
||
const toast = document.createElement('div');
|
||
toast.className = `toast ${type}`;
|
||
const icons = { success: '✅', error: '❌', warning: '⚠️', info: 'ℹ️' };
|
||
toast.innerHTML = `<span>${icons[type] || 'ℹ️'}</span><span>${message}</span>`;
|
||
container.appendChild(toast);
|
||
setTimeout(() => {
|
||
toast.style.opacity = '0';
|
||
toast.style.transform = 'translateX(-30px)';
|
||
setTimeout(() => toast.remove(), 300);
|
||
}, duration);
|
||
}
|
||
function escapeHtml(text) {
|
||
if (text === undefined || text === null) return '';
|
||
const div = document.createElement('div');
|
||
div.textContent = String(text);
|
||
return div.innerHTML;
|
||
}
|
||
function formatBytes(bytes) {
|
||
if (bytes === 0) return '0 B';
|
||
const k = 1024;
|
||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||
}
|
||
function syntaxHighlightJson(json) {
|
||
if (!json) return '';
|
||
json = escapeHtml(json);
|
||
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
|
||
let cls = 'json-number';
|
||
if (/^"/.test(match)) cls = /:$/.test(match) ? 'json-key' : '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 toKebabCase(str) {
|
||
return str.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2').toLowerCase();
|
||
}
|
||
function toCamelCase(str) {
|
||
if (!str) return str;
|
||
return str.charAt(0).toLowerCase() + str.slice(1);
|
||
}
|
||
function normalizeSwaggerKeys(obj) {
|
||
if (obj === null || typeof obj !== 'object') return obj;
|
||
if (Array.isArray(obj)) return obj.map(normalizeSwaggerKeys);
|
||
const normalized = {};
|
||
for (const key in obj) normalized[key.trim()] = normalizeSwaggerKeys(obj[key]);
|
||
return normalized;
|
||
}
|
||
/* =========================================================================
|
||
Theme
|
||
========================================================================= */
|
||
const themeToggle = document.getElementById('themeToggle');
|
||
const themeIcon = document.getElementById('themeIcon');
|
||
const html = document.documentElement;
|
||
const savedTheme = localStorage.getItem('swagger-sdk-theme') || 'dark';
|
||
html.setAttribute('data-theme', savedTheme);
|
||
themeIcon.textContent = savedTheme === 'dark' ? '☀️' : '🌙';
|
||
themeToggle.addEventListener('click', () => {
|
||
const currentTheme = html.getAttribute('data-theme');
|
||
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||
html.setAttribute('data-theme', newTheme);
|
||
localStorage.setItem('swagger-sdk-theme', newTheme);
|
||
themeIcon.textContent = newTheme === 'dark' ? '☀️' : '🌙';
|
||
});
|
||
/* =========================================================================
|
||
Global Settings Bindings
|
||
========================================================================= */
|
||
function initGlobalSettings() {
|
||
GlobalSettings.load();
|
||
const bindings = [
|
||
{ id: 'gBaseUrl', key: 'baseUrl' },
|
||
{ id: 'gCorsProxy', key: 'corsProxy' },
|
||
{ id: 'gXPoweredBy', key: 'xPoweredBy' },
|
||
{ id: 'gXApiKey', key: 'xApiKey' },
|
||
{ id: 'gVersion', key: 'version' },
|
||
];
|
||
bindings.forEach(({ id, key }) => {
|
||
const el = document.getElementById(id);
|
||
el.value = GlobalSettings[key] || '';
|
||
el.addEventListener('input', () => {
|
||
GlobalSettings[key] = el.value;
|
||
GlobalSettings.save();
|
||
});
|
||
});
|
||
updateAuthStatusUI();
|
||
}
|
||
function updateAuthStatusUI() {
|
||
const statusEl = document.getElementById('authStatus');
|
||
if (!statusEl) return;
|
||
if (GlobalSettings.isAuthenticated()) {
|
||
if (GlobalSettings.isTokenExpired()) {
|
||
statusEl.className = 'auth-status unauthenticated';
|
||
statusEl.innerHTML = '<span class="auth-status-dot"></span><span>منقضی شده</span>';
|
||
} else {
|
||
statusEl.className = 'auth-status authenticated';
|
||
statusEl.innerHTML = '<span class="auth-status-dot"></span><span>احراز شده ✓</span>';
|
||
}
|
||
} else {
|
||
statusEl.className = 'auth-status unauthenticated';
|
||
statusEl.innerHTML = '<span class="auth-status-dot"></span><span>غیرفعال</span>';
|
||
}
|
||
updateCurrentTokenInfo();
|
||
}
|
||
function updateCurrentTokenInfo() {
|
||
const infoEl = document.getElementById('currentTokenInfo');
|
||
if (!infoEl) return;
|
||
if (!GlobalSettings.isAuthenticated()) {
|
||
infoEl.innerHTML = '<span style="color: var(--danger);">❌ هیچ توکنی ثبت نشده است.</span>';
|
||
return;
|
||
}
|
||
const expiresAt = GlobalSettings.expiresAt;
|
||
const expiresDate = expiresAt ? new Date(expiresAt * 1000).toLocaleString('fa-IR') : 'N/A';
|
||
const isExpired = GlobalSettings.isTokenExpired();
|
||
infoEl.innerHTML = `
|
||
<div style="margin-bottom: 6px;"><span class="json-key">accessToken:</span> <span class="json-string">"${escapeHtml(GlobalSettings.accessToken.substring(0, 30))}..."</span></div>
|
||
<div style="margin-bottom: 6px;"><span class="json-key">refreshToken:</span> <span class="json-string">"${escapeHtml(GlobalSettings.refreshToken.substring(0, 30))}..."</span></div>
|
||
<div style="margin-bottom: 6px;"><span class="json-key">expiresAt:</span> <span class="json-number">${expiresAt}</span> <span class="json-comment">(${expiresDate})</span></div>
|
||
<div style="margin-top: 10px; padding: 8px; background: ${isExpired ? 'rgba(229,62,62,0.1)' : 'rgba(56,161,105,0.1)'}; border-radius: 4px; color: ${isExpired ? 'var(--danger)' : 'var(--success)'}; font-weight: 700;">
|
||
${isExpired ? '⚠️ توکن منقضی شده است' : '✅ توکن معتبر است'}
|
||
</div>`;
|
||
}
|
||
/* =========================================================================
|
||
File Upload
|
||
========================================================================= */
|
||
const fileInput = document.getElementById('fileInput');
|
||
const uploadZone = document.getElementById('uploadZone');
|
||
const loadFileBtn = document.getElementById('loadFileBtn');
|
||
const resetAppBtn = document.getElementById('resetAppBtn');
|
||
loadFileBtn.addEventListener('click', () => fileInput.click());
|
||
uploadZone.addEventListener('click', () => fileInput.click());
|
||
uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.classList.add('dragover'); });
|
||
uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('dragover'));
|
||
uploadZone.addEventListener('drop', (e) => {
|
||
e.preventDefault();
|
||
uploadZone.classList.remove('dragover');
|
||
const file = e.dataTransfer.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
fileInput.addEventListener('change', (e) => {
|
||
const file = e.target.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
function handleFile(file) {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
try {
|
||
const json = JSON.parse(e.target.result);
|
||
processSwagger(normalizeSwaggerKeys(json));
|
||
showToast('فایل Swagger با موفقیت بارگذاری شد', 'success');
|
||
} catch (err) {
|
||
showToast('خطا: ' + err.message, 'error');
|
||
}
|
||
};
|
||
reader.readAsText(file);
|
||
}
|
||
/* =========================================================================
|
||
Reset Application
|
||
========================================================================= */
|
||
resetAppBtn.addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
if (!confirm('آیا از پاکسازی کامل محتوای بارگذاری شده مطمئن هستید؟\n✅ تمام کنترلرها، مدلها و اندپوینتها پاک میشوند\n✅ تنظیمات عمومی و توکنهای احراز هویت حفظ میشوند\n✅ برنامه به حالت اولیه بازمیگردد')) return;
|
||
resetApplication();
|
||
});
|
||
function resetApplication() {
|
||
document.querySelectorAll('.modal-overlay[id^="testModal_"]').forEach((modal) => modal.remove());
|
||
document.getElementById('modelModal').classList.remove('active');
|
||
document.getElementById('providerModal').classList.remove('active');
|
||
document.getElementById('authModal').classList.remove('active');
|
||
document.getElementById('formBuilderModal').classList.remove('active');
|
||
AppState.swagger = null;
|
||
AppState.controllers = {};
|
||
AppState.allSchemas = {};
|
||
AppState.activeController = null;
|
||
AppState.selectedModel = null;
|
||
AppState.generatedCode = '';
|
||
AppState.generatedProviderCode = '';
|
||
AppState.generatedProviderFilename = '';
|
||
AppState.searchTerms = { controllers: '', models: '', endpoints: '' };
|
||
document.getElementById('uploadZone').style.display = '';
|
||
document.getElementById('loadedContent').style.display = 'none';
|
||
document.getElementById('statsGrid').innerHTML = '';
|
||
document.getElementById('controllerTabs').innerHTML = '';
|
||
document.getElementById('controllerContent').innerHTML = '';
|
||
document.getElementById('controllersList').innerHTML = `
|
||
<div class="empty-state">
|
||
<div class="empty-state-icon">📭</div>
|
||
<p>ابتدا فایل Swagger را بارگذاری کنید</p>
|
||
</div>
|
||
`;
|
||
resetAppBtn.style.display = 'none';
|
||
fileInput.value = '';
|
||
window._lastResponseData = null;
|
||
showToast('🗑️ محتوای بارگذاری شده با موفقیت پاکسازی شد', 'success', 4000);
|
||
}
|
||
/* =========================================================================
|
||
Swagger Parser
|
||
========================================================================= */
|
||
function processSwagger(swagger) {
|
||
AppState.swagger = swagger;
|
||
AppState.allSchemas = swagger.components?.schemas || {};
|
||
AppState.controllers = extractControllers(swagger);
|
||
renderStats();
|
||
renderControllersList();
|
||
renderControllerTabs();
|
||
uploadZone.style.display = 'none';
|
||
document.getElementById('loadedContent').style.display = 'block';
|
||
resetAppBtn.style.display = '';
|
||
const firstCtrl = Object.keys(AppState.controllers)[0];
|
||
if (firstCtrl) selectController(firstCtrl);
|
||
}
|
||
function extractControllers(swagger) {
|
||
const controllers = {};
|
||
const paths = swagger.paths || {};
|
||
Object.keys(paths).forEach((path) => {
|
||
const pathItem = paths[path];
|
||
Object.keys(pathItem).forEach((method) => {
|
||
if (!['get', 'post', 'put', 'delete', 'patch'].includes(method)) return;
|
||
const operation = pathItem[method];
|
||
const tags = operation.tags || ['Default'];
|
||
tags.forEach((tag) => {
|
||
if (!controllers[tag]) controllers[tag] = { name: tag, endpoints: [], models: new Set() };
|
||
controllers[tag].endpoints.push({ path, method, operation, summary: operation.summary || '' });
|
||
const reqBody = operation.requestBody;
|
||
if (reqBody?.content) Object.values(reqBody.content).forEach((ct) => {
|
||
if (ct.schema) extractModelsFromSchema(ct.schema, controllers[tag].models);
|
||
});
|
||
Object.values(operation.responses || {}).forEach((resp) => {
|
||
if (resp.content) Object.values(resp.content).forEach((ct) => {
|
||
if (ct.schema) extractModelsFromSchema(ct.schema, controllers[tag].models);
|
||
});
|
||
});
|
||
});
|
||
});
|
||
});
|
||
return controllers;
|
||
}
|
||
function extractModelsFromSchema(schema, modelSet) {
|
||
if (!schema) return;
|
||
if (schema.$ref) {
|
||
const refName = schema.$ref.replace('#/components/schemas/', '');
|
||
if (!modelSet.has(refName) && AppState.allSchemas[refName]) {
|
||
modelSet.add(refName);
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema.properties) Object.values(refSchema.properties).forEach((p) => extractModelsFromSchema(p, modelSet));
|
||
if (refSchema.items) extractModelsFromSchema(refSchema.items, modelSet);
|
||
}
|
||
} else if (schema.items) {
|
||
extractModelsFromSchema(schema.items, modelSet);
|
||
} else if (schema.properties) {
|
||
Object.values(schema.properties).forEach((p) => extractModelsFromSchema(p, modelSet));
|
||
}
|
||
}
|
||
/* =========================================================================
|
||
Render Functions
|
||
========================================================================= */
|
||
function renderStats() {
|
||
const grid = document.getElementById('statsGrid');
|
||
const totalControllers = Object.keys(AppState.controllers).length;
|
||
const totalEndpoints = Object.values(AppState.controllers).reduce((sum, c) => sum + c.endpoints.length, 0);
|
||
const totalModels = Object.keys(AppState.allSchemas).length;
|
||
const usedModels = new Set();
|
||
Object.values(AppState.controllers).forEach((c) => c.models.forEach((m) => usedModels.add(m)));
|
||
grid.innerHTML = `
|
||
<div class="stat-card"><div class="stat-value">${totalControllers}</div><div class="stat-label">کنترلرها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${totalEndpoints}</div><div class="stat-label">اندپوینتها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${totalModels}</div><div class="stat-label">کل مدلها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${usedModels.size}</div><div class="stat-label">مدلهای استفاده شده</div></div>`;
|
||
}
|
||
function renderControllersList() {
|
||
const list = document.getElementById('controllersList');
|
||
list.innerHTML = '';
|
||
const searchWrapper = document.createElement('div');
|
||
searchWrapper.className = 'search-input-wrapper';
|
||
searchWrapper.innerHTML = `<input type="text" class="search-input" id="controllerSearch" placeholder="جستجوی کنترلر..."><span class="search-icon">🔍</span><button type="button" class="search-clear" id="controllerSearchClear">✕</button>`;
|
||
list.appendChild(searchWrapper);
|
||
const ctrlIcons = {
|
||
Account: '👤', FileProvider: '📁', StringProvider: '🔤', TagProvider: '🏷️',
|
||
ContentProvider: '📝', CategoryProvider: '📂', SubCategoryProvider: '📑',
|
||
TermsAndConditionsProvider: '📜', TestProvider: '🧪', TestIdentity: '🔐',
|
||
TestFeatures: '⚙️', Startup: '🚀', Default: '📦',
|
||
};
|
||
const container = document.createElement('div');
|
||
container.id = 'controllersContainer';
|
||
list.appendChild(container);
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
document.getElementById('controllerSearch').addEventListener('input', (e) => {
|
||
AppState.searchTerms.controllers = e.target.value;
|
||
document.getElementById('controllerSearchClear').classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
});
|
||
document.getElementById('controllerSearchClear').addEventListener('click', () => {
|
||
document.getElementById('controllerSearch').value = '';
|
||
AppState.searchTerms.controllers = '';
|
||
document.getElementById('controllerSearchClear').classList.remove('visible');
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
});
|
||
}
|
||
function renderFilteredControllers(container, ctrlIcons) {
|
||
container.innerHTML = '';
|
||
const searchTerm = AppState.searchTerms.controllers.toLowerCase();
|
||
Object.keys(AppState.controllers).sort().forEach((name) => {
|
||
if (searchTerm && !name.toLowerCase().includes(searchTerm)) return;
|
||
const ctrl = AppState.controllers[name];
|
||
const btn = document.createElement('button');
|
||
btn.type = 'button';
|
||
btn.className = 'controller-item' + (AppState.activeController === name ? ' active' : '');
|
||
btn.innerHTML = `<span class="ctrl-icon">${ctrlIcons[name] || '📦'}</span><span class="ctrl-name">${name}</span><span class="ctrl-badge">${ctrl.endpoints.length}</span>`;
|
||
btn.addEventListener('click', () => selectController(name));
|
||
container.appendChild(btn);
|
||
});
|
||
}
|
||
function renderControllerTabs() {
|
||
const tabs = document.getElementById('controllerTabs');
|
||
tabs.innerHTML = '';
|
||
const tabIcons = { overview: '📊', models: '📦', endpoints: '🔌', provider: '⚙️' };
|
||
const tabNames = { overview: 'نمای کلی', models: 'مدلها', endpoints: 'اندپوینتها', provider: 'Service' };
|
||
['overview', 'models', 'endpoints', 'provider'].forEach((tab) => {
|
||
const btn = document.createElement('button');
|
||
btn.type = 'button';
|
||
btn.className = 'controller-tab' + (tab === 'overview' ? ' active' : '');
|
||
btn.dataset.tab = tab;
|
||
btn.innerHTML = `<span>${tabIcons[tab]}</span><span>${tabNames[tab]}</span>`;
|
||
btn.addEventListener('click', () => switchTab(tab));
|
||
tabs.appendChild(btn);
|
||
});
|
||
}
|
||
function switchTab(tabName) {
|
||
document.querySelectorAll('.controller-tab').forEach((t) => t.classList.toggle('active', t.dataset.tab === tabName));
|
||
renderControllerContent(tabName);
|
||
}
|
||
function selectController(name) {
|
||
AppState.activeController = name;
|
||
document.querySelectorAll('.controller-item').forEach((item) => item.classList.toggle('active', item.dataset.controller === name));
|
||
const activeTab = document.querySelector('.controller-tab.active')?.dataset.tab || 'overview';
|
||
renderControllerContent(activeTab);
|
||
}
|
||
function renderControllerContent(tabName) {
|
||
const content = document.getElementById('controllerContent');
|
||
const ctrl = AppState.controllers[AppState.activeController];
|
||
if (!ctrl) return;
|
||
if (tabName === 'overview') renderOverview(ctrl, content);
|
||
else if (tabName === 'models') renderModels(ctrl, content);
|
||
else if (tabName === 'endpoints') renderEndpoints(ctrl, content);
|
||
else if (tabName === 'provider') renderProviderService(ctrl, content);
|
||
}
|
||
function renderOverview(ctrl, container) {
|
||
const methodCounts = { get: 0, post: 0, put: 0, delete: 0 };
|
||
ctrl.endpoints.forEach((e) => { if (methodCounts[e.method] !== undefined) methodCounts[e.method]++; });
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">📊</div><div class="section-title"><h3>کنترلر ${ctrl.name}</h3><div class="subtitle">نمای کلی</div></div></div>
|
||
<div class="stats-grid">
|
||
<div class="stat-card"><div class="stat-value">${ctrl.endpoints.length}</div><div class="stat-label">اندپوینتها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${ctrl.models.size}</div><div class="stat-label">مدلها</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#63b3ed">${methodCounts.get}</div><div class="stat-label">GET</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#68d391">${methodCounts.post}</div><div class="stat-label">POST</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#f6ad55">${methodCounts.put}</div><div class="stat-label">PUT</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#fc8181">${methodCounts.delete}</div><div class="stat-label">DELETE</div></div>
|
||
</div>
|
||
</div>
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">🔌</div><div class="section-title"><h3>اندپوینتهای اخیر</h3></div></div>
|
||
${renderEndpointsTable(ctrl.endpoints.slice(0, 5), true)}
|
||
</div>`;
|
||
attachTestButtonHandlers();
|
||
}
|
||
function renderModels(ctrl, container) {
|
||
const models = Array.from(ctrl.models).sort();
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">📦</div><div class="section-title"><h3>مدلهای کنترلر ${ctrl.name}</h3></div></div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="modelSearch" placeholder="جستجوی مدل...">
|
||
<span class="search-icon">🔍</span>
|
||
<button type="button" class="search-clear" id="modelSearchClear">✕</button>
|
||
</div>
|
||
<div class="models-grid" id="modelsGrid"></div>
|
||
</div>`;
|
||
renderFilteredModels(models);
|
||
document.getElementById('modelSearch').addEventListener('input', (e) => {
|
||
AppState.searchTerms.models = e.target.value;
|
||
document.getElementById('modelSearchClear').classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredModels(models);
|
||
});
|
||
document.getElementById('modelSearchClear').addEventListener('click', () => {
|
||
document.getElementById('modelSearch').value = '';
|
||
AppState.searchTerms.models = '';
|
||
document.getElementById('modelSearchClear').classList.remove('visible');
|
||
renderFilteredModels(models);
|
||
});
|
||
}
|
||
function renderFilteredModels(allModels) {
|
||
const grid = document.getElementById('modelsGrid');
|
||
if (!grid) return;
|
||
const searchTerm = AppState.searchTerms.models.toLowerCase();
|
||
const filtered = allModels.filter((n) => !searchTerm || n.toLowerCase().includes(searchTerm));
|
||
if (filtered.length === 0) {
|
||
grid.innerHTML = '<div class="empty-state" style="grid-column: 1/-1;"><p>مدلی یافت نشد</p></div>';
|
||
return;
|
||
}
|
||
grid.innerHTML = filtered.map((name) => {
|
||
const schema = AppState.allSchemas[name];
|
||
const propsCount = schema?.properties ? Object.keys(schema.properties).length : 0;
|
||
const type = schema?.enum ? 'Enum' : 'DTO';
|
||
const icon = type === 'Enum' ? '🔢' : '📦';
|
||
return `<div class="model-card" data-model="${name}"><button type="button" class="fb-card-btn" data-fb-model="${name}" title="تولید فرم x-form">🧩</button><div class="model-card-header"><div class="model-card-icon">${icon}</div><div class="model-card-name" title="${name}">${name}</div></div><div class="model-card-meta"><span>🔹 ${type}</span><span>📐 ${propsCount} فیلد</span></div></div>`;
|
||
}).join('');
|
||
grid.querySelectorAll('.model-card').forEach((card) => {
|
||
card.addEventListener('click', () => openModelModal(card.dataset.model));
|
||
});
|
||
grid.querySelectorAll('[data-fb-model]').forEach((b) => {
|
||
b.addEventListener('click', (e) => { e.stopPropagation(); XFormBuilder.open(b.dataset.fbModel); });
|
||
});
|
||
}
|
||
function renderEndpoints(ctrl, container) {
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">🔌</div><div class="section-title"><h3>اندپوینتهای کنترلر ${ctrl.name}</h3><div class="subtitle">برای تست هر اندپوینت روی دکمه 🧪 کلیک کنید</div></div></div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="endpointSearch" placeholder="جستجوی اندپوینت...">
|
||
<span class="search-icon">🔍</span>
|
||
<button type="button" class="search-clear" id="endpointSearchClear">✕</button>
|
||
</div>
|
||
<div id="endpointsTable"></div>
|
||
</div>`;
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
document.getElementById('endpointSearch').addEventListener('input', (e) => {
|
||
AppState.searchTerms.endpoints = e.target.value;
|
||
document.getElementById('endpointSearchClear').classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
document.getElementById('endpointSearchClear').addEventListener('click', () => {
|
||
document.getElementById('endpointSearch').value = '';
|
||
AppState.searchTerms.endpoints = '';
|
||
document.getElementById('endpointSearchClear').classList.remove('visible');
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
}
|
||
function renderFilteredEndpoints(allEndpoints) {
|
||
const tableContainer = document.getElementById('endpointsTable');
|
||
if (!tableContainer) return;
|
||
const searchTerm = AppState.searchTerms.endpoints.toLowerCase();
|
||
const filtered = allEndpoints.filter((e) => !searchTerm || e.path.toLowerCase().includes(searchTerm) || (e.summary || '').toLowerCase().includes(searchTerm));
|
||
if (filtered.length === 0) {
|
||
tableContainer.innerHTML = '<div class="empty-state"><p>اندپوینتی یافت نشد</p></div>';
|
||
return;
|
||
}
|
||
tableContainer.innerHTML = renderEndpointsTable(filtered, true);
|
||
attachTestButtonHandlers();
|
||
}
|
||
function renderEndpointsTable(endpoints, showTestBtn = false) {
|
||
const rows = endpoints.map((e, idx) => {
|
||
const endpointKey = `${e.method}:${e.path}`;
|
||
const testBtn = showTestBtn ? `<button type="button" class="test-btn" data-endpoint-key="${encodeURIComponent(endpointKey)}">🧪 تست</button>` : '';
|
||
return `<tr><td><span class="method-badge method-${e.method}">${e.method.toUpperCase()}</span></td><td class="endpoint-path">${e.path}</td><td>${e.summary || '-'}</td><td style="text-align: center;">${testBtn}</td></tr>`;
|
||
}).join('');
|
||
return `<table class="endpoints-table"><thead><tr><th>متد</th><th>مسیر</th><th>توضیحات</th><th style="text-align: center; width: 80px;">عملیات</th></tr></thead><tbody>${rows}</tbody></table>`;
|
||
}
|
||
function attachTestButtonHandlers() {
|
||
document.querySelectorAll('.test-btn').forEach((btn) => {
|
||
btn.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
const endpointKey = decodeURIComponent(btn.dataset.endpointKey);
|
||
const [method, path] = endpointKey.split(/:(.+)/);
|
||
const ctrl = AppState.controllers[AppState.activeController];
|
||
if (!ctrl) return;
|
||
const endpoint = ctrl.endpoints.find((ep) => ep.method === method && ep.path === path);
|
||
if (endpoint) openEndpointTestModal(endpoint);
|
||
});
|
||
});
|
||
}
|
||
/* =========================================================================
|
||
ENDPOINT TEST MODAL
|
||
========================================================================= */
|
||
function openEndpointTestModal(endpoint) {
|
||
const modalId = 'testModal_' + btoa(endpoint.method + ':' + endpoint.path).replace(/[^a-zA-Z0-9]/g, '');
|
||
let existingModal = document.getElementById(modalId);
|
||
if (existingModal) {
|
||
existingModal.style.zIndex = 1000 + document.querySelectorAll('.modal-overlay.active').length;
|
||
existingModal.classList.add('active');
|
||
return;
|
||
}
|
||
const modalOverlay = document.createElement('div');
|
||
modalOverlay.className = 'modal-overlay active';
|
||
modalOverlay.id = modalId;
|
||
modalOverlay.style.zIndex = 1000 + document.querySelectorAll('.modal-overlay.active').length;
|
||
const parameters = endpoint.operation.parameters || [];
|
||
const pathParams = parameters.filter((p) => p.in === 'path' && p.name !== 'version');
|
||
const queryParams = parameters.filter((p) => p.in === 'query');
|
||
let bodySchema = null, isFormData = false;
|
||
const requestBody = endpoint.operation.requestBody;
|
||
if (requestBody?.content) {
|
||
if (requestBody.content['multipart/form-data']) {
|
||
isFormData = true;
|
||
bodySchema = requestBody.content['multipart/form-data'].schema;
|
||
} else if (requestBody.content['application/json']) {
|
||
bodySchema = requestBody.content['application/json'].schema;
|
||
} else if (requestBody.content['application/json-patch+json']) {
|
||
bodySchema = requestBody.content['application/json-patch+json'].schema;
|
||
}
|
||
}
|
||
const displayPath = endpoint.path.replace('{version}', GlobalSettings.version || '1.0');
|
||
let html = `
|
||
<div class="modal" style="max-width: 1100px;">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span class="method-badge method-${endpoint.method}" style="font-size: 12px; padding: 4px 12px;">${endpoint.method.toUpperCase()}</span>
|
||
<span style="font-family: 'Fira Code', monospace; direction: ltr; font-size: 13px;">${escapeHtml(displayPath)}</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-test-modal>✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
${endpoint.summary ? `<div style="margin-bottom: 14px; padding: 10px; background: var(--column-bg); border-radius: 6px; font-size: 12px; color: var(--text-muted);">📝 ${escapeHtml(endpoint.summary)}</div>` : ''}
|
||
<div class="cors-info-box">
|
||
<strong>💡 نکته CORS:</strong> اگر با خطای CORS مواجه شدید، در نوار تنظیمات بالا فیلد <strong>CORS Proxy</strong> را با یکی از مقادیر زیر پر کنید:
|
||
<br><code>https://corsproxy.io/?</code> یا <code>https://api.allorigins.win/raw?url=</code>
|
||
<br>یا سرور خود را با هدرهای CORS مناسب پیکربندی کنید.
|
||
</div>
|
||
<div class="test-form">`;
|
||
if (pathParams.length > 0) {
|
||
html += `<div class="test-form-section"><div class="test-form-section-title">📍 Path Parameters</div>
|
||
${pathParams.map((p) => `<div class="test-field"><label>${p.name} ${p.required ? '<span class="required">*</span>' : ''}</label><input type="text" data-param-type="path" data-param-name="${p.name}" placeholder="${p.description || p.name}" value="${p.schema?.default || ''}"></div>`).join('')}</div>`;
|
||
}
|
||
if (queryParams.length > 0) {
|
||
html += `<div class="test-form-section"><div class="test-form-section-title">🔎 Query Parameters</div>
|
||
${queryParams.map((p) => {
|
||
const inputType = p.schema?.type === 'boolean' ? 'select' : p.schema?.type === 'integer' || p.schema?.type === 'number' ? 'number' : 'text';
|
||
let inputHtml = inputType === 'select' ? `<select data-param-type="query" data-param-name="${p.name}"><option value="">-- انتخاب --</option><option value="true">true</option><option value="false">false</option></select>` : `<input type="${inputType}" data-param-type="query" data-param-name="${p.name}" placeholder="${p.description || p.name}" value="${p.schema?.default ?? ''}">`;
|
||
return `<div class="test-field"><label>${p.name} ${p.required ? '<span class="required">*</span>' : ''}</label>${inputHtml}</div>`;
|
||
}).join('')}</div>`;
|
||
}
|
||
if (bodySchema) {
|
||
if (isFormData) {
|
||
html += `<div class="test-form-section full-width"><div class="test-form-section-title">📎 Form Data (multipart/form-data)</div><div class="test-field"><label>files (File Upload)</label><input type="file" data-param-type="file" data-param-name="files" multiple></div></div>`;
|
||
} else {
|
||
const exampleBody = generateExampleBody(bodySchema);
|
||
html += `<div class="test-form-section full-width"><div class="test-form-section-title">📦 Request Body (application/json)</div><div class="test-field"><label>Body (JSON)</label><textarea data-param-type="body" data-param-name="body" rows="10">${escapeHtml(JSON.stringify(exampleBody, null, 2))}</textarea></div></div>`;
|
||
}
|
||
}
|
||
html += `</div>
|
||
<div class="test-actions">
|
||
<button type="button" class="btn btn-success" id="${modalId}_executeBtn"><span>🚀</span><span>اجرای درخواست</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="${modalId}_curlBtn"><span>📋</span><span>کپی cURL</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="${modalId}_toggleDebugBtn"><span>🔍</span><span>نمایش/مخفی Debug Log</span></button>
|
||
<button type="button" class="btn btn-accent" style="background: linear-gradient(135deg, var(--accent), var(--accent-dark)); color: var(--primary-dark);" id="${modalId}_copyResponseBtn">
|
||
<span>📋</span><span>کپی پاسخ در کلیپبورد</span>
|
||
</button>
|
||
</div>
|
||
<div id="${modalId}_debugLog" class="debug-log" style="display: none;"></div>
|
||
<div id="${modalId}_responseArea"></div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" data-close-test-modal>بستن</button>
|
||
</div>
|
||
</div>`;
|
||
modalOverlay.innerHTML = html;
|
||
document.body.appendChild(modalOverlay);
|
||
modalOverlay.querySelectorAll('[data-close-test-modal]').forEach((btn) => {
|
||
btn.addEventListener('click', () => {
|
||
modalOverlay.classList.remove('active');
|
||
setTimeout(() => modalOverlay.remove(), 200);
|
||
});
|
||
});
|
||
modalOverlay.addEventListener('click', (e) => {
|
||
if (e.target === modalOverlay) {
|
||
modalOverlay.classList.remove('active');
|
||
setTimeout(() => modalOverlay.remove(), 200);
|
||
}
|
||
});
|
||
document.getElementById(`${modalId}_executeBtn`).addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
executeEndpointRequest(endpoint, modalId);
|
||
});
|
||
document.getElementById(`${modalId}_curlBtn`).addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
copyCurlCommand(endpoint, modalId);
|
||
});
|
||
document.getElementById(`${modalId}_toggleDebugBtn`).addEventListener('click', () => {
|
||
const debugLog = document.getElementById(`${modalId}_debugLog`);
|
||
debugLog.style.display = debugLog.style.display === 'none' ? 'block' : 'none';
|
||
});
|
||
document.getElementById(`${modalId}_copyResponseBtn`).addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
copyResponseToClipboard();
|
||
});
|
||
}
|
||
function generateExampleBody(schema) {
|
||
if (!schema) return {};
|
||
if (schema.$ref) {
|
||
const refName = schema.$ref.replace('#/components/schemas/', '');
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema) return generateExampleFromSchema(refSchema);
|
||
return {};
|
||
}
|
||
return generateExampleFromSchema(schema);
|
||
}
|
||
function generateExampleFromSchema(schema) {
|
||
if (!schema || !schema.properties) return {};
|
||
const example = {};
|
||
for (const [key, prop] of Object.entries(schema.properties)) example[key] = generateExampleValue(prop);
|
||
return example;
|
||
}
|
||
function generateExampleValue(prop) {
|
||
if (!prop) return null;
|
||
if (prop.$ref) {
|
||
const refName = prop.$ref.replace('#/components/schemas/', '');
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema?.properties) return generateExampleFromSchema(refSchema);
|
||
return {};
|
||
}
|
||
if (prop.type === 'array') {
|
||
if (prop.items) return [generateExampleValue(prop.items)];
|
||
return [];
|
||
}
|
||
if (prop.enum && prop.enum.length > 0) return prop.enum[0];
|
||
switch (prop.type) {
|
||
case 'string':
|
||
if (prop.format === 'date-time') return new Date().toISOString();
|
||
if (prop.format === 'uuid') return '00000000-0000-0000-0000-000000000000';
|
||
return '';
|
||
case 'integer':
|
||
case 'number':
|
||
return prop.default ?? 0;
|
||
case 'boolean':
|
||
return prop.default ?? false;
|
||
default:
|
||
return null;
|
||
}
|
||
}
|
||
/* =========================================================================
|
||
Execute Request
|
||
========================================================================= */
|
||
async function executeEndpointRequest(endpoint, modalId) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const executeBtn = document.getElementById(`${modalId}_executeBtn`);
|
||
const debugLog = document.getElementById(`${modalId}_debugLog`);
|
||
executeBtn.disabled = true;
|
||
executeBtn.innerHTML = '<span class="loading-spinner"></span><span>در حال ارسال...</span>';
|
||
debugLog.innerHTML = `<span class="log-info">[${new Date().toLocaleTimeString()}] شروع اجرای درخواست...</span>\n`;
|
||
responseArea.innerHTML = `<div class="response-panel"><div class="response-header"><span class="response-status info">⏳ در انتظار...</span></div></div>`;
|
||
try {
|
||
let url = endpoint.path.replace('{version}', GlobalSettings.version || '1.0');
|
||
const modal = document.getElementById(modalId);
|
||
modal.querySelectorAll('[data-param-type="path"]').forEach((input) => {
|
||
const name = input.dataset.paramName;
|
||
const value = input.value;
|
||
if (!value) throw new Error(`پارامتر مسیر {${name}} خالی است`);
|
||
url = url.replace(`{${name}}`, encodeURIComponent(value));
|
||
});
|
||
if (url.includes('{') && url.includes('}')) throw new Error('لطفاً تمام پارامترهای مسیر را پر کنید');
|
||
const queryParams = new URLSearchParams();
|
||
modal.querySelectorAll('[data-param-type="query"]').forEach((input) => {
|
||
if (input.value !== '' && input.value !== null && input.value !== undefined) queryParams.append(input.dataset.paramName, input.value);
|
||
});
|
||
const queryString = queryParams.toString();
|
||
if (queryString) url += '?' + queryString;
|
||
let fullUrl = GlobalSettings.baseUrl.replace(/\/$/, '') + url;
|
||
const proxiedUrl = GlobalSettings.buildUrl(fullUrl);
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] URL: ${escapeHtml(fullUrl)}</span>\n`;
|
||
if (GlobalSettings.corsProxy) {
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] CORS Proxy: ${escapeHtml(GlobalSettings.corsProxy)}</span>\n`;
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] Proxied URL: ${escapeHtml(proxiedUrl)}</span>\n`;
|
||
}
|
||
const headers = GlobalSettings.buildHeaders();
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] Headers:</span>\n`;
|
||
for (const [k, v] of Object.entries(headers)) debugLog.innerHTML += ` <span class="log-info">${escapeHtml(k)}: ${escapeHtml(String(v).substring(0, 50))}${String(v).length > 50 ? '...' : ''}</span>\n`;
|
||
const options = { method: endpoint.method.toUpperCase(), headers: headers };
|
||
const bodyInput = modal.querySelector('[data-param-type="body"]');
|
||
const fileInput = modal.querySelector('[data-param-type="file"]');
|
||
if (bodyInput && bodyInput.value.trim()) {
|
||
headers['Content-Type'] = 'application/json';
|
||
try {
|
||
const bodyStr = bodyInput.value;
|
||
JSON.parse(bodyStr);
|
||
options.body = bodyStr;
|
||
debugLog.innerHTML += `<span class="log-request">[${new Date().toLocaleTimeString()}] Body (JSON): ${escapeHtml(bodyStr.substring(0, 200))}${bodyStr.length > 200 ? '...' : ''}</span>\n`;
|
||
} catch (e) {
|
||
throw new Error('JSON نامعتبر است: ' + e.message);
|
||
}
|
||
} else if (fileInput && fileInput.files.length > 0) {
|
||
const formData = new FormData();
|
||
for (const file of fileInput.files) formData.append('files', file, file.name);
|
||
options.body = formData;
|
||
delete headers['Content-Type'];
|
||
debugLog.innerHTML += `<span class="log-request">[${new Date().toLocaleTimeString()}] Body: FormData با ${fileInput.files.length} فایل</span>\n`;
|
||
}
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] ارسال درخواست ${endpoint.method.toUpperCase()}...</span>\n`;
|
||
const startTime = performance.now();
|
||
const response = await fetch(proxiedUrl, options);
|
||
const endTime = performance.now();
|
||
const duration = Math.round(endTime - startTime);
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] پاسخ دریافت شد - Status: ${response.status}</span>\n`;
|
||
const contentType = response.headers.get('content-type') || '';
|
||
let responseBody, responseText;
|
||
if (contentType.includes('application/json')) {
|
||
responseText = await response.text();
|
||
try { responseBody = JSON.parse(responseText); } catch (e) { responseBody = responseText; }
|
||
} else {
|
||
responseText = await response.text();
|
||
responseBody = responseText;
|
||
}
|
||
const responseHeaders = {};
|
||
response.headers.forEach((value, key) => { responseHeaders[key] = value; });
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] Response Size: ${formatBytes(responseText.length)}</span>\n`;
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] Duration: ${duration}ms</span>\n`;
|
||
window._lastResponseData = {
|
||
method: endpoint.method, path: endpoint.path, status: response.status, statusText: response.statusText,
|
||
headers: responseHeaders, body: responseBody, bodyText: responseText, duration: duration, url: fullUrl, timestamp: new Date().toISOString(),
|
||
};
|
||
renderResponse(response, responseBody, responseText, responseHeaders, duration, modalId);
|
||
} catch (error) {
|
||
debugLog.innerHTML += `<span class="log-error">[${new Date().toLocaleTimeString()}] ❌ خطا: ${escapeHtml(error.message)}</span>\n`;
|
||
renderErrorResponse(error, modalId);
|
||
} finally {
|
||
executeBtn.disabled = false;
|
||
executeBtn.innerHTML = '<span>🚀</span><span>اجرای درخواست</span>';
|
||
}
|
||
}
|
||
function renderResponse(response, body, bodyText, headers, duration, modalId) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const statusClass = response.status >= 200 && response.status < 300 ? 'success' : response.status >= 300 && response.status < 400 ? 'redirect' : 'error';
|
||
const bodyFormatted = typeof body === 'object' ? syntaxHighlightJson(JSON.stringify(body, null, 2)) : escapeHtml(bodyText || '');
|
||
const headersHtml = Object.entries(headers).map(([k, v]) => `<div><span class="json-key">${escapeHtml(k)}</span>: <span class="json-string">${escapeHtml(v)}</span></div>`).join('');
|
||
responseArea.innerHTML = `
|
||
<div class="response-panel">
|
||
<div class="response-header">
|
||
<span class="response-status ${statusClass}">${response.status} ${response.statusText}</span>
|
||
<span class="response-time">⏱️ ${duration}ms</span>
|
||
<span class="response-size">📦 ${formatBytes(bodyText.length)}</span>
|
||
</div>
|
||
<div class="response-tabs">
|
||
<button type="button" class="response-tab active" data-tab="body">Body</button>
|
||
<button type="button" class="response-tab" data-tab="headers">Headers</button>
|
||
<button type="button" class="response-tab" data-tab="raw">Raw</button>
|
||
</div>
|
||
<div id="${modalId}_tab_body" class="response-body">${bodyFormatted || '<span style="color: #6a9955;">// Empty response</span>'}</div>
|
||
<div id="${modalId}_tab_headers" class="response-body" style="display: none;">${headersHtml || '<span style="color: #6a9955;">// No headers</span>'}</div>
|
||
<div id="${modalId}_tab_raw" class="response-body" style="display: none;">${escapeHtml(bodyText || '')}</div>
|
||
</div>`;
|
||
responseArea.querySelectorAll('.response-tab').forEach((tab) => {
|
||
tab.addEventListener('click', () => {
|
||
responseArea.querySelectorAll('.response-tab').forEach((t) => t.classList.remove('active'));
|
||
tab.classList.add('active');
|
||
const tabName = tab.dataset.tab;
|
||
document.getElementById(`${modalId}_tab_body`).style.display = tabName === 'body' ? 'block' : 'none';
|
||
document.getElementById(`${modalId}_tab_headers`).style.display = tabName === 'headers' ? 'block' : 'none';
|
||
document.getElementById(`${modalId}_tab_raw`).style.display = tabName === 'raw' ? 'block' : 'none';
|
||
});
|
||
});
|
||
}
|
||
function copyResponseToClipboard() {
|
||
if (!window._lastResponseData) {
|
||
showToast('❌ هیچ پاسخی برای کپی وجود ندارد. ابتدا یک درخواست را اجرا کنید.', 'warning');
|
||
return;
|
||
}
|
||
const r = window._lastResponseData;
|
||
const clipboardData = {
|
||
meta: { method: r.method, path: r.path, url: r.url, timestamp: r.timestamp, duration: r.duration + 'ms' },
|
||
response: { status: r.status, statusText: r.statusText, headers: r.headers, body: r.body },
|
||
};
|
||
const jsonString = JSON.stringify(clipboardData, null, 2);
|
||
navigator.clipboard.writeText(jsonString).then(() => {
|
||
showToast('✅ پاسخ در کلیپبورد کپی شد', 'success');
|
||
}).catch((err) => {
|
||
try {
|
||
const textarea = document.createElement('textarea');
|
||
textarea.value = jsonString;
|
||
textarea.style.position = 'fixed';
|
||
textarea.style.opacity = '0';
|
||
document.body.appendChild(textarea);
|
||
textarea.select();
|
||
document.execCommand('copy');
|
||
document.body.removeChild(textarea);
|
||
showToast('✅ پاسخ در کلیپبورد کپی شد', 'success');
|
||
} catch (fallbackErr) {
|
||
showToast('❌ خطا در کپی در کلیپبورد: ' + fallbackErr.message, 'error');
|
||
}
|
||
});
|
||
}
|
||
function renderErrorResponse(error, modalId) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const isCorsError = error.message?.includes('Failed to fetch') || error.message?.includes('NetworkError') || error.message?.includes('CORS') || error.message?.includes('Load failed');
|
||
responseArea.innerHTML = `
|
||
<div class="response-panel">
|
||
<div class="response-header"><span class="response-status error">❌ خطا</span></div>
|
||
<div class="response-body" style="color: #f56565;">${escapeHtml(error.message || String(error))}</div>
|
||
${isCorsError ? `
|
||
<div style="margin-top: 12px; padding: 12px; background: rgba(221,107,32,0.1); border: 1px solid rgba(221,107,32,0.3); border-radius: 6px;">
|
||
<strong style="color: var(--warning);">💡 راهحلهای مشکل CORS:</strong>
|
||
<ol style="margin-top: 8px; padding-right: 20px; font-size: 12px; line-height: 1.8;">
|
||
<li><strong>استفاده از CORS Proxy:</strong> در نوار تنظیمات بالا، فیلد <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px; direction: ltr;">CORS Proxy</code> را با یکی از مقادیر زیر پر کنید:
|
||
<ul style="margin-top: 4px; padding-right: 20px; direction: ltr; text-align: left;">
|
||
<li><code>https://corsproxy.io/?</code></li>
|
||
<li><code>https://api.allorigins.win/raw?url=</code></li>
|
||
</ul>
|
||
</li>
|
||
<li><strong>پیکربندی سرور:</strong> در Startup.cs سرور .NET خود، CORS را فعال کنید.</li>
|
||
<li><strong>افزونه مرورگر:</strong> برای تست موقت از افزونههای "CORS Unblock" استفاده کنید.</li>
|
||
</ol>
|
||
</div>` : ''}
|
||
</div>`;
|
||
}
|
||
function copyCurlCommand(endpoint, modalId) {
|
||
const modal = document.getElementById(modalId);
|
||
let url = endpoint.path.replace('{version}', GlobalSettings.version || '1.0');
|
||
modal.querySelectorAll('[data-param-type="path"]').forEach((input) => { url = url.replace(`{${input.dataset.paramName}}`, input.value || 'VALUE'); });
|
||
const queryParams = new URLSearchParams();
|
||
modal.querySelectorAll('[data-param-type="query"]').forEach((input) => { if (input.value) queryParams.append(input.dataset.paramName, input.value); });
|
||
const qs = queryParams.toString();
|
||
if (qs) url += '?' + qs;
|
||
const fullUrl = GlobalSettings.buildUrl(GlobalSettings.baseUrl.replace(/\/$/, '') + url);
|
||
const headers = GlobalSettings.buildHeaders();
|
||
let curl = `curl -X ${endpoint.method.toUpperCase()} '${fullUrl}'`;
|
||
for (const [k, v] of Object.entries(headers)) curl += ` \\\n-H '${k}: ${v}'`;
|
||
const bodyInput = modal.querySelector('[data-param-type="body"]');
|
||
if (bodyInput && bodyInput.value.trim()) {
|
||
curl += ` \\\n-H 'Content-Type: application/json'`;
|
||
curl += ` \\\n-d '${bodyInput.value.replace(/'/g, "'\\''")}'`;
|
||
}
|
||
navigator.clipboard.writeText(curl).then(() => showToast('دستور cURL کپی شد', 'success'));
|
||
}
|
||
/* =========================================================================
|
||
Authentication
|
||
========================================================================= */
|
||
document.getElementById('openAuthBtn').addEventListener('click', () => {
|
||
document.getElementById('authModal').classList.add('active');
|
||
updateCurrentTokenInfo();
|
||
});
|
||
document.querySelectorAll('[data-close-auth]').forEach((btn) => btn.addEventListener('click', () => document.getElementById('authModal').classList.remove('active')));
|
||
document.getElementById('authModal').addEventListener('click', (e) => { if (e.target.id === 'authModal') document.getElementById('authModal').classList.remove('active'); });
|
||
document.getElementById('doLoginBtn').addEventListener('click', async (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const btn = document.getElementById('doLoginBtn');
|
||
const userSelectBy = document.getElementById('loginUserSelectBy').value.trim();
|
||
const password = document.getElementById('loginPassword').value;
|
||
const language = document.getElementById('loginLanguage').value.trim() || 'fa-IR';
|
||
if (!userSelectBy || !password) { showToast('لطفاً userSelectBy و password را وارد کنید', 'warning'); return; }
|
||
btn.disabled = true;
|
||
btn.innerHTML = '<span class="loading-spinner"></span><span>در حال ورود...</span>';
|
||
try {
|
||
const body = {
|
||
userSelectBy: userSelectBy, password: password, language: language,
|
||
device: { os: 'Web', browser: 'SDK-Manager', osVersion: navigator.platform, userAgent: navigator.userAgent, deviceType: 3, identifier: 'web-sdk-manager-' + Date.now() },
|
||
};
|
||
const url = GlobalSettings.buildUrl(GlobalSettings.baseUrl.replace(/\/$/, '') + '/Account/Authenticate');
|
||
const headers = GlobalSettings.buildHeaders();
|
||
headers['Content-Type'] = 'application/json';
|
||
const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
throw new Error(`خطای ${response.status}: ${errorText.substring(0, 300)}`);
|
||
}
|
||
const data = await response.json();
|
||
if (data.accessToken) {
|
||
GlobalSettings.accessToken = data.accessToken;
|
||
GlobalSettings.refreshToken = data.refreshToken || '';
|
||
GlobalSettings.expiresAt = data.expiresAt || 0;
|
||
GlobalSettings.save();
|
||
document.getElementById('manualAccessToken').value = data.accessToken;
|
||
document.getElementById('manualRefreshToken').value = data.refreshToken || '';
|
||
document.getElementById('manualExpiresAt').value = data.expiresAt || '';
|
||
updateAuthStatusUI();
|
||
showToast('✅ ورود با موفقیت انجام شد', 'success');
|
||
} else {
|
||
throw new Error('پاسخ نامعتبر: accessToken یافت نشد.');
|
||
}
|
||
} catch (error) {
|
||
let errorMsg = error.message;
|
||
if (error.message?.includes('Failed to fetch') || error.message?.includes('NetworkError')) errorMsg = 'خطای شبکه/CORS. لطفاً CORS Proxy را در تنظیمات عمومی تنظیم کنید.';
|
||
showToast('❌ خطا در ورود: ' + errorMsg, 'error', 6000);
|
||
} finally {
|
||
btn.disabled = false;
|
||
btn.innerHTML = '<span>🚀</span><span>ورود به سیستم</span>';
|
||
}
|
||
});
|
||
document.getElementById('saveManualTokenBtn').addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const accessToken = document.getElementById('manualAccessToken').value.trim();
|
||
if (!accessToken) { showToast('لطفاً accessToken را وارد کنید', 'warning'); return; }
|
||
GlobalSettings.accessToken = accessToken;
|
||
GlobalSettings.refreshToken = document.getElementById('manualRefreshToken').value.trim();
|
||
GlobalSettings.expiresAt = parseInt(document.getElementById('manualExpiresAt').value) || 0;
|
||
GlobalSettings.save();
|
||
updateAuthStatusUI();
|
||
showToast('✅ توکنها ذخیره شدند', 'success');
|
||
});
|
||
document.getElementById('clearTokenBtn').addEventListener('click', (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
GlobalSettings.accessToken = '';
|
||
GlobalSettings.refreshToken = '';
|
||
GlobalSettings.expiresAt = 0;
|
||
GlobalSettings.save();
|
||
document.getElementById('manualAccessToken').value = '';
|
||
document.getElementById('manualRefreshToken').value = '';
|
||
document.getElementById('manualExpiresAt').value = '';
|
||
updateAuthStatusUI();
|
||
showToast('🗑️ توکنها پاک شدند', 'info');
|
||
});
|
||
/* =========================================================================
|
||
Provider Service Generator
|
||
========================================================================= */
|
||
function renderProviderService(ctrl, content) {
|
||
const providerCode = generateProviderService(ctrl.name, ctrl.endpoints);
|
||
AppState.generatedProviderCode = providerCode.code;
|
||
AppState.generatedProviderFilename = providerCode.filename;
|
||
content.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">⚙️</div><div class="section-title"><h3>Service برای کنترلر ${ctrl.name}</h3></div></div>
|
||
<div style="display: flex; gap: 8px; margin-bottom: 14px; flex-wrap: wrap;">
|
||
<button type="button" class="btn btn-success" onclick="downloadProviderFile()"><span>💾</span><span>دانلود ${providerCode.filename}</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="openProviderModal()"><span>👁️</span><span>مشاهده کامل</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="copyProviderCode()"><span>📋</span><span>کپی</span></button>
|
||
</div>
|
||
<div class="code-block-header"><span>📄 ${providerCode.filename}</span><span style="color: var(--accent);">TypeScript | ${providerCode.methodCount} متد</span></div>
|
||
<div class="code-block"><pre>${highlightTS(providerCode.code)}</pre></div>
|
||
</div>`;
|
||
}
|
||
function generateProviderService(controllerName, endpoints) {
|
||
const filtered = endpoints.filter((e) => !e.path.toLowerCase().includes('/test/'));
|
||
if (filtered.length === 0) return { code: '// هیچ اندپوینتی یافت نشد\n', filename: `${controllerName}.service.ts`, methodCount: 0 };
|
||
const className = `X${controllerName}Service`;
|
||
const routeEnumName = `X${controllerName}ServiceRoute`;
|
||
const paramEnumName = `X${controllerName}Param`;
|
||
const endPointEnumValue = `XApiEndPoint.${controllerName}sService`;
|
||
const basePath = extractBasePath(filtered);
|
||
const routeEntries = [], paramEntries = new Map(), methods = [];
|
||
filtered.forEach((ep) => {
|
||
const routeInfo = extractRouteInfo(ep.path, basePath);
|
||
if (!routeEntries.find((r) => r.name === routeInfo.routeName)) routeEntries.push(routeInfo);
|
||
extractPathParams(ep.path, basePath).forEach((p) => paramEntries.set(p.name, p.name));
|
||
(ep.operation.parameters || []).filter((p) => p.in === 'query').forEach((p) => paramEntries.set(p.name, p.name));
|
||
methods.push(generateMethod(ep, routeInfo.routeName, routeInfo.routeValue, basePath));
|
||
});
|
||
const imports = generateImports(controllerName, methods);
|
||
const routeEnum = generateRouteEnum(routeEnumName, routeEntries);
|
||
const paramEnum = generateParamEnum(paramEnumName, Array.from(paramEntries.values()));
|
||
const classCode = generateProviderClass(className, routeEnumName, paramEnumName, endPointEnumValue, controllerName, methods);
|
||
return { code: `${imports}\n\n${routeEnum}\n\n${paramEnum}\n\n${classCode}\n`, filename: `${controllerName}.service.ts`, methodCount: methods.length };
|
||
}
|
||
function extractBasePath(endpoints) {
|
||
const firstPath = endpoints[0].path;
|
||
const parts = firstPath.split('/').filter((p) => p);
|
||
for (let i = 0; i < parts.length; i++) {
|
||
const part = parts[i];
|
||
if (part.endsWith('Provider') || part === 'Account' || part === 'Startup' || part === 'TestIdentity' || part === 'TestFeatures') return '/' + parts.slice(0, i + 1).join('/');
|
||
}
|
||
return '';
|
||
}
|
||
function extractRouteInfo(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath)) relativePath = path.substring(basePath.length);
|
||
if (relativePath.startsWith('/')) relativePath = relativePath.substring(1);
|
||
let routeName, routeValue = relativePath;
|
||
if (relativePath === '' || relativePath === '/') routeName = 'All';
|
||
else {
|
||
const segments = relativePath.split('/').filter((s) => s);
|
||
routeName = segments.map((s) => s.startsWith('{') && s.endsWith('}') ? 'ById' : s.charAt(0).toUpperCase() + s.slice(1)).join('');
|
||
if (routeName === 'ById') routeName = 'Get';
|
||
}
|
||
return { routeName, routeValue };
|
||
}
|
||
function extractPathParams(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath)) relativePath = path.substring(basePath.length);
|
||
const params = [];
|
||
for (const match of relativePath.matchAll(/\{([^}]+)\}/g)) if (match[1] !== 'version') params.push({ name: match[1] });
|
||
return params;
|
||
}
|
||
function generateRouteEnum(enumName, entries) {
|
||
const lines = entries.map((e) => `${e.name} = '${e.value}',`).join('\n');
|
||
return `/**\n * All Available EndPoint Routes ...\n */\nexport enum ${enumName} {\n${lines}\n}`;
|
||
}
|
||
function generateParamEnum(enumName, paramNames) {
|
||
if (paramNames.length === 0) return `/**\n * All Params ...\n */\nexport enum ${enumName} {\n// No params\n}`;
|
||
const lines = paramNames.map((p) => `${p.charAt(0).toUpperCase() + p.slice(1)} = '${p}',`).join('\n');
|
||
return `/**\n * All Params ...\n */\nexport enum ${enumName} {\n${lines}\n}`;
|
||
}
|
||
function generateImports(controllerName, methods) {
|
||
const needsFormData = methods.some((m) => m.isFormData);
|
||
const needsConnectionId = methods.some((m) => m.hasConnectionId);
|
||
const needsFillRouteParams = methods.some((m) => m.hasPathParams);
|
||
const needsXQuery = methods.some((m) => m.isXQuery);
|
||
const coreImports = ['XValidators'];
|
||
if (needsFormData) coreImports.push('toArray', 'hasChild');
|
||
let imports = `import {\n${coreImports.join(',\n')},\n} from 'x-framework-core';\nimport {\nHttpEvent, HttpClient, HttpParams, HttpHeaders, HttpResponse,\n} from '@angular/common/http';\nimport {\nX_API_CONFIG, XBaseApiService, XApiConfiguration${needsXQuery ? ', XQueryDto, XQueryResultDto' : ''},\n} from 'x-framework-identity-sdk';\nimport { Observable } from 'rxjs';\nimport { Router } from '@angular/router';\nimport { Inject, Injectable } from '@angular/core';`;
|
||
if (needsFillRouteParams) imports += `\nimport { fillRouteParams } from '../../tools/x-route.tools';`;
|
||
imports += `\nimport { XApiEndPoint } from '../../typings/x-endpoint.typings';`;
|
||
imports += `\nimport { X${controllerName}ServiceRoute, X${controllerName}Param } from '../x-${toKebabCase(controllerName)}.typings';`;
|
||
if (needsConnectionId) imports += `\nimport { applyConnectionIdToHeader } from '../../typings/x-push-provider.typings';`;
|
||
imports += `\nimport { X_SAHERELM_API_SDK_CONFIG } from '../../tokens/x-injectable-tokens';`;
|
||
imports += `\nimport { XSaherElmApiSDKConfig } from '../../config/x-saherelm-api-sdk.config';`;
|
||
return imports;
|
||
}
|
||
function generateMethod(endpoint, routeName, routeValue, basePath) {
|
||
const method = endpoint.method;
|
||
const operation = endpoint.operation;
|
||
const parameters = operation.parameters || [];
|
||
const pathParams = parameters.filter((p) => p.in === 'path' && p.name !== 'version');
|
||
const queryParams = parameters.filter((p) => p.in === 'query');
|
||
let bodyType = null, bodyParamName = null, isFormData = false;
|
||
const requestBody = operation.requestBody;
|
||
if (requestBody?.content) {
|
||
if (requestBody.content['multipart/form-data']) {
|
||
isFormData = true;
|
||
bodyType = 'FormData';
|
||
bodyParamName = 'formData';
|
||
} else if (requestBody.content['application/json']) {
|
||
bodyType = resolveType(requestBody.content['application/json'].schema);
|
||
bodyParamName = 'model';
|
||
}
|
||
}
|
||
let returnType = 'void';
|
||
const successResponse = operation.responses?.['200'];
|
||
if (successResponse?.content?.['application/json']?.schema) returnType = resolveType(successResponse.content['application/json'].schema);
|
||
const isXQuery = queryParams.some((p) => ['Filter', 'ContainsDetail', 'SortBy', 'IsAscending', 'Page', 'PageSize'].includes(p.name));
|
||
const hasConnectionId = ['post', 'put', 'delete', 'patch'].includes(method);
|
||
const methodName = toCamelCase(routeName);
|
||
return {
|
||
methodName, httpMethod: method, routeName, routeValue,
|
||
summary: (operation.summary || '').replace(/\r?\n/g, ' ').trim(),
|
||
pathParams, queryParams, bodyType, bodyParamName, returnType,
|
||
isFormData, isXQuery, hasConnectionId, hasPathParams: pathParams.length > 0,
|
||
};
|
||
}
|
||
function resolveType(schema) {
|
||
if (!schema) return 'any';
|
||
if (schema.$ref) return schema.$ref.replace('#/components/schemas/', '');
|
||
if (schema.type === 'array') return `Array<${resolveType(schema.items)}>`;
|
||
if (schema.type === 'string') {
|
||
if (schema.format === 'date-time') return 'Date';
|
||
if (schema.format === 'binary') return 'File';
|
||
return 'string';
|
||
}
|
||
if (schema.type === 'integer' || schema.type === 'number') return 'number';
|
||
if (schema.type === 'boolean') return 'boolean';
|
||
return 'any';
|
||
}
|
||
function generateProviderClass(className, routeEnumName, paramEnumName, endPointEnumValue, controllerName, methods) {
|
||
const methodsCode = methods.map((m) => generateMethodCode(m, routeEnumName, paramEnumName)).join('\n\n');
|
||
return `/**\n * Provides all Provider Actions as a Service ...\n */\n@Injectable({\nprovidedIn: 'root',\n})\nexport class ${className} extends XBaseApiService {\n//\n//#region Constructor ...\nconstructor(\nprotected router: Router,\nprotected httpClient: HttpClient,\n@Inject(X_SAHERELM_API_SDK_CONFIG) config: XSaherElmApiSDKConfig,\n@Inject(X_API_CONFIG) apiConfig: XApiConfiguration\n) {\nsuper(${endPointEnumValue}, true, true, httpClient, config, apiConfig);\n}\n//#endregion\n//\n//#region Actions ...\n//\n${methodsCode}\n//#endregion\n}`;
|
||
}
|
||
function generateMethodCode(methodInfo, routeEnumName, paramEnumName) {
|
||
const { methodName, httpMethod, routeName, summary, pathParams, queryParams, bodyType, bodyParamName, returnType, isFormData, isXQuery, hasConnectionId, hasPathParams } = methodInfo;
|
||
const signatureParams = [];
|
||
pathParams.forEach((p) => signatureParams.push({ name: p.name, type: 'string', required: true }));
|
||
if (bodyType && !isFormData) signatureParams.push({ name: bodyParamName, type: bodyType, required: true });
|
||
if (!isXQuery) queryParams.forEach((p) => signatureParams.push({ name: p.name, type: 'string', required: p.required || false }));
|
||
else signatureParams.push({ name: 'query', type: 'XQueryDto', required: true });
|
||
if (hasConnectionId) signatureParams.push({ name: 'connectionId', type: 'string', required: false });
|
||
let jsDoc = `/**\n`;
|
||
if (summary) jsDoc += `* ${summary}\n`;
|
||
signatureParams.forEach((p) => (jsDoc += `*\n* @param ${p.name}\n`));
|
||
jsDoc += `*\n* @param observe\n* @param reportProgress\n*/`;
|
||
const overloads = [];
|
||
['body', 'response', 'events'].forEach((obs) => {
|
||
let obsReturnType = obs === 'body' ? returnType : obs === 'response' ? `HttpResponse<${returnType}>` : `HttpEvent<${returnType}>`;
|
||
const obsParams = signatureParams.map((p) => `${p.name}${p.required ? '' : '?'}: ${p.type}`);
|
||
obsParams.push(`observe?: '${obs}'`);
|
||
obsParams.push(`reportProgress?: boolean`);
|
||
overloads.push(` public ${methodName}(\n${obsParams.join(',\n')}\n): Observable<${obsReturnType}>;`);
|
||
});
|
||
const finalParams = signatureParams.map((p) => `${p.name}${p.required ? '' : '?'}: ${p.type}`);
|
||
finalParams.push(`observe: any = 'body'`);
|
||
finalParams.push(`reportProgress: boolean = false`);
|
||
const methodBody = generateMethodBody(methodInfo, routeEnumName, paramEnumName);
|
||
return `${jsDoc}\n${overloads.join('\n')}\npublic ${methodName}(\n${finalParams.join(',\n')}\n): Observable<any> {\n${methodBody}\n}`;
|
||
}
|
||
function generateMethodBody(methodInfo, routeEnumName, paramEnumName) {
|
||
const { httpMethod, routeName, pathParams, queryParams, bodyType, bodyParamName, returnType, isFormData, isXQuery, hasConnectionId, hasPathParams } = methodInfo;
|
||
let body = '';
|
||
const validations = [];
|
||
pathParams.forEach((p) => validations.push(`XValidators.validateNotEmpty(${p.name});`));
|
||
if (bodyType && !isFormData) validations.push(`XValidators.validateNotNull(${bodyParamName});`);
|
||
if (validations.length > 0) {
|
||
body += ` //\n // Validate Args ...\n`;
|
||
validations.forEach((v) => (body += ` ${v}\n`));
|
||
}
|
||
body += ` //\n // Base Requirements ...\n let params: HttpParams = null;\n let headers: HttpHeaders = this.defaultHeaders;\n //\n // Authentication ...\n headers = this.addAuthentication(headers);\n`;
|
||
if (httpMethod !== 'get' && !isFormData) body += ` headers = this.addAcceptJson(headers);\n headers = this.addContentType(headers);\n`;
|
||
if (hasConnectionId) body += ` headers = applyConnectionIdToHeader(connectionId, headers);\n`;
|
||
body += ` //\n // Prepare Endpoint\n`;
|
||
if (hasPathParams) {
|
||
const paramMappings = pathParams.map((p) => ` {\n key: ${paramEnumName}.${p.name.charAt(0).toUpperCase() + p.name.slice(1)},\n value: ${p.name}.toString(),\n }`).join(',\n');
|
||
body += ` const endPointPath = fillRouteParams(\n this.getActionRoute(${routeEnumName}.${routeName}),\n [\n${paramMappings}\n ]\n );\n`;
|
||
} else {
|
||
body += ` const endPointPath = this.getActionRoute(${routeEnumName}.${routeName});\n`;
|
||
}
|
||
if (isXQuery) body += ` params = this.generateXQueryHttpParams(query);\n`;
|
||
body += ` //\n // Prepare Result ...\n`;
|
||
let bodyArg = '';
|
||
if (isFormData) bodyArg = 'formData';
|
||
else if (bodyType && httpMethod !== 'get' && httpMethod !== 'delete') bodyArg = bodyParamName;
|
||
if (bodyArg) body += ` return this.httpClient.${httpMethod}<${returnType}>(endPointPath, ${bodyArg}, {\n`;
|
||
else body += ` return this.httpClient.${httpMethod}<${returnType}>(endPointPath, {\n`;
|
||
body += ` withCredentials: this.apiConfig.withCredentials,\n headers,\n observe,\n params,\n reportProgress,\n });\n`;
|
||
return body;
|
||
}
|
||
function openProviderModal() {
|
||
document.getElementById('providerModalTitle').textContent = `Service - ${AppState.activeController}`;
|
||
document.getElementById('providerModalBody').innerHTML = `<div class="code-block-header"><span>📄 ${AppState.generatedProviderFilename}</span><span style="color: var(--accent);">TypeScript</span></div><div class="code-block"><pre>${highlightTS(AppState.generatedProviderCode)}</pre></div>`;
|
||
document.getElementById('providerModal').classList.add('active');
|
||
}
|
||
function downloadProviderFile() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
const blob = new Blob([AppState.generatedProviderCode], { type: 'text/typescript;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = AppState.generatedProviderFilename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
showToast(`فایل ${AppState.generatedProviderFilename} دانلود شد`, 'success');
|
||
}
|
||
function copyProviderCode() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
navigator.clipboard.writeText(AppState.generatedProviderCode).then(() => showToast('کد کپی شد', 'success'));
|
||
}
|
||
document.querySelectorAll('[data-close-provider]').forEach((btn) => btn.addEventListener('click', () => document.getElementById('providerModal').classList.remove('active')));
|
||
/* =========================================================================
|
||
DTO Generator
|
||
========================================================================= */
|
||
function openModelModal(modelName) {
|
||
AppState.selectedModel = modelName;
|
||
const schema = AppState.allSchemas[modelName];
|
||
if (!schema) { showToast('مدل یافت نشد', 'error'); return; }
|
||
document.getElementById('modelModalTitle').textContent = `مدل ${modelName}`;
|
||
const body = document.getElementById('modelModalBody');
|
||
const tsCode = generateTypeScriptDto(modelName, schema);
|
||
AppState.generatedCode = tsCode;
|
||
const props = schema.properties || {};
|
||
const propsList = Object.keys(props).map((name) => {
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const required = (schema.required || []).includes(name);
|
||
return `<tr><td style="font-family: 'Fira Code', monospace; font-size: 12px; direction: ltr; text-align: left;">${name}</td><td style="font-family: 'Fira Code', monospace; font-size: 12px; color: var(--info); direction: ltr; text-align: left;">${tsType}</td><td>${required ? '<span style="color: var(--danger); font-weight: 700;">ضروری</span>' : '<span style="color: var(--text-muted);">اختیاری</span>'}</td></tr>`;
|
||
}).join('');
|
||
body.innerHTML = `<table class="endpoints-table" style="margin-bottom: 20px;"><thead><tr><th>فیلد</th><th>نوع</th><th>وضعیت</th></tr></thead><tbody>${propsList}</tbody></table><div class="code-block-header"><span>📄 ${toFileName(modelName)}.ts</span><span style="color: var(--accent);">TypeScript</span></div><div class="code-block"><pre>${highlightTS(tsCode)}</pre></div>`;
|
||
document.getElementById('modelModal').classList.add('active');
|
||
}
|
||
document.querySelectorAll('[data-close-modal]').forEach((btn) => btn.addEventListener('click', () => document.getElementById('modelModal').classList.remove('active')));
|
||
document.getElementById('downloadDtoBtn').addEventListener('click', () => {
|
||
if (!AppState.selectedModel || !AppState.generatedCode) return;
|
||
const filename = toFileName(AppState.selectedModel) + '.ts';
|
||
const blob = new Blob([AppState.generatedCode], { type: 'text/typescript;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
showToast(`فایل ${filename} دانلود شد`, 'success');
|
||
});
|
||
document.getElementById('copyCodeBtn').addEventListener('click', () => {
|
||
if (!AppState.generatedCode) return;
|
||
navigator.clipboard.writeText(AppState.generatedCode).then(() => showToast('کد کپی شد', 'success'));
|
||
});
|
||
function generateTypeScriptDto(modelName, schema) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
if (schema.enum) return generateEnum(modelName, schema);
|
||
const parentType = props.id?.type === 'integer' ? 'XBaseNumberIDDto' : 'XBaseDto';
|
||
const interfaceCode = generateInterface(modelName, schema, parentType);
|
||
const defaultObjName = 'default' + modelName.replace(/^X/, '');
|
||
const defaultObjCode = generateDefaultObject(modelName, props, defaultObjName, parentType);
|
||
const prepareFuncCode = generatePrepareFunction(modelName, props, defaultObjName);
|
||
const isDefaultCode = `/**\n * Check Model is Default ...\n */\nexport function isDefault${modelName.replace(/^X/, '')}(model?: ${modelName}) {\n return isSameObject(prepare${modelName.replace(/^X/, '')}Fields(model), ${defaultObjName});\n}`;
|
||
const typeGuardCode = generateTypeGuard(modelName, props, requiredFields);
|
||
return `${interfaceCode}\n\n${defaultObjCode}\n\n${prepareFuncCode}\n\n${isDefaultCode}\n\n${typeGuardCode}\n`;
|
||
}
|
||
function generateInterface(modelName, schema, parentType) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
const fields = Object.keys(props).map((name) => {
|
||
if (['id', 'deleted'].includes(name)) return '';
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const optional = requiredFields.includes(name) ? '' : '?';
|
||
return ` ${name}${optional}: ${tsType};`;
|
||
}).filter((f) => f).join('\n');
|
||
return `/**\n * ${schema.description || `Model ${modelName}`}\n */\nexport interface ${modelName} extends ${parentType} {\n${fields}\n}`;
|
||
}
|
||
function generateDefaultObject(modelName, props, defaultObjName, parentType) {
|
||
const fields = Object.keys(props).map((name) => {
|
||
if (['id', 'deleted'].includes(name)) return '';
|
||
const prop = props[name];
|
||
let defaultValue = 'undefined';
|
||
if (prop.type === 'string') defaultValue = prop.format === 'date-time' ? 'undefined' : "''";
|
||
else if (prop.type === 'integer' || prop.type === 'number') defaultValue = '0';
|
||
else if (prop.type === 'boolean') defaultValue = 'false';
|
||
else if (prop.type === 'array') defaultValue = '[]';
|
||
return ` ${name}: ${defaultValue},`;
|
||
}).filter((f) => f).join('\n');
|
||
return `/**\n * Default model ...\n */\nexport const ${defaultObjName}: ${modelName} = {\n${fields}\n};`;
|
||
}
|
||
function generatePrepareFunction(modelName, props, defaultObjName) {
|
||
const fields = Object.keys(props).map((name) => {
|
||
if (['id', 'deleted'].includes(name)) return '';
|
||
const prop = props[name];
|
||
let check;
|
||
if (prop.type === 'array') check = `!isNullOrUndefined(model.${name}) && !hasChild(model.${name}) ? [...model.${name}] : ${defaultObjName}.${name}`;
|
||
else if (prop.type === 'string' && prop.format !== 'date-time') check = `!isNullOrEmptyString(model.${name}) ? model.${name} : ${defaultObjName}.${name}`;
|
||
else check = `!isNullOrUndefined(model.${name}) ? model.${name} : ${defaultObjName}.${name}`;
|
||
return ` ${name}: ${check},`;
|
||
}).filter((f) => f).join('\n');
|
||
return `/**\n * Preparing Dto Fields ...\n */\nexport function prepare${modelName.replace(/^X/, '')}Fields(model?: ${modelName}) {\n if (isNullOrUndefined(model)) model = { ...${defaultObjName} };\n model = {\n${fields}\n };\n return model;\n}`;
|
||
}
|
||
function generateTypeGuard(modelName, props, requiredFields) {
|
||
let guardFields = requiredFields.filter((f) => f !== 'deleted');
|
||
if (guardFields.length === 0) {
|
||
guardFields = Object.keys(props).filter((n) => !['deleted'].includes(n) && props[n] && !props[n].$ref && props[n].type !== 'array' && ['string', 'integer', 'number', 'boolean'].includes(props[n].type)).slice(0, 5);
|
||
}
|
||
const fieldsList = guardFields.map((f) => ` '${f}',`).join('\n');
|
||
return `/**\n * Model Type Guard ...\n */\nexport const is${modelName} = typeGuard<${modelName}>([\n${fieldsList}\n]);`;
|
||
}
|
||
function generateEnum(modelName, schema) {
|
||
const values = schema.enum || [];
|
||
const isInt = values.length > 0 && typeof values[0] === 'number';
|
||
const entries = values.map((v) => isInt ? ` ${v} = ${v},` : ` ${String(v).replace(/[^a-zA-Z0-9_]/g, '_')} = '${v}',`).join('\n');
|
||
return `/**\n * ${schema.description || `Enum ${modelName}`}\n */\nexport enum ${modelName} {\n${entries}\n}`;
|
||
}
|
||
function toFileName(modelName) {
|
||
return modelName.replace(/^X/, 'x-').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
|
||
}
|
||
/* =========================================================================
|
||
Syntax Highlighting
|
||
========================================================================= */
|
||
function highlightTS(code) {
|
||
const tokens = [];
|
||
let remaining = code;
|
||
while (remaining.length > 0) {
|
||
let matched = false;
|
||
if (remaining.startsWith('/*')) {
|
||
const endIdx = remaining.indexOf('*/');
|
||
if (endIdx !== -1) {
|
||
tokens.push({ type: 'comment', content: remaining.substring(0, endIdx + 2) });
|
||
remaining = remaining.substring(endIdx + 2);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched && remaining.startsWith('//')) {
|
||
const endIdx = remaining.indexOf('\n');
|
||
if (endIdx !== -1) {
|
||
tokens.push({ type: 'comment', content: remaining.substring(0, endIdx) });
|
||
remaining = remaining.substring(endIdx);
|
||
matched = true;
|
||
} else {
|
||
tokens.push({ type: 'comment', content: remaining });
|
||
remaining = '';
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched && (remaining.startsWith("'") || remaining.startsWith('"') || remaining.startsWith('`'))) {
|
||
const quote = remaining[0];
|
||
let idx = 1;
|
||
while (idx < remaining.length) {
|
||
if (remaining[idx] === '\\') idx += 2;
|
||
else if (remaining[idx] === quote) { idx++; break; }
|
||
else idx++;
|
||
}
|
||
tokens.push({ type: 'string', content: remaining.substring(0, idx) });
|
||
remaining = remaining.substring(idx);
|
||
matched = true;
|
||
}
|
||
if (!matched && /^[0-9]/.test(remaining)) {
|
||
const match = remaining.match(/^[0-9]+(\.[0-9]+)?/);
|
||
if (match) {
|
||
tokens.push({ type: 'number', content: match[0] });
|
||
remaining = remaining.substring(match[0].length);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched && /[a-zA-Z_$]/.test(remaining[0])) {
|
||
const match = remaining.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/);
|
||
if (match) {
|
||
const word = match[0];
|
||
const keywords = ['export', 'interface', 'const', 'function', 'enum', 'extends', 'import', 'from', 'return', 'if', 'public', 'private', 'protected', 'class', 'constructor'];
|
||
const types = ['string', 'number', 'boolean', 'any', 'void', 'Date', 'File', 'Array', 'Observable', 'HttpResponse', 'HttpEvent', 'HttpParams', 'HttpHeaders', 'FormData'];
|
||
if (keywords.includes(word)) tokens.push({ type: 'keyword', content: word });
|
||
else if (types.includes(word) || /^[A-Z]/.test(word)) tokens.push({ type: 'type', content: word });
|
||
else tokens.push({ type: 'identifier', content: word });
|
||
remaining = remaining.substring(match[0].length);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched) {
|
||
tokens.push({ type: 'plain', content: remaining[0] });
|
||
remaining = remaining.substring(1);
|
||
}
|
||
}
|
||
return tokens.map((t) => {
|
||
const escaped = escapeHtml(t.content);
|
||
if (t.type === 'comment') return `<span class="code-comment">${escaped}</span>`;
|
||
if (t.type === 'string') return `<span class="code-string">${escaped}</span>`;
|
||
if (t.type === 'number') return `<span class="code-number">${escaped}</span>`;
|
||
if (t.type === 'keyword') return `<span class="code-keyword">${escaped}</span>`;
|
||
if (t.type === 'type') return `<span class="code-type">${escaped}</span>`;
|
||
return escaped;
|
||
}).join('');
|
||
}
|
||
/* =========================================================================
|
||
XForm Builder
|
||
========================================================================= */
|
||
const XFormBuilder = (function () {
|
||
const LS = 'xfw-form-builder-v1:';
|
||
const TYPES = ['text', 'number', 'password', 'email', 'tel', 'url', 'color', 'select', 'radio', 'checkbox', 'toggle', 'hidden', 'date', 'slider', 'markdown', 'map', 'color_picker', 'avatar_upload', 'selector'];
|
||
const APPS = ['none', 'legacy', 'standard', 'fill', 'outline'];
|
||
const UPDS = ['change', 'blur', 'submit'];
|
||
const LPOS = ['before', 'after'];
|
||
const TENUM = { text: 'Text', number: 'Number', password: 'Password', email: 'Email', tel: 'Tel', url: 'Url', color: 'Color', select: 'Select', radio: 'Radio', checkbox: 'CheckBox', toggle: 'Toggle', hidden: 'Hidden', date: 'Date', slider: 'Slider', markdown: 'MarkDown', map: 'Map', color_picker: 'ColorPicker', avatar_upload: 'AvatarUpload', selector: 'Selector' };
|
||
const AENUM = { none: 'None', legacy: 'Legacy', standard: 'Standard', fill: 'Fill', outline: 'Outline' };
|
||
const UENUM = { change: 'CHANGE', blur: 'BLUR', submit: 'SUBMIT' };
|
||
const PENUM = { before: 'Before', after: 'After' };
|
||
const DPOS = { prefix: 'Prefix', suffix: 'Suffix' };
|
||
const PRESENT = [{ v: 'without_dialog', l: 'بدون دیالوگ (without_dialog)' }, { v: 'width_dialog', l: 'با دیالوگ (width_dialog)' }];
|
||
const EKEYS = { required: 'required', email: 'invalid_email', minlength: 'min_length', maxlength: 'max_length', min: 'min_value', max: 'max_value', pattern: 'invalid_format', xPhoneNumberValidator: 'invalid_phone_number', xUrlValidator: 'invalid_url', xNotZeroValidator: 'select_a_value', xValidateDate: 'invalid_date' };
|
||
let st = null, timer = null;
|
||
const $ = (id) => document.getElementById(id);
|
||
const clone = (o) => JSON.parse(JSON.stringify(o));
|
||
const kebab = (s) => toKebabCase(String(s).replace(/^X/, ''));
|
||
const human = (s) => String(s).replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, c => c.toUpperCase());
|
||
const refName = (r) => String(r).replace('#/components/schemas/', '');
|
||
function deref(p) { if (p && p.$ref) { const n = refName(p.$ref); return { ref: n, s: AppState.allSchemas[n] || {} }; } return { ref: null, s: p || {} }; }
|
||
function get(o, p) { return p.split('.').reduce((a, k) => (a == null ? undefined : a[k]), o); }
|
||
function set(o, p, v) { const ks = p.split('.'); const last = ks.pop(); let t = o; ks.forEach(k => { if (t[k] == null || typeof t[k] !== 'object') t[k] = {}; t = t[k]; }); t[last] = v; }
|
||
function defCfg(type, s) {
|
||
switch (type) {
|
||
case 'select': return { multiple: false, options: (s.enum || []).map(v => ({ value: v, viewValue: String(v) })) };
|
||
case 'radio': return { options: (s.enum || []).map(v => ({ value: v, viewValue: String(v) })) };
|
||
case 'date': return { datePickerPosition: 'suffix', disableInput: false, disablePicker: false, applyStateColor: true };
|
||
case 'slider': return { min: 0, max: 100, step: 1, vertical: false, thumbLabel: true, invert: false };
|
||
case 'markdown': return { hasToolbar: true, wrapWithCard: false, isInPage: true };
|
||
case 'map': return { presentType: 'without_dialog', zoom: 14, canSelect: true, disableInput: true, showSearchBar: true };
|
||
case 'color_picker': return { presentType: 'without_dialog', disableInput: false };
|
||
case 'avatar_upload': return { canDrop: true, wrapWithCard: false };
|
||
case 'selector': return { disableInput: true };
|
||
case 'text': return { readonly: false };
|
||
default: return {};
|
||
}
|
||
}
|
||
function infer(name, prop) {
|
||
const n = String(name).toLowerCase(); const { ref, s } = deref(prop);
|
||
if (['id', 'deleted', 'rowversion', 'concurrencystamp'].includes(n)) return { type: 'hidden', include: !['deleted', 'rowversion', 'concurrencystamp'].includes(n) };
|
||
if (s.enum) return { type: 'select' };
|
||
if (s.type === 'boolean') return { type: 'toggle' };
|
||
if (s.type === 'array') { const it = deref(s.items || {}); return { type: it.s.enum ? 'select' : 'selector' }; }
|
||
if (ref) return { type: 'selector' };
|
||
if (s.format === 'date-time' || s.format === 'date') return { type: 'date' };
|
||
if (s.format === 'binary') return { type: 'avatar_upload' };
|
||
if (/password/.test(n)) return { type: 'password' };
|
||
if (/email/.test(n) || s.format === 'email') return { type: 'email' };
|
||
if (/(mobile|phone|tel)/.test(n)) return { type: 'tel' };
|
||
if (/(url|uri|website|link)/.test(n)) return { type: 'url' };
|
||
if (/color/.test(n)) return { type: 'color_picker' };
|
||
if (/(latitude|longitude|longlat|latlng|location|geo)/.test(n)) return { type: 'map' };
|
||
if (/id$/.test(n)) return { type: 'selector' };
|
||
if (/(description|content|body|note|comment|markdown|detail)/.test(n) || (s.maxLength && s.maxLength > 200)) return { type: 'markdown' };
|
||
if (s.type === 'integer' || s.type === 'number') return { type: 'number' };
|
||
return { type: 'text' };
|
||
}
|
||
function inferVals(name, prop, required, type) {
|
||
const { s } = deref(prop); const num = s.type === 'integer' || s.type === 'number';
|
||
return {
|
||
required: !!required, email: type === 'email', phone: type === 'tel', url: type === 'url', notZero: false,
|
||
minLength: s.minLength ?? null, maxLength: s.maxLength ?? null, min: num ? (s.minimum ?? null) : null, max: num ? (s.maximum ?? null) : null,
|
||
pattern: s.pattern || '', dateStart: '', dateEnd: '', custom: []
|
||
};
|
||
}
|
||
function activeErrKeys(v) {
|
||
const k = []; if (v.required) k.push('required'); if (v.email) k.push('email');
|
||
if (v.minLength != null && v.minLength !== '') k.push('minlength'); if (v.maxLength != null && v.maxLength !== '') k.push('maxlength');
|
||
if (v.min != null && v.min !== '') k.push('min'); if (v.max != null && v.max !== '') k.push('max');
|
||
if (v.pattern) k.push('pattern'); if (v.phone) k.push('xPhoneNumberValidator'); if (v.url) k.push('xUrlValidator');
|
||
if (v.notZero) k.push('xNotZeroValidator'); if (v.dateStart && v.dateEnd) k.push('xValidateDate'); return k;
|
||
}
|
||
function syncErr(c) {
|
||
const old = {}; (c.errorHandlers || []).forEach(e => old[e.errorName] = e.errorMessage);
|
||
c.errorHandlers = activeErrKeys(c.validators).map(k => ({ errorName: k, errorMessage: old[k] || EKEYS[k] || k }));
|
||
}
|
||
const emptyIcon = () => ({ name: '', color: '', tooltip: '', applyStateColor: false, handler: false });
|
||
function makeControl(name, prop, required, index) {
|
||
const { s } = deref(prop); const inf = infer(name, prop); const type = inf.type;
|
||
const cfg = defCfg(type, s);
|
||
if (type === 'select' && s.type === 'array') { cfg.multiple = true; cfg.options = (deref(s.items || {}).s.enum || []).map(v => ({ value: v, viewValue: String(v) })); }
|
||
const c = {
|
||
include: inf.include !== false, index, propName: name, updateOn: 'change',
|
||
type: { type, config: cfg },
|
||
appearance: {
|
||
appearance: 'fill', labelPosition: 'after', hidden: false, disabled: false,
|
||
label: (s.description || human(name)), placeholder: '', hint: '', tooltip: '', cssClass: []
|
||
},
|
||
use: { prefixIcon: false, suffixIcon: false, formatter: false, progressBar: false, autoComplete: false },
|
||
icons: { prefix: emptyIcon(), suffix: emptyIcon() },
|
||
formatter: { type: 'number', inputType: '', locale: 'fa-IR', seperator: ',', currencyLable: '', stringFormatter: [] },
|
||
progressBar: { color: 'primary' },
|
||
autoComplete: { color: 'light', opened: false, cssClass: [] },
|
||
validators: inferVals(name, prop, required, type),
|
||
errorHandlers: [], events: { focusHandler: false, actionProvider: false, valueChanged: false, statusChanged: false, onBlured: false, onFocused: false },
|
||
raw: ''
|
||
};
|
||
syncErr(c); return c;
|
||
}
|
||
function buildState(model) {
|
||
const schema = AppState.allSchemas[model] || {}; const props = schema.properties || {}; const req = schema.required || [];
|
||
const base = String(model).replace(/^X/, '').replace(/Dto$/, '');
|
||
return {
|
||
modelName: model, formName: kebab(base) || 'form', output: 'factory', useEnums: true, prune: true, updateOn: 'change',
|
||
dtoImportPath: './' + toFileName(model), libImportPath: 'x-framework-components',
|
||
formValidators: { custom: [] }, formErrors: [],
|
||
controls: Object.keys(props).map((k, i) => makeControl(k, props[k], req.includes(k), i)),
|
||
view: 'form', section: 'form', search: ''
|
||
};
|
||
}
|
||
const F = {
|
||
general: [
|
||
{ p: 'include', l: 'درج در فرم', k: 'bool', s: 1 },
|
||
{ p: 'index', l: 'index', k: 'number' },
|
||
{ p: 'propName', l: 'propName (keyof T)', k: 'text' },
|
||
{ p: 'type.type', l: 'نوع کنترل (XFormControlType)', k: 'select', o: TYPES, s: 1 },
|
||
{ p: 'updateOn', l: 'updateOn', k: 'select', o: UPDS },
|
||
{ sec: 'گیرندهها و رخدادها' },
|
||
{ p: 'events.focusHandler', l: 'focusHandler: Subject', k: 'bool' },
|
||
{ p: 'events.actionProvider', l: 'actionProvider: Subject', k: 'bool' },
|
||
{ p: 'events.valueChanged', l: 'eventHandlers.valueChanged', k: 'bool' },
|
||
{ p: 'events.statusChanged', l: 'eventHandlers.statusChanged', k: 'bool' },
|
||
{ p: 'events.onBlured', l: 'eventHandlers.onBlured', k: 'bool' },
|
||
{ p: 'events.onFocused', l: 'eventHandlers.onFocused', k: 'bool' }
|
||
],
|
||
appearance: [
|
||
{ p: 'appearance.appearance', l: 'appearance', k: 'select', o: APPS },
|
||
{ p: 'appearance.labelPosition', l: 'labelPosition', k: 'select', o: LPOS },
|
||
{ p: 'appearance.label', l: 'label (XResourceIdentifier)', k: 'text' },
|
||
{ p: 'appearance.placeholder', l: 'placeholder', k: 'text' },
|
||
{ p: 'appearance.hint', l: 'hint', k: 'text' },
|
||
{ p: 'appearance.tooltip', l: 'tooltip', k: 'text' },
|
||
{ p: 'appearance.hidden', l: 'hidden', k: 'bool' },
|
||
{ p: 'appearance.disabled', l: 'disabled', k: 'bool' },
|
||
{ p: 'appearance.cssClass', l: 'cssClass (جدا با کاما)', k: 'tags', full: 1 }
|
||
],
|
||
icons: [
|
||
{ sec: 'آیکون Prefix' }, { p: 'use.prefixIcon', l: 'فعال', k: 'bool', s: 1 },
|
||
{ p: 'icons.prefix.name', l: 'name', k: 'text' }, { p: 'icons.prefix.color', l: 'color', k: 'text' },
|
||
{ p: 'icons.prefix.tooltip', l: 'tooltip', k: 'text' },
|
||
{ p: 'icons.prefix.applyStateColor', l: 'applyStateColor', k: 'bool' },
|
||
{ p: 'icons.prefix.handler', l: 'handler (تابع)', k: 'bool' },
|
||
{ sec: 'آیکون Suffix' }, { p: 'use.suffixIcon', l: 'فعال', k: 'bool', s: 1 },
|
||
{ p: 'icons.suffix.name', l: 'name', k: 'text' }, { p: 'icons.suffix.color', l: 'color', k: 'text' },
|
||
{ p: 'icons.suffix.tooltip', l: 'tooltip', k: 'text' },
|
||
{ p: 'icons.suffix.applyStateColor', l: 'applyStateColor', k: 'bool' },
|
||
{ p: 'icons.suffix.handler', l: 'handler (تابع)', k: 'bool' }
|
||
],
|
||
tools: [
|
||
{ sec: 'Formatter' }, { p: 'use.formatter', l: 'فعال', k: 'bool', s: 1 },
|
||
{ p: 'formatter.type', l: 'type (XFormInputFormatter)', k: 'text' },
|
||
{ p: 'formatter.inputType', l: 'inputType (XStringInputFormatType)', k: 'text' },
|
||
{ p: 'formatter.locale', l: 'locale', k: 'text' }, { p: 'formatter.seperator', l: 'seperator', k: 'text' },
|
||
{ p: 'formatter.currencyLable', l: 'currencyLable', k: 'text' },
|
||
{ p: 'formatter.stringFormatter', l: 'stringFormatter (اعداد)', k: 'nums', full: 1 },
|
||
{ sec: 'ProgressBar' }, { p: 'use.progressBar', l: 'فعال', k: 'bool', s: 1 },
|
||
{ p: 'progressBar.color', l: 'color', k: 'text' },
|
||
{ sec: 'AutoComplete' }, { p: 'use.autoComplete', l: 'فعال', k: 'bool', s: 1 },
|
||
{ p: 'autoComplete.color', l: 'color', k: 'text' },
|
||
{ p: 'autoComplete.opened', l: 'opened', k: 'bool' },
|
||
{ p: 'autoComplete.cssClass', l: 'cssClass', k: 'tags', full: 1 },
|
||
{ note: 'items بهصورت () => [] و itemTemplate با کامنت TODO تولید میشود؛ برای مقداردهی واقعی از تب «TS دستی» استفاده کنید.' }
|
||
],
|
||
validators: [
|
||
{ p: 'validators.required', l: 'Validators.required', k: 'bool' },
|
||
{ p: 'validators.email', l: 'Validators.email', k: 'bool' },
|
||
{ p: 'validators.minLength', l: 'minLength', k: 'number' },
|
||
{ p: 'validators.maxLength', l: 'maxLength', k: 'number' },
|
||
{ p: 'validators.min', l: 'min', k: 'number' }, { p: 'validators.max', l: 'max', k: 'number' },
|
||
{ p: 'validators.pattern', l: 'pattern (RegExp)', k: 'text', full: 1 },
|
||
{ p: 'validators.phone', l: 'XFormValidators.validatePhoneNumber()', k: 'bool' },
|
||
{ p: 'validators.url', l: 'XFormValidators.validateUrl()', k: 'bool' },
|
||
{ p: 'validators.notZero', l: 'XFormValidators.validateNotZero()', k: 'bool' },
|
||
{ p: 'validators.dateStart', l: 'validateDate: start', k: 'text' },
|
||
{ p: 'validators.dateEnd', l: 'validateDate: end', k: 'text' },
|
||
{ p: 'validators.custom', l: 'اعتبارسنجهای دلخواه (هر خط یک عبارت TS)', k: 'lines', full: 1 }
|
||
],
|
||
form: [
|
||
{ p: 'formName', l: 'name (XFormConfig.name)', k: 'text' },
|
||
{ p: 'output', l: 'شکل خروجی', k: 'select', o: [{ v: 'factory', l: 'تابع Factory' }, { v: 'const', l: 'ثابت (const)' }], s: 1 },
|
||
{ p: 'updateOn', l: 'updateOn فرم', k: 'select', o: UPDS },
|
||
{ p: 'useEnums', l: 'استفاده از Enum های فریمورک', k: 'bool' },
|
||
{ p: 'prune', l: 'حذف مقادیر خالی/پیشفرض از کد', k: 'bool' },
|
||
{ p: 'dtoImportPath', l: 'مسیر import مدل DTO', k: 'text' },
|
||
{ p: 'libImportPath', l: 'مسیر import کتابخانه', k: 'text' },
|
||
{ p: 'formValidators.custom', l: 'اعتبارسنجهای سطح فرم (هر خط یک عبارت TS)', k: 'lines', full: 1 }
|
||
]
|
||
};
|
||
const TQ = {
|
||
select: [{ p: 'type.config.multiple', l: 'multiple', k: 'bool' }],
|
||
radio: [], checkbox: [], toggle: [],
|
||
text: [{ p: 'type.config.readonly', l: 'readonly', k: 'bool' }],
|
||
date: [{ p: 'type.config.datePickerPosition', l: 'datePickerPosition', k: 'select', o: ['prefix', 'suffix'] },
|
||
{ p: 'type.config.disableInput', l: 'disableInput', k: 'bool' },
|
||
{ p: 'type.config.disablePicker', l: 'disablePicker', k: 'bool' },
|
||
{ p: 'type.config.applyStateColor', l: 'applyStateColor', k: 'bool' }],
|
||
slider: [{ p: 'type.config.min', l: 'min', k: 'number' }, { p: 'type.config.max', l: 'max', k: 'number' },
|
||
{ p: 'type.config.step', l: 'step', k: 'number' }, { p: 'type.config.vertical', l: 'vertical', k: 'bool' },
|
||
{ p: 'type.config.thumbLabel', l: 'thumbLabel', k: 'bool' }, { p: 'type.config.invert', l: 'invert', k: 'bool' }],
|
||
markdown: [{ p: 'type.config.mode', l: 'mode', k: 'text' }, { p: 'type.config.hasToolbar', l: 'hasToolbar', k: 'bool' },
|
||
{ p: 'type.config.wrapWithCard', l: 'wrapWithCard', k: 'bool' }, { p: 'type.config.isInPage', l: 'isInPage', k: 'bool' },
|
||
{ p: 'type.config.cardTitle', l: 'cardTitle', k: 'text' }],
|
||
map: [{ p: 'type.config.presentType', l: 'presentType', k: 'select', o: PRESENT },
|
||
{ p: 'type.config.zoom', l: 'zoom', k: 'number' }, { p: 'type.config.canSelect', l: 'canSelect', k: 'bool' },
|
||
{ p: 'type.config.disableInput', l: 'disableInput', k: 'bool' }, { p: 'type.config.disableIcon', l: 'disableIcon', k: 'bool' },
|
||
{ p: 'type.config.showSearchBar', l: 'showSearchBar', k: 'bool' }],
|
||
color_picker: [{ p: 'type.config.presentType', l: 'presentType', k: 'select', o: PRESENT },
|
||
{ p: 'type.config.outputFormat', l: 'outputFormat', k: 'text' },
|
||
{ p: 'type.config.disableInput', l: 'disableInput', k: 'bool' }, { p: 'type.config.disableIcon', l: 'disableIcon', k: 'bool' }],
|
||
avatar_upload: [{ p: 'type.config.canDrop', l: 'canDrop', k: 'bool' },
|
||
{ p: 'type.config.minAllowedFileSize', l: 'minAllowedFileSize', k: 'number' },
|
||
{ p: 'type.config.maxAllowedFileSize', l: 'maxAllowedFileSize', k: 'number' },
|
||
{ p: 'type.config.allowedExtensions', l: 'allowedExtensions', k: 'tags', full: 1 }],
|
||
selector: [{ p: 'type.config.disableInput', l: 'disableInput', k: 'bool' }, { p: 'type.config.disableIcon', l: 'disableIcon', k: 'bool' },
|
||
{ p: 'type.config.inputCssClass', l: 'inputCssClass', k: 'tags', full: 1 }]
|
||
};
|
||
function cur() { return typeof st.view === 'number' ? st.controls[st.view] : null; }
|
||
function fileName() { return 'x-' + kebab(String(st.modelName).replace(/^X/, '').replace(/Dto$/, '')) + '.form.ts'; }
|
||
function fieldHtml(f, obj) {
|
||
if (f.sec) return `<div class="fb-sec">${f.sec}</div>`;
|
||
if (f.note) return `<div class="fb-note">💡 ${f.note}</div>`;
|
||
const v = get(obj, f.p), attrs = `data-fb-path="${f.p}" data-fb-kind="${f.k}" ${f.s ? 'data-fb-structural="1"' : ''}`;
|
||
const cls = 'fb-field' + (f.full || ['tags', 'lines', 'json', 'textarea'].includes(f.k) ? ' full' : '');
|
||
let inner = '';
|
||
if (f.k === 'bool') return `<div class="${cls}"><label class="fb-check"><input type="checkbox" ${attrs} ${v ? 'checked' : ''}><span>${f.l}</span></label></div>`;
|
||
if (f.k === 'select') {
|
||
const opts = (f.o || []).map(o => {
|
||
const ov = typeof o === 'object' ? o.v : o, ol = typeof o === 'object' ? o.l : o;
|
||
return `<option value="${escapeHtml(ov)}" ${String(v) === String(ov) ? 'selected' : ''}>${escapeHtml(ol)}</option>`;
|
||
}).join('');
|
||
inner = `<select ${attrs}>${opts}</select>`;
|
||
} else if (f.k === 'number') { inner = `<input type="number" ${attrs} value="${v == null ? '' : v}">`; }
|
||
else if (f.k === 'tags') { inner = `<input type="text" ${attrs} value="${escapeHtml(Array.isArray(v) ? v.join(', ') : (v || ''))}">`; }
|
||
else if (f.k === 'nums') { inner = `<input type="text" ${attrs} value="${escapeHtml(Array.isArray(v) ? v.join(', ') : '')}">`; }
|
||
else if (f.k === 'lines') { inner = `<textarea ${attrs}>${escapeHtml(Array.isArray(v) ? v.join('\n') : (v || ''))}</textarea>`; }
|
||
else if (f.k === 'json') { inner = `<textarea ${attrs} style="min-height:190px">${escapeHtml(JSON.stringify(v ?? {}, null, 2))}</textarea>`; }
|
||
else if (f.k === 'textarea') { inner = `<textarea ${attrs}>${escapeHtml(v || '')}</textarea>`; }
|
||
else { inner = `<input type="text" ${attrs} value="${escapeHtml(v == null ? '' : v)}">`; }
|
||
return `<div class="${cls}"><label>${f.l}</label>${inner}${f.h ? `<div class="fb-hint">${f.h}</div>` : ''}</div>`;
|
||
}
|
||
const fieldsHtml = (arr, obj) => `<div class="fb-grid">${arr.map(f => fieldHtml(f, obj)).join('')}</div>`;
|
||
function errHtml(target) {
|
||
const list = target === 'form' ? st.formErrors : cur().errorHandlers;
|
||
const rows = list.map((e, i) => `<div class="fb-err-row">
|
||
<input type="text" data-fb-err="${i}" data-fb-err-key="errorName" data-fb-err-target="${target}" value="${escapeHtml(e.errorName)}" placeholder="errorName">
|
||
<input type="text" data-fb-err="${i}" data-fb-err-key="errorMessage" data-fb-err-target="${target}" value="${escapeHtml(e.errorMessage)}" placeholder="errorMessage (XResourceIdentifier)">
|
||
<button type="button" class="fb-mini" data-fb-act="delerr" data-fb-idx="${i}" data-fb-err-target="${target}">🗑️</button></div>`).join('');
|
||
return `<div class="fb-grid">
|
||
<div class="fb-sec">هندلرهای خطا (errorHandlers)</div>
|
||
<div class="full" style="grid-column:1/-1">${rows || '<div class="fb-hint">موردی ثبت نشده است</div>'}</div>
|
||
<div style="grid-column:1/-1;display:flex;gap:8px;margin-top:8px">
|
||
<button type="button" class="btn btn-info btn-xs" data-fb-act="adderr" data-fb-err-target="${target}">➕ افزودن</button>
|
||
${target === 'form' ? '' : '<button type="button" class="btn btn-accent btn-xs" data-fb-act="autoerr">⚡ تولید از اعتبارسنجها</button>'}
|
||
</div></div>`;
|
||
}
|
||
function panelHtml() {
|
||
const s = st.section;
|
||
if (s === 'code') return `<div class="code-block-header"><span>📄 ${fileName()}</span><span style="color:var(--accent)">TypeScript</span></div>
|
||
<div class="code-block" style="max-height:430px"><pre>${highlightTS(generate())}</pre></div>`;
|
||
if (s === 'form') return fieldsHtml(F.form, st) + errHtml('form');
|
||
const c = cur(); if (!c) return '<div class="fb-note">یک فیلد را از لیست انتخاب کنید.</div>';
|
||
if (s === 'general') return fieldsHtml(F.general, c);
|
||
if (s === 'appearance') return fieldsHtml(F.appearance, c);
|
||
if (s === 'icons') return fieldsHtml(F.icons, c);
|
||
if (s === 'tools') return fieldsHtml(F.tools, c);
|
||
if (s === 'validators') return fieldsHtml(F.validators, c);
|
||
if (s === 'errors') return errHtml('control');
|
||
if (s === 'typeconfig') return fieldsHtml(TQ[c.type.type] || [], c) +
|
||
`<div class="fb-grid"><div class="fb-sec">پیکربندی کامل نوع (type.config) – JSON</div>
|
||
${fieldHtml({ p: 'type.config', l: c.type.type + ' config', k: 'json' }, c)}</div>`;
|
||
if (s === 'raw') return `<div class="fb-grid">
|
||
<div class="fb-note">اگر این بخش پر باشد، <b>کل پیکربندی این کنترل</b> با همین قطعه TS جایگزین میشود (آزادی کامل: تابع، Subject، TemplateRef، …).</div>
|
||
${fieldHtml({ p: 'raw', l: 'قطعه کد TypeScript', k: 'textarea' }, c)}
|
||
<div style="grid-column:1/-1"><button type="button" class="btn btn-info btn-xs" data-fb-act="seedraw">⚙️ تولید قطعه از تنظیمات فعلی</button></div></div>`;
|
||
return '';
|
||
}
|
||
function render() {
|
||
const tabs = [['form', '⚙️ فرم'], ['general', '🧱 عمومی'], ['appearance', '🎨 نمایش'], ['icons', '🖼️ آیکون'],
|
||
['tools', '🧮 فرمتر/تکمیل'], ['validators', '✅ اعتبارسنجی'], ['errors', '⛔ خطاها'], ['typeconfig', '🧩 نوع'], ['raw', '✍️ TS دستی'], ['code', '📄 کد نهایی']];
|
||
const list = st.controls.map((c, i) => ({ c, i }))
|
||
.filter(x => !st.search || x.c.propName.toLowerCase().includes(st.search.toLowerCase()))
|
||
.map(({ c, i }) => `<div class="fb-item ${st.view === i ? 'active' : ''} ${c.include ? '' : 'off'}" data-fb-act="select" data-fb-idx="${i}">
|
||
<input type="checkbox" ${c.include ? 'checked' : ''} data-fb-act="include" data-fb-idx="${i}">
|
||
<span class="fb-nm" title="${c.propName}">${c.propName}</span>
|
||
<span class="fb-tp">${c.type.type}</span>
|
||
<button type="button" class="fb-mini" data-fb-act="up" data-fb-idx="${i}">▲</button>
|
||
<button type="button" class="fb-mini" data-fb-act="down" data-fb-idx="${i}">▼</button></div>`).join('');
|
||
$('fbTitle').textContent = `تولید پیکربندی فرم (x-form) — ${st.modelName}`;
|
||
$('fbBody').innerHTML = `
|
||
<div class="fb-toolbar">
|
||
<div class="fb-tf"><label>نام فرم</label><input type="text" data-fb-path="formName" data-fb-kind="text" value="${escapeHtml(st.formName)}"></div>
|
||
<div class="fb-tf"><label>خروجی</label><select data-fb-path="output" data-fb-kind="text" data-fb-structural="1">
|
||
<option value="factory" ${st.output === 'factory' ? 'selected' : ''}>Factory</option><option value="const" ${st.output === 'const' ? 'selected' : ''}>const</option></select></div>
|
||
<div class="fb-tf"><label>فایل</label><input type="text" value="${fileName()}" readonly></div>
|
||
<div class="fb-tf"><label> </label><span class="auth-status authenticated"><span class="auth-status-dot"></span><span>${st.controls.filter(c => c.include).length} از ${st.controls.length} فیلد</span></span></div>
|
||
</div>
|
||
<div class="fb-layout">
|
||
<div class="fb-col">
|
||
<div class="search-input-wrapper"><input type="text" class="search-input" id="fbSearch" placeholder="جستجوی فیلد..." value="${escapeHtml(st.search)}"><span class="search-icon">🔍</span></div>
|
||
<div style="display:flex;gap:6px"><button type="button" class="btn btn-xs btn-info" data-fb-act="all">انتخاب همه</button>
|
||
<button type="button" class="btn btn-xs btn-ghost" style="background:var(--card-bg);color:var(--text);border:1px solid var(--border)" data-fb-act="none">هیچ</button></div>
|
||
<div class="fb-list">${list || '<div class="fb-hint">فیلدی یافت نشد</div>'}</div>
|
||
</div>
|
||
<div class="fb-col">
|
||
<div class="fb-tabs">${tabs.map(([k, l]) => `<button type="button" class="fb-tab ${st.section === k ? 'active' : ''}" data-fb-act="tab" data-fb-tab="${k}">${l}</button>`).join('')}</div>
|
||
<div class="fb-panel">${panelHtml()}</div>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
function generate() {
|
||
const imps = new Set(['XFormConfig']); const ext = new Set();
|
||
const R = (expr, ...i) => { i.forEach(x => imps.add(x)); return { __raw: expr }; };
|
||
const RX = (expr, mod) => { ext.add(mod + '|' + expr); return { __raw: expr }; };
|
||
const E = (en, mem, fb) => st.useEnums && mem ? R(`${en}.${mem}`, en) : fb;
|
||
const q = (s) => "'" + String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n') + "'";
|
||
const empty = (v) => v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length) ||
|
||
(typeof v === 'object' && !v.__raw && !Array.isArray(v) && !Object.keys(v).some(k => !empty(v[k]))) || (st.prune && v === false);
|
||
const key = (k) => /^[A-Za-z_$][\w$]*$/.test(k) ? k : q(k);
|
||
function ser(v, ind) {
|
||
const p = ' '.repeat(ind), p2 = ' '.repeat(ind + 2);
|
||
if (v && typeof v === 'object' && v.__raw !== undefined) return v.__raw;
|
||
if (Array.isArray(v)) return v.length ? '[\n' + v.map(x => p2 + ser(x, ind + 2)).join(',\n') + '\n' + p + ']' : '[]';
|
||
if (v && typeof v === 'object') {
|
||
const ks = Object.keys(v).filter(k => !empty(v[k]));
|
||
return ks.length ? '{\n' + ks.map(k => p2 + key(k) + ': ' + ser(v[k], ind + 2)).join(',\n') + '\n' + p + '}' : '{}';
|
||
}
|
||
if (typeof v === 'string') return q(v);
|
||
if (v == null) return 'undefined';
|
||
return String(v);
|
||
}
|
||
function vExprs(v) {
|
||
const out = []; const num = (x) => x != null && x !== '';
|
||
if (v.required) out.push(RX('Validators.required', '@angular/forms'));
|
||
if (v.email) out.push(RX('Validators.email', '@angular/forms'));
|
||
if (num(v.minLength)) out.push(RX(`Validators.minLength(${+v.minLength})`, '@angular/forms'));
|
||
if (num(v.maxLength)) out.push(RX(`Validators.maxLength(${+v.maxLength})`, '@angular/forms'));
|
||
if (num(v.min)) out.push(RX(`Validators.min(${+v.min})`, '@angular/forms'));
|
||
if (num(v.max)) out.push(RX(`Validators.max(${+v.max})`, '@angular/forms'));
|
||
if (v.pattern) out.push(RX(`Validators.pattern(${q(v.pattern)})`, '@angular/forms'));
|
||
if (v.phone) out.push(R('XFormValidators.validatePhoneNumber()', 'XFormValidators'));
|
||
if (v.url) out.push(R('XFormValidators.validateUrl()', 'XFormValidators'));
|
||
if (v.notZero) out.push(R('XFormValidators.validateNotZero()', 'XFormValidators'));
|
||
if (v.dateStart && v.dateEnd) out.push(R(`XFormValidators.validateDate(${q(v.dateStart)}, ${q(v.dateEnd)})`, 'XFormValidators'));
|
||
(v.custom || []).filter(Boolean).forEach(x => out.push({ __raw: x }));
|
||
return out;
|
||
}
|
||
function iconObj(ic) {
|
||
const o = { name: ic.name || undefined, color: ic.color || undefined, tooltip: ic.tooltip || undefined, applyStateColor: ic.applyStateColor || undefined };
|
||
if (ic.handler) o.handler = { __raw: '() => {\n // TODO: icon handler\n }' };
|
||
return o;
|
||
}
|
||
function normCfg(t, cfg) {
|
||
const c = clone(cfg || {});
|
||
if (t === 'date' && c.datePickerPosition) c.datePickerPosition = E('XFormDatePickerControlPickerPosition', DPOS[c.datePickerPosition], c.datePickerPosition);
|
||
if (t === 'map' && c.presentType) c.presentType = E('XFormMapControlPresentType', c.presentType === 'width_dialog' ? 'WithDialog' : 'WithoutDialog', c.presentType);
|
||
if (t === 'color_picker' && c.presentType) c.presentType = E('XFormColorPickerControlPresentType', c.presentType === 'width_dialog' ? 'WithDialog' : 'WithoutDialog', c.presentType);
|
||
return c;
|
||
}
|
||
function ctrlObj(c) {
|
||
if (c.raw && c.raw.trim()) return { __raw: c.raw.trim() };
|
||
const t = c.type.type, a = c.appearance, o = { index: c.index, propName: c.propName };
|
||
const cfg = normCfg(t, c.type.config);
|
||
o.type = { type: E('XFormControlType', TENUM[t], t), config: Object.keys(cfg).some(k => !empty(cfg[k])) ? cfg : undefined };
|
||
if (c.updateOn && c.updateOn !== 'change') o.updateOn = E('XFormUpdateOn', UENUM[c.updateOn], c.updateOn);
|
||
const ap = {
|
||
appearance: E('XFormControlAppearance', AENUM[a.appearance], a.appearance), label: a.label || undefined,
|
||
placeholder: a.placeholder || undefined, hint: a.hint || undefined, tooltip: a.tooltip || undefined,
|
||
hidden: a.hidden || undefined, disabled: a.disabled || undefined,
|
||
cssClass: (a.cssClass || []).length ? a.cssClass : undefined,
|
||
labelPosition: (t === 'checkbox' || t === 'toggle' || t === 'radio') ? E('XFormControlLabelPosition', PENUM[a.labelPosition], a.labelPosition) : undefined
|
||
};
|
||
const icons = {}; if (c.use.prefixIcon) icons.prefix = iconObj(c.icons.prefix); if (c.use.suffixIcon) icons.suffix = iconObj(c.icons.suffix);
|
||
if (Object.keys(icons).length) ap.icons = icons;
|
||
if (c.use.formatter) {
|
||
const f = c.formatter;
|
||
ap.formatter = {
|
||
type: f.type || undefined, inputType: f.inputType || undefined, locale: f.locale || undefined,
|
||
seperator: f.seperator || undefined, currencyLable: f.currencyLable || undefined,
|
||
stringFormatter: (f.stringFormatter || []).length ? f.stringFormatter : undefined
|
||
};
|
||
}
|
||
if (c.use.progressBar) ap.progressBar = { color: c.progressBar.color || undefined };
|
||
if (c.use.autoComplete) {
|
||
const ac = c.autoComplete;
|
||
ap.autoComplete = {
|
||
color: ac.color || undefined, opened: ac.opened || undefined, cssClass: (ac.cssClass || []).length ? ac.cssClass : undefined,
|
||
items: { __raw: '() => [] /* TODO: provider آیتمها */' },
|
||
itemTemplate: { __raw: 'undefined /* TODO: TemplateRef آیتم */' }
|
||
};
|
||
}
|
||
o.appearance = ap;
|
||
const vs = vExprs(c.validators); if (vs.length) o.validators = { validators: vs };
|
||
const eh = (c.errorHandlers || []).filter(e => e.errorName).map(e => ({ errorName: e.errorName, errorMessage: e.errorMessage || EKEYS[e.errorName] || e.errorName }));
|
||
if (eh.length) o.errorHandlers = eh;
|
||
if (c.events.focusHandler) o.focusHandler = R('new Subject<any>()', '@Subject');
|
||
if (c.events.actionProvider) o.actionProvider = R('new Subject<XFormControlActionProviderModel>()', '@Subject', 'XFormControlActionProviderModel');
|
||
const ev = {};['valueChanged', 'statusChanged', 'onBlured', 'onFocused'].forEach(k => { if (c.events[k]) ev[k] = { __raw: `(model) => {\n // TODO: ${k}\n }` }; });
|
||
if (Object.keys(ev).length) o.eventHandlers = ev;
|
||
return o;
|
||
}
|
||
const controls = st.controls.filter(c => c.include).sort((a, b) => a.index - b.index).map(ctrlObj);
|
||
const fvs = vExprs({ ...(st.formValidators || {}), custom: (st.formValidators || {}).custom || [] });
|
||
const cfg = {
|
||
name: st.formName,
|
||
model: st.output === 'factory' ? { __raw: 'model' } : undefined,
|
||
updateOn: st.updateOn !== 'change' ? E('XFormUpdateOn', UENUM[st.updateOn], st.updateOn) : undefined,
|
||
validators: fvs.length ? { validators: fvs } : undefined,
|
||
controls,
|
||
errorHandlers: (st.formErrors || []).filter(e => e.errorName).length ? st.formErrors.filter(e => e.errorName) : undefined
|
||
};
|
||
const body = ser(cfg, st.output === 'factory' ? 4 : 2);
|
||
const model = st.modelName, base = String(model).replace(/^X/, '').replace(/Dto$/, '');
|
||
const rx = [...ext].filter(x => x.startsWith('@angular/forms|')).map(x => x.split('|')[1]);
|
||
const needSubject = [...ext].some(x => x === '@Subject|new Subject<any>()') || imps.has('@Subject');
|
||
const lib = [...imps].filter(x => !x.startsWith('@'));
|
||
let head = `/* eslint-disable */\n// Generated by XFramework Backend SDK Manager — x-form Config Builder\n`;
|
||
if (rx.length) head += `import { ${[...new Set(rx)].join(', ')} } from '@angular/forms';\n`;
|
||
if (needSubject) head += `import { Subject } from 'rxjs';\n`;
|
||
head += `import {\n ${lib.sort().join(',\n ')},\n} from '${st.libImportPath}';\n`;
|
||
head += `import { ${model} } from '${st.dtoImportPath}';\n\n`;
|
||
const doc = `/**\n * پیکربندی فرم «${st.formName}» بر مبنای مدل ${model}\n * تولید خودکار + قابل ویرایش دستی\n */\n`;
|
||
const out = st.output === 'factory'
|
||
? `${doc}export function provide${base}FormConfig(model?: Partial<${model}>): XFormConfig<${model}> {\n return ${body};\n}\n`
|
||
: `${doc}export const x${base}FormConfig: XFormConfig<${model}> = ${body};\n`;
|
||
return head + out;
|
||
}
|
||
const save = () => { clearTimeout(timer); timer = setTimeout(() => { try { localStorage.setItem(LS + st.modelName, JSON.stringify(st)); } catch (e) { } }, 400); };
|
||
function refreshCodeIfNeeded() { if (st.section === 'code') render(); }
|
||
function onInput(e) {
|
||
const el = e.target;
|
||
if (el.id === 'fbSearch') { st.search = el.value; render(); const s = $('fbSearch'); if (s) { s.focus(); s.setSelectionRange(s.value.length, s.value.length); } return; }
|
||
if (el.dataset.fbErr !== undefined) {
|
||
const tgt = el.dataset.fbErrTarget === 'form' ? st.formErrors : cur().errorHandlers;
|
||
tgt[+el.dataset.fbErr][el.dataset.fbErrKey] = el.value; save(); return;
|
||
}
|
||
const p = el.dataset.fbPath; if (!p) return;
|
||
const k = el.dataset.fbKind; const obj = (typeof st.view === 'number' && !F.form.some(f => f.p === p)) ? cur() : st;
|
||
let v;
|
||
if (k === 'bool') v = el.checked;
|
||
else if (k === 'number') v = el.value === '' ? null : +el.value;
|
||
else if (k === 'tags') v = el.value.split(',').map(x => x.trim()).filter(Boolean);
|
||
else if (k === 'nums') v = el.value.split(',').map(x => +x.trim()).filter(x => !isNaN(x));
|
||
else if (k === 'lines') v = el.value.split('\n').map(x => x.trim()).filter(Boolean);
|
||
else if (k === 'json') { try { v = JSON.parse(el.value || '{}'); el.style.borderColor = ''; } catch (err) { el.style.borderColor = 'var(--danger)'; return; } }
|
||
else v = el.value;
|
||
const target = (p.startsWith('formName') || p === 'output' || p === 'useEnums' || p === 'prune' || p === 'updateOn' && obj === st || p.startsWith('formValidators') || p.endsWith('ImportPath')) && !p.startsWith('validators') ? st : obj;
|
||
set(target, p, v);
|
||
if (typeof st.view === 'number' && p.startsWith('validators.')) syncErr(cur());
|
||
if (p === 'type.type') {
|
||
const { s } = deref((AppState.allSchemas[st.modelName].properties || {})[cur().propName] || {});
|
||
cur().type.config = defCfg(v, s); syncErr(cur()); showToast('پیکربندی نوع کنترل بازنشانی شد', 'info');
|
||
}
|
||
save();
|
||
if (el.dataset.fbStructural || k === 'bool' || k === 'select') render(); else refreshCodeIfNeeded();
|
||
}
|
||
function onClick(e) {
|
||
const btn = e.target.closest('[data-fb-act]'); if (!btn) return;
|
||
const act = btn.dataset.fbAct, i = +btn.dataset.fbIdx;
|
||
if (act === 'include') { e.stopPropagation(); st.controls[i].include = btn.checked; normalize(); save(); render(); return; }
|
||
if (act === 'select') { st.view = i; if (st.section === 'form' || st.section === 'code') st.section = 'general'; render(); return; }
|
||
if (act === 'tab') { st.section = btn.dataset.fbTab; if (st.section !== 'form' && st.section !== 'code' && typeof st.view !== 'number') { const f = st.controls.findIndex(c => c.include); st.view = f < 0 ? 0 : f; } render(); return; }
|
||
if (act === 'up' || act === 'down') {
|
||
const j = act === 'up' ? i - 1 : i + 1; if (j < 0 || j >= st.controls.length) return;
|
||
const a = st.controls;[a[i], a[j]] = [a[j], a[i]]; normalize(); if (st.view === i) st.view = j; else if (st.view === j) st.view = i; save(); render(); return;
|
||
}
|
||
if (act === 'all' || act === 'none') { st.controls.forEach(c => c.include = act === 'all'); save(); render(); return; }
|
||
if (act === 'adderr') { const t = btn.dataset.fbErrTarget === 'form' ? st.formErrors : cur().errorHandlers; t.push({ errorName: '', errorMessage: '' }); save(); render(); return; }
|
||
if (act === 'delerr') { const t = btn.dataset.fbErrTarget === 'form' ? st.formErrors : cur().errorHandlers; t.splice(i, 1); save(); render(); return; }
|
||
if (act === 'autoerr') { syncErr(cur()); save(); render(); showToast('هندلرهای خطا بازتولید شد', 'success'); return; }
|
||
if (act === 'seedraw') { const c = cur(); c.raw = ''; c.raw = generateSnippet(c); save(); render(); showToast('قطعه TS تولید شد؛ اکنون آزادانه ویرایش کنید', 'success'); return; }
|
||
}
|
||
function normalize() { st.controls.forEach((c, i) => c.index = i); }
|
||
function generateSnippet(c) {
|
||
const one = clone(st); one.controls = [clone(c)]; one.output = 'const';
|
||
const bak = st; st = one; const txt = generate(); st = bak;
|
||
const m = txt.match(/controls:\s*\[[\s\S]*\n\s*\]/);
|
||
return m ? m[0].replace(/^controls:\s*\[\s*/, '').replace(/\s*\]$/, '') : '{ /* manual config */ }';
|
||
}
|
||
function download() {
|
||
const blob = new Blob([generate()], { type: 'text/typescript;charset=utf-8' });
|
||
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fileName();
|
||
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(a.href);
|
||
showToast(`فایل ${fileName()} دانلود شد`, 'success');
|
||
}
|
||
function copy() { navigator.clipboard.writeText(generate()).then(() => showToast('کد فرم کپی شد', 'success')); }
|
||
function exportJson() {
|
||
const blob = new Blob([JSON.stringify(st, null, 2)], { type: 'application/json' });
|
||
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fileName().replace('.ts', '.json');
|
||
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(a.href);
|
||
showToast('پیکربندی سازنده فرم خروجی گرفته شد', 'success');
|
||
}
|
||
function importJson(file) {
|
||
const r = new FileReader();
|
||
r.onload = (ev) => {
|
||
try { st = JSON.parse(ev.target.result); render(); save(); showToast('پیکربندی وارد شد', 'success'); }
|
||
catch (err) { showToast('فایل نامعتبر: ' + err.message, 'error'); }
|
||
};
|
||
r.readAsText(file);
|
||
}
|
||
function open(model) {
|
||
if (!model || !AppState.allSchemas[model]) { showToast('مدل یافت نشد', 'error'); return; }
|
||
let saved = null; try { saved = JSON.parse(localStorage.getItem(LS + model) || 'null'); } catch (e) { }
|
||
st = saved && saved.modelName === model ? saved : buildState(model);
|
||
st.view = 'form'; st.section = 'form'; st.search = '';
|
||
render(); $('formBuilderModal').classList.add('active');
|
||
if (saved) showToast('پیکربندی ذخیرهشده این مدل بازیابی شد', 'info');
|
||
}
|
||
function init() {
|
||
$('fbBody').addEventListener('input', onInput);
|
||
$('fbBody').addEventListener('change', onInput);
|
||
$('fbBody').addEventListener('click', onClick);
|
||
$('fbDownloadBtn').addEventListener('click', download);
|
||
$('fbCopyBtn').addEventListener('click', copy);
|
||
$('fbExportBtn').addEventListener('click', exportJson);
|
||
$('fbImportBtn').addEventListener('click', () => $('fbImportInput').click());
|
||
$('fbImportInput').addEventListener('change', (e) => { if (e.target.files[0]) importJson(e.target.files[0]); e.target.value = ''; });
|
||
$('fbResetBtn').addEventListener('click', () => {
|
||
if (!confirm('پیکربندی فرم این مدل به حالت استنتاج اولیه بازنشانی شود؟')) return;
|
||
localStorage.removeItem(LS + st.modelName); st = buildState(st.modelName); render(); showToast('بازنشانی شد', 'success');
|
||
});
|
||
document.querySelectorAll('[data-close-fb]').forEach(b => b.addEventListener('click', () => $('formBuilderModal').classList.remove('active')));
|
||
$('formBuilderModal').addEventListener('click', (e) => { if (e.target.id === 'formBuilderModal') $('formBuilderModal').classList.remove('active'); });
|
||
$('openFormBuilderBtn').addEventListener('click', () => open(AppState.selectedModel));
|
||
}
|
||
return { open, init };
|
||
})();
|
||
// ============ Initialize ============
|
||
initGlobalSettings();
|
||
XFormBuilder.init();
|
||
showToast('XFramework Backend SDK Manager v1.8.0 آماده استفاده است', 'success', 4000);
|
||
</script>
|
||
</body>
|
||
|
||
</html> |