@codenotch/codenotch.react 1.0.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +145 -0
  2. package/dist/components/Auml.d.ts +46 -0
  3. package/dist/components/Auml.d.ts.map +1 -0
  4. package/dist/components/Auml.js +208 -0
  5. package/dist/components/CodeEditor.d.ts +39 -0
  6. package/dist/components/CodeEditor.d.ts.map +1 -0
  7. package/dist/components/CodeEditor.js +174 -0
  8. package/dist/core/ProcessUtils.d.ts +10 -0
  9. package/dist/core/ProcessUtils.d.ts.map +1 -0
  10. package/dist/core/ProcessUtils.js +65 -0
  11. package/dist/core/SignalR.d.ts +30 -0
  12. package/dist/core/SignalR.d.ts.map +1 -0
  13. package/dist/core/SignalR.js +245 -0
  14. package/dist/index.d.ts +60 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +370 -0
  17. package/dist/models/AppManifestModels.d.ts +46 -0
  18. package/dist/models/AppManifestModels.d.ts.map +1 -0
  19. package/dist/models/AppManifestModels.js +2 -0
  20. package/dist/models/Codenotch.d.ts +256 -0
  21. package/dist/models/Codenotch.d.ts.map +1 -0
  22. package/dist/models/Codenotch.js +2 -0
  23. package/dist/models/Misc.d.ts +28 -0
  24. package/dist/models/Misc.d.ts.map +1 -0
  25. package/dist/models/Misc.js +2 -0
  26. package/dist/models/ProjectManifestModels.d.ts +126 -0
  27. package/dist/models/ProjectManifestModels.d.ts.map +1 -0
  28. package/dist/models/ProjectManifestModels.js +158 -0
  29. package/dist/utils/I18nUtils.d.ts +7 -0
  30. package/dist/utils/I18nUtils.d.ts.map +1 -0
  31. package/dist/utils/I18nUtils.js +37 -0
  32. package/package.json +44 -0
  33. package/src/components/CodeEditor.tsx +203 -0
  34. package/src/core/ProcessUtils.ts +86 -0
  35. package/src/core/SignalR.ts +375 -0
  36. package/src/index.ts +387 -0
  37. package/src/models/AppManifestModels.ts +54 -0
  38. package/src/models/Codenotch.ts +285 -0
  39. package/src/models/Misc.ts +32 -0
package/src/index.ts ADDED
@@ -0,0 +1,387 @@
1
+ import ReactDOM from "react-dom";
2
+ import { SignalR } from "./core/SignalR";
3
+ import ProcessUtils from "./core/ProcessUtils";
4
+ import { IDisposable } from "./models/Misc";
5
+ import { ICodenotchApi, ICodenotchDialog, ICodenotchEnv, IProcessResult } from "./models/Codenotch";
6
+ import { v4 } from "uuid";
7
+ import CodeEditor from "./components/CodeEditor";
8
+
9
+ var signalR: SignalR | undefined = undefined;
10
+
11
+ /**
12
+ * The Codenotch runtime environment, populated by {@link init}.
13
+ * Prefer reading it through `useCodenotch().env`.
14
+ */
15
+ const env: ICodenotchEnv = {};
16
+
17
+ const MISSING_CLUSTER_URL_ERROR = "Codenotch cluster URL is not defined. Please set it in the Codenotch configuration.";
18
+ const MISSING_SERVICE_NAME_ERROR = "Codenotch service name is not defined. Please set it in the Codenotch configuration.";
19
+ const MISSING_TENANT_NAME_ERROR = "Codenotch tenant name is not defined. Please set it in the Codenotch configuration.";
20
+
21
+ /**
22
+ * Initialize the Codenotch environment from the given key-value pairs.
23
+ *
24
+ * This is normally called once, by the page hosting the application, with the
25
+ * environment variables injected by the Codenotch runtime (URL parameters or
26
+ * any other source). It must be called before `useCodenotch()` is used.
27
+ *
28
+ * Recognized key formats:
29
+ * - `i18n.<key>.<language>` — a translation, stored in `env.i18n[language][key]`.
30
+ * The first language found becomes the current language if none is set.
31
+ * - `GLOBAL.<name>` — JSON value assigned to `window[name]` (or `globalThis`).
32
+ * - `appManifest` / `projectManifest` — parsed as JSON into the environment.
33
+ * - anything else — copied as-is onto {@link env}.
34
+ *
35
+ * The UI theme is resolved from the `_theme` URL parameter, or from
36
+ * `prefers-color-scheme` as a fallback.
37
+ *
38
+ * @param envVariables An object containing the Codenotch environment variables as key-value pairs.
39
+ * @example
40
+ * import { init } from 'codenotch-react';
41
+ * init({
42
+ * clusterUrl: 'https://cluster.example.com',
43
+ * serviceName: 'myproject',
44
+ * tenantName: 'acme',
45
+ * 'i18n.welcome.en': 'Welcome',
46
+ * 'i18n.welcome.fr': 'Bienvenue'
47
+ * });
48
+ */
49
+ function init(envVariables: any): void {
50
+
51
+
52
+ // Ensure envVariables is an object
53
+ if (typeof envVariables === 'object' && envVariables !== null) {
54
+
55
+ let i18nLanguages = new Set<string>();
56
+
57
+ Object.keys(envVariables).forEach((key) => {
58
+ try {
59
+ if (key.startsWith('GLOBAL.')) {
60
+ // Global variable, we set it directly on the window object
61
+ let globalKey = key.substring('GLOBAL.'.length);
62
+ let globalObject = typeof window !== 'undefined' ? window : globalThis;
63
+ (globalObject as any)[globalKey] = JSON.parse(envVariables[key]);
64
+ console.log(`Codenotch global variable ${globalKey} set!`);
65
+ return;
66
+ }
67
+ else if (key.startsWith("i18n.")) {
68
+ // Special case
69
+ let parts = key.split("."); // i18n.someKey.fr
70
+ let language = parts[parts.length - 1]; // fr
71
+ let keyName = parts.slice(1, parts.length - 1).join("."); // someKey
72
+ i18nLanguages.add(language);
73
+
74
+ let value = `${envVariables[key]}`.trim();
75
+ if (value.startsWith('"') && value.endsWith('"')) {
76
+ // Parse like json
77
+ value = JSON.parse(value);
78
+ }
79
+
80
+ env.i18n = env.i18n ?? {};
81
+ env.i18n[language] = env.i18n[language] ?? {};
82
+ env.i18n[language][keyName] = value;
83
+ }
84
+ else {
85
+ (env as any)[key] = envVariables[key];
86
+
87
+ if (['appManifest', 'projectManifest'].includes(key)) {
88
+ // Must be Json
89
+ try {
90
+ (env as any)[key] = JSON.parse(envVariables[key]);
91
+ }
92
+ catch (error) {
93
+ console.warn(`Codenotch environment variable ${key} is not a valid JSON string. Using raw value.`);
94
+ }
95
+ }
96
+
97
+ console.log(`Codenotch environment variable ${key} set to ${(env as any)[key]}`);
98
+ }
99
+ }
100
+ catch (error) {
101
+ console.error(`Error processing Codenotch environment variable ${key}:`, error);
102
+ }
103
+ });
104
+
105
+ if (env.language === undefined) {
106
+ // If current language is not defined, we set it to the first language found in i18n
107
+ if (i18nLanguages.size > 0) {
108
+ env.language = Array.from(i18nLanguages)[0];
109
+ console.log(`Codenotch current language set to ${env.language}`);
110
+ }
111
+ }
112
+
113
+ }
114
+
115
+ // Instantiate SignalR for further use in the API
116
+ if (env.clusterUrl && env.serviceName) {
117
+ signalR = new SignalR(env.clusterUrl, env.serviceName, false, env.accessToken);
118
+ }
119
+
120
+ // Get theme like AEC does
121
+ try {
122
+ let urlParams = Object.fromEntries(new URLSearchParams(window.location.search).entries());
123
+ if (urlParams["_theme"]) {
124
+ let theme = urlParams["_theme"].toLowerCase();
125
+ if (theme === "light" || theme === "dark") {
126
+ env.theme = theme;
127
+ }
128
+ }
129
+ else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
130
+ env.theme = 'dark';
131
+ }
132
+ else {
133
+ env.theme = 'light';
134
+ }
135
+ }
136
+ catch {
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Return the Codenotch client API bound to the current environment.
142
+ *
143
+ * Despite its name this is NOT a React hook — it is a plain function with no
144
+ * hook rules attached: it can be called anywhere (components, handlers, plain
145
+ * modules). `init()` must have been called first, which the Codenotch runtime
146
+ * does automatically when serving the application.
147
+ *
148
+ * @returns The Codenotch API: BPMN processes, SioQL queries, i18n, signals, theme…
149
+ * @example
150
+ * import { useCodenotch } from 'codenotch-react';
151
+ *
152
+ * const MyApp: React.FC = () => {
153
+ * const cn = useCodenotch();
154
+ * return <h1>{cn.i18n('welcome')}</h1>;
155
+ * };
156
+ */
157
+ function useCodenotch(): ICodenotchApi {
158
+ return {
159
+ env: env,
160
+ uuid: () => v4(),
161
+ getProjectFileUrl: (relativePath: string): string => {
162
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
163
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
164
+ relativePath = relativePath.replace(/\\/g, "/");
165
+ if (relativePath.startsWith("/")) relativePath = relativePath.substring(1);
166
+ let url = `${env.clusterUrl}/${env.serviceName}/project/file?name=""&path=${encodeURIComponent(relativePath)}`;
167
+ return url;
168
+ },
169
+ getProjectFile: async (relativePath: string): Promise<string | undefined> => {
170
+ let url = useCodenotch().getProjectFileUrl(relativePath);
171
+ let resp = await fetch(url);
172
+ if (resp.status.toString().startsWith('2') === false) {
173
+ throw new Error(`Failed to fetch file content: ${resp.status} ${resp.statusText}`);
174
+ }
175
+ let content = await resp.text();
176
+ return content;
177
+ },
178
+ requestSioql: async (sioql: string, verbose?: boolean): Promise<any> => {
179
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
180
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
181
+
182
+ const request: RequestInit = {
183
+ method: 'POST',
184
+ mode: 'cors',
185
+ credentials: 'same-origin',
186
+ headers: { 'Content-Type': 'application/json' },
187
+ body: `"${sioql.replace(/\"/g, '\\\"')}"`
188
+ };
189
+
190
+ if (`${env.accessToken ?? ''}`.trim() !== "") {
191
+ if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
192
+ request.headers = {
193
+ ...request.headers, [`${env.tenantName}AccessToken`]: env.accessToken!
194
+ };
195
+ }
196
+
197
+ const response = await fetch(`${env.clusterUrl}/${env.serviceName}/sioql${verbose ? "?v=true" : ""}`, request);
198
+ if (!response.ok) {
199
+ const error = await response.text();
200
+ throw new Error(error);
201
+ }
202
+
203
+ return await response.json();
204
+ },
205
+ i18n: (key: string, ...args: any[]): string => {
206
+ try {
207
+ if (env.i18n === undefined || Object.keys(env.i18n).length === 0) {
208
+ console.warn("Codenotch i18n is not defined. Please set it in the Codenotch configuration.");
209
+ return key;
210
+ }
211
+
212
+ let language = env.language ?? "en";
213
+ let isLanguageExists = env.i18n[language] !== undefined;
214
+ if (isLanguageExists === false) {
215
+ let fallbackLanguage = Object.keys(env.i18n)[0];
216
+ console.warn(`Codenotch i18n language ${language} is not defined. Falling back to ${fallbackLanguage}. Please set the correct language in the Codenotch configuration.`);
217
+ language = fallbackLanguage;
218
+ }
219
+
220
+ let dico = env.i18n[language];
221
+ let value = dico[key];
222
+
223
+ if (typeof value !== "string") {
224
+ console.warn(`Codenotch i18n key ${key} is not defined for language ${language}. Please set it in the Codenotch configuration.`);
225
+ return key;
226
+ }
227
+ args = args ?? [];
228
+
229
+ let result = value.replace(/{([\d ]*)}/g, (match, p1) => {
230
+ let argValue = args[p1.trim()];
231
+ // Instead of returning 'undefined', returns an empty string
232
+ return argValue !== undefined ? argValue : "";
233
+ });
234
+
235
+ return result;
236
+ }
237
+ catch (error) {
238
+ console.error("Error in i18n function:", error);
239
+ return key;
240
+ }
241
+ },
242
+ startProcess: async (processName: any, startNodeId: any, inputs: any): Promise<IProcessResult> => {
243
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
244
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
245
+ if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
246
+ if (signalR === undefined) throw new Error("SignalR not available. Cannot start process.");
247
+ return ProcessUtils.startProcess((processInstanceId, callbacks) => signalR!.subscribeToProcessInstance(processInstanceId, callbacks),
248
+ env.clusterUrl,
249
+ env.tenantName,
250
+ env.serviceName,
251
+ processName,
252
+ inputs,
253
+ undefined,
254
+ startNodeId ?? 'start',
255
+ env.accessToken);
256
+ },
257
+ getUrlParams: () => {
258
+ let result: { [key: string]: string } = {};
259
+ if (typeof window !== 'undefined') {
260
+ const params = new URL(window.location.href).searchParams;
261
+ params.forEach((value: string, key: string) => {
262
+ if (result[key] === undefined) {
263
+ result[key] = value;
264
+ }
265
+ });
266
+ }
267
+ return result;
268
+ },
269
+ showDialog: (node: JSX.Element): ICodenotchDialog => {
270
+ let dialogId = "codenotch-dialog-" + Math.random().toString(36).substring(2, 9);
271
+ let result: ICodenotchDialog = {
272
+ id: dialogId,
273
+ close: () => {
274
+ let dialogElement = document.getElementById(dialogId);
275
+ if (dialogElement) {
276
+ dialogElement.remove();
277
+ }
278
+ }
279
+ };
280
+
281
+ // Find "cn-dialog-container" element in the page
282
+ let container = document.getElementById("cn-dialog-container");
283
+ if (container === null) {
284
+ container = document.createElement("div");
285
+ container.id = "cn-dialog-container";
286
+ container.style.zIndex = "9999";
287
+ container.style.position = "fixed";
288
+ container.style.top = "0";
289
+ container.style.left = "0";
290
+ container.style.minWidth = "100vw";
291
+ container.style.minHeight = "100vh";
292
+ container.style.maxWidth = "100vw";
293
+ container.style.maxHeight = "100vh";
294
+ container.style.display = "flex";
295
+ container.style.alignItems = "center";
296
+ container.style.justifyContent = "center";
297
+ container.style.pointerEvents = 'none';
298
+ document.body.appendChild(container);
299
+ }
300
+
301
+ let dialogElement = document.createElement('dialog');
302
+ dialogElement.id = dialogId;
303
+ dialogElement.style.zIndex = "9999";
304
+ dialogElement.style.position = "fixed";
305
+ dialogElement.style.top = "0";
306
+ dialogElement.style.left = "0";
307
+ dialogElement.style.minWidth = "100vw";
308
+ dialogElement.style.minHeight = "100vh";
309
+ dialogElement.style.maxWidth = "100vw";
310
+ dialogElement.style.maxHeight = "100vh";
311
+ dialogElement.style.display = "flex";
312
+ dialogElement.style.alignItems = "center";
313
+ dialogElement.style.justifyContent = "center";
314
+ dialogElement.style.pointerEvents = 'all';
315
+ dialogElement.style.background = '#78787822';
316
+ dialogElement.style.backdropFilter = 'blur(2px)';
317
+
318
+ container.appendChild(dialogElement);
319
+
320
+ ReactDOM.render(node, dialogElement, () => {
321
+ dialogElement.showModal();
322
+ });
323
+
324
+ return result;
325
+ },
326
+ listenSignal: async (signalId: string, callback: (data: any) => void): Promise<IDisposable> => {
327
+
328
+ if (!signalR) {
329
+ throw new Error("SignalR not available. Cannot listen to signal.");
330
+ }
331
+
332
+ let unsubscribeFunc = await signalR.subscribeToSignal(signalId, callback);
333
+
334
+ return {
335
+ dispose: () => {
336
+ unsubscribeFunc();
337
+ }
338
+ };
339
+
340
+ },
341
+ setTheme: (theme: 'light' | 'dark') => {
342
+ if (env.theme === theme) return;
343
+ if (env.theme) document.documentElement.classList.remove(env.theme);
344
+
345
+ env.theme = theme;
346
+ document.documentElement.classList.add(theme);
347
+ },
348
+ setLanguage: (lang: string) => {
349
+ if (env.language === lang) return;
350
+ env.language = lang;
351
+ },
352
+ getLanguages: () => {
353
+ return env.projectManifest?.languages ?? [];
354
+ },
355
+ getLanguage: () => {
356
+ return env.language;
357
+ },
358
+ getTheme: () => {
359
+ return env.theme;
360
+ },
361
+ getProjectManifest: () => {
362
+ if (env.projectManifest === undefined) {
363
+ throw new Error("Project manifest is not defined in Codenotch environment. Please set it in the Codenotch configuration.");
364
+ }
365
+ return env.projectManifest;
366
+ },
367
+ getAppManifest: () => {
368
+ return env.appManifest;
369
+ }
370
+ };
371
+ }
372
+
373
+ export {
374
+ env,
375
+ useCodenotch,
376
+ init,
377
+ CodeEditor
378
+ };
379
+
380
+ // Public models. Re-exported from the package root so that the typings
381
+ // generated by the Codenotch IDE (typings/i18n.d.ts and typings/process.d.ts,
382
+ // which augment the 'codenotch-react' module) merge with the real
383
+ // TranslationRegistry / ProcessRegistry declarations.
384
+ export * from "./models/Codenotch";
385
+ export * from "./models/Misc";
386
+ export * from "./models/AppManifestModels";
387
+ export * from "@codenotch/codenotch.core";
@@ -0,0 +1,54 @@
1
+
2
+ export interface ApplicationManifest {
3
+ pwa?: PWAManifest;
4
+
5
+ html?: HTMLManifest;
6
+
7
+ auml?: AUMLManifest;
8
+ }
9
+
10
+ export interface HTMLManifest {
11
+ title?: string;
12
+ description?: string;
13
+ author?: string;
14
+ keywords?: string;
15
+ charset?: string;
16
+ }
17
+
18
+ export interface PWAManifest {
19
+ background_color?: string;
20
+ description?: string;
21
+ dir?: string;
22
+ display?: string;
23
+ icons?: PWAManifestIcon[];
24
+ lang?: string;
25
+ name?: string;
26
+ orientation?: string;
27
+ prefer_related_applications?: boolean;
28
+ related_applications?: PWAManifestRelatedApplications[];
29
+ scope?: string;
30
+ short_name?: string;
31
+ start_url?: string;
32
+ theme_color?: string;
33
+ shortcuts?: string;
34
+
35
+ display_override?: string[];
36
+ }
37
+
38
+ export interface PWAManifestIcon {
39
+ src?: string;
40
+ sizes?: string;
41
+ type?: string;
42
+ }
43
+
44
+ export interface PWAManifestRelatedApplications {
45
+ platform?: string;
46
+ url?: string;
47
+ id?: string;
48
+ }
49
+
50
+ export interface AUMLManifest {
51
+ name?: string;
52
+ description?: string;
53
+ logoURL?: string;
54
+ }