-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction-planner.js
More file actions
280 lines (262 loc) · 13.5 KB
/
Copy pathfunction-planner.js
File metadata and controls
280 lines (262 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* This file contains the code for the function planner tool.
*
* Future ideas:
* - some initial model settings propagate into in-progress model without resetting? (i.e. new functions, into read-only functions, etc)
*/
import go from 'gojs';
import { makeAllButtons } from './src/buttons.js';
import { Model } from './src/model.js';
import { setupDiagram } from './src/diagram.js';
import { setupDragAndDrop } from './src/save-load.js';
import { setupProblemChecking } from './src/problem-checker.js';
import { setupInspector } from './src/inspector.js';
import { makeFunctionInspector } from './src/function-inspector.js';
import { makeModuleInspector } from './src/module-inspector.js';
import { setupEditingPresence } from './src/editing-presence.js';
import './function-planner.css';
const BASIC_MODEL = {
functions: [{ key: "1", name: 'main' },],
calls: []
};
const DEFAULT_ALLOWED_TYPES = ['int', 'float', 'str', 'bool', 'list', 'tuple', 'dict', 'set'];
/** Small inset so the node isn't flush against the viewport edge after a jump. */
const JUMP_VIEW_PADDING = 12;
/**
* Shift the diagram position by the smallest amount that fully shows `bounds`.
* No-op when already entirely in view. (Unlike Diagram.scrollToRect, does not center.)
* @param {go.Diagram} diagram
* @param {go.Rect} bounds
*/
function scrollMinimallyToShow(diagram, bounds) {
if (!bounds || !bounds.isReal()) {
return;
}
const view = diagram.viewportBounds;
const pad = JUMP_VIEW_PADDING;
const left = bounds.x - pad;
const right = bounds.right + pad;
const top = bounds.y - pad;
const bottom = bounds.bottom + pad;
let x = view.x;
let y = view.y;
const vw = view.width;
const vh = view.height;
if (right - left <= vw) {
if (left < view.x) {
x = left;
} else if (right > view.right) {
x = right - vw;
}
} else {
// Wider than the viewport: pin the left edge into view.
x = left;
}
if (bottom - top <= vh) {
if (top < view.y) {
y = top;
} else if (bottom > view.bottom) {
y = bottom - vh;
}
} else {
y = top;
}
if (x !== view.x || y !== view.y) {
diagram.position = new go.Point(x, y);
}
}
/**
* Initialize the Function Planner in the given root element.
* @param {HTMLElement|string} rootElem
* @param {string} planId - Module/plan identifier used for downloads, exports, and IndexedDB when enabled
* (prefer a human-readable base plan id, not a student-plan UUID)
* @param {object} options - Additional options
* @param {string} options.title - Title to show at the top of the diagram, optional
* @param {object} options.initialModel - Initial model to load if no saved model exists, defaults to a basic plan with a single "main" function
* @param {string[]} options.allowedTypes - List of allowed types for function parameters and returns
* @param {number} options.minFunctions - Minimum number of functions required (for validation), defaults to 1
* @param {number} options.maxFunctions - Maximum number of functions allowed (for validation), defaults to Infinity
* @param {number} options.minTestable - Minimum number of testable functions required (for validation), defaults to 0
* @param {number} options.maxTestable - Maximum number of testable functions allowed (for validation), defaults to Infinity
* @param {number} options.minInputFuncs - Minimum number of input-only functions required (for validation), defaults to 0
* @param {number} options.maxInputFuncs - Maximum number of input-only functions allowed (for validation), defaults to Infinity
* @param {number} options.minOutputFuncs - Minimum number of output-only functions required (for validation), defaults to 0
* @param {number} options.maxOutputFuncs - Maximum number of output-only functions allowed (for validation), defaults to Infinity
* @param {number} options.minModuleDescLength - Minimum length of module description (for validation), defaults to 25
* @param {number} options.minFuncDescLength - Minimum length of function description (for validation), defaults to 20
* @param {number} options.minParamDescLength - Minimum length of parameter description (for validation), defaults to 12
* @param {number} options.minReturnDescLength - Minimum length of return description (for validation), defaults to 12
* @param {string} options.docStyle - Docstring style to use (numpy, google, sphinx, epydoc), defaults to "numpy"
* @param {boolean} options.canClaimFuncs - If true, functions can be "claimed" by one author, colorizing/exporting them separately
* @param {boolean} options.adminMode - If true, enables admin mode features (nothing is read-only or not shown, allows editing read-only properties)
* @param {boolean} options.callGraphOnly - If true, hides the module and function inspectors, only shows the call graph (and suppresses most problem checking)
* @param {boolean} [options.showSaveJSON] Show Save as JSON (default: true when local, false when collaborative)
* @param {boolean} [options.showLoadJSON] Show Load from JSON (default: true when local, false when collaborative)
* @param {boolean} [options.showImportPython] Show Import from Python (default: false)
* @param {boolean} [options.showTestDocumentation] Show module test documentation (default: false)
* @param {boolean} [options.showGlobalCode] Show module global code editor (default: false)
* @param {boolean} [options.showTestGlobalCode] Show test global code editor (default: false)
* @param {string} [options.showCodeFor] Regex of function names that show function code (default: "")
* @param {string} [options.showTestCodeFor] Regex of function names that show test code (default: "")
* @param {boolean|string[]} [options.moduleReadOnly] Module field read-only policy (true=all, false=none, or field names)
* @param {{ for: string, fields: true|string[] }[]} [options.functionReadOnly] Per-function read-only rules (regex + fields)
* @param {string[]|null} [options.externalAuthors] When non-null (collaborative hosts),
* authors are locked to this list of stable ids (typically member emails) instead of free-text entry.
* @param {Record<string, string>} [options.authorLabels] Map of stable author id → display name.
* When an id has no entry, the id itself is shown (free-text / demo authors).
* @param {import('yjs').Doc} [options.ydoc] External Y.Doc shared with a WebsocketProvider (server is source of truth)
* @param {import('y-protocols/awareness').Awareness} [options.awareness] Shared awareness from the host WebsocketProvider
* @param {boolean} [options.useIndexedDB] Local IndexedDB persistence; defaults to false when ydoc is set, otherwise true
* @param {boolean} [options.readonly] Global read-only mode (diagram + inspectors still visible)
* @param {string} [options.licenseKey] GoJS license key (optional; academic demos may omit)
* @param {{ title: string, icon: string, onClick?: function, disabled?: boolean }[][]} [options.extraFabs]
* Extra bottom-left FAB groups (arrays of { title, icon, onClick, disabled? }), stacked above theme/settings/help
* @returns {{ model: Model, diagram: go.Diagram, destroy: () => void }}
*/
export default function init(
rootElem,
planId,
options={},
) {
rootElem = typeof rootElem === 'string' ? document.getElementById(rootElem) : rootElem;
rootElem.classList.add("func-planner");
options = { ...options };
options.title = options.title || null;
options.initialModel = options.initialModel ?? BASIC_MODEL;
options.allowedTypes = options.allowedTypes ?? DEFAULT_ALLOWED_TYPES;
options.adminMode = options.adminMode ?? false;
options.callGraphOnly = options.callGraphOnly ?? false;
options.canClaimFuncs = options.canClaimFuncs ?? false;
options.externalAuthors = options.externalAuthors ?? null;
options.authorLabels = options.authorLabels && typeof options.authorLabels === 'object'
? { ...options.authorLabels }
: {};
options.readonly = options.readonly ?? false;
options.useIndexedDB = options.useIndexedDB ?? !options.ydoc;
options.collaborative = Boolean(options.ydoc) || options.useIndexedDB === false;
// Local demos default to Save/Load JSON on; collaborative hosts opt in explicitly.
options.showSaveJSON = options.showSaveJSON ?? !options.collaborative;
options.showLoadJSON = options.showLoadJSON ?? !options.collaborative;
options.showImportPython = options.showImportPython ?? false;
options.showTestDocumentation = options.showTestDocumentation ?? false;
options.showGlobalCode = options.showGlobalCode ?? false;
options.showTestGlobalCode = options.showTestGlobalCode ?? false;
options.showCodeFor = options.showCodeFor ?? '';
options.showTestCodeFor = options.showTestCodeFor ?? '';
options.moduleReadOnly = options.moduleReadOnly ?? false;
options.functionReadOnly = options.functionReadOnly ?? [];
options.extraFabs = options.extraFabs ?? [];
options.theme = localStorage.getItem('func-planner-theme') === 'dark' ? 'dark' : 'light';
if (options.readonly && !options.adminMode) {
rootElem.classList.add('func-planner--readonly');
}
const model = new Model(planId, options.initialModel, {
ydoc: options.ydoc,
useIndexedDB: options.useIndexedDB,
});
const diagram = setupDiagram(rootElem, model, options);
makeAllButtons(diagram, model, options);
if (!options.collaborative) {
setupDragAndDrop(model, options, diagram.div);
}
setupProblemChecking(model, options);
const editingPresence = setupEditingPresence(diagram, options);
// Show the appropriate inspector based on selection
if (!options.callGraphOnly) {
const inspectorDiv = setupInspector(diagram.div);
const moduleInspector = makeModuleInspector(model, options);
const [funcInspector, setFuncInspectorKey] = makeFunctionInspector(model, options);
inspectorDiv.append(moduleInspector, funcInspector);
funcInspector.style.display = 'none';
editingPresence.attachInspector(inspectorDiv);
diagram.addDiagramListener('ChangedSelection', (e) => {
let subject = e.subject.first();
if (!subject) {
moduleInspector.style.display = '';
funcInspector.style.display = 'none';
editingPresence.publishEditingKey(null);
} else if (subject instanceof go.Link) {
return; // keep same
// or could show the fromNode in function inspector or revert to module inspector
} else {
setFuncInspectorKey(subject.data.key);
moduleInspector.style.display = 'none';
funcInspector.style.display = '';
editingPresence.publishEditingKey(subject.data.key);
}
});
}
return {
model,
diagram,
/**
* Replace authors from an external source (plan members). Pass null to
* stop treating authors as externally owned (local demos only).
* Labels are host-ephemeral (id → display name); only ids are persisted.
* @param {string[]|null} ids
* @param {Record<string, string>} [labels={}]
*/
setExternalAuthors(ids, labels={}) {
options.externalAuthors = ids;
options.authorLabels = labels && typeof labels === 'object' ? { ...labels } : {};
if (ids == null) {
editingPresence.refreshEditors();
return;
}
model.syncExternalAuthors(ids, options.authorLabels);
// Refresh label-dependent UI when ids are unchanged but names changed.
model.notifyModelData('authors');
diagram.findTopLevelGroups().each((group) => { group.updateTargetBindings(); });
editingPresence.refreshEditors();
},
/**
* Select a function node and scroll just enough for it to be fully visible.
* @param {string} key
* @returns {boolean} true if the node was found
*/
jumpToFunction(key) {
if (key == null || key === '') {
return false;
}
const node = diagram.findNodeForKey(key);
if (!node) {
return false;
}
diagram.select(node);
node.ensureBounds();
// Unconnected nodes are viewport-aligned (not in document bounds). Scrolling
// to their document coords corrupts the digraph viewport.
if (node.layerName !== 'Unconnected') {
scrollMinimallyToShow(diagram, node.actualBounds);
}
return true;
},
/**
* Clear function selection so the module inspector is shown (member at module level).
* @returns {boolean}
*/
jumpToModule() {
diagram.clearSelection();
return true;
},
destroy() {
editingPresence.destroy();
try {
diagram.div?.querySelectorAll('*');
diagram.clear();
if (diagram.div?.parentNode) {
diagram.div.parentNode.removeChild(diagram.div);
}
diagram.div = null;
} catch (_) {
// diagram may already be torn down
}
model.destroy();
if (rootElem) {
rootElem.replaceChildren();
rootElem.classList.remove('func-planner', 'dark-mode', 'func-planner--readonly');
}
},
};
}
export { BASIC_MODEL, DEFAULT_ALLOWED_TYPES, Model };