@memberjunction/ng-artifacts 5.40.2 → 5.41.0
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.
- package/dist/lib/__tests__/interactive-form-apply.service.test.js +6 -1
- package/dist/lib/__tests__/interactive-form-apply.service.test.js.map +1 -1
- package/dist/lib/components/plugins/component-artifact-viewer.component.d.ts +3 -2
- package/dist/lib/components/plugins/component-artifact-viewer.component.d.ts.map +1 -1
- package/dist/lib/components/plugins/component-artifact-viewer.component.js +10 -3
- package/dist/lib/components/plugins/component-artifact-viewer.component.js.map +1 -1
- package/dist/lib/services/interactive-form-apply.service.d.ts +15 -0
- package/dist/lib/services/interactive-form-apply.service.d.ts.map +1 -1
- package/dist/lib/services/interactive-form-apply.service.js +91 -18
- package/dist/lib/services/interactive-form-apply.service.js.map +1 -1
- package/package.json +19 -19
|
@@ -36,9 +36,14 @@ vi.mock('@angular/core', () => ({
|
|
|
36
36
|
}));
|
|
37
37
|
const mockDialog = {
|
|
38
38
|
Open: () => ({
|
|
39
|
+
// The real MJDialogRef.Result emits the clicked MJDialogAction object
|
|
40
|
+
// ({ text, primary }) — the service detects intent via `action.primary`.
|
|
41
|
+
// Map the test's 'apply'/'cancel' intent onto that shape.
|
|
39
42
|
Result: {
|
|
40
43
|
subscribe: (cb) => {
|
|
41
|
-
cb(
|
|
44
|
+
cb(hoisted.dialogResult === 'apply'
|
|
45
|
+
? { text: 'Apply', primary: true }
|
|
46
|
+
: { text: 'Cancel' });
|
|
42
47
|
},
|
|
43
48
|
},
|
|
44
49
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-form-apply.service.test.js","sourceRoot":"","sources":["../../../src/lib/__tests__/interactive-form-apply.service.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,QAAQ,CAA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AEH,MAAM,GAAG,GAAG,IAAI,2BAA2B,EAAE,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,CAAC;QAC7E,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3E,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC","sourcesContent":["/**\n * End-to-end-ish coverage for the Apply-to-my-form flow.\n *\n * The service is the join point that closes the chat-artifact → action loop:\n * form-aware artifact viewer → applyFormRequested →\n * conversation-chat-area / artifact-resource → ConfirmAndApply →\n * Get Active Form For Entity (action) → Create or Modify (action)\n *\n * These tests mock the dialog, notifications, and the GraphQL action\n * client so we can drive both branches (no-existing → Create; existing →\n * Modify) and the cancellation path, plus the failure surfaces. Without\n * this suite the original \"Apply button is wired to nothing\" bug would\n * regress silently — the unit tests on the actions wouldn't notice.\n */\nimport { describe, it, expect, vi, beforeEach } from 'vitest';\nimport type { ComponentSpec } from '@memberjunction/interactive-component-types';\n\n// ─── Hoisted state buckets the mocks read/write ──────────────────────────\n\nconst hoisted = vi.hoisted(() => ({\n dialogResult: 'apply' as 'apply' | 'cancel',\n actionResponses: new Map<string, { Success: boolean; Message?: string; ResultCode?: string }>(),\n actionCalls: [] as Array<{ id: string; params: unknown }>,\n runViewResponses: [] as Array<{ Success: boolean; Results: Array<{ ID: string }>; ErrorMessage?: string }>,\n notifications: [] as Array<{ message: string; type: string }>,\n}));\n\n// ─── Module mocks ────────────────────────────────────────────────────────\n\nvi.mock('@angular/core', () => ({\n Injectable: () => (target: Function) => target,\n inject: (token: { Instance?: unknown } | typeof Object) => {\n // Return the mock singletons by class identity.\n const name = (token as { name?: string }).name ?? '';\n if (name === 'MJDialogService') return mockDialog;\n if (name === 'MJNotificationService') return mockNotifications;\n return {};\n },\n}));\n\nconst mockDialog = {\n Open: () => ({\n Result: {\n subscribe: (cb: (r: { result: string }) => void) => {\n cb({ result: hoisted.dialogResult });\n },\n },\n }),\n};\n\nconst mockNotifications = {\n CreateSimpleNotification: (message: string, type: string) => {\n hoisted.notifications.push({ message, type });\n },\n};\n\nvi.mock('@memberjunction/ng-ui-components', () => ({ MJDialogService: class MJDialogService {} }));\nvi.mock('@memberjunction/ng-notifications', () => ({ MJNotificationService: class MJNotificationService {} }));\n\nvi.mock('@memberjunction/graphql-dataprovider', () => ({\n GraphQLActionClient: class {\n async RunAction(actionId: string, params: unknown) {\n hoisted.actionCalls.push({ id: actionId, params });\n return hoisted.actionResponses.get(actionId) ?? { Success: false, Message: 'mock: no response set' };\n }\n },\n GraphQLDataProvider: class {},\n}));\n\nvi.mock('@memberjunction/core', async () => {\n const actual = await vi.importActual<Record<string, unknown>>('@memberjunction/core');\n return {\n ...actual,\n Metadata: { Provider: null },\n LogError: vi.fn(),\n RunView: class {\n async RunView() {\n return hoisted.runViewResponses.shift() ?? { Success: true, Results: [] };\n }\n },\n };\n});\n\n// ─── Test setup ──────────────────────────────────────────────────────────\n\nimport { InteractiveFormApplyService } from '../services/interactive-form-apply.service';\n\nfunction mockProvider(overrides: Partial<{ EntityByName: () => unknown; CurrentUser: unknown }> = {}) {\n return {\n EntityByName: () => ({ ID: 'ENT-1', Name: 'MJ: Apps' }),\n CurrentUser: { ID: 'U1', Name: 'Test' },\n ExecuteGQL: () => Promise.resolve({}), // marks it as a GraphQL provider\n ...overrides,\n } as unknown as Parameters<InteractiveFormApplyService['ConfirmAndApply']>[2];\n}\n\nfunction spec(over: Partial<ComponentSpec> = {}): ComponentSpec {\n return { name: 'Form', componentRole: 'form', location: 'embedded', code: '() => null', ...over } as ComponentSpec;\n}\n\nbeforeEach(() => {\n hoisted.dialogResult = 'apply';\n hoisted.actionResponses.clear();\n hoisted.actionCalls.length = 0;\n hoisted.runViewResponses.length = 0;\n hoisted.notifications.length = 0;\n});\n\ndescribe('InteractiveFormApplyService', () => {\n\n it('returns failure when no metadata provider is available', async () => {\n const svc = new InteractiveFormApplyService();\n // No provider — neither passed nor on Metadata.Provider.\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps');\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/No metadata provider/);\n });\n\n it('returns failure when the declared entity is not registered', async () => {\n const svc = new InteractiveFormApplyService();\n const provider = mockProvider({ EntityByName: () => undefined });\n const result = await svc.ConfirmAndApply(spec(), 'MJ: NotAnEntity', provider);\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/not registered/);\n });\n\n it('cancellation by user yields a friendly failure result, no action invoked', async () => {\n hoisted.dialogResult = 'cancel';\n // Seed action-id lookup so the path past dialog is reachable in case the\n // implementation order changes; with dialog returning 'cancel' the\n // Create action should never be called.\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/Cancelled/);\n // Only Get Active Form should have been called (to populate dialog text);\n // Create / Modify should NOT have been called.\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls.filter(id => id !== 'ACT-GET-ACTIVE')).toEqual([]);\n });\n\n it('no existing override → calls Create Interactive Form', async () => {\n // RunView lookups: each call resolves the next action ID.\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-CREATE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n hoisted.actionResponses.set('ACT-CREATE', {\n Success: true,\n Message: JSON.stringify({ ComponentID: 'NEW-COMP', OverrideID: 'NEW-OVER', Version: '1.0.0' }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec({ name: 'CompactForm' }), 'MJ: Apps', mockProvider());\n\n expect(result.Success).toBe(true);\n expect(result.Mode).toBe('create');\n expect(result.OverrideID).toBe('NEW-OVER');\n expect(result.Version).toBe('1.0.0');\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls).toEqual(['ACT-GET-ACTIVE', 'ACT-CREATE']);\n // Success notification surfaced.\n expect(hoisted.notifications.some(n => n.type === 'success')).toBe(true);\n });\n\n it('existing Active override → calls Modify Interactive Form (Pending sibling produced)', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-MODIFY' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({\n Active: { OverrideID: 'OVER-EXISTING', ComponentID: 'COMP-EXISTING', ComponentVersion: '1.0.0' },\n Variants: [],\n }),\n });\n hoisted.actionResponses.set('ACT-MODIFY', {\n Success: true,\n Message: JSON.stringify({ Mode: 'new-version', ComponentID: 'NEW-COMP', OverrideID: 'NEW-OVER', Version: '1.1.0' }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n\n expect(result.Success).toBe(true);\n expect(result.Mode).toBe('modify-new-version');\n expect(result.Version).toBe('1.1.0');\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls).toEqual(['ACT-GET-ACTIVE', 'ACT-MODIFY']);\n });\n\n it('Get Active failure short-circuits with an error', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: false,\n Message: 'DB unavailable',\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/Could not check for existing override/);\n });\n\n it('failure on the Create action surfaces the error notification', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-CREATE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n hoisted.actionResponses.set('ACT-CREATE', {\n Success: false,\n ResultCode: 'LINT_FAILED',\n Message: 'Spec failed linting.',\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(hoisted.notifications.some(n => n.type === 'error')).toBe(true);\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"interactive-form-apply.service.test.js","sourceRoot":"","sources":["../../../src/lib/__tests__/interactive-form-apply.service.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAG9D,4EAA4E;AAE5E,MAAM,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAC9B,YAAY,EAAE,OAA6B;IAC3C,eAAe,EAAE,IAAI,GAAG,EAAuE;IAC/F,WAAW,EAAE,EAA4C;IACzD,gBAAgB,EAAE,EAAwF;IAC1G,aAAa,EAAE,EAA8C;CAChE,CAAC,CAAC,CAAC;AAEJ,4EAA4E;AAE5E,EAAE,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,CAAC;IAC5B,UAAU,EAAE,GAAG,EAAE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,KAAK,CAAC,CAAC;QACnC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3E,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC","sourcesContent":["/**\n * End-to-end-ish coverage for the Apply-to-my-form flow.\n *\n * The service is the join point that closes the chat-artifact → action loop:\n * form-aware artifact viewer → applyFormRequested →\n * conversation-chat-area / artifact-resource → ConfirmAndApply →\n * Get Active Form For Entity (action) → Create or Modify (action)\n *\n * These tests mock the dialog, notifications, and the GraphQL action\n * client so we can drive both branches (no-existing → Create; existing →\n * Modify) and the cancellation path, plus the failure surfaces. Without\n * this suite the original \"Apply button is wired to nothing\" bug would\n * regress silently — the unit tests on the actions wouldn't notice.\n */\nimport { describe, it, expect, vi, beforeEach } from 'vitest';\nimport type { ComponentSpec } from '@memberjunction/interactive-component-types';\n\n// ─── Hoisted state buckets the mocks read/write ──────────────────────────\n\nconst hoisted = vi.hoisted(() => ({\n dialogResult: 'apply' as 'apply' | 'cancel',\n actionResponses: new Map<string, { Success: boolean; Message?: string; ResultCode?: string }>(),\n actionCalls: [] as Array<{ id: string; params: unknown }>,\n runViewResponses: [] as Array<{ Success: boolean; Results: Array<{ ID: string }>; ErrorMessage?: string }>,\n notifications: [] as Array<{ message: string; type: string }>,\n}));\n\n// ─── Module mocks ────────────────────────────────────────────────────────\n\nvi.mock('@angular/core', () => ({\n Injectable: () => (target: Function) => target,\n inject: (token: { Instance?: unknown } | typeof Object) => {\n // Return the mock singletons by class identity.\n const name = (token as { name?: string }).name ?? '';\n if (name === 'MJDialogService') return mockDialog;\n if (name === 'MJNotificationService') return mockNotifications;\n return {};\n },\n}));\n\nconst mockDialog = {\n Open: () => ({\n // The real MJDialogRef.Result emits the clicked MJDialogAction object\n // ({ text, primary }) — the service detects intent via `action.primary`.\n // Map the test's 'apply'/'cancel' intent onto that shape.\n Result: {\n subscribe: (cb: (r: { text: string; primary?: boolean }) => void) => {\n cb(\n hoisted.dialogResult === 'apply'\n ? { text: 'Apply', primary: true }\n : { text: 'Cancel' },\n );\n },\n },\n }),\n};\n\nconst mockNotifications = {\n CreateSimpleNotification: (message: string, type: string) => {\n hoisted.notifications.push({ message, type });\n },\n};\n\nvi.mock('@memberjunction/ng-ui-components', () => ({ MJDialogService: class MJDialogService {} }));\nvi.mock('@memberjunction/ng-notifications', () => ({ MJNotificationService: class MJNotificationService {} }));\n\nvi.mock('@memberjunction/graphql-dataprovider', () => ({\n GraphQLActionClient: class {\n async RunAction(actionId: string, params: unknown) {\n hoisted.actionCalls.push({ id: actionId, params });\n return hoisted.actionResponses.get(actionId) ?? { Success: false, Message: 'mock: no response set' };\n }\n },\n GraphQLDataProvider: class {},\n}));\n\nvi.mock('@memberjunction/core', async () => {\n const actual = await vi.importActual<Record<string, unknown>>('@memberjunction/core');\n return {\n ...actual,\n Metadata: { Provider: null },\n LogError: vi.fn(),\n RunView: class {\n async RunView() {\n return hoisted.runViewResponses.shift() ?? { Success: true, Results: [] };\n }\n },\n };\n});\n\n// ─── Test setup ──────────────────────────────────────────────────────────\n\nimport { InteractiveFormApplyService } from '../services/interactive-form-apply.service';\n\nfunction mockProvider(overrides: Partial<{ EntityByName: () => unknown; CurrentUser: unknown }> = {}) {\n return {\n EntityByName: () => ({ ID: 'ENT-1', Name: 'MJ: Apps' }),\n CurrentUser: { ID: 'U1', Name: 'Test' },\n ExecuteGQL: () => Promise.resolve({}), // marks it as a GraphQL provider\n ...overrides,\n } as unknown as Parameters<InteractiveFormApplyService['ConfirmAndApply']>[2];\n}\n\nfunction spec(over: Partial<ComponentSpec> = {}): ComponentSpec {\n return { name: 'Form', componentRole: 'form', location: 'embedded', code: '() => null', ...over } as ComponentSpec;\n}\n\nbeforeEach(() => {\n hoisted.dialogResult = 'apply';\n hoisted.actionResponses.clear();\n hoisted.actionCalls.length = 0;\n hoisted.runViewResponses.length = 0;\n hoisted.notifications.length = 0;\n});\n\ndescribe('InteractiveFormApplyService', () => {\n\n it('returns failure when no metadata provider is available', async () => {\n const svc = new InteractiveFormApplyService();\n // No provider — neither passed nor on Metadata.Provider.\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps');\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/No metadata provider/);\n });\n\n it('returns failure when the declared entity is not registered', async () => {\n const svc = new InteractiveFormApplyService();\n const provider = mockProvider({ EntityByName: () => undefined });\n const result = await svc.ConfirmAndApply(spec(), 'MJ: NotAnEntity', provider);\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/not registered/);\n });\n\n it('cancellation by user yields a friendly failure result, no action invoked', async () => {\n hoisted.dialogResult = 'cancel';\n // Seed action-id lookup so the path past dialog is reachable in case the\n // implementation order changes; with dialog returning 'cancel' the\n // Create action should never be called.\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/Cancelled/);\n // Only Get Active Form should have been called (to populate dialog text);\n // Create / Modify should NOT have been called.\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls.filter(id => id !== 'ACT-GET-ACTIVE')).toEqual([]);\n });\n\n it('no existing override → calls Create Interactive Form', async () => {\n // RunView lookups: each call resolves the next action ID.\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-CREATE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n hoisted.actionResponses.set('ACT-CREATE', {\n Success: true,\n Message: JSON.stringify({ ComponentID: 'NEW-COMP', OverrideID: 'NEW-OVER', Version: '1.0.0' }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec({ name: 'CompactForm' }), 'MJ: Apps', mockProvider());\n\n expect(result.Success).toBe(true);\n expect(result.Mode).toBe('create');\n expect(result.OverrideID).toBe('NEW-OVER');\n expect(result.Version).toBe('1.0.0');\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls).toEqual(['ACT-GET-ACTIVE', 'ACT-CREATE']);\n // Success notification surfaced.\n expect(hoisted.notifications.some(n => n.type === 'success')).toBe(true);\n });\n\n it('existing Active override → calls Modify Interactive Form (Pending sibling produced)', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-MODIFY' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({\n Active: { OverrideID: 'OVER-EXISTING', ComponentID: 'COMP-EXISTING', ComponentVersion: '1.0.0' },\n Variants: [],\n }),\n });\n hoisted.actionResponses.set('ACT-MODIFY', {\n Success: true,\n Message: JSON.stringify({ Mode: 'new-version', ComponentID: 'NEW-COMP', OverrideID: 'NEW-OVER', Version: '1.1.0' }),\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n\n expect(result.Success).toBe(true);\n expect(result.Mode).toBe('modify-new-version');\n expect(result.Version).toBe('1.1.0');\n const calls = hoisted.actionCalls.map(c => c.id);\n expect(calls).toEqual(['ACT-GET-ACTIVE', 'ACT-MODIFY']);\n });\n\n it('Get Active failure short-circuits with an error', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: false,\n Message: 'DB unavailable',\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(result.Message).toMatch(/Could not check for existing override/);\n });\n\n it('failure on the Create action surfaces the error notification', async () => {\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-GET-ACTIVE' }] });\n hoisted.runViewResponses.push({ Success: true, Results: [{ ID: 'ACT-CREATE' }] });\n hoisted.actionResponses.set('ACT-GET-ACTIVE', {\n Success: true,\n Message: JSON.stringify({ Active: null, Variants: [] }),\n });\n hoisted.actionResponses.set('ACT-CREATE', {\n Success: false,\n ResultCode: 'LINT_FAILED',\n Message: 'Spec failed linting.',\n });\n\n const svc = new InteractiveFormApplyService();\n const result = await svc.ConfirmAndApply(spec(), 'MJ: Apps', mockProvider());\n expect(result.Success).toBe(false);\n expect(hoisted.notifications.some(n => n.type === 'error')).toBe(true);\n });\n});\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AfterViewInit, OnInit, OnChanges, SimpleChanges, EventEmitter } from '@angular/core';
|
|
1
|
+
import { AfterViewInit, OnInit, OnChanges, SimpleChanges, EventEmitter, ChangeDetectorRef } from '@angular/core';
|
|
2
2
|
import { BaseArtifactViewerPluginComponent, ArtifactViewerTab } from '../base-artifact-viewer.component';
|
|
3
3
|
import { MJReactComponent, AngularAdapterService } from '@memberjunction/ng-react';
|
|
4
4
|
import { ComponentSpec } from '@memberjunction/interactive-component-types';
|
|
@@ -15,6 +15,7 @@ import * as i0 from "@angular/core";
|
|
|
15
15
|
*/
|
|
16
16
|
export declare class ComponentArtifactViewerComponent extends BaseArtifactViewerPluginComponent implements OnInit, AfterViewInit, OnChanges {
|
|
17
17
|
private adapter;
|
|
18
|
+
private cdr;
|
|
18
19
|
reactComponent?: MJReactComponent;
|
|
19
20
|
tabsChanged: EventEmitter<void>;
|
|
20
21
|
openEntityRecord: EventEmitter<{
|
|
@@ -73,7 +74,7 @@ export declare class ComponentArtifactViewerComponent extends BaseArtifactViewer
|
|
|
73
74
|
* pluginLoaded fires, before React component finishes loading.
|
|
74
75
|
*/
|
|
75
76
|
get hasDisplayContent(): boolean;
|
|
76
|
-
constructor(adapter: AngularAdapterService);
|
|
77
|
+
constructor(adapter: AngularAdapterService, cdr: ChangeDetectorRef);
|
|
77
78
|
ngOnChanges(changes: SimpleChanges): Promise<void>;
|
|
78
79
|
/**
|
|
79
80
|
* Synchronously load the component spec from artifact content.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-artifact-viewer.component.d.ts","sourceRoot":"","sources":["../../../../src/lib/components/plugins/component-artifact-viewer.component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAU,YAAY,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"component-artifact-viewer.component.d.ts","sourceRoot":"","sources":["../../../../src/lib/components/plugins/component-artifact-viewer.component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAU,YAAY,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE/I,OAAO,EAAE,iCAAiC,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACzG,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAA8B,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAExG,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAqB,MAAM,sBAAsB,CAAC;AAE7G,OAAO,EAAgC,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;;AAE7G;;;;;;;GAOG;AACH,qBAOa,gCAAiC,SAAQ,iCAAkC,YAAW,MAAM,EAAE,aAAa,EAAE,SAAS;IA+ErH,OAAO,CAAC,OAAO;IAAyB,OAAO,CAAC,GAAG;IA9ElC,cAAc,CAAC,EAA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,OAAO,CAExC;IAED;;;;;OAKG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAYzB,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAItC;;OAEG;IACI,iBAAiB,IAAI,iBAAiB,EAAE;IA+D/C;;;OAGG;IACI,sBAAsB,IAAI,MAAM,EAAE;IAIzC,OAAO,CAAC,qBAAqB;IAS7B;;;;;;OAMG;IACH,2BAA2B,IAAI,IAAI;IAenC,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAYtC;;;OAGG;IACH,kBAAkB,CAAC,KAAK,EAAE;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,YAAY,CAAA;KAAC,GAAG,IAAI;IAQxD,uBAAuB,IAAI,YAAY,GAAG,IAAI;IA8B9D;;OAEG;IACH,IAAoB,gBAAgB,IAAI,OAAO,CAE9C;IAED;;OAEG;IACa,kBAAkB,IAAI,IAAI;IAgB1C;;;;;OAKG;YACW,yBAAyB;IA+CvC;;;;;OAKG;YACW,gBAAgB;IAqB9B,gFAAgF;YAClE,kBAAkB;IAWhC,mFAAmF;IACnF,OAAO,CAAC,kBAAkB;IAU1B;;;OAGG;IACU,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkC7D,gFAAgF;IACnE,cAAc,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAsB/E,+EAA+E;IACxE,cAAc,IAAI,IAAI;yCA5gBlB,gCAAgC;2CAAhC,gCAAgC;CAmhB5C"}
|
|
@@ -322,6 +322,7 @@ function ComponentArtifactViewerComponent_Conditional_6_Template(rf, ctx) { if (
|
|
|
322
322
|
*/
|
|
323
323
|
let ComponentArtifactViewerComponent = class ComponentArtifactViewerComponent extends BaseArtifactViewerPluginComponent {
|
|
324
324
|
adapter;
|
|
325
|
+
cdr;
|
|
325
326
|
reactComponent;
|
|
326
327
|
tabsChanged = new EventEmitter();
|
|
327
328
|
openEntityRecord = new EventEmitter();
|
|
@@ -384,9 +385,10 @@ let ComponentArtifactViewerComponent = class ComponentArtifactViewerComponent ex
|
|
|
384
385
|
// Use this.component directly - it's available synchronously after loadComponentSpec()
|
|
385
386
|
return !!this.component?.namespace || !!this.component?.code;
|
|
386
387
|
}
|
|
387
|
-
constructor(adapter) {
|
|
388
|
+
constructor(adapter, cdr) {
|
|
388
389
|
super();
|
|
389
390
|
this.adapter = adapter;
|
|
391
|
+
this.cdr = cdr;
|
|
390
392
|
}
|
|
391
393
|
async ngOnChanges(changes) {
|
|
392
394
|
// When artifactVersion input changes, reload the component spec
|
|
@@ -682,6 +684,11 @@ let ComponentArtifactViewerComponent = class ComponentArtifactViewerComponent ex
|
|
|
682
684
|
this.formRecordIsReal = false;
|
|
683
685
|
this.formRecordLabel = 'Mock data';
|
|
684
686
|
}
|
|
687
|
+
// This runs after an await on a RunView that resolves outside Angular's zone,
|
|
688
|
+
// so nothing would refresh the view until the next user event — leaving the
|
|
689
|
+
// "Could not bind a record" message up until the user clicks. Force CD so the
|
|
690
|
+
// auto-loaded record binds and the form mounts immediately on first render.
|
|
691
|
+
this.cdr.detectChanges();
|
|
685
692
|
}
|
|
686
693
|
/**
|
|
687
694
|
* Load the first row by NameField (then __mj_CreatedAt) so different users
|
|
@@ -803,7 +810,7 @@ let ComponentArtifactViewerComponent = class ComponentArtifactViewerComponent ex
|
|
|
803
810
|
entityName: this.formEntityInfo.Name,
|
|
804
811
|
});
|
|
805
812
|
}
|
|
806
|
-
static ɵfac = function ComponentArtifactViewerComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ComponentArtifactViewerComponent)(i0.ɵɵdirectiveInject(i1.AngularAdapterService)); };
|
|
813
|
+
static ɵfac = function ComponentArtifactViewerComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ComponentArtifactViewerComponent)(i0.ɵɵdirectiveInject(i1.AngularAdapterService), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); };
|
|
807
814
|
static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ComponentArtifactViewerComponent, selectors: [["mj-component-artifact-viewer"]], viewQuery: function ComponentArtifactViewerComponent_Query(rf, ctx) { if (rf & 1) {
|
|
808
815
|
i0.ɵɵviewQuery(_c0, 5);
|
|
809
816
|
} if (rf & 2) {
|
|
@@ -830,7 +837,7 @@ export { ComponentArtifactViewerComponent };
|
|
|
830
837
|
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ComponentArtifactViewerComponent, [{
|
|
831
838
|
type: Component,
|
|
832
839
|
args: [{ standalone: false, selector: 'mj-component-artifact-viewer', template: "<div class=\"component-artifact-viewer\" [ngClass]=\"cssClass\">\n <!-- Component Preview (full screen) -->\n <div class=\"component-preview\">\n @if (hasError) {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-triangle\"></i>\n <h3>{{ errorMessage }}</h3>\n <p>This component could not be loaded. This usually happens when:</p>\n <ul style=\"text-align: left; max-width: 500px; color: var(--mj-text-muted); line-height: 1.6;\">\n <li>The component registry is unavailable or unreachable</li>\n <li>The component version does not exist in the registry</li>\n <li>There was a network error during component retrieval</li>\n </ul>\n @if (errorDetails) {\n <details style=\"margin-top: 20px;\">\n <summary>Technical Details</summary>\n <pre>{{ errorDetails }}</pre>\n </details>\n }\n </div>\n } @else if (isFormArtifact) {\n <!-- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n FORM-AWARE BRANCH\n Spec declares componentRole: 'form'. Render via\n <mj-interactive-form> bound to a real Top-1 record\n (or a synthetic NewRecord fallback). Picker chip\n lets the user swap records; Apply promotes the\n spec to an EntityFormOverride.\n \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 -->\n <div class=\"form-artifact-toolstrip\">\n <i class=\"fa-solid fa-circle-info\" aria-hidden=\"true\"></i>\n <span class=\"form-artifact-toolstrip-label\">Previewing record:</span>\n <button\n type=\"button\"\n class=\"form-artifact-picker-chip\"\n (click)=\"showRecordPicker = !showRecordPicker\">\n <i class=\"fa-solid fa-magnifying-glass\"></i>\n <strong>{{ formRecordLabel || 'No record' }}</strong>\n @if (!formRecordIsReal) {\n <span class=\"form-artifact-picker-chip-badge\">Mock</span>\n }\n <i class=\"fa-solid fa-chevron-down\"></i>\n </button>\n @if (formEntityInfo) {\n <span class=\"form-artifact-toolstrip-entity\">{{ formEntityInfo.DisplayName || formEntityInfo.Name }}</span>\n }\n @if (formInitError) {\n <span class=\"form-artifact-toolstrip-warning\" [title]=\"formInitError\">\n <i class=\"fa-solid fa-triangle-exclamation\"></i>\n </span>\n }\n <span style=\"flex: 1;\"></span>\n @if (formEntityInfo) {\n <button\n type=\"button\"\n class=\"form-artifact-apply-btn\"\n (click)=\"onApplyClicked()\">\n <i class=\"fa-solid fa-circle-check\"></i>\n Apply to my form\n </button>\n }\n </div>\n\n @if (showRecordPicker && formEntityInfo) {\n <div class=\"form-artifact-picker-panel\" (click)=\"$event.stopPropagation()\">\n <input\n type=\"text\"\n class=\"form-artifact-picker-search\"\n placeholder=\"Search records by name\u2026\"\n [value]=\"recordSearchTerm\"\n (input)=\"onPickerSearchInput($any($event.target).value)\" />\n @if (recordSearchResults.length > 0) {\n <ul class=\"form-artifact-picker-results\">\n @for (r of recordSearchResults; track r.ID) {\n <li\n class=\"form-artifact-picker-row\"\n (click)=\"onPickerSelect(r)\">\n <i class=\"fa-solid fa-circle-dot\"></i>\n <span>{{ r.Label }}</span>\n </li>\n }\n </ul>\n } @else if (recordSearchTerm.length > 0) {\n <div class=\"form-artifact-picker-empty\">No matches.</div>\n } @else {\n <div class=\"form-artifact-picker-empty\">Start typing to search.</div>\n }\n </div>\n }\n\n @if (formRecord && component) {\n <div class=\"form-artifact-form-host\">\n <mj-interactive-form\n [componentSpec]=\"component\"\n [record]=\"formRecord\">\n </mj-interactive-form>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>Form preview unavailable</h3>\n <p>{{ formInitError || 'Could not bind a record to this form.' }}</p>\n </div>\n }\n } @else if (isPermissionBlocked) {\n <!-- Permission warning \u2014 user lacks access to one or more data sources -->\n <div class=\"permission-warning\">\n <div class=\"permission-warning-icon\">\n <i class=\"fa-solid fa-shield-halved\"></i>\n </div>\n <h3>Insufficient Permissions</h3>\n <p>This component requires data access that you don't currently have:</p>\n\n @if (permissionResult!.missingEntities.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Entities</span>\n <ul>\n @for (entity of permissionResult!.missingEntities; track entity) {\n <li><i class=\"fa-solid fa-table\"></i> {{ entity }}</li>\n }\n </ul>\n </div>\n }\n\n @if (permissionResult!.missingQueries.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Queries</span>\n <ul>\n @for (query of permissionResult!.missingQueries; track query) {\n <li><i class=\"fa-solid fa-database\"></i> {{ query }}</li>\n }\n </ul>\n </div>\n }\n\n <p class=\"permission-warning-hint\">Contact your administrator to request access.</p>\n </div>\n } @else {\n <!-- Default (non-form) interactive component path -->\n @if (component && (component.code || component.namespace)) {\n <mj-react-component\n #reactComponent\n [component]=\"component\"\n (componentEvent)=\"onComponentEvent($event)\"\n (openEntityRecord)=\"onOpenEntityRecord($event)\"\n (initialized)=\"onReactComponentInitialized()\">\n </mj-react-component>\n } @else if (component) {\n <!-- Component spec exists but no code - show informational message -->\n <div class=\"no-code-state\">\n <i class=\"fa-solid fa-file-lines\"></i>\n <h3>Component Specification</h3>\n <p>This component has specifications but no executable code yet.</p>\n <p>View the Functional, Data, or Spec tabs for details.</p>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>No Component Loaded</h3>\n <p>The component data is missing or invalid.</p>\n </div>\n }\n }\n </div>\n\n <!-- Feedback overlay panel (invoked from header button via AskUserForFeedback) -->\n @if (ShowFeedbackPanel && resolvedComponentSpec) {\n <mj-component-feedback-panel\n [ComponentSpec]=\"resolvedComponentSpec\"\n [ReactContainerElement]=\"reactComponent?.container?.nativeElement || null\"\n (Closed)=\"ShowFeedbackPanel = false\">\n </mj-component-feedback-panel>\n }\n</div>\n", styles: [".component-artifact-viewer {\n display: flex;\n flex-direction: column;\n height: 100%;\n width: 100%;\n background: var(--mj-bg-surface);\n}\n\n.component-preview {\n flex: 1;\n padding: 15px;\n overflow: auto;\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n\n/* Ensure React component takes full height */\n.component-preview mj-react-component {\n flex: 1;\n min-height: 0;\n display: flex;\n flex-direction: column;\n}\n\n.error-state {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px;\n text-align: center;\n color: var(--mj-status-error);\n flex: 1;\n min-height: 300px;\n}\n.error-state i {\n font-size: 48px;\n margin-bottom: 16px;\n}\n.error-state h3 {\n margin: 0 0 8px 0;\n font-size: 20px;\n}\n.error-state p {\n margin: 0 0 12px 0;\n color: var(--mj-text-muted);\n}\n.error-state details {\n margin-top: 16px;\n text-align: left;\n max-width: 600px;\n}\n.error-state details summary {\n cursor: pointer;\n color: var(--mj-text-secondary);\n font-weight: 500;\n margin-bottom: 8px;\n}\n.error-state details summary:hover {\n color: var(--mj-text-primary);\n}\n.error-state details pre {\n background: var(--mj-bg-surface-sunken);\n padding: 12px;\n border-radius: 4px;\n overflow-x: auto;\n font-size: 12px;\n color: var(--mj-text-secondary);\n margin: 0;\n}\n\n/* State for component spec without executable code */\n.no-code-state {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px;\n text-align: center;\n color: var(--mj-text-muted);\n flex: 1;\n}\n.no-code-state i {\n font-size: 48px;\n margin-bottom: 16px;\n color: var(--mj-brand-primary);\n}\n.no-code-state h3 {\n margin: 0 0 8px 0;\n font-size: 20px;\n color: var(--mj-text-secondary);\n}\n.no-code-state p {\n margin: 0 0 8px 0;\n color: var(--mj-text-muted);\n}\n\n\n/* ====================================================================\n FORM-AWARE BRANCH (componentRole === 'form')\n Top strip: record-picker chip + Apply button.\n Below: dropdown picker panel.\n Below: <mj-interactive-form> bound to the picked record.\n ==================================================================== */\n\n.form-artifact-toolstrip {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 8px 14px;\n background: var(--mj-bg-surface-card);\n border-bottom: 1px solid var(--mj-border-default);\n font-size: 12px;\n color: var(--mj-text-secondary);\n}\n.form-artifact-toolstrip-label {\n font-weight: 600;\n}\n.form-artifact-toolstrip-entity {\n margin-left: 4px;\n padding: 2px 8px;\n background: color-mix(in srgb, var(--mj-brand-primary) 10%, var(--mj-bg-surface));\n color: var(--mj-brand-primary);\n border: 1px solid color-mix(in srgb, var(--mj-brand-primary) 30%, var(--mj-bg-surface));\n border-radius: 999px;\n font-size: 11px;\n font-weight: 600;\n}\n.form-artifact-toolstrip-warning {\n color: var(--mj-status-warning-text);\n}\n\n.form-artifact-picker-chip {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n background: var(--mj-bg-surface);\n border: 1px solid var(--mj-border-default);\n border-radius: var(--mj-radius-md, 8px);\n padding: 4px 10px;\n font-size: 12px;\n color: var(--mj-text-primary);\n cursor: pointer;\n}\n.form-artifact-picker-chip:hover,\n.form-artifact-picker-chip:focus {\n border-color: var(--mj-border-focus);\n outline: none;\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mj-brand-primary) 15%, transparent);\n}\n.form-artifact-picker-chip strong {\n color: var(--mj-text-primary);\n font-weight: 600;\n}\n.form-artifact-picker-chip-badge {\n background: var(--mj-status-warning-bg);\n color: var(--mj-status-warning-text);\n border: 1px solid var(--mj-status-warning-border);\n font-size: 10px;\n font-weight: 700;\n padding: 1px 6px;\n border-radius: 999px;\n}\n\n.form-artifact-apply-btn {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n background: var(--mj-brand-primary);\n color: var(--mj-text-inverse, #ffffff);\n border: 1px solid var(--mj-brand-primary);\n border-radius: var(--mj-radius-md, 8px);\n padding: 5px 12px;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n}\n.form-artifact-apply-btn:hover {\n background: var(--mj-brand-primary-hover, var(--mj-brand-primary));\n}\n\n.form-artifact-picker-panel {\n background: var(--mj-bg-surface);\n border-bottom: 1px solid var(--mj-border-default);\n padding: 10px 14px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.form-artifact-picker-search {\n width: 100%;\n padding: 7px 10px;\n border: 1px solid var(--mj-border-default);\n border-radius: var(--mj-radius-md, 8px);\n background: var(--mj-bg-surface);\n font-size: 13px;\n color: var(--mj-text-primary);\n}\n.form-artifact-picker-search:focus {\n outline: none;\n border-color: var(--mj-border-focus);\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mj-brand-primary) 15%, transparent);\n}\n.form-artifact-picker-results {\n list-style: none;\n margin: 0;\n padding: 0;\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n.form-artifact-picker-row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 8px;\n border-radius: 6px;\n cursor: pointer;\n font-size: 13px;\n}\n.form-artifact-picker-row:hover {\n background: var(--mj-bg-surface-hover);\n}\n.form-artifact-picker-row i {\n color: var(--mj-text-muted);\n font-size: 10px;\n}\n.form-artifact-picker-empty {\n color: var(--mj-text-muted);\n font-size: 12px;\n font-style: italic;\n}\n\n.form-artifact-form-host {\n flex: 1;\n overflow: auto;\n background: var(--mj-bg-page);\n}\n\n/* ====================================================================\n PERMISSION WARNING\n Shown before rendering when the user lacks read access to one or\n more entities/queries required by the component.\n ==================================================================== */\n\n.permission-warning {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px;\n text-align: center;\n flex: 1;\n min-height: 300px;\n}\n.permission-warning-icon {\n font-size: 48px;\n margin-bottom: 16px;\n color: var(--mj-status-warning-text, #b45309);\n}\n.permission-warning h3 {\n margin: 0 0 8px 0;\n font-size: 20px;\n color: var(--mj-text-primary);\n}\n.permission-warning > p {\n margin: 0 0 16px 0;\n color: var(--mj-text-muted);\n}\n.permission-warning-section {\n text-align: left;\n max-width: 400px;\n width: 100%;\n margin-bottom: 12px;\n}\n.permission-warning-section-label {\n display: block;\n font-size: 11px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--mj-text-muted);\n margin-bottom: 4px;\n}\n.permission-warning-section ul {\n list-style: none;\n margin: 0;\n padding: 0;\n display: flex;\n flex-direction: column;\n gap: 4px;\n}\n.permission-warning-section li {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 10px;\n font-size: 13px;\n color: var(--mj-text-primary);\n background: var(--mj-bg-surface-sunken, var(--mj-bg-surface));\n border-radius: 6px;\n}\n.permission-warning-section li i {\n color: var(--mj-status-warning-text, #b45309);\n font-size: 12px;\n}\n.permission-warning-hint {\n margin-top: 8px;\n font-size: 12px;\n color: var(--mj-text-muted);\n}\n"] }]
|
|
833
|
-
}], () => [{ type: i1.AngularAdapterService }], { reactComponent: [{
|
|
840
|
+
}], () => [{ type: i1.AngularAdapterService }, { type: i0.ChangeDetectorRef }], { reactComponent: [{
|
|
834
841
|
type: ViewChild,
|
|
835
842
|
args: ['reactComponent']
|
|
836
843
|
}], tabsChanged: [{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-artifact-viewer.component.js","sourceRoot":"","sources":["../../../../src/lib/components/plugins/component-artifact-viewer.component.ts","../../../../src/lib/components/plugins/component-artifact-viewer.component.html"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAmD,MAAM,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC5H,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,iCAAiC,EAAqB,MAAM,mCAAmC,CAAC;AAEzG,OAAO,EAAE,0BAA0B,EAAiB,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAAE,UAAU,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC1G,OAAO,EAAc,YAAY,EAAE,YAAY,EAAc,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAAE,4BAA4B,EAA8B,MAAM,mCAAmC,CAAC;;;;;;;;;ICOjG,AADF,kCAAmC,cACxB;IAAA,iCAAiB;IAAA,iBAAU;IACpC,2BAAK;IAAA,YAAkB;IACzB,AADyB,iBAAM,EACrB;;;IADH,eAAkB;IAAlB,yCAAkB;;;IAZ7B,8BAAyB;IACvB,uBAAgD;IAChD,0BAAI;IAAA,YAAkB;IAAA,iBAAK;IAC3B,yBAAG;IAAA,8EAA8D;IAAA,iBAAI;IAEnE,AADF,6BAA+F,SACzF;IAAA,oEAAoD;IAAA,iBAAK;IAC7D,0BAAI;IAAA,qEAAoD;IAAA,iBAAK;IAC7D,2BAAI;IAAA,qEAAoD;IAC1D,AAD0D,iBAAK,EAC1D;IACL,sHAAoB;IAMtB,iBAAM;;;IAbA,eAAkB;IAAlB,yCAAkB;IAOtB,gBAKC;IALD,+CAKC;;;IAqBG,gCAA8C;IAAA,oBAAI;IAAA,iBAAO;;;IAK3D,gCAA6C;IAAA,YAAuD;IAAA,iBAAO;;;IAA9D,cA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6BACI,KAAK,YACP,8BAA8B;;kBAMvC,SAAS;mBAAC,gBAAgB;;kBAC1B,MAAM;;kBACN,MAAM;;kBAQN,MAAM;;kFAXI,gCAAgC","sourcesContent":["import { Component, ViewChild, AfterViewInit, OnInit, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';\nimport { RegisterClass, SafeJSONParse } from '@memberjunction/global';\nimport { BaseArtifactViewerPluginComponent, ArtifactViewerTab } from '../base-artifact-viewer.component';\nimport { MJReactComponent, AngularAdapterService } from '@memberjunction/ng-react';\nimport { BuildComponentCompleteCode, ComponentSpec } from '@memberjunction/interactive-component-types';\nimport { isFormRole, getDeclaredFormEntityName } from '@memberjunction/interactive-component-types/forms';\nimport { BaseEntity, CompositeKey, DataSnapshot, EntityInfo, LogError, RunView } from '@memberjunction/core';\nimport { DataRequirementsViewerComponent } from './data-requirements-viewer/data-requirements-viewer.component';\nimport { evaluateComponentPermissions, PermissionEvaluationResult } from './component-permission-evaluation';\n\n/**\n * Viewer component for interactive Component artifacts (React-based UI components)\n *\n * Features:\n * - Live component preview with React rendering\n * - Dynamic tabs for component metadata (via GetAdditionalTabs)\n * - Provides tabs for: Code, Functional Requirements, Technical Design, Data Requirements\n */\n@Component({\n standalone: false,\n selector: 'mj-component-artifact-viewer',\n templateUrl: './component-artifact-viewer.component.html',\n styleUrls: ['./component-artifact-viewer.component.css']\n})\n@RegisterClass(BaseArtifactViewerPluginComponent, 'ComponentArtifactViewerPlugin')\nexport class ComponentArtifactViewerComponent extends BaseArtifactViewerPluginComponent implements OnInit, AfterViewInit, OnChanges {\n @ViewChild('reactComponent') reactComponent?: MJReactComponent;\n @Output() tabsChanged = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{entityName: string; compositeKey: CompositeKey}>();\n\n /**\n * Emitted when the user clicks \"Apply to my form\" on a form-role artifact.\n * Carries the spec (ready to hand to the agent's Create/Modify action) and\n * the entity name. The host is responsible for confirming + invoking the\n * actual server action.\n */\n @Output() applyFormRequested = new EventEmitter<{ spec: ComponentSpec; entityName: string }>();\n\n // ── Form-aware state (only populated when componentRole === 'form') ──\n\n /** True when this artifact's spec declares `componentRole: 'form'`. */\n public isFormArtifact = false;\n\n /** Entity the form targets — resolved from spec.entityName / dataRequirements. */\n public formEntityInfo: EntityInfo | null = null;\n\n /** The real or fixture record currently bound to the form preview. */\n public formRecord: BaseEntity | null = null;\n\n /** True iff `formRecord` is a real DB row (vs a fixture NewRecord()). */\n public formRecordIsReal = false;\n\n /** Label for the chip (e.g. the record's Name field). */\n public formRecordLabel = '';\n\n /** Picker UI state. */\n public showRecordPicker = false;\n public recordSearchTerm = '';\n public recordSearchResults: Array<{ ID: string; Label: string }> = [];\n public formInitError: string | null = null;\n\n // Component data\n public component: ComponentSpec | null = null;\n public componentCode: string = \"\";\n public componentName: string = '';\n\n /**\n * Cached resolved spec from the registry, preserved even after the React component\n * is destroyed (e.g., when a render error removes <mj-react-component> from the DOM).\n */\n private _cachedResolvedSpec: ComponentSpec | null = null;\n\n public get resolvedComponentSpec(): ComponentSpec | null {\n // Prefer the live React component's resolved spec (most up-to-date),\n // then fall back to our cached copy (survives DOM destruction),\n // then fall back to the stripped local spec as last resort.\n return this.reactComponent?.resolvedComponentSpec || this._cachedResolvedSpec || this.component;\n }\n\n // Feedback panel\n public ShowFeedbackPanel = false;\n\n // Error state\n public hasError = false;\n public errorMessage = '';\n public errorDetails = '';\n\n // Permission state\n public permissionResult: PermissionEvaluationResult | null = null;\n\n /**\n * Whether this plugin has content to display in the Display tab.\n * Returns true only if the component has code that can be rendered.\n *\n * IMPORTANT: Uses this.component (synchronously loaded from artifact JSON)\n * instead of resolvedComponentSpec (which depends on async React loading).\n * This ensures hasDisplayContent returns correct value immediately when\n * pluginLoaded fires, before React component finishes loading.\n */\n public override get hasDisplayContent(): boolean {\n // Use this.component directly - it's available synchronously after loadComponentSpec()\n return !!this.component?.namespace || !!this.component?.code\n }\n\n constructor(private adapter: AngularAdapterService) {\n super();\n }\n\n async ngOnChanges(changes: SimpleChanges): Promise<void> {\n // When artifactVersion input changes, reload the component spec\n if (changes['artifactVersion']) {\n this.loadComponentSpec();\n // Notify parent that tabs may have changed (on subsequent changes)\n if (!changes['artifactVersion'].firstChange) {\n this.tabsChanged.emit();\n }\n }\n }\n\n /**\n * Synchronously load the component spec from artifact content.\n * This is intentionally synchronous so that tabs are available immediately\n * when the parent queries GetAdditionalTabs() after pluginLoaded fires.\n *\n * The bridge purges the runtime registry + manager fetch cache itself when\n * it (re)initializes for the new spec, so we don't need to clear caches\n * from here — the bridge instance may not even exist yet when ngOnChanges\n * fires for the first time.\n */\n private loadComponentSpec(): void {\n try {\n // Clear cached resolved spec from previous version so stale data doesn't persist\n this._cachedResolvedSpec = null;\n this.permissionResult = null;\n\n if (this.artifactVersion?.Content) {\n this.component = SafeJSONParse(this.artifactVersion.Content) as ComponentSpec;\n this.extractComponentParts();\n this.evaluatePermissions();\n // Form-aware detection. Done here (not in ngAfterViewInit) so the\n // template's `@if (isFormArtifact)` branch decides which preview\n // to mount on the very first render — no flash of the non-form\n // path before the form-aware UI takes over.\n this.detectAndInitFormArtifact();\n } else {\n throw new Error('Artifact content is empty');\n }\n } catch (error) {\n console.error('Failed to load component spec:', error);\n this.hasError = true;\n this.errorMessage = 'Failed to load component';\n this.errorDetails = error instanceof Error ? error.message : String(error);\n }\n }\n\n /**\n * Evaluate whether the current user has sufficient permissions for\n * all entities and queries referenced in the component's dataRequirements.\n * Uses the best available spec: resolved (from registry) > cached > stripped artifact.\n * Runs synchronously against already-loaded client-side metadata.\n */\n private evaluatePermissions(): void {\n const spec = this.resolvedComponentSpec;\n if (!spec) return;\n\n const provider = this.ProviderToUse;\n const currentUser = provider.CurrentUser;\n if (!currentUser) return; // No user context — skip check\n\n this.permissionResult = evaluateComponentPermissions(spec, currentUser, provider);\n }\n\n /** Whether the component should be blocked from rendering due to missing permissions. */\n public get isPermissionBlocked(): boolean {\n return !!this.permissionResult && !this.permissionResult.canRun;\n }\n\n /**\n * Component initialization.\n * Note: loadComponentSpec() is called in ngOnChanges which runs before ngOnInit,\n * ensuring tabs are available when pluginLoaded fires.\n * The async adapter initialization happens here and doesn't block tab availability.\n */\n async ngOnInit(): Promise<void> {\n // Initialize Angular adapter for React components (async operation)\n try {\n await this.adapter.initialize();\n } catch (error) {\n console.error('Failed to initialize Angular adapter:', error);\n this.hasError = true;\n this.errorMessage = 'Failed to initialize component runtime';\n this.errorDetails = error instanceof Error ? error.message : String(error);\n }\n }\n\n async ngAfterViewInit(): Promise<void> {\n // Component initialization happens automatically via mj-react-component\n }\n\n /**\n * Provide additional tabs for viewing component metadata\n */\n public GetAdditionalTabs(): ArtifactViewerTab[] {\n const tabs: ArtifactViewerTab[] = [];\n\n const resolvedComponent = this.resolvedComponentSpec;\n\n if (!resolvedComponent) {\n return tabs;\n }\n\n // Functional Requirements tab\n if (resolvedComponent.functionalRequirements) {\n tabs.push({\n label: 'Functional',\n icon: 'fa-clipboard-list',\n contentType: 'markdown',\n content: resolvedComponent.functionalRequirements\n });\n }\n\n // Technical Design tab\n if (resolvedComponent.technicalDesign) {\n tabs.push({\n label: 'Technical',\n icon: 'fa-wrench',\n contentType: 'markdown',\n content: resolvedComponent.technicalDesign\n });\n }\n\n // Data Requirements tab - uses custom component for rich visualization\n if (resolvedComponent.dataRequirements) {\n tabs.push({\n label: 'Data',\n icon: 'fa-database',\n contentType: 'component',\n component: DataRequirementsViewerComponent,\n componentInputs: { dataRequirements: resolvedComponent.dataRequirements }\n });\n }\n\n // Code tab (lazy-loaded) - only show if there's actual code\n if (resolvedComponent.code && resolvedComponent.code.trim()) {\n tabs.push({\n label: 'Code',\n icon: 'fa-code',\n contentType: 'code',\n language: 'typescript',\n content: () => BuildComponentCompleteCode(resolvedComponent)\n });\n }\n\n // Spec tab - Shows fully resolved component spec in JSON format (rightmost)\n tabs.push({\n label: 'Spec',\n icon: 'fa-file-code',\n contentType: 'json',\n content: () => JSON.stringify(resolvedComponent, null, 2),\n language: 'json'\n });\n\n return tabs;\n }\n\n /**\n * Remove standard JSON tab since we provide \"Resolved JSON\" custom tab\n * The custom tab shows the fully resolved component spec instead of raw artifact JSON\n */\n public GetStandardTabRemovals(): string[] {\n return ['JSON'];\n }\n\n private extractComponentParts(): void {\n if (this.resolvedComponentSpec?.name) {\n this.componentName = this.resolvedComponentSpec.name;\n }\n if (this.resolvedComponentSpec?.code) {\n this.componentCode = BuildComponentCompleteCode(this.resolvedComponentSpec);\n }\n }\n\n /**\n * Called when MJReactComponent finishes loading the full component spec from the registry.\n * The full spec may contain Functional, Technical, and Data tabs not in the stripped spec.\n * Caches the resolved spec so it survives DOM destruction (e.g., if the component fails to\n * render and <mj-react-component> is removed by the @if/else block).\n * Emits tabsChanged so the parent panel re-evaluates allTabs and renders the new tab labels.\n */\n onReactComponentInitialized(): void {\n if (this.reactComponent?.resolvedComponentSpec &&\n this.reactComponent.resolvedComponentSpec !== this.component) {\n // Cache the resolved spec so it's available even after the React component is destroyed\n this._cachedResolvedSpec = this.reactComponent.resolvedComponentSpec;\n this.tabsChanged.emit();\n\n // Re-evaluate permissions against the resolved spec — the stripped artifact\n // spec has no dataRequirements, so the initial check in loadComponentSpec()\n // passes trivially. The resolved spec from the registry contains the full\n // dataRequirements with entity and query references.\n this.evaluatePermissions();\n }\n }\n\n onComponentEvent(event: unknown): void {\n console.log('Component event:', event);\n\n // Handle error events from React component\n if (event && typeof event === 'object' && 'type' in event && event.type === 'error') {\n const errorEvent = event as { type: 'error'; payload: { error: string; source: string } };\n this.hasError = true;\n this.errorMessage = 'Component Failed to Load';\n this.errorDetails = errorEvent.payload.error || 'Unknown error occurred while loading the component';\n }\n }\n\n /**\n * Handle entity record open request from React component\n * Propagates the event up to parent components\n */\n onOpenEntityRecord(event: {entityName: string; key: CompositeKey}): void {\n // Transform to use 'compositeKey' name for consistency with Angular components\n this.openEntityRecord.emit({\n entityName: event.entityName,\n compositeKey: event.key\n });\n }\n\n public override GetCurrentStateSnapshot(): DataSnapshot | null {\n // First try the component's explicit or auto-captured data state.\n // MJReactComponent.getCurrentDataState() already includes the fallback\n // to intercepted RunView/RunQuery results when the React component\n // doesn't register getCurrentDataState() via callbacks.RegisterMethod.\n const dataState = this.reactComponent?.getCurrentDataState?.();\n if (dataState && typeof dataState === 'object') {\n return dataState as DataSnapshot;\n }\n\n // Fallback for components with no captured data — static mockups,\n // pure-display components, or components whose data hooks haven't fired.\n // Rather than short-circuit Analyze with \"No data available\", emit a\n // minimal snapshot so the user can still open an agent conversation about\n // the component. The artifact itself is attached to the conversation as an\n // Input junction, so the agent can reason from the spec + any static data\n // baked into the component code.\n const spec = this.resolvedComponentSpec;\n if (!spec) return null;\n\n const snap = new DataSnapshot();\n snap.title = spec.title || spec.name || this.getDisplayTitle() || undefined;\n snap.interpretation =\n `Interactive component artifact${spec.name ? ` \"${spec.name}\"` : ''}. ` +\n `No live data was captured — the component either has no data-fetching ` +\n `hooks or has not yet run its queries. The component specification is ` +\n `attached to this conversation; the agent should inspect it directly.`;\n return snap;\n }\n\n /**\n * Component artifacts support feedback when a resolved spec is available.\n */\n public override get SupportsFeedback(): boolean {\n return !!this.resolvedComponentSpec;\n }\n\n /**\n * Toggle the feedback panel open. Called from the artifact viewer header button.\n */\n public override AskUserForFeedback(): void {\n this.ShowFeedbackPanel = !this.ShowFeedbackPanel;\n }\n\n // ════════════════════════════════════════════════════════════════════\n // FORM-AWARE BRANCH\n //\n // When the artifact's spec declares `componentRole: 'form'`, the viewer\n // delegates rendering to `<mj-interactive-form>` instead of the raw\n // `<mj-react-component>` path. This gives the React form a proper\n // FormHostProps binding (bound to a real DB record by default) and lets\n // the user swap records via a search picker before applying.\n //\n // Triggered from `loadComponentSpec()` after the spec parses.\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Detect form-role and kick off entity + record resolution. Failure modes\n * (missing entity, RunView failure, entity has no rows) fall back to a\n * synthetic record from `BaseEntity.NewRecord()` so the form still mounts\n * against type-appropriate empty values.\n */\n private async detectAndInitFormArtifact(): Promise<void> {\n this.isFormArtifact = false;\n this.formEntityInfo = null;\n this.formRecord = null;\n this.formRecordIsReal = false;\n this.formRecordLabel = '';\n this.formInitError = null;\n\n const spec = this.component;\n if (!spec || !isFormRole(spec)) return;\n\n this.isFormArtifact = true;\n\n const entityName = getDeclaredFormEntityName(spec);\n if (!entityName) {\n this.formInitError = 'Form artifact has no declared entity. Showing without record context.';\n return;\n }\n\n const provider = this.ProviderToUse;\n const entity = provider?.EntityByName(entityName);\n if (!entity) {\n this.formInitError = `Entity \"${entityName}\" not registered with the active provider.`;\n return;\n }\n this.formEntityInfo = entity;\n\n // Load Top-1 record by default. If empty / fails, fall back to a fresh\n // synthetic record. Either way the form mounts — failure to find a real\n // record is informational, not fatal.\n const record = await this.loadTopOneRecord(entity);\n if (record) {\n this.formRecord = record;\n this.formRecordIsReal = true;\n this.formRecordLabel = this.computeRecordLabel(record);\n } else {\n this.formRecord = await this.buildFixtureRecord(entity);\n this.formRecordIsReal = false;\n this.formRecordLabel = 'Mock data';\n }\n }\n\n /**\n * Load the first row by NameField (then __mj_CreatedAt) so different users\n * opening the same form-role artifact see the same record bound to the\n * preview. (Retrospective fix #7 — un-ordered Top-1 was physical-order\n * and non-deterministic.)\n */\n private async loadTopOneRecord(entity: EntityInfo): Promise<BaseEntity | null> {\n try {\n const orderBy = entity.NameField?.Name\n ? `${entity.NameField.Name} ASC`\n : `__mj_CreatedAt DESC`;\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n const result = await rv.RunView<BaseEntity>({\n EntityName: entity.Name,\n MaxRows: 1,\n OrderBy: orderBy,\n ResultType: 'entity_object',\n }, this.ProviderToUse.CurrentUser);\n if (result.Success && (result.Results?.length ?? 0) > 0) {\n return result.Results[0];\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: Top-1 RunView failed for ${entity.Name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n return null;\n }\n\n /** Synthetic \"create-mode\" record when no real row exists or RunView failed. */\n private async buildFixtureRecord(entity: EntityInfo): Promise<BaseEntity | null> {\n try {\n const fresh = await this.ProviderToUse.GetEntityObject<BaseEntity>(entity.Name, this.ProviderToUse.CurrentUser);\n fresh.NewRecord();\n return fresh;\n } catch (err) {\n LogError(`ComponentArtifactViewer: failed to build fixture record for ${entity.Name}: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n }\n\n /** Pull a human-readable label from the record's NameField or first text field. */\n private computeRecordLabel(record: BaseEntity): string {\n const nameField = record.EntityInfo.NameField?.Name;\n if (nameField) {\n const v = record.Get(nameField);\n if (v != null && String(v).trim().length > 0) return String(v);\n }\n if (record.PrimaryKey?.HasValue) return record.PrimaryKey.ToConcatenatedString();\n return record.EntityInfo.Name;\n }\n\n /**\n * Search-as-you-type for the picker. Queries by name field (or any\n * indexed string field, best-effort). Limits to 8 hits for tightness.\n */\n public async onPickerSearchInput(term: string): Promise<void> {\n this.recordSearchTerm = term;\n if (!this.formEntityInfo || term.trim().length === 0) {\n this.recordSearchResults = [];\n return;\n }\n const nameField = this.formEntityInfo.NameField?.Name;\n if (!nameField) {\n this.recordSearchResults = [];\n return;\n }\n try {\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n // Best-effort LIKE filter against the entity's name field. Wrap the\n // term so we don't break SQL — RunView passes ExtraFilter as-is.\n const safe = term.replace(/'/g, \"''\");\n const result = await rv.RunView<BaseEntity>({\n EntityName: this.formEntityInfo.Name,\n ExtraFilter: `${nameField} LIKE '%${safe}%'`,\n MaxRows: 8,\n ResultType: 'entity_object',\n }, this.ProviderToUse.CurrentUser);\n if (result.Success) {\n this.recordSearchResults = (result.Results ?? []).map(r => ({\n ID: r.PrimaryKey?.ToConcatenatedString() ?? '',\n Label: this.computeRecordLabel(r),\n }));\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: picker search failed: ${err instanceof Error ? err.message : String(err)}`);\n this.recordSearchResults = [];\n }\n }\n\n /** User picked a different record from the search results. Re-bind the form. */\n public async onPickerSelect(item: { ID: string; Label: string }): Promise<void> {\n if (!this.formEntityInfo) return;\n try {\n const rec = await this.ProviderToUse.GetEntityObject<BaseEntity>(\n this.formEntityInfo.Name, this.ProviderToUse.CurrentUser,\n );\n const pk = new CompositeKey();\n pk.LoadFromURLSegment(this.formEntityInfo, item.ID);\n const loaded = await rec.InnerLoad(pk);\n if (loaded) {\n this.formRecord = rec;\n this.formRecordIsReal = true;\n this.formRecordLabel = item.Label;\n this.showRecordPicker = false;\n this.recordSearchTerm = '';\n this.recordSearchResults = [];\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: failed to load picked record ${item.ID}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n /** Bubble Apply intent up to the host (Form Builder dashboard / Sage chat). */\n public onApplyClicked(): void {\n if (!this.component || !this.formEntityInfo) return;\n this.applyFormRequested.emit({\n spec: this.component,\n entityName: this.formEntityInfo.Name,\n });\n }\n}\n","<div class=\"component-artifact-viewer\" [ngClass]=\"cssClass\">\n <!-- Component Preview (full screen) -->\n <div class=\"component-preview\">\n @if (hasError) {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-triangle\"></i>\n <h3>{{ errorMessage }}</h3>\n <p>This component could not be loaded. This usually happens when:</p>\n <ul style=\"text-align: left; max-width: 500px; color: var(--mj-text-muted); line-height: 1.6;\">\n <li>The component registry is unavailable or unreachable</li>\n <li>The component version does not exist in the registry</li>\n <li>There was a network error during component retrieval</li>\n </ul>\n @if (errorDetails) {\n <details style=\"margin-top: 20px;\">\n <summary>Technical Details</summary>\n <pre>{{ errorDetails }}</pre>\n </details>\n }\n </div>\n } @else if (isFormArtifact) {\n <!-- ════════════════════════════════════════════════\n FORM-AWARE BRANCH\n Spec declares componentRole: 'form'. Render via\n <mj-interactive-form> bound to a real Top-1 record\n (or a synthetic NewRecord fallback). Picker chip\n lets the user swap records; Apply promotes the\n spec to an EntityFormOverride.\n ════════════════════════════════════════════════ -->\n <div class=\"form-artifact-toolstrip\">\n <i class=\"fa-solid fa-circle-info\" aria-hidden=\"true\"></i>\n <span class=\"form-artifact-toolstrip-label\">Previewing record:</span>\n <button\n type=\"button\"\n class=\"form-artifact-picker-chip\"\n (click)=\"showRecordPicker = !showRecordPicker\">\n <i class=\"fa-solid fa-magnifying-glass\"></i>\n <strong>{{ formRecordLabel || 'No record' }}</strong>\n @if (!formRecordIsReal) {\n <span class=\"form-artifact-picker-chip-badge\">Mock</span>\n }\n <i class=\"fa-solid fa-chevron-down\"></i>\n </button>\n @if (formEntityInfo) {\n <span class=\"form-artifact-toolstrip-entity\">{{ formEntityInfo.DisplayName || formEntityInfo.Name }}</span>\n }\n @if (formInitError) {\n <span class=\"form-artifact-toolstrip-warning\" [title]=\"formInitError\">\n <i class=\"fa-solid fa-triangle-exclamation\"></i>\n </span>\n }\n <span style=\"flex: 1;\"></span>\n @if (formEntityInfo) {\n <button\n type=\"button\"\n class=\"form-artifact-apply-btn\"\n (click)=\"onApplyClicked()\">\n <i class=\"fa-solid fa-circle-check\"></i>\n Apply to my form\n </button>\n }\n </div>\n\n @if (showRecordPicker && formEntityInfo) {\n <div class=\"form-artifact-picker-panel\" (click)=\"$event.stopPropagation()\">\n <input\n type=\"text\"\n class=\"form-artifact-picker-search\"\n placeholder=\"Search records by name…\"\n [value]=\"recordSearchTerm\"\n (input)=\"onPickerSearchInput($any($event.target).value)\" />\n @if (recordSearchResults.length > 0) {\n <ul class=\"form-artifact-picker-results\">\n @for (r of recordSearchResults; track r.ID) {\n <li\n class=\"form-artifact-picker-row\"\n (click)=\"onPickerSelect(r)\">\n <i class=\"fa-solid fa-circle-dot\"></i>\n <span>{{ r.Label }}</span>\n </li>\n }\n </ul>\n } @else if (recordSearchTerm.length > 0) {\n <div class=\"form-artifact-picker-empty\">No matches.</div>\n } @else {\n <div class=\"form-artifact-picker-empty\">Start typing to search.</div>\n }\n </div>\n }\n\n @if (formRecord && component) {\n <div class=\"form-artifact-form-host\">\n <mj-interactive-form\n [componentSpec]=\"component\"\n [record]=\"formRecord\">\n </mj-interactive-form>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>Form preview unavailable</h3>\n <p>{{ formInitError || 'Could not bind a record to this form.' }}</p>\n </div>\n }\n } @else if (isPermissionBlocked) {\n <!-- Permission warning — user lacks access to one or more data sources -->\n <div class=\"permission-warning\">\n <div class=\"permission-warning-icon\">\n <i class=\"fa-solid fa-shield-halved\"></i>\n </div>\n <h3>Insufficient Permissions</h3>\n <p>This component requires data access that you don't currently have:</p>\n\n @if (permissionResult!.missingEntities.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Entities</span>\n <ul>\n @for (entity of permissionResult!.missingEntities; track entity) {\n <li><i class=\"fa-solid fa-table\"></i> {{ entity }}</li>\n }\n </ul>\n </div>\n }\n\n @if (permissionResult!.missingQueries.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Queries</span>\n <ul>\n @for (query of permissionResult!.missingQueries; track query) {\n <li><i class=\"fa-solid fa-database\"></i> {{ query }}</li>\n }\n </ul>\n </div>\n }\n\n <p class=\"permission-warning-hint\">Contact your administrator to request access.</p>\n </div>\n } @else {\n <!-- Default (non-form) interactive component path -->\n @if (component && (component.code || component.namespace)) {\n <mj-react-component\n #reactComponent\n [component]=\"component\"\n (componentEvent)=\"onComponentEvent($event)\"\n (openEntityRecord)=\"onOpenEntityRecord($event)\"\n (initialized)=\"onReactComponentInitialized()\">\n </mj-react-component>\n } @else if (component) {\n <!-- Component spec exists but no code - show informational message -->\n <div class=\"no-code-state\">\n <i class=\"fa-solid fa-file-lines\"></i>\n <h3>Component Specification</h3>\n <p>This component has specifications but no executable code yet.</p>\n <p>View the Functional, Data, or Spec tabs for details.</p>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>No Component Loaded</h3>\n <p>The component data is missing or invalid.</p>\n </div>\n }\n }\n </div>\n\n <!-- Feedback overlay panel (invoked from header button via AskUserForFeedback) -->\n @if (ShowFeedbackPanel && resolvedComponentSpec) {\n <mj-component-feedback-panel\n [ComponentSpec]=\"resolvedComponentSpec\"\n [ReactContainerElement]=\"reactComponent?.container?.nativeElement || null\"\n (Closed)=\"ShowFeedbackPanel = false\">\n </mj-component-feedback-panel>\n }\n</div>\n"]}
|
|
1
|
+
{"version":3,"file":"component-artifact-viewer.component.js","sourceRoot":"","sources":["../../../../src/lib/components/plugins/component-artifact-viewer.component.ts","../../../../src/lib/components/plugins/component-artifact-viewer.component.html"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAmD,MAAM,EAAE,YAAY,EAAqB,MAAM,eAAe,CAAC;AAC/I,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,iCAAiC,EAAqB,MAAM,mCAAmC,CAAC;AAEzG,OAAO,EAAE,0BAA0B,EAAiB,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAAE,UAAU,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC1G,OAAO,EAAc,YAAY,EAAE,YAAY,EAAc,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAAE,4BAA4B,EAA8B,MAAM,mCAAmC,CAAC;;;;;;;;;ICOjG,AADF,kCAAmC,cACxB;IAAA,iCAAiB;IAAA,iBAAU;IACpC,2BAAK;IAAA,YAAkB;IACzB,AADyB,iBAAM,EACrB;;;IADH,eAAkB;IAAlB,yCAAkB;;;IAZ7B,8BAAyB;IACvB,uBAAgD;IAChD,0BAAI;IAAA,YAAkB;IAAA,iBAAK;IAC3B,yBAAG;IAAA,8EAA8D;IAAA,iBAAI;IAEnE,AADF,6BAA+F,SACzF;IAAA,oEAAoD;IAAA,iBAAK;IAC7D,0BAAI;IAAA,qEAAoD;IAAA,iBAAK;IAC7D,2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ACrC,CAAC,CAAC;IACL,CAAC;0HAlhBU,gCAAgC;6DAAhC,gCAAgC;;;;;;YCvB3C,AAFF,8BAA4D,aAE3B;YAuI3B,AAjCA,AApFA,AAjBF,mGAAgB,mEAiBa,6EAoFK,kEAiCzB;YA0BX,iBAAM;YAGN,0HAAkD;YAOpD,iBAAM;;YA7KiC,sCAAoB;YAGvD,eA+JC;YA/JD,6FA+JC;YAIH,eAMC;YAND,6EAMC;;;ADnJU,gCAAgC;IAD5C,aAAa,CAAC,iCAAiC,EAAE,+BAA+B,CAAC;GACrE,gCAAgC,CAmhB5C;;iFAnhBY,gCAAgC;cAP5C,SAAS;6BACI,KAAK,YACP,8BAA8B;;kBAMvC,SAAS;mBAAC,gBAAgB;;kBAC1B,MAAM;;kBACN,MAAM;;kBAQN,MAAM;;kFAXI,gCAAgC","sourcesContent":["import { Component, ViewChild, AfterViewInit, OnInit, OnChanges, SimpleChanges, Output, EventEmitter, ChangeDetectorRef } from '@angular/core';\nimport { RegisterClass, SafeJSONParse } from '@memberjunction/global';\nimport { BaseArtifactViewerPluginComponent, ArtifactViewerTab } from '../base-artifact-viewer.component';\nimport { MJReactComponent, AngularAdapterService } from '@memberjunction/ng-react';\nimport { BuildComponentCompleteCode, ComponentSpec } from '@memberjunction/interactive-component-types';\nimport { isFormRole, getDeclaredFormEntityName } from '@memberjunction/interactive-component-types/forms';\nimport { BaseEntity, CompositeKey, DataSnapshot, EntityInfo, LogError, RunView } from '@memberjunction/core';\nimport { DataRequirementsViewerComponent } from './data-requirements-viewer/data-requirements-viewer.component';\nimport { evaluateComponentPermissions, PermissionEvaluationResult } from './component-permission-evaluation';\n\n/**\n * Viewer component for interactive Component artifacts (React-based UI components)\n *\n * Features:\n * - Live component preview with React rendering\n * - Dynamic tabs for component metadata (via GetAdditionalTabs)\n * - Provides tabs for: Code, Functional Requirements, Technical Design, Data Requirements\n */\n@Component({\n standalone: false,\n selector: 'mj-component-artifact-viewer',\n templateUrl: './component-artifact-viewer.component.html',\n styleUrls: ['./component-artifact-viewer.component.css']\n})\n@RegisterClass(BaseArtifactViewerPluginComponent, 'ComponentArtifactViewerPlugin')\nexport class ComponentArtifactViewerComponent extends BaseArtifactViewerPluginComponent implements OnInit, AfterViewInit, OnChanges {\n @ViewChild('reactComponent') reactComponent?: MJReactComponent;\n @Output() tabsChanged = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{entityName: string; compositeKey: CompositeKey}>();\n\n /**\n * Emitted when the user clicks \"Apply to my form\" on a form-role artifact.\n * Carries the spec (ready to hand to the agent's Create/Modify action) and\n * the entity name. The host is responsible for confirming + invoking the\n * actual server action.\n */\n @Output() applyFormRequested = new EventEmitter<{ spec: ComponentSpec; entityName: string }>();\n\n // ── Form-aware state (only populated when componentRole === 'form') ──\n\n /** True when this artifact's spec declares `componentRole: 'form'`. */\n public isFormArtifact = false;\n\n /** Entity the form targets — resolved from spec.entityName / dataRequirements. */\n public formEntityInfo: EntityInfo | null = null;\n\n /** The real or fixture record currently bound to the form preview. */\n public formRecord: BaseEntity | null = null;\n\n /** True iff `formRecord` is a real DB row (vs a fixture NewRecord()). */\n public formRecordIsReal = false;\n\n /** Label for the chip (e.g. the record's Name field). */\n public formRecordLabel = '';\n\n /** Picker UI state. */\n public showRecordPicker = false;\n public recordSearchTerm = '';\n public recordSearchResults: Array<{ ID: string; Label: string }> = [];\n public formInitError: string | null = null;\n\n // Component data\n public component: ComponentSpec | null = null;\n public componentCode: string = \"\";\n public componentName: string = '';\n\n /**\n * Cached resolved spec from the registry, preserved even after the React component\n * is destroyed (e.g., when a render error removes <mj-react-component> from the DOM).\n */\n private _cachedResolvedSpec: ComponentSpec | null = null;\n\n public get resolvedComponentSpec(): ComponentSpec | null {\n // Prefer the live React component's resolved spec (most up-to-date),\n // then fall back to our cached copy (survives DOM destruction),\n // then fall back to the stripped local spec as last resort.\n return this.reactComponent?.resolvedComponentSpec || this._cachedResolvedSpec || this.component;\n }\n\n // Feedback panel\n public ShowFeedbackPanel = false;\n\n // Error state\n public hasError = false;\n public errorMessage = '';\n public errorDetails = '';\n\n // Permission state\n public permissionResult: PermissionEvaluationResult | null = null;\n\n /**\n * Whether this plugin has content to display in the Display tab.\n * Returns true only if the component has code that can be rendered.\n *\n * IMPORTANT: Uses this.component (synchronously loaded from artifact JSON)\n * instead of resolvedComponentSpec (which depends on async React loading).\n * This ensures hasDisplayContent returns correct value immediately when\n * pluginLoaded fires, before React component finishes loading.\n */\n public override get hasDisplayContent(): boolean {\n // Use this.component directly - it's available synchronously after loadComponentSpec()\n return !!this.component?.namespace || !!this.component?.code\n }\n\n constructor(private adapter: AngularAdapterService, private cdr: ChangeDetectorRef) {\n super();\n }\n\n async ngOnChanges(changes: SimpleChanges): Promise<void> {\n // When artifactVersion input changes, reload the component spec\n if (changes['artifactVersion']) {\n this.loadComponentSpec();\n // Notify parent that tabs may have changed (on subsequent changes)\n if (!changes['artifactVersion'].firstChange) {\n this.tabsChanged.emit();\n }\n }\n }\n\n /**\n * Synchronously load the component spec from artifact content.\n * This is intentionally synchronous so that tabs are available immediately\n * when the parent queries GetAdditionalTabs() after pluginLoaded fires.\n *\n * The bridge purges the runtime registry + manager fetch cache itself when\n * it (re)initializes for the new spec, so we don't need to clear caches\n * from here — the bridge instance may not even exist yet when ngOnChanges\n * fires for the first time.\n */\n private loadComponentSpec(): void {\n try {\n // Clear cached resolved spec from previous version so stale data doesn't persist\n this._cachedResolvedSpec = null;\n this.permissionResult = null;\n\n if (this.artifactVersion?.Content) {\n this.component = SafeJSONParse(this.artifactVersion.Content) as ComponentSpec;\n this.extractComponentParts();\n this.evaluatePermissions();\n // Form-aware detection. Done here (not in ngAfterViewInit) so the\n // template's `@if (isFormArtifact)` branch decides which preview\n // to mount on the very first render — no flash of the non-form\n // path before the form-aware UI takes over.\n this.detectAndInitFormArtifact();\n } else {\n throw new Error('Artifact content is empty');\n }\n } catch (error) {\n console.error('Failed to load component spec:', error);\n this.hasError = true;\n this.errorMessage = 'Failed to load component';\n this.errorDetails = error instanceof Error ? error.message : String(error);\n }\n }\n\n /**\n * Evaluate whether the current user has sufficient permissions for\n * all entities and queries referenced in the component's dataRequirements.\n * Uses the best available spec: resolved (from registry) > cached > stripped artifact.\n * Runs synchronously against already-loaded client-side metadata.\n */\n private evaluatePermissions(): void {\n const spec = this.resolvedComponentSpec;\n if (!spec) return;\n\n const provider = this.ProviderToUse;\n const currentUser = provider.CurrentUser;\n if (!currentUser) return; // No user context — skip check\n\n this.permissionResult = evaluateComponentPermissions(spec, currentUser, provider);\n }\n\n /** Whether the component should be blocked from rendering due to missing permissions. */\n public get isPermissionBlocked(): boolean {\n return !!this.permissionResult && !this.permissionResult.canRun;\n }\n\n /**\n * Component initialization.\n * Note: loadComponentSpec() is called in ngOnChanges which runs before ngOnInit,\n * ensuring tabs are available when pluginLoaded fires.\n * The async adapter initialization happens here and doesn't block tab availability.\n */\n async ngOnInit(): Promise<void> {\n // Initialize Angular adapter for React components (async operation)\n try {\n await this.adapter.initialize();\n } catch (error) {\n console.error('Failed to initialize Angular adapter:', error);\n this.hasError = true;\n this.errorMessage = 'Failed to initialize component runtime';\n this.errorDetails = error instanceof Error ? error.message : String(error);\n }\n }\n\n async ngAfterViewInit(): Promise<void> {\n // Component initialization happens automatically via mj-react-component\n }\n\n /**\n * Provide additional tabs for viewing component metadata\n */\n public GetAdditionalTabs(): ArtifactViewerTab[] {\n const tabs: ArtifactViewerTab[] = [];\n\n const resolvedComponent = this.resolvedComponentSpec;\n\n if (!resolvedComponent) {\n return tabs;\n }\n\n // Functional Requirements tab\n if (resolvedComponent.functionalRequirements) {\n tabs.push({\n label: 'Functional',\n icon: 'fa-clipboard-list',\n contentType: 'markdown',\n content: resolvedComponent.functionalRequirements\n });\n }\n\n // Technical Design tab\n if (resolvedComponent.technicalDesign) {\n tabs.push({\n label: 'Technical',\n icon: 'fa-wrench',\n contentType: 'markdown',\n content: resolvedComponent.technicalDesign\n });\n }\n\n // Data Requirements tab - uses custom component for rich visualization\n if (resolvedComponent.dataRequirements) {\n tabs.push({\n label: 'Data',\n icon: 'fa-database',\n contentType: 'component',\n component: DataRequirementsViewerComponent,\n componentInputs: { dataRequirements: resolvedComponent.dataRequirements }\n });\n }\n\n // Code tab (lazy-loaded) - only show if there's actual code\n if (resolvedComponent.code && resolvedComponent.code.trim()) {\n tabs.push({\n label: 'Code',\n icon: 'fa-code',\n contentType: 'code',\n language: 'typescript',\n content: () => BuildComponentCompleteCode(resolvedComponent)\n });\n }\n\n // Spec tab - Shows fully resolved component spec in JSON format (rightmost)\n tabs.push({\n label: 'Spec',\n icon: 'fa-file-code',\n contentType: 'json',\n content: () => JSON.stringify(resolvedComponent, null, 2),\n language: 'json'\n });\n\n return tabs;\n }\n\n /**\n * Remove standard JSON tab since we provide \"Resolved JSON\" custom tab\n * The custom tab shows the fully resolved component spec instead of raw artifact JSON\n */\n public GetStandardTabRemovals(): string[] {\n return ['JSON'];\n }\n\n private extractComponentParts(): void {\n if (this.resolvedComponentSpec?.name) {\n this.componentName = this.resolvedComponentSpec.name;\n }\n if (this.resolvedComponentSpec?.code) {\n this.componentCode = BuildComponentCompleteCode(this.resolvedComponentSpec);\n }\n }\n\n /**\n * Called when MJReactComponent finishes loading the full component spec from the registry.\n * The full spec may contain Functional, Technical, and Data tabs not in the stripped spec.\n * Caches the resolved spec so it survives DOM destruction (e.g., if the component fails to\n * render and <mj-react-component> is removed by the @if/else block).\n * Emits tabsChanged so the parent panel re-evaluates allTabs and renders the new tab labels.\n */\n onReactComponentInitialized(): void {\n if (this.reactComponent?.resolvedComponentSpec &&\n this.reactComponent.resolvedComponentSpec !== this.component) {\n // Cache the resolved spec so it's available even after the React component is destroyed\n this._cachedResolvedSpec = this.reactComponent.resolvedComponentSpec;\n this.tabsChanged.emit();\n\n // Re-evaluate permissions against the resolved spec — the stripped artifact\n // spec has no dataRequirements, so the initial check in loadComponentSpec()\n // passes trivially. The resolved spec from the registry contains the full\n // dataRequirements with entity and query references.\n this.evaluatePermissions();\n }\n }\n\n onComponentEvent(event: unknown): void {\n console.log('Component event:', event);\n\n // Handle error events from React component\n if (event && typeof event === 'object' && 'type' in event && event.type === 'error') {\n const errorEvent = event as { type: 'error'; payload: { error: string; source: string } };\n this.hasError = true;\n this.errorMessage = 'Component Failed to Load';\n this.errorDetails = errorEvent.payload.error || 'Unknown error occurred while loading the component';\n }\n }\n\n /**\n * Handle entity record open request from React component\n * Propagates the event up to parent components\n */\n onOpenEntityRecord(event: {entityName: string; key: CompositeKey}): void {\n // Transform to use 'compositeKey' name for consistency with Angular components\n this.openEntityRecord.emit({\n entityName: event.entityName,\n compositeKey: event.key\n });\n }\n\n public override GetCurrentStateSnapshot(): DataSnapshot | null {\n // First try the component's explicit or auto-captured data state.\n // MJReactComponent.getCurrentDataState() already includes the fallback\n // to intercepted RunView/RunQuery results when the React component\n // doesn't register getCurrentDataState() via callbacks.RegisterMethod.\n const dataState = this.reactComponent?.getCurrentDataState?.();\n if (dataState && typeof dataState === 'object') {\n return dataState as DataSnapshot;\n }\n\n // Fallback for components with no captured data — static mockups,\n // pure-display components, or components whose data hooks haven't fired.\n // Rather than short-circuit Analyze with \"No data available\", emit a\n // minimal snapshot so the user can still open an agent conversation about\n // the component. The artifact itself is attached to the conversation as an\n // Input junction, so the agent can reason from the spec + any static data\n // baked into the component code.\n const spec = this.resolvedComponentSpec;\n if (!spec) return null;\n\n const snap = new DataSnapshot();\n snap.title = spec.title || spec.name || this.getDisplayTitle() || undefined;\n snap.interpretation =\n `Interactive component artifact${spec.name ? ` \"${spec.name}\"` : ''}. ` +\n `No live data was captured — the component either has no data-fetching ` +\n `hooks or has not yet run its queries. The component specification is ` +\n `attached to this conversation; the agent should inspect it directly.`;\n return snap;\n }\n\n /**\n * Component artifacts support feedback when a resolved spec is available.\n */\n public override get SupportsFeedback(): boolean {\n return !!this.resolvedComponentSpec;\n }\n\n /**\n * Toggle the feedback panel open. Called from the artifact viewer header button.\n */\n public override AskUserForFeedback(): void {\n this.ShowFeedbackPanel = !this.ShowFeedbackPanel;\n }\n\n // ════════════════════════════════════════════════════════════════════\n // FORM-AWARE BRANCH\n //\n // When the artifact's spec declares `componentRole: 'form'`, the viewer\n // delegates rendering to `<mj-interactive-form>` instead of the raw\n // `<mj-react-component>` path. This gives the React form a proper\n // FormHostProps binding (bound to a real DB record by default) and lets\n // the user swap records via a search picker before applying.\n //\n // Triggered from `loadComponentSpec()` after the spec parses.\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Detect form-role and kick off entity + record resolution. Failure modes\n * (missing entity, RunView failure, entity has no rows) fall back to a\n * synthetic record from `BaseEntity.NewRecord()` so the form still mounts\n * against type-appropriate empty values.\n */\n private async detectAndInitFormArtifact(): Promise<void> {\n this.isFormArtifact = false;\n this.formEntityInfo = null;\n this.formRecord = null;\n this.formRecordIsReal = false;\n this.formRecordLabel = '';\n this.formInitError = null;\n\n const spec = this.component;\n if (!spec || !isFormRole(spec)) return;\n\n this.isFormArtifact = true;\n\n const entityName = getDeclaredFormEntityName(spec);\n if (!entityName) {\n this.formInitError = 'Form artifact has no declared entity. Showing without record context.';\n return;\n }\n\n const provider = this.ProviderToUse;\n const entity = provider?.EntityByName(entityName);\n if (!entity) {\n this.formInitError = `Entity \"${entityName}\" not registered with the active provider.`;\n return;\n }\n this.formEntityInfo = entity;\n\n // Load Top-1 record by default. If empty / fails, fall back to a fresh\n // synthetic record. Either way the form mounts — failure to find a real\n // record is informational, not fatal.\n const record = await this.loadTopOneRecord(entity);\n if (record) {\n this.formRecord = record;\n this.formRecordIsReal = true;\n this.formRecordLabel = this.computeRecordLabel(record);\n } else {\n this.formRecord = await this.buildFixtureRecord(entity);\n this.formRecordIsReal = false;\n this.formRecordLabel = 'Mock data';\n }\n // This runs after an await on a RunView that resolves outside Angular's zone,\n // so nothing would refresh the view until the next user event — leaving the\n // \"Could not bind a record\" message up until the user clicks. Force CD so the\n // auto-loaded record binds and the form mounts immediately on first render.\n this.cdr.detectChanges();\n }\n\n /**\n * Load the first row by NameField (then __mj_CreatedAt) so different users\n * opening the same form-role artifact see the same record bound to the\n * preview. (Retrospective fix #7 — un-ordered Top-1 was physical-order\n * and non-deterministic.)\n */\n private async loadTopOneRecord(entity: EntityInfo): Promise<BaseEntity | null> {\n try {\n const orderBy = entity.NameField?.Name\n ? `${entity.NameField.Name} ASC`\n : `__mj_CreatedAt DESC`;\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n const result = await rv.RunView<BaseEntity>({\n EntityName: entity.Name,\n MaxRows: 1,\n OrderBy: orderBy,\n ResultType: 'entity_object',\n }, this.ProviderToUse.CurrentUser);\n if (result.Success && (result.Results?.length ?? 0) > 0) {\n return result.Results[0];\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: Top-1 RunView failed for ${entity.Name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n return null;\n }\n\n /** Synthetic \"create-mode\" record when no real row exists or RunView failed. */\n private async buildFixtureRecord(entity: EntityInfo): Promise<BaseEntity | null> {\n try {\n const fresh = await this.ProviderToUse.GetEntityObject<BaseEntity>(entity.Name, this.ProviderToUse.CurrentUser);\n fresh.NewRecord();\n return fresh;\n } catch (err) {\n LogError(`ComponentArtifactViewer: failed to build fixture record for ${entity.Name}: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n }\n\n /** Pull a human-readable label from the record's NameField or first text field. */\n private computeRecordLabel(record: BaseEntity): string {\n const nameField = record.EntityInfo.NameField?.Name;\n if (nameField) {\n const v = record.Get(nameField);\n if (v != null && String(v).trim().length > 0) return String(v);\n }\n if (record.PrimaryKey?.HasValue) return record.PrimaryKey.ToConcatenatedString();\n return record.EntityInfo.Name;\n }\n\n /**\n * Search-as-you-type for the picker. Queries by name field (or any\n * indexed string field, best-effort). Limits to 8 hits for tightness.\n */\n public async onPickerSearchInput(term: string): Promise<void> {\n this.recordSearchTerm = term;\n if (!this.formEntityInfo || term.trim().length === 0) {\n this.recordSearchResults = [];\n return;\n }\n const nameField = this.formEntityInfo.NameField?.Name;\n if (!nameField) {\n this.recordSearchResults = [];\n return;\n }\n try {\n const rv = RunView.FromMetadataProvider(this.ProviderToUse);\n // Best-effort LIKE filter against the entity's name field. Wrap the\n // term so we don't break SQL — RunView passes ExtraFilter as-is.\n const safe = term.replace(/'/g, \"''\");\n const result = await rv.RunView<BaseEntity>({\n EntityName: this.formEntityInfo.Name,\n ExtraFilter: `${nameField} LIKE '%${safe}%'`,\n MaxRows: 8,\n ResultType: 'entity_object',\n }, this.ProviderToUse.CurrentUser);\n if (result.Success) {\n this.recordSearchResults = (result.Results ?? []).map(r => ({\n ID: r.PrimaryKey?.ToConcatenatedString() ?? '',\n Label: this.computeRecordLabel(r),\n }));\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: picker search failed: ${err instanceof Error ? err.message : String(err)}`);\n this.recordSearchResults = [];\n }\n }\n\n /** User picked a different record from the search results. Re-bind the form. */\n public async onPickerSelect(item: { ID: string; Label: string }): Promise<void> {\n if (!this.formEntityInfo) return;\n try {\n const rec = await this.ProviderToUse.GetEntityObject<BaseEntity>(\n this.formEntityInfo.Name, this.ProviderToUse.CurrentUser,\n );\n const pk = new CompositeKey();\n pk.LoadFromURLSegment(this.formEntityInfo, item.ID);\n const loaded = await rec.InnerLoad(pk);\n if (loaded) {\n this.formRecord = rec;\n this.formRecordIsReal = true;\n this.formRecordLabel = item.Label;\n this.showRecordPicker = false;\n this.recordSearchTerm = '';\n this.recordSearchResults = [];\n }\n } catch (err) {\n LogError(`ComponentArtifactViewer: failed to load picked record ${item.ID}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n /** Bubble Apply intent up to the host (Form Builder dashboard / Sage chat). */\n public onApplyClicked(): void {\n if (!this.component || !this.formEntityInfo) return;\n this.applyFormRequested.emit({\n spec: this.component,\n entityName: this.formEntityInfo.Name,\n });\n }\n}\n","<div class=\"component-artifact-viewer\" [ngClass]=\"cssClass\">\n <!-- Component Preview (full screen) -->\n <div class=\"component-preview\">\n @if (hasError) {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-triangle\"></i>\n <h3>{{ errorMessage }}</h3>\n <p>This component could not be loaded. This usually happens when:</p>\n <ul style=\"text-align: left; max-width: 500px; color: var(--mj-text-muted); line-height: 1.6;\">\n <li>The component registry is unavailable or unreachable</li>\n <li>The component version does not exist in the registry</li>\n <li>There was a network error during component retrieval</li>\n </ul>\n @if (errorDetails) {\n <details style=\"margin-top: 20px;\">\n <summary>Technical Details</summary>\n <pre>{{ errorDetails }}</pre>\n </details>\n }\n </div>\n } @else if (isFormArtifact) {\n <!-- ════════════════════════════════════════════════\n FORM-AWARE BRANCH\n Spec declares componentRole: 'form'. Render via\n <mj-interactive-form> bound to a real Top-1 record\n (or a synthetic NewRecord fallback). Picker chip\n lets the user swap records; Apply promotes the\n spec to an EntityFormOverride.\n ════════════════════════════════════════════════ -->\n <div class=\"form-artifact-toolstrip\">\n <i class=\"fa-solid fa-circle-info\" aria-hidden=\"true\"></i>\n <span class=\"form-artifact-toolstrip-label\">Previewing record:</span>\n <button\n type=\"button\"\n class=\"form-artifact-picker-chip\"\n (click)=\"showRecordPicker = !showRecordPicker\">\n <i class=\"fa-solid fa-magnifying-glass\"></i>\n <strong>{{ formRecordLabel || 'No record' }}</strong>\n @if (!formRecordIsReal) {\n <span class=\"form-artifact-picker-chip-badge\">Mock</span>\n }\n <i class=\"fa-solid fa-chevron-down\"></i>\n </button>\n @if (formEntityInfo) {\n <span class=\"form-artifact-toolstrip-entity\">{{ formEntityInfo.DisplayName || formEntityInfo.Name }}</span>\n }\n @if (formInitError) {\n <span class=\"form-artifact-toolstrip-warning\" [title]=\"formInitError\">\n <i class=\"fa-solid fa-triangle-exclamation\"></i>\n </span>\n }\n <span style=\"flex: 1;\"></span>\n @if (formEntityInfo) {\n <button\n type=\"button\"\n class=\"form-artifact-apply-btn\"\n (click)=\"onApplyClicked()\">\n <i class=\"fa-solid fa-circle-check\"></i>\n Apply to my form\n </button>\n }\n </div>\n\n @if (showRecordPicker && formEntityInfo) {\n <div class=\"form-artifact-picker-panel\" (click)=\"$event.stopPropagation()\">\n <input\n type=\"text\"\n class=\"form-artifact-picker-search\"\n placeholder=\"Search records by name…\"\n [value]=\"recordSearchTerm\"\n (input)=\"onPickerSearchInput($any($event.target).value)\" />\n @if (recordSearchResults.length > 0) {\n <ul class=\"form-artifact-picker-results\">\n @for (r of recordSearchResults; track r.ID) {\n <li\n class=\"form-artifact-picker-row\"\n (click)=\"onPickerSelect(r)\">\n <i class=\"fa-solid fa-circle-dot\"></i>\n <span>{{ r.Label }}</span>\n </li>\n }\n </ul>\n } @else if (recordSearchTerm.length > 0) {\n <div class=\"form-artifact-picker-empty\">No matches.</div>\n } @else {\n <div class=\"form-artifact-picker-empty\">Start typing to search.</div>\n }\n </div>\n }\n\n @if (formRecord && component) {\n <div class=\"form-artifact-form-host\">\n <mj-interactive-form\n [componentSpec]=\"component\"\n [record]=\"formRecord\">\n </mj-interactive-form>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>Form preview unavailable</h3>\n <p>{{ formInitError || 'Could not bind a record to this form.' }}</p>\n </div>\n }\n } @else if (isPermissionBlocked) {\n <!-- Permission warning — user lacks access to one or more data sources -->\n <div class=\"permission-warning\">\n <div class=\"permission-warning-icon\">\n <i class=\"fa-solid fa-shield-halved\"></i>\n </div>\n <h3>Insufficient Permissions</h3>\n <p>This component requires data access that you don't currently have:</p>\n\n @if (permissionResult!.missingEntities.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Entities</span>\n <ul>\n @for (entity of permissionResult!.missingEntities; track entity) {\n <li><i class=\"fa-solid fa-table\"></i> {{ entity }}</li>\n }\n </ul>\n </div>\n }\n\n @if (permissionResult!.missingQueries.length > 0) {\n <div class=\"permission-warning-section\">\n <span class=\"permission-warning-section-label\">Queries</span>\n <ul>\n @for (query of permissionResult!.missingQueries; track query) {\n <li><i class=\"fa-solid fa-database\"></i> {{ query }}</li>\n }\n </ul>\n </div>\n }\n\n <p class=\"permission-warning-hint\">Contact your administrator to request access.</p>\n </div>\n } @else {\n <!-- Default (non-form) interactive component path -->\n @if (component && (component.code || component.namespace)) {\n <mj-react-component\n #reactComponent\n [component]=\"component\"\n (componentEvent)=\"onComponentEvent($event)\"\n (openEntityRecord)=\"onOpenEntityRecord($event)\"\n (initialized)=\"onReactComponentInitialized()\">\n </mj-react-component>\n } @else if (component) {\n <!-- Component spec exists but no code - show informational message -->\n <div class=\"no-code-state\">\n <i class=\"fa-solid fa-file-lines\"></i>\n <h3>Component Specification</h3>\n <p>This component has specifications but no executable code yet.</p>\n <p>View the Functional, Data, or Spec tabs for details.</p>\n </div>\n } @else {\n <div class=\"error-state\">\n <i class=\"fa-solid fa-exclamation-circle\"></i>\n <h3>No Component Loaded</h3>\n <p>The component data is missing or invalid.</p>\n </div>\n }\n }\n </div>\n\n <!-- Feedback overlay panel (invoked from header button via AskUserForFeedback) -->\n @if (ShowFeedbackPanel && resolvedComponentSpec) {\n <mj-component-feedback-panel\n [ComponentSpec]=\"resolvedComponentSpec\"\n [ReactContainerElement]=\"reactComponent?.container?.nativeElement || null\"\n (Closed)=\"ShowFeedbackPanel = false\">\n </mj-component-feedback-panel>\n }\n</div>\n"]}
|
|
@@ -35,6 +35,21 @@ export declare class InteractiveFormApplyService {
|
|
|
35
35
|
* the Action entity when ActionEngine isn't loaded.
|
|
36
36
|
*/
|
|
37
37
|
private resolveActionIdByName;
|
|
38
|
+
/**
|
|
39
|
+
* Activate the override produced by a successful Create so a net-new form goes
|
|
40
|
+
* live immediately. Best-effort: on failure the form stays a Pending draft the
|
|
41
|
+
* user can activate manually, so we log and return false rather than failing the
|
|
42
|
+
* whole apply.
|
|
43
|
+
*/
|
|
44
|
+
private activateCreatedOverride;
|
|
45
|
+
/**
|
|
46
|
+
* Align a freshly generated spec to an existing Component lineage before Modify.
|
|
47
|
+
* MJ identifies a form lineage by Component Name and refuses to change it between
|
|
48
|
+
* versions, so we rename the incoming spec — both `spec.name` and the root
|
|
49
|
+
* `function` declaration in `spec.code` (the linter requires them to match) — to
|
|
50
|
+
* the existing lineage name.
|
|
51
|
+
*/
|
|
52
|
+
private alignSpecToLineage;
|
|
38
53
|
/** Show a confirmation dialog explaining what's about to happen. */
|
|
39
54
|
private confirm;
|
|
40
55
|
private parseActiveResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-form-apply.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/interactive-form-apply.service.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAsB,KAAK,iBAAiB,EAAiB,MAAM,sBAAsB,CAAC;AAIjG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;;AAEjF,iFAAiF;AACjF,MAAM,WAAW,0BAA0B;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,gFAAgF;IAChF,IAAI,CAAC,EAAE,QAAQ,GAAG,oBAAoB,GAAG,iBAAiB,CAAC;IAC3D,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,qBACa,2BAA2B;IACpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2B;IAClD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAiC;IAE/D;;;OAGG;IACU,eAAe,CACxB,IAAI,EAAE,aAAa,EACnB,UAAU,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,iBAAiB,GAC7B,OAAO,CAAC,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"interactive-form-apply.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/interactive-form-apply.service.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAsB,KAAK,iBAAiB,EAAiB,MAAM,sBAAsB,CAAC;AAIjG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;;AAEjF,iFAAiF;AACjF,MAAM,WAAW,0BAA0B;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,gFAAgF;IAChF,IAAI,CAAC,EAAE,QAAQ,GAAG,oBAAoB,GAAG,iBAAiB,CAAC;IAC3D,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,qBACa,2BAA2B;IACpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2B;IAClD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAiC;IAE/D;;;OAGG;IACU,eAAe,CACxB,IAAI,EAAE,aAAa,EACnB,UAAU,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,iBAAiB,GAC7B,OAAO,CAAC,0BAA0B,CAAC;IAsFtC;;;;;;OAMG;YACW,eAAe;IA+B7B;;;OAGG;YACW,qBAAqB;IAoBnC;;;;;OAKG;YACW,uBAAuB;IAoBrC;;;;;;OAMG;IACH,OAAO,CAAC,kBAAkB;IAW1B,oEAAoE;YACtD,OAAO;IA+BrB,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,SAAS;IAsCjB,OAAO,CAAC,IAAI;yCA7RH,2BAA2B;6CAA3B,2BAA2B;CAiSvC"}
|
|
@@ -64,19 +64,49 @@ export class InteractiveFormApplyService {
|
|
|
64
64
|
// Step 3: run Create or Modify.
|
|
65
65
|
const formName = spec.name ?? 'Custom Form';
|
|
66
66
|
if (hasExistingActive) {
|
|
67
|
+
// MJ's Modify operates on a Component *lineage* keyed by Name — the spec
|
|
68
|
+
// name must match the existing Component across versions. A freshly
|
|
69
|
+
// generated form usually has a different name, so align it to the existing
|
|
70
|
+
// lineage (spec.name + the root `function` declaration the linter checks)
|
|
71
|
+
// before modifying.
|
|
72
|
+
if (payload?.Active?.ComponentName) {
|
|
73
|
+
this.alignSpecToLineage(spec, payload.Active.ComponentName);
|
|
74
|
+
}
|
|
67
75
|
const modifyResult = await this.runActionByName(client, 'Modify Interactive Form', [
|
|
68
76
|
{ Name: 'OverrideID', Value: payload.Active.OverrideID, Type: 'Input' },
|
|
69
77
|
{ Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },
|
|
70
78
|
{ Name: 'Notes', Value: `Applied from chat artifact at ${new Date().toISOString()}`, Type: 'Input' },
|
|
79
|
+
// A user "Apply" is a deliberate save, never an in-flight refinement —
|
|
80
|
+
// so always snapshot a new restorable version rather than risk an
|
|
81
|
+
// in-place overwrite. Passing an explicit bump makes this deterministic
|
|
82
|
+
// across every source status (the 'in-place' default only applies to a
|
|
83
|
+
// Pending source, which is the agent's iteration loop, not this path).
|
|
84
|
+
// The prior version is demoted to Inactive on activation and stays in
|
|
85
|
+
// Form Builder's version rail.
|
|
86
|
+
{ Name: 'VersionBumpKind', Value: 'minor', Type: 'Input' },
|
|
71
87
|
]);
|
|
72
|
-
|
|
88
|
+
// Auto-activate the resulting version too. "Apply to my form" is an explicit
|
|
89
|
+
// user action — they expect the applied form to go live, not sit as a Pending
|
|
90
|
+
// draft the runtime variant switcher (Active variants only) can't reach. The
|
|
91
|
+
// prior version is preserved as history and restorable from Form Builder.
|
|
92
|
+
const modifyActivated = modifyResult.Success
|
|
93
|
+
? await this.activateCreatedOverride(client, modifyResult.Message)
|
|
94
|
+
: false;
|
|
95
|
+
return this.summarize(modifyResult, 'modify', user, modifyActivated);
|
|
73
96
|
}
|
|
74
97
|
const createResult = await this.runActionByName(client, 'Create Interactive Form', [
|
|
75
98
|
{ Name: 'EntityName', Value: entityName, Type: 'Input' },
|
|
76
99
|
{ Name: 'Name', Value: formName, Type: 'Input' },
|
|
77
100
|
{ Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },
|
|
78
101
|
]);
|
|
79
|
-
|
|
102
|
+
// Net-new "Apply to my form" is an explicit, confirmed user action, so we
|
|
103
|
+
// activate the freshly-created (Pending) override immediately — the form goes
|
|
104
|
+
// live in one step. Refining an EXISTING active form (the branch above) stays
|
|
105
|
+
// Pending so a live form is never silently replaced.
|
|
106
|
+
const activated = createResult.Success
|
|
107
|
+
? await this.activateCreatedOverride(client, createResult.Message)
|
|
108
|
+
: false;
|
|
109
|
+
return this.summarize(createResult, 'create', user, activated);
|
|
80
110
|
}
|
|
81
111
|
// ── internals ────────────────────────────────────────────────────────
|
|
82
112
|
/**
|
|
@@ -120,10 +150,11 @@ export class InteractiveFormApplyService {
|
|
|
120
150
|
async resolveActionIdByName(name) {
|
|
121
151
|
try {
|
|
122
152
|
// ActionEngine may not be initialised in the chat surface — query directly.
|
|
153
|
+
// The core Action table is registered as the "MJ: Actions" entity.
|
|
123
154
|
const { RunView } = await import('@memberjunction/core');
|
|
124
155
|
const rv = new RunView();
|
|
125
156
|
const result = await rv.RunView({
|
|
126
|
-
EntityName: 'Actions',
|
|
157
|
+
EntityName: 'MJ: Actions',
|
|
127
158
|
ExtraFilter: `Name='${name.replace(/'/g, "''")}'`,
|
|
128
159
|
Fields: ['ID'],
|
|
129
160
|
MaxRows: 1,
|
|
@@ -136,22 +167,66 @@ export class InteractiveFormApplyService {
|
|
|
136
167
|
return null;
|
|
137
168
|
}
|
|
138
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* Activate the override produced by a successful Create so a net-new form goes
|
|
172
|
+
* live immediately. Best-effort: on failure the form stays a Pending draft the
|
|
173
|
+
* user can activate manually, so we log and return false rather than failing the
|
|
174
|
+
* whole apply.
|
|
175
|
+
*/
|
|
176
|
+
async activateCreatedOverride(client, createMessage) {
|
|
177
|
+
let overrideId;
|
|
178
|
+
try {
|
|
179
|
+
overrideId = JSON.parse(createMessage ?? '{}').OverrideID;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
overrideId = undefined;
|
|
183
|
+
}
|
|
184
|
+
if (!overrideId)
|
|
185
|
+
return false;
|
|
186
|
+
const activateResult = await this.runActionByName(client, 'Activate Interactive Form Version', [
|
|
187
|
+
{ Name: 'OverrideID', Value: overrideId, Type: 'Input' },
|
|
188
|
+
]);
|
|
189
|
+
if (!activateResult.Success) {
|
|
190
|
+
LogError(`InteractiveFormApplyService: created override ${overrideId} but auto-activation failed: ${activateResult.Message ?? 'unknown error'}`);
|
|
191
|
+
}
|
|
192
|
+
return activateResult.Success;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Align a freshly generated spec to an existing Component lineage before Modify.
|
|
196
|
+
* MJ identifies a form lineage by Component Name and refuses to change it between
|
|
197
|
+
* versions, so we rename the incoming spec — both `spec.name` and the root
|
|
198
|
+
* `function` declaration in `spec.code` (the linter requires them to match) — to
|
|
199
|
+
* the existing lineage name.
|
|
200
|
+
*/
|
|
201
|
+
alignSpecToLineage(spec, existingName) {
|
|
202
|
+
const s = spec;
|
|
203
|
+
const currentName = s.name;
|
|
204
|
+
if (!currentName || currentName === existingName)
|
|
205
|
+
return;
|
|
206
|
+
s.name = existingName;
|
|
207
|
+
if (typeof s.code === 'string' && s.code.length > 0) {
|
|
208
|
+
const escaped = currentName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
209
|
+
s.code = s.code.replace(new RegExp(`function\\s+${escaped}\\s*\\(`), `function ${existingName}(`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
139
212
|
/** Show a confirmation dialog explaining what's about to happen. */
|
|
140
213
|
async confirm(hasExistingActive, entityName, currentVersion) {
|
|
214
|
+
// The dialog renders string content as plain text (not innerHTML), so use
|
|
215
|
+
// plain text here — HTML tags would show raw.
|
|
141
216
|
const content = hasExistingActive
|
|
142
|
-
? `You already have
|
|
143
|
-
: `This will create a custom form for
|
|
217
|
+
? `You already have a custom form for "${entityName}" (v${currentVersion ?? '?'}). Applying this will create a new version and make it your active form. The previous version is preserved and can be restored from Form Builder.`
|
|
218
|
+
: `This will create a custom form for "${entityName}" scoped to your user and make it active. Other users will continue to see the default form.`;
|
|
144
219
|
// MJDialogAction surface is {text, primary?, themeColor?}; the
|
|
145
220
|
// dialog's Result observable emits the entire clicked action (or
|
|
146
221
|
// undefined for backdrop/X dismissal). Detect intent via the
|
|
147
222
|
// `primary` flag — Apply / Create Pending are the primary actions;
|
|
148
223
|
// Cancel and dismissal both resolve false.
|
|
149
224
|
const ref = this.dialog.Open({
|
|
150
|
-
title:
|
|
225
|
+
title: 'Apply this form?',
|
|
151
226
|
content,
|
|
152
227
|
width: 540,
|
|
153
228
|
actions: [
|
|
154
|
-
{ text:
|
|
229
|
+
{ text: 'Apply', primary: true, themeColor: 'primary' },
|
|
155
230
|
{ text: 'Cancel' },
|
|
156
231
|
],
|
|
157
232
|
});
|
|
@@ -171,7 +246,7 @@ export class InteractiveFormApplyService {
|
|
|
171
246
|
return null;
|
|
172
247
|
}
|
|
173
248
|
}
|
|
174
|
-
summarize(result, kind, _user) {
|
|
249
|
+
summarize(result, kind, _user, activated = false) {
|
|
175
250
|
if (!result.Success) {
|
|
176
251
|
this.notifications.CreateSimpleNotification(`Apply failed: ${result.Message ?? result.ResultCode ?? 'unknown error'}`, 'error', 5000);
|
|
177
252
|
return { Success: false, Message: result.Message };
|
|
@@ -185,10 +260,14 @@ export class InteractiveFormApplyService {
|
|
|
185
260
|
? 'create'
|
|
186
261
|
: (payload.Mode === 'in-place' ? 'modify-in-place' : 'modify-new-version');
|
|
187
262
|
const note = kind === 'create'
|
|
188
|
-
?
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
263
|
+
? (activated
|
|
264
|
+
? 'Custom form is now active for your user.'
|
|
265
|
+
: 'Custom form created as a Pending draft — activate it from Form Builder to go live.')
|
|
266
|
+
: (activated
|
|
267
|
+
? `Updated form is now active${payload.Version ? ` (v${payload.Version})` : ''} for your user.`
|
|
268
|
+
: (mode === 'modify-in-place'
|
|
269
|
+
? 'Pending version updated. Activate it from Form Builder when ready.'
|
|
270
|
+
: `Pending v${payload.Version ?? '?'} created. Activate it from Form Builder when ready.`));
|
|
192
271
|
this.notifications.CreateSimpleNotification(note, 'success', 4000);
|
|
193
272
|
return {
|
|
194
273
|
Success: true,
|
|
@@ -210,10 +289,4 @@ export class InteractiveFormApplyService {
|
|
|
210
289
|
type: Injectable,
|
|
211
290
|
args: [{ providedIn: 'root' }]
|
|
212
291
|
}], null, null); })();
|
|
213
|
-
/** Minimal HTML escape — the dialog content goes through `[innerHTML]` upstream. */
|
|
214
|
-
function escape(s) {
|
|
215
|
-
return s.replace(/[&<>"']/g, c => ({
|
|
216
|
-
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
|
217
|
-
}[c] ?? c));
|
|
218
|
-
}
|
|
219
292
|
//# sourceMappingURL=interactive-form-apply.service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-form-apply.service.js","sourceRoot":"","sources":["../../../src/lib/services/interactive-form-apply.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAyC,MAAM,sBAAsB,CAAC;AACjG,OAAO,EAAE,mBAAmB,EAAuB,MAAM,sCAAsC,CAAC;AAChG,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;;AAkBnE,MAAM,OAAO,2BAA2B;IACnB,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;IACjC,aAAa,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;IAE/D;;;OAGG;IACI,KAAK,CAAC,eAAe,CACxB,IAAmB,EACnB,UAAkB,EAClB,QAA4B;QAE5B,MAAM,CAAC,GAAG,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAC;QACxC,IAAI,CAAC,CAAC,E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UAAU,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QAC/B,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO;KACtE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Apply-to-my-form service.\n *\n * When the form-aware artifact viewer's \"Apply to my form\" button fires\n * `applyFormRequested`, the host calls this service. It:\n * 1. Looks up the entity to confirm it's registered.\n * 2. Reads the current Active override for the (entity, user) pair via\n * the `Get Active Form For Entity` action.\n * 3. Shows a confirmation dialog explaining what's about to happen\n * (Create new vs. Modify existing → Pending).\n * 4. On confirmation, runs `Create Interactive Form` or\n * `Modify Interactive Form` accordingly.\n * 5. Surfaces success / failure via the notification service.\n *\n * The service centralizes the Create-vs-Modify decision so every host\n * (standalone artifact viewer in Explorer, chat conversation surfaces,\n * eventually the cockpit's chat-pane Apply flow) follows the same rules.\n */\nimport { Injectable, inject } from '@angular/core';\nimport { Metadata, LogError, type IMetadataProvider, type UserInfo } from '@memberjunction/core';\nimport { GraphQLActionClient, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { MJDialogService } from '@memberjunction/ng-ui-components';\nimport type { ComponentSpec } from '@memberjunction/interactive-component-types';\n\n/** Result of an apply attempt — surfaced to the caller for any post-apply UI. */\nexport interface InteractiveFormApplyResult {\n Success: boolean;\n /** Mode the server ran: 'create' / 'modify-new-version' / 'modify-in-place'. */\n Mode?: 'create' | 'modify-new-version' | 'modify-in-place';\n /** OverrideID the user can now reference. */\n OverrideID?: string;\n /** ComponentID that now holds the spec. */\n ComponentID?: string;\n /** Version string (e.g. '1.0.0' for create, '1.1.0' for modify-new). */\n Version?: string;\n Message?: string;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class InteractiveFormApplyService {\n private readonly dialog = inject(MJDialogService);\n private readonly notifications = inject(MJNotificationService);\n\n /**\n * Confirm with the user and apply the spec. Routes to Create / Modify\n * automatically based on whether an Active override already exists.\n */\n public async ConfirmAndApply(\n spec: ComponentSpec,\n entityName: string,\n provider?: IMetadataProvider,\n ): Promise<InteractiveFormApplyResult> {\n const p = provider ?? Metadata.Provider;\n if (!p) {\n return this.fail('No metadata provider configured.');\n }\n const entity = p.EntityByName(entityName);\n if (!entity) {\n return this.fail(`Entity '${entityName}' is not registered.`);\n }\n const user = p.CurrentUser;\n if (!user) {\n return this.fail('No current user.');\n }\n const gqlProvider = p as unknown as GraphQLDataProvider;\n if (!gqlProvider || typeof (gqlProvider as { ExecuteGQL?: unknown }).ExecuteGQL !== 'function') {\n return this.fail('Action invocation requires a GraphQL provider.');\n }\n\n const client = new GraphQLActionClient(gqlProvider);\n\n // Step 1: detect existing state via Get Active Form For Entity.\n const activeResult = await this.runActionByName(client, 'Get Active Form For Entity', [\n { Name: 'EntityName', Value: entityName, Type: 'Input' },\n ]);\n if (!activeResult.Success) {\n return this.fail(`Could not check for existing override: ${activeResult.Message ?? 'unknown error'}`);\n }\n const payload = this.parseActiveResult(activeResult.Message);\n const hasExistingActive = !!payload?.Active?.OverrideID;\n\n // Step 2: confirm with the user.\n const proceed = await this.confirm(hasExistingActive, entityName, payload?.Active?.ComponentVersion);\n if (!proceed) {\n return { Success: false, Message: 'Cancelled by user.' };\n }\n\n // Step 3: run Create or Modify.\n const formName = (spec as unknown as { name?: string }).name ?? 'Custom Form';\n if (hasExistingActive) {\n const modifyResult = await this.runActionByName(client, 'Modify Interactive Form', [\n { Name: 'OverrideID', Value: payload!.Active!.OverrideID!, Type: 'Input' },\n { Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },\n { Name: 'Notes', Value: `Applied from chat artifact at ${new Date().toISOString()}`, Type: 'Input' },\n ]);\n return this.summarize(modifyResult, 'modify', user);\n }\n const createResult = await this.runActionByName(client, 'Create Interactive Form', [\n { Name: 'EntityName', Value: entityName, Type: 'Input' },\n { Name: 'Name', Value: formName, Type: 'Input' },\n { Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },\n ]);\n return this.summarize(createResult, 'create', user);\n }\n\n // ── internals ────────────────────────────────────────────────────────\n\n /**\n * Look up an action by name and run it. The actions module ships with\n * `__CreateInteractiveForm` / `__ModifyInteractiveForm` / etc. as their\n * DriverClass names but registers under the human-readable form name.\n * GraphQLActionClient.RunAction() takes the action ID; we fetch it by\n * name from the action metadata loaded on the provider.\n */\n private async runActionByName(\n client: GraphQLActionClient,\n actionName: string,\n params: Array<{ Name: string; Value: string; Type: 'Input' }>,\n ): Promise<{ Success: boolean; Message?: string; ResultCode?: string }> {\n try {\n // The action ID is required by RunAction. We look it up from the\n // action engine's cached metadata if available; otherwise we ask\n // the GraphQL provider directly.\n const actionId = await this.resolveActionIdByName(actionName);\n if (!actionId) {\n return { Success: false, Message: `Action '${actionName}' not found.` };\n }\n const result = await client.RunAction(actionId, params);\n // ActionResult.Result is the MJActionResultCodeEntity carrying\n // the string ResultCode; surface it on the failure path for\n // diagnostic messaging. ActionResult itself doesn't expose\n // ResultCode directly.\n const resultCode = (result as { Result?: { ResultCode?: string } })?.Result?.ResultCode;\n return {\n Success: !!result.Success,\n Message: result.Message ?? undefined,\n ResultCode: resultCode ?? undefined,\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n LogError(`InteractiveFormApplyService.runActionByName(${actionName}): ${message}`);\n return { Success: false, Message: message };\n }\n }\n\n /**\n * Resolve an action ID by Name. Falls back to a direct RunView against\n * the Action entity when ActionEngine isn't loaded.\n */\n private async resolveActionIdByName(name: string): Promise<string | null> {\n try {\n // ActionEngine may not be initialised in the chat surface — query directly.\n const { RunView } = await import('@memberjunction/core');\n const rv = new RunView();\n const result = await rv.RunView<{ ID: string }>({\n EntityName: 'Actions',\n ExtraFilter: `Name='${name.replace(/'/g, \"''\")}'`,\n Fields: ['ID'],\n MaxRows: 1,\n ResultType: 'simple',\n });\n return result.Success ? (result.Results?.[0]?.ID ?? null) : null;\n } catch (err) {\n LogError(`InteractiveFormApplyService.resolveActionIdByName(${name}): ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n }\n\n /** Show a confirmation dialog explaining what's about to happen. */\n private async confirm(\n hasExistingActive: boolean,\n entityName: string,\n currentVersion: string | null | undefined,\n ): Promise<boolean> {\n const content = hasExistingActive\n ? `You already have an active custom form for <strong>${escape(entityName)}</strong> (v${escape(currentVersion ?? '?')}). Applying this artifact will create a <strong>new Pending version</strong> — your live form stays active until you explicitly activate the new version in Form Builder.`\n : `This will create a custom form for <strong>${escape(entityName)}</strong> scoped to your user. Other users will continue to see the default form.`;\n // MJDialogAction surface is {text, primary?, themeColor?}; the\n // dialog's Result observable emits the entire clicked action (or\n // undefined for backdrop/X dismissal). Detect intent via the\n // `primary` flag — Apply / Create Pending are the primary actions;\n // Cancel and dismissal both resolve false.\n const ref = this.dialog.Open({\n title: hasExistingActive ? 'Apply as new Pending version?' : 'Apply this form?',\n content,\n width: 540,\n actions: [\n { text: hasExistingActive ? 'Create Pending' : 'Apply', primary: true, themeColor: 'primary' },\n { text: 'Cancel' },\n ],\n });\n return new Promise<boolean>(resolve => {\n ref.Result.subscribe((res: unknown) => {\n resolve((res as { primary?: boolean })?.primary === true);\n });\n });\n }\n\n private parseActiveResult(message: string | undefined): {\n Active?: { OverrideID?: string; ComponentVersion?: string };\n } | null {\n if (!message) return null;\n try {\n return JSON.parse(message) as { Active?: { OverrideID?: string; ComponentVersion?: string } };\n } catch {\n return null;\n }\n }\n\n private summarize(\n result: { Success: boolean; Message?: string; ResultCode?: string },\n kind: 'create' | 'modify',\n _user: UserInfo,\n ): InteractiveFormApplyResult {\n if (!result.Success) {\n this.notifications.CreateSimpleNotification(\n `Apply failed: ${result.Message ?? result.ResultCode ?? 'unknown error'}`,\n 'error', 5000,\n );\n return { Success: false, Message: result.Message };\n }\n let payload: Record<string, unknown> = {};\n try { payload = JSON.parse(result.Message ?? '{}'); } catch { /* best effort */ }\n const mode: InteractiveFormApplyResult['Mode'] = kind === 'create'\n ? 'create'\n : (payload.Mode === 'in-place' ? 'modify-in-place' : 'modify-new-version');\n const note = kind === 'create'\n ? 'Custom form is now active for your user.'\n : (mode === 'modify-in-place'\n ? 'Pending version updated. Activate it from Form Builder when ready.'\n : `Pending v${payload.Version ?? '?'} created. Activate it from Form Builder when ready.`);\n this.notifications.CreateSimpleNotification(note, 'success', 4000);\n return {\n Success: true,\n Mode: mode,\n OverrideID: payload.OverrideID as string | undefined,\n ComponentID: payload.ComponentID as string | undefined,\n Version: payload.Version as string | undefined,\n Message: result.Message,\n };\n }\n\n private fail(message: string): InteractiveFormApplyResult {\n this.notifications.CreateSimpleNotification(`Apply failed: ${message}`, 'error', 5000);\n return { Success: false, Message: message };\n }\n}\n\n/** Minimal HTML escape — the dialog content goes through `[innerHTML]` upstream. */\nfunction escape(s: string): string {\n return s.replace(/[&<>\"']/g, c => ({\n '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''',\n }[c] ?? c));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"interactive-form-apply.service.js","sourceRoot":"","sources":["../../../src/lib/services/interactive-form-apply.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAyC,MAAM,sBAAsB,CAAC;AACjG,OAAO,EAAE,mBAAmB,EAAuB,MAAM,sCAAsC,CAAC;AAChG,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;;AAkBnE,MAAM,OAAO,2BAA2B;IACnB,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;IACjC,aAAa,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;IAE/D;;;OAGG;IACI,KAAK,C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yFormRequested`, the host calls this service. It:\n * 1. Looks up the entity to confirm it's registered.\n * 2. Reads the current Active override for the (entity, user) pair via\n * the `Get Active Form For Entity` action.\n * 3. Shows a confirmation dialog explaining what's about to happen\n * (Create new vs. Modify existing → Pending).\n * 4. On confirmation, runs `Create Interactive Form` or\n * `Modify Interactive Form` accordingly.\n * 5. Surfaces success / failure via the notification service.\n *\n * The service centralizes the Create-vs-Modify decision so every host\n * (standalone artifact viewer in Explorer, chat conversation surfaces,\n * eventually the cockpit's chat-pane Apply flow) follows the same rules.\n */\nimport { Injectable, inject } from '@angular/core';\nimport { Metadata, LogError, type IMetadataProvider, type UserInfo } from '@memberjunction/core';\nimport { GraphQLActionClient, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { MJDialogService } from '@memberjunction/ng-ui-components';\nimport type { ComponentSpec } from '@memberjunction/interactive-component-types';\n\n/** Result of an apply attempt — surfaced to the caller for any post-apply UI. */\nexport interface InteractiveFormApplyResult {\n Success: boolean;\n /** Mode the server ran: 'create' / 'modify-new-version' / 'modify-in-place'. */\n Mode?: 'create' | 'modify-new-version' | 'modify-in-place';\n /** OverrideID the user can now reference. */\n OverrideID?: string;\n /** ComponentID that now holds the spec. */\n ComponentID?: string;\n /** Version string (e.g. '1.0.0' for create, '1.1.0' for modify-new). */\n Version?: string;\n Message?: string;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class InteractiveFormApplyService {\n private readonly dialog = inject(MJDialogService);\n private readonly notifications = inject(MJNotificationService);\n\n /**\n * Confirm with the user and apply the spec. Routes to Create / Modify\n * automatically based on whether an Active override already exists.\n */\n public async ConfirmAndApply(\n spec: ComponentSpec,\n entityName: string,\n provider?: IMetadataProvider,\n ): Promise<InteractiveFormApplyResult> {\n const p = provider ?? Metadata.Provider;\n if (!p) {\n return this.fail('No metadata provider configured.');\n }\n const entity = p.EntityByName(entityName);\n if (!entity) {\n return this.fail(`Entity '${entityName}' is not registered.`);\n }\n const user = p.CurrentUser;\n if (!user) {\n return this.fail('No current user.');\n }\n const gqlProvider = p as unknown as GraphQLDataProvider;\n if (!gqlProvider || typeof (gqlProvider as { ExecuteGQL?: unknown }).ExecuteGQL !== 'function') {\n return this.fail('Action invocation requires a GraphQL provider.');\n }\n\n const client = new GraphQLActionClient(gqlProvider);\n\n // Step 1: detect existing state via Get Active Form For Entity.\n const activeResult = await this.runActionByName(client, 'Get Active Form For Entity', [\n { Name: 'EntityName', Value: entityName, Type: 'Input' },\n ]);\n if (!activeResult.Success) {\n return this.fail(`Could not check for existing override: ${activeResult.Message ?? 'unknown error'}`);\n }\n const payload = this.parseActiveResult(activeResult.Message);\n const hasExistingActive = !!payload?.Active?.OverrideID;\n\n // Step 2: confirm with the user.\n const proceed = await this.confirm(hasExistingActive, entityName, payload?.Active?.ComponentVersion);\n if (!proceed) {\n return { Success: false, Message: 'Cancelled by user.' };\n }\n\n // Step 3: run Create or Modify.\n const formName = (spec as unknown as { name?: string }).name ?? 'Custom Form';\n if (hasExistingActive) {\n // MJ's Modify operates on a Component *lineage* keyed by Name — the spec\n // name must match the existing Component across versions. A freshly\n // generated form usually has a different name, so align it to the existing\n // lineage (spec.name + the root `function` declaration the linter checks)\n // before modifying.\n if (payload?.Active?.ComponentName) {\n this.alignSpecToLineage(spec, payload.Active.ComponentName);\n }\n const modifyResult = await this.runActionByName(client, 'Modify Interactive Form', [\n { Name: 'OverrideID', Value: payload!.Active!.OverrideID!, Type: 'Input' },\n { Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },\n { Name: 'Notes', Value: `Applied from chat artifact at ${new Date().toISOString()}`, Type: 'Input' },\n // A user \"Apply\" is a deliberate save, never an in-flight refinement —\n // so always snapshot a new restorable version rather than risk an\n // in-place overwrite. Passing an explicit bump makes this deterministic\n // across every source status (the 'in-place' default only applies to a\n // Pending source, which is the agent's iteration loop, not this path).\n // The prior version is demoted to Inactive on activation and stays in\n // Form Builder's version rail.\n { Name: 'VersionBumpKind', Value: 'minor', Type: 'Input' },\n ]);\n // Auto-activate the resulting version too. \"Apply to my form\" is an explicit\n // user action — they expect the applied form to go live, not sit as a Pending\n // draft the runtime variant switcher (Active variants only) can't reach. The\n // prior version is preserved as history and restorable from Form Builder.\n const modifyActivated = modifyResult.Success\n ? await this.activateCreatedOverride(client, modifyResult.Message)\n : false;\n return this.summarize(modifyResult, 'modify', user, modifyActivated);\n }\n const createResult = await this.runActionByName(client, 'Create Interactive Form', [\n { Name: 'EntityName', Value: entityName, Type: 'Input' },\n { Name: 'Name', Value: formName, Type: 'Input' },\n { Name: 'Spec', Value: JSON.stringify(spec), Type: 'Input' },\n ]);\n // Net-new \"Apply to my form\" is an explicit, confirmed user action, so we\n // activate the freshly-created (Pending) override immediately — the form goes\n // live in one step. Refining an EXISTING active form (the branch above) stays\n // Pending so a live form is never silently replaced.\n const activated = createResult.Success\n ? await this.activateCreatedOverride(client, createResult.Message)\n : false;\n return this.summarize(createResult, 'create', user, activated);\n }\n\n // ── internals ────────────────────────────────────────────────────────\n\n /**\n * Look up an action by name and run it. The actions module ships with\n * `__CreateInteractiveForm` / `__ModifyInteractiveForm` / etc. as their\n * DriverClass names but registers under the human-readable form name.\n * GraphQLActionClient.RunAction() takes the action ID; we fetch it by\n * name from the action metadata loaded on the provider.\n */\n private async runActionByName(\n client: GraphQLActionClient,\n actionName: string,\n params: Array<{ Name: string; Value: string; Type: 'Input' }>,\n ): Promise<{ Success: boolean; Message?: string; ResultCode?: string }> {\n try {\n // The action ID is required by RunAction. We look it up from the\n // action engine's cached metadata if available; otherwise we ask\n // the GraphQL provider directly.\n const actionId = await this.resolveActionIdByName(actionName);\n if (!actionId) {\n return { Success: false, Message: `Action '${actionName}' not found.` };\n }\n const result = await client.RunAction(actionId, params);\n // ActionResult.Result is the MJActionResultCodeEntity carrying\n // the string ResultCode; surface it on the failure path for\n // diagnostic messaging. ActionResult itself doesn't expose\n // ResultCode directly.\n const resultCode = (result as { Result?: { ResultCode?: string } })?.Result?.ResultCode;\n return {\n Success: !!result.Success,\n Message: result.Message ?? undefined,\n ResultCode: resultCode ?? undefined,\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n LogError(`InteractiveFormApplyService.runActionByName(${actionName}): ${message}`);\n return { Success: false, Message: message };\n }\n }\n\n /**\n * Resolve an action ID by Name. Falls back to a direct RunView against\n * the Action entity when ActionEngine isn't loaded.\n */\n private async resolveActionIdByName(name: string): Promise<string | null> {\n try {\n // ActionEngine may not be initialised in the chat surface — query directly.\n // The core Action table is registered as the \"MJ: Actions\" entity.\n const { RunView } = await import('@memberjunction/core');\n const rv = new RunView();\n const result = await rv.RunView<{ ID: string }>({\n EntityName: 'MJ: Actions',\n ExtraFilter: `Name='${name.replace(/'/g, \"''\")}'`,\n Fields: ['ID'],\n MaxRows: 1,\n ResultType: 'simple',\n });\n return result.Success ? (result.Results?.[0]?.ID ?? null) : null;\n } catch (err) {\n LogError(`InteractiveFormApplyService.resolveActionIdByName(${name}): ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n }\n\n /**\n * Activate the override produced by a successful Create so a net-new form goes\n * live immediately. Best-effort: on failure the form stays a Pending draft the\n * user can activate manually, so we log and return false rather than failing the\n * whole apply.\n */\n private async activateCreatedOverride(\n client: GraphQLActionClient,\n createMessage: string | undefined,\n ): Promise<boolean> {\n let overrideId: string | undefined;\n try {\n overrideId = (JSON.parse(createMessage ?? '{}') as { OverrideID?: string }).OverrideID;\n } catch {\n overrideId = undefined;\n }\n if (!overrideId) return false;\n const activateResult = await this.runActionByName(client, 'Activate Interactive Form Version', [\n { Name: 'OverrideID', Value: overrideId, Type: 'Input' },\n ]);\n if (!activateResult.Success) {\n LogError(`InteractiveFormApplyService: created override ${overrideId} but auto-activation failed: ${activateResult.Message ?? 'unknown error'}`);\n }\n return activateResult.Success;\n }\n\n /**\n * Align a freshly generated spec to an existing Component lineage before Modify.\n * MJ identifies a form lineage by Component Name and refuses to change it between\n * versions, so we rename the incoming spec — both `spec.name` and the root\n * `function` declaration in `spec.code` (the linter requires them to match) — to\n * the existing lineage name.\n */\n private alignSpecToLineage(spec: ComponentSpec, existingName: string): void {\n const s = spec as { name?: string; code?: string };\n const currentName = s.name;\n if (!currentName || currentName === existingName) return;\n s.name = existingName;\n if (typeof s.code === 'string' && s.code.length > 0) {\n const escaped = currentName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n s.code = s.code.replace(new RegExp(`function\\\\s+${escaped}\\\\s*\\\\(`), `function ${existingName}(`);\n }\n }\n\n /** Show a confirmation dialog explaining what's about to happen. */\n private async confirm(\n hasExistingActive: boolean,\n entityName: string,\n currentVersion: string | null | undefined,\n ): Promise<boolean> {\n // The dialog renders string content as plain text (not innerHTML), so use\n // plain text here — HTML tags would show raw.\n const content = hasExistingActive\n ? `You already have a custom form for \"${entityName}\" (v${currentVersion ?? '?'}). Applying this will create a new version and make it your active form. The previous version is preserved and can be restored from Form Builder.`\n : `This will create a custom form for \"${entityName}\" scoped to your user and make it active. Other users will continue to see the default form.`;\n // MJDialogAction surface is {text, primary?, themeColor?}; the\n // dialog's Result observable emits the entire clicked action (or\n // undefined for backdrop/X dismissal). Detect intent via the\n // `primary` flag — Apply / Create Pending are the primary actions;\n // Cancel and dismissal both resolve false.\n const ref = this.dialog.Open({\n title: 'Apply this form?',\n content,\n width: 540,\n actions: [\n { text: 'Apply', primary: true, themeColor: 'primary' },\n { text: 'Cancel' },\n ],\n });\n return new Promise<boolean>(resolve => {\n ref.Result.subscribe((res: unknown) => {\n resolve((res as { primary?: boolean })?.primary === true);\n });\n });\n }\n\n private parseActiveResult(message: string | undefined): {\n Active?: { OverrideID?: string; ComponentVersion?: string; ComponentName?: string };\n } | null {\n if (!message) return null;\n try {\n return JSON.parse(message) as { Active?: { OverrideID?: string; ComponentVersion?: string; ComponentName?: string } };\n } catch {\n return null;\n }\n }\n\n private summarize(\n result: { Success: boolean; Message?: string; ResultCode?: string },\n kind: 'create' | 'modify',\n _user: UserInfo,\n activated: boolean = false,\n ): InteractiveFormApplyResult {\n if (!result.Success) {\n this.notifications.CreateSimpleNotification(\n `Apply failed: ${result.Message ?? result.ResultCode ?? 'unknown error'}`,\n 'error', 5000,\n );\n return { Success: false, Message: result.Message };\n }\n let payload: Record<string, unknown> = {};\n try { payload = JSON.parse(result.Message ?? '{}'); } catch { /* best effort */ }\n const mode: InteractiveFormApplyResult['Mode'] = kind === 'create'\n ? 'create'\n : (payload.Mode === 'in-place' ? 'modify-in-place' : 'modify-new-version');\n const note = kind === 'create'\n ? (activated\n ? 'Custom form is now active for your user.'\n : 'Custom form created as a Pending draft — activate it from Form Builder to go live.')\n : (activated\n ? `Updated form is now active${payload.Version ? ` (v${payload.Version})` : ''} for your user.`\n : (mode === 'modify-in-place'\n ? 'Pending version updated. Activate it from Form Builder when ready.'\n : `Pending v${payload.Version ?? '?'} created. Activate it from Form Builder when ready.`));\n this.notifications.CreateSimpleNotification(note, 'success', 4000);\n return {\n Success: true,\n Mode: mode,\n OverrideID: payload.OverrideID as string | undefined,\n ComponentID: payload.ComponentID as string | undefined,\n Version: payload.Version as string | undefined,\n Message: result.Message,\n };\n }\n\n private fail(message: string): InteractiveFormApplyResult {\n this.notifications.CreateSimpleNotification(`Apply failed: ${message}`, 'error', 5000);\n return { Success: false, Message: message };\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/ng-artifacts",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.41.0",
|
|
4
4
|
"description": "MemberJunction: Artifact viewer plugin system for rendering different artifact types (JSON, Code, Markdown, HTML, SVG, Components)",
|
|
5
5
|
"main": "./dist/public-api.js",
|
|
6
6
|
"typings": "./dist/public-api.d.ts",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"/dist"
|
|
9
9
|
],
|
|
10
10
|
"scripts": {
|
|
11
|
-
"test": "
|
|
11
|
+
"test": "vitest run",
|
|
12
12
|
"build": "ngc",
|
|
13
13
|
"test:watch": "vitest"
|
|
14
14
|
},
|
|
@@ -32,23 +32,23 @@
|
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@angular/cdk": "21.1.3",
|
|
34
34
|
"@angular/forms": "21.1.3",
|
|
35
|
-
"@memberjunction/core": "5.
|
|
36
|
-
"@memberjunction/core-entities": "5.
|
|
37
|
-
"@memberjunction/global": "5.
|
|
38
|
-
"@memberjunction/graphql-dataprovider": "5.
|
|
39
|
-
"@memberjunction/interactive-component-types": "5.
|
|
40
|
-
"@memberjunction/ng-base-forms": "5.
|
|
41
|
-
"@memberjunction/ng-base-types": "5.
|
|
42
|
-
"@memberjunction/ng-code-editor": "5.
|
|
43
|
-
"@memberjunction/ng-export-service": "5.
|
|
44
|
-
"@memberjunction/ng-markdown": "5.
|
|
45
|
-
"@memberjunction/ng-notifications": "5.
|
|
46
|
-
"@memberjunction/ng-pagination": "5.
|
|
47
|
-
"@memberjunction/ng-query-viewer": "5.
|
|
48
|
-
"@memberjunction/ng-react": "5.
|
|
49
|
-
"@memberjunction/ng-shared-generic": "5.
|
|
50
|
-
"@memberjunction/ng-trees": "5.
|
|
51
|
-
"@memberjunction/ng-ui-components": "5.
|
|
35
|
+
"@memberjunction/core": "5.41.0",
|
|
36
|
+
"@memberjunction/core-entities": "5.41.0",
|
|
37
|
+
"@memberjunction/global": "5.41.0",
|
|
38
|
+
"@memberjunction/graphql-dataprovider": "5.41.0",
|
|
39
|
+
"@memberjunction/interactive-component-types": "5.41.0",
|
|
40
|
+
"@memberjunction/ng-base-forms": "5.41.0",
|
|
41
|
+
"@memberjunction/ng-base-types": "5.41.0",
|
|
42
|
+
"@memberjunction/ng-code-editor": "5.41.0",
|
|
43
|
+
"@memberjunction/ng-export-service": "5.41.0",
|
|
44
|
+
"@memberjunction/ng-markdown": "5.41.0",
|
|
45
|
+
"@memberjunction/ng-notifications": "5.41.0",
|
|
46
|
+
"@memberjunction/ng-pagination": "5.41.0",
|
|
47
|
+
"@memberjunction/ng-query-viewer": "5.41.0",
|
|
48
|
+
"@memberjunction/ng-react": "5.41.0",
|
|
49
|
+
"@memberjunction/ng-shared-generic": "5.41.0",
|
|
50
|
+
"@memberjunction/ng-trees": "5.41.0",
|
|
51
|
+
"@memberjunction/ng-ui-components": "5.41.0",
|
|
52
52
|
"mammoth": "^1.8.0",
|
|
53
53
|
"pdfjs-dist": "^4.10.38",
|
|
54
54
|
"rxjs": "^7.8.2",
|