@adminforth/foreign-inline-show 1.0.1

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.
@@ -0,0 +1,13 @@
1
+
2
+ #!/bin/bash
3
+
4
+ # write npm run output both to console and to build.log
5
+ npm run build 2>&1 | tee build.log
6
+ build_status=${PIPESTATUS[0]}
7
+
8
+ # if exist status from the npm run build is not 0
9
+ # then exit with the status code from the npm run build
10
+ if [ $build_status -ne 0 ]; then
11
+ echo "Build failed. Exiting with status code $build_status"
12
+ exit $build_status
13
+ fi
@@ -0,0 +1,44 @@
1
+ #!/bin/sh
2
+
3
+ set -x
4
+
5
+ COMMIT_SHORT_SHA=$(echo $CI_COMMIT_SHA | cut -c1-8)
6
+
7
+
8
+ if [ "$CI_STEP_STATUS" = "success" ]; then
9
+ MESSAGE="Did a build without issues on \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\`. Commit: _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
10
+
11
+ curl -s -X POST -H "Content-Type: application/json" -d '{
12
+ "username": "'"$CI_COMMIT_AUTHOR"'",
13
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
14
+ "attachments": [
15
+ {
16
+ "mrkdwn_in": ["text", "pretext"],
17
+ "color": "#36a64f",
18
+ "text": "'"$MESSAGE"'"
19
+ }
20
+ ]
21
+ }' "$DEVELOPERS_SLACK_WEBHOOK"
22
+ exit 0
23
+ fi
24
+ export BUILD_LOG=$(cat ./build.log)
25
+
26
+ BUILD_LOG=$(echo $BUILD_LOG | sed 's/"/\\"/g')
27
+
28
+ MESSAGE="Broke \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\` with commit _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
29
+ CODE_BLOCK="\`\`\`$BUILD_LOG\n\`\`\`"
30
+
31
+ echo "Sending slack message to developers $MESSAGE"
32
+ # Send the message
33
+ curl -sS -X POST -H "Content-Type: application/json" -d '{
34
+ "username": "'"$CI_COMMIT_AUTHOR"'",
35
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
36
+ "attachments": [
37
+ {
38
+ "mrkdwn_in": ["text", "pretext"],
39
+ "color": "#8A1C12",
40
+ "text": "'"$CODE_BLOCK"'",
41
+ "pretext": "'"$MESSAGE"'"
42
+ }
43
+ ]
44
+ }' "$DEVELOPERS_SLACK_WEBHOOK" 2>&1
@@ -0,0 +1,40 @@
1
+ clone:
2
+ git:
3
+ image: woodpeckerci/plugin-git
4
+ settings:
5
+ partial: false
6
+ depth: 5
7
+
8
+ steps:
9
+ init-secrets:
10
+ when:
11
+ - event: push
12
+ image: infisical/cli
13
+ environment:
14
+ INFISICAL_TOKEN:
15
+ from_secret: VAULT_TOKEN
16
+ commands:
17
+ - infisical export --domain https://vault.devforth.io/api --format=dotenv-export --env="prod" > /woodpecker/deploy.vault.env
18
+
19
+ release:
20
+ image: node:20
21
+ when:
22
+ - event: push
23
+ commands:
24
+ - apt update && apt install -y rsync
25
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
26
+ - npm clean-install
27
+ - /bin/bash ./.woodpecker/buildRelease.sh
28
+ - npm audit signatures
29
+ - npx semantic-release
30
+
31
+ slack-on-failure:
32
+ when:
33
+ - event: push
34
+ status: [failure, success]
35
+ - event: push
36
+ image: curlimages/curl
37
+ commands:
38
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
39
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh
40
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+
2
+ # Changelog
3
+
4
+ The complete changelog is available on the [GitHub Releases page](https://github.com/devforth/adminforth-foreign-inline-list/releases).
5
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Devforth.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # AdminForth ForeignInlineList Plugin
2
+
3
+ <img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT" /> <img src="https://woodpecker.devforth.io/api/badges/3848/status.svg" alt="Build Status" /> <a href="https://www.npmjs.com/package/@adminforth/foreign-inline-show"> <img src="https://img.shields.io/npm/dt/@adminforth/foreign-inline-show" alt="npm downloads" /></a> <a href="https://www.npmjs.com/package/@adminforth/foreign-inline-show"><img src="https://img.shields.io/npm/v/@adminforth/foreign-inline-show" alt="npm version" /></a> <a href="https://www.npmjs.com/package/@adminforth/foreign-inline-show">
4
+
5
+ Allows to add an inline show of connected foreign resource records on a adminforth show page.
6
+
7
+ ## For usage, see [AdminForth ForeignInlineList Documentation](https://adminforth.dev/docs/tutorial/Plugins/ForeignInlineList/)
package/build.log ADDED
@@ -0,0 +1,10 @@
1
+
2
+ > @adminforth/foreign-inline-show@1.0.27 build
3
+ > tsc && rsync -av --exclude 'node_modules' custom dist/
4
+
5
+ sending incremental file list
6
+ custom/
7
+ custom/InlineShow.vue
8
+
9
+ sent 4,078 bytes received 39 bytes 8,234.00 bytes/sec
10
+ total size is 3,934 speedup is 0.96
@@ -0,0 +1,122 @@
1
+ <template>
2
+ <td colspan="2" class="pb-3 px-0 pt-0">
3
+ <div v-if="loading" role="status" class="max-w-sm animate-pulse">
4
+ <div class="h-2.5 bg-gray-200 rounded-full dark:bg-gray-700 w-48 mb-4"></div>
5
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px] mb-2.5"></div>
6
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 mb-2.5"></div>
7
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[330px] mb-2.5"></div>
8
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[300px] mb-2.5"></div>
9
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px]"></div>
10
+ <span class="sr-only">{{ $t('Loading...') }}</span>
11
+ </div>
12
+ <div
13
+ v-else-if="coreStore.record"
14
+ class="relative w-full flex flex-col gap-4"
15
+ >
16
+ <div class="flex items-center gap-1">
17
+ <h4 v-if="parentRecord"
18
+ class="px-6 py-4"
19
+ >{{ listResource.label }} {{$t('inline record')}}</h4>
20
+ </div>
21
+ <div v-if="parentRecord">
22
+ <ShowTable
23
+ :columns="filteredColumns"
24
+ :resource="listResource"
25
+ :record="parentRecord"
26
+ />
27
+ </div>
28
+ </div>
29
+ </td>
30
+ </template>
31
+
32
+
33
+ <script setup lang="ts">
34
+ import { useCoreStore } from '@/stores/core';
35
+ import { onMounted, ref, computed, watchEffect } from 'vue';
36
+ import {callAdminForthApi} from '@/utils';
37
+ import { showSuccesTost, showErrorTost } from '@/composables/useFrontendApi';
38
+ import ShowTable from '@/components/ShowTable.vue';
39
+ import { useI18n } from 'vue-i18n';
40
+
41
+
42
+ const sort = ref([]);
43
+ const parentRecord = ref(null);
44
+ const props = defineProps(['column', 'record', 'meta', 'resource', 'adminUser']);
45
+ const loading = ref(true);
46
+ const { t } = useI18n();
47
+ const coreStore = useCoreStore();
48
+ const listResource = ref(null);
49
+
50
+ const parentResourceRefColumn = computed(() => {
51
+ if (!props.resource || !listResource.value) return null;
52
+
53
+ return props.resource.columns.find(c =>
54
+ c.foreignResource?.polymorphicResources
55
+ ? c.foreignResource.polymorphicResources.some(pr => pr.resourceId === listResource.value.resourceId)
56
+ : c.foreignResource?.resourceId === listResource.value.resourceId
57
+ );
58
+ });
59
+
60
+ onMounted(async () => {
61
+ listResource.value = (await callAdminForthApi({
62
+ path: `/plugin/${props.meta.pluginInstanceId}/get_resource`,
63
+ method: 'POST',
64
+ body: {},
65
+ })).resource;
66
+ await getParentRecord();
67
+
68
+ });
69
+
70
+ async function getParentRecord() {
71
+ if (!listResource.value || !parentResourceRefColumn.value) {
72
+ console.warn('No parent resource or reference column found');
73
+ parentRecord.value = null;
74
+ loading.value = false;
75
+ }
76
+
77
+ const foreignKeyValue = props.record[parentResourceRefColumn.value.name];
78
+ if (!foreignKeyValue) {
79
+ console.warn('No foreign key value found in the record', props.record);
80
+ parentRecord.value = null;
81
+ loading.value = false;
82
+ }
83
+
84
+ const data = await callAdminForthApi({
85
+ path: '/get_resource_data',
86
+ method: 'POST',
87
+ body: {
88
+ source: 'show',
89
+ resourceId: listResource.value.resourceId,
90
+ filters: [{
91
+ field: listResource.value.columns.find(c => c.primaryKey).name,
92
+ operator: 'eq',
93
+ value: foreignKeyValue.pk ?? foreignKeyValue,
94
+ }],
95
+ limit: 1,
96
+ offset: 0,
97
+ sort: Array.isArray(sort.value) ? sort.value : [],
98
+ },
99
+ });
100
+ if (!data) {
101
+ console.error('No data returned from API', data);
102
+ parentRecord.value = null;
103
+ loading.value = false;
104
+ }
105
+ if (data.error) {
106
+ showErrorTost(data.error);
107
+ parentRecord.value = null;
108
+ loading.value = false;
109
+ }
110
+ loading.value = false;
111
+ parentRecord.value = data.data?.[0] || null;
112
+ }
113
+ const filteredColumns = computed(() => {
114
+ return listResource.value?.columns?.filter(col => {
115
+ const isInjectedField =
116
+ col.virtual && col.name?.startsWith('foreignInlineList_');
117
+
118
+ return col.showIn?.show && !isInjectedField;
119
+ }) || [];
120
+ });
121
+ </script>
122
+
@@ -0,0 +1,122 @@
1
+ <template>
2
+ <td colspan="2" class="pb-3 px-0 pt-0">
3
+ <div v-if="loading" role="status" class="max-w-sm animate-pulse">
4
+ <div class="h-2.5 bg-gray-200 rounded-full dark:bg-gray-700 w-48 mb-4"></div>
5
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px] mb-2.5"></div>
6
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 mb-2.5"></div>
7
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[330px] mb-2.5"></div>
8
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[300px] mb-2.5"></div>
9
+ <div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px]"></div>
10
+ <span class="sr-only">{{ $t('Loading...') }}</span>
11
+ </div>
12
+ <div
13
+ v-else-if="coreStore.record"
14
+ class="relative w-full flex flex-col gap-4"
15
+ >
16
+ <div class="flex items-center gap-1">
17
+ <h4 v-if="parentRecord"
18
+ class="px-6 py-4"
19
+ >{{ listResource.label }} {{$t('inline record')}}</h4>
20
+ </div>
21
+ <div v-if="parentRecord">
22
+ <ShowTable
23
+ :columns="filteredColumns"
24
+ :resource="listResource"
25
+ :record="parentRecord"
26
+ />
27
+ </div>
28
+ </div>
29
+ </td>
30
+ </template>
31
+
32
+
33
+ <script setup lang="ts">
34
+ import { useCoreStore } from '@/stores/core';
35
+ import { onMounted, ref, computed, watchEffect } from 'vue';
36
+ import {callAdminForthApi} from '@/utils';
37
+ import { showSuccesTost, showErrorTost } from '@/composables/useFrontendApi';
38
+ import ShowTable from '@/components/ShowTable.vue';
39
+ import { useI18n } from 'vue-i18n';
40
+
41
+
42
+ const sort = ref([]);
43
+ const parentRecord = ref(null);
44
+ const props = defineProps(['column', 'record', 'meta', 'resource', 'adminUser']);
45
+ const loading = ref(true);
46
+ const { t } = useI18n();
47
+ const coreStore = useCoreStore();
48
+ const listResource = ref(null);
49
+
50
+ const parentResourceRefColumn = computed(() => {
51
+ if (!props.resource || !listResource.value) return null;
52
+
53
+ return props.resource.columns.find(c =>
54
+ c.foreignResource?.polymorphicResources
55
+ ? c.foreignResource.polymorphicResources.some(pr => pr.resourceId === listResource.value.resourceId)
56
+ : c.foreignResource?.resourceId === listResource.value.resourceId
57
+ );
58
+ });
59
+
60
+ onMounted(async () => {
61
+ listResource.value = (await callAdminForthApi({
62
+ path: `/plugin/${props.meta.pluginInstanceId}/get_resource`,
63
+ method: 'POST',
64
+ body: {},
65
+ })).resource;
66
+ await getParentRecord();
67
+
68
+ });
69
+
70
+ async function getParentRecord() {
71
+ if (!listResource.value || !parentResourceRefColumn.value) {
72
+ console.warn('No parent resource or reference column found');
73
+ parentRecord.value = null;
74
+ loading.value = false;
75
+ }
76
+
77
+ const foreignKeyValue = props.record[parentResourceRefColumn.value.name];
78
+ if (!foreignKeyValue) {
79
+ console.warn('No foreign key value found in the record', props.record);
80
+ parentRecord.value = null;
81
+ loading.value = false;
82
+ }
83
+
84
+ const data = await callAdminForthApi({
85
+ path: '/get_resource_data',
86
+ method: 'POST',
87
+ body: {
88
+ source: 'show',
89
+ resourceId: listResource.value.resourceId,
90
+ filters: [{
91
+ field: listResource.value.columns.find(c => c.primaryKey).name,
92
+ operator: 'eq',
93
+ value: foreignKeyValue.pk ?? foreignKeyValue,
94
+ }],
95
+ limit: 1,
96
+ offset: 0,
97
+ sort: Array.isArray(sort.value) ? sort.value : [],
98
+ },
99
+ });
100
+ if (!data) {
101
+ console.error('No data returned from API', data);
102
+ parentRecord.value = null;
103
+ loading.value = false;
104
+ }
105
+ if (data.error) {
106
+ showErrorTost(data.error);
107
+ parentRecord.value = null;
108
+ loading.value = false;
109
+ }
110
+ loading.value = false;
111
+ parentRecord.value = data.data?.[0] || null;
112
+ }
113
+ const filteredColumns = computed(() => {
114
+ return listResource.value?.columns?.filter(col => {
115
+ const isInjectedField =
116
+ col.virtual && col.name?.startsWith('foreignInlineList_');
117
+
118
+ return col.showIn?.show && !isInjectedField;
119
+ }) || [];
120
+ });
121
+ </script>
122
+
package/dist/index.js ADDED
@@ -0,0 +1,132 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import clone from 'clone';
11
+ import { AdminForthPlugin, suggestIfTypo } from "adminforth";
12
+ import { interpretResource, ActionCheckSource } from "adminforth";
13
+ export default class ForeignInlineShowPlugin extends AdminForthPlugin {
14
+ constructor(options) {
15
+ super(options, import.meta.url);
16
+ this.options = options;
17
+ }
18
+ instanceUniqueRepresentation(pluginOptions) {
19
+ return `${pluginOptions.foreignResourceId}`;
20
+ }
21
+ setupEndpoints(server) {
22
+ process.env.HEAVY_DEBUG && console.log(`🪲 ForeignInlineShowPlugin.setupEndpoints, registering: '/plugin/${this.pluginInstanceId}/get_resource'`);
23
+ server.endpoint({
24
+ method: 'POST',
25
+ path: `/plugin/${this.pluginInstanceId}/get_resource`,
26
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser }) {
27
+ const resource = this.adminforth.config.resources.find((res) => this.options.foreignResourceId === res.resourceId);
28
+ if (!resource) {
29
+ return { error: `Resource ${this.options.foreignResourceId} not found` };
30
+ }
31
+ const resourceCopy = clone(Object.assign(Object.assign({}, resource), { plugins: undefined }));
32
+ if (this.options.modifyTableResourceConfig) {
33
+ this.options.modifyTableResourceConfig(resourceCopy);
34
+ }
35
+ const { allowedActions } = yield interpretResource(adminUser, resourceCopy, {}, ActionCheckSource.DisplayButtons, this.adminforth);
36
+ return {
37
+ resource: Object.assign(Object.assign({}, resourceCopy), { options: Object.assign(Object.assign({}, resourceCopy.options), { allowedActions }) })
38
+ };
39
+ })
40
+ });
41
+ server.endpoint({
42
+ method: 'POST',
43
+ path: `/plugin/${this.pluginInstanceId}/start_bulk_action`,
44
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, tr }) {
45
+ const { resourceId, actionId, recordIds } = body;
46
+ const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
47
+ if (!resource) {
48
+ return { error: yield tr(`Resource {resourceId} not found`, 'errors', { resourceId }) };
49
+ }
50
+ const resourceCopy = JSON.parse(JSON.stringify(Object.assign(Object.assign({}, resource), { plugins: undefined })));
51
+ if (this.options.modifyTableResourceConfig) {
52
+ this.options.modifyTableResourceConfig(resourceCopy);
53
+ }
54
+ const { allowedActions } = yield interpretResource(adminUser, resourceCopy, { requestBody: body }, ActionCheckSource.BulkActionRequest, this.adminforth);
55
+ const action = resourceCopy.options.bulkActions.find((act) => act.id == actionId);
56
+ if (!action) {
57
+ return { error: yield tr(`Action {actionId} not found`, 'errors', { actionId }) };
58
+ }
59
+ if (action.allowed) {
60
+ const execAllowed = yield action.allowed({ adminUser, resourceCopy, selectedIds: recordIds, allowedActions });
61
+ if (!execAllowed) {
62
+ return { error: yield tr(`Action "{actionId}" not allowed`, 'errors', { actionId: action.label }) };
63
+ }
64
+ }
65
+ const response = yield action.action({ selectedIds: recordIds, adminUser, resourceCopy, tr });
66
+ return Object.assign({ actionId,
67
+ recordIds,
68
+ resourceId }, response);
69
+ })
70
+ });
71
+ }
72
+ modifyResourceConfig(adminforth, resourceConfig) {
73
+ const _super = Object.create(null, {
74
+ modifyResourceConfig: { get: () => super.modifyResourceConfig }
75
+ });
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ var _a, _b, _c, _d, _e;
78
+ _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
79
+ this.adminforth = adminforth;
80
+ this.foreignResource = adminforth.config.resources.find((resource) => resource.resourceId === this.options.foreignResourceId);
81
+ if (!this.foreignResource) {
82
+ const similar = suggestIfTypo(adminforth.config.resources.map((res) => res.resourceId), this.options.foreignResourceId);
83
+ throw new Error(`ForeignInlineShowPlugin: Resource with ID "${this.options.foreignResourceId}" not found. ${similar ? `Did you mean "${similar}"?` : ''}`);
84
+ }
85
+ const newColumn = {
86
+ name: `foreignInlineShow_${this.foreignResource.resourceId}`,
87
+ label: 'Foreign Inline Show',
88
+ virtual: true,
89
+ showIn: {
90
+ show: true,
91
+ list: false,
92
+ edit: false,
93
+ create: false,
94
+ filter: false,
95
+ },
96
+ components: {
97
+ showRow: {
98
+ file: this.componentPath('InlineShow.vue'),
99
+ meta: Object.assign(Object.assign({}, this.options), { pluginInstanceId: this.pluginInstanceId })
100
+ }
101
+ },
102
+ };
103
+ if ((_a = this.options.placeInGroup) === null || _a === void 0 ? void 0 : _a.name) {
104
+ const fieldGroupTypes = [
105
+ 'fieldGroups',
106
+ 'createFieldGroups',
107
+ 'editFieldGroups',
108
+ 'showFieldGroups'
109
+ ];
110
+ let columnAdded = false;
111
+ for (const groupType of fieldGroupTypes) {
112
+ const targetGroup = (_c = (_b = resourceConfig.options) === null || _b === void 0 ? void 0 : _b[groupType]) === null || _c === void 0 ? void 0 : _c.find(group => { var _a; return group.groupName === ((_a = this.options.placeInGroup) === null || _a === void 0 ? void 0 : _a.name); });
113
+ if (targetGroup) {
114
+ if (this.options.placeInGroup.position < 0 || this.options.placeInGroup.position > targetGroup.columns.length) {
115
+ throw new Error(`ForeignInlineShowPlugin: Invalid position ${(_d = this.options.placeInGroup) === null || _d === void 0 ? void 0 : _d.position}. Must be between 0 and ${targetGroup.columns.length} for group "${(_e = this.options.placeInGroup) === null || _e === void 0 ? void 0 : _e.name}"`);
116
+ }
117
+ if (!columnAdded) {
118
+ const beforeColumnName = targetGroup.columns[this.options.placeInGroup.position - 1];
119
+ const beforeColumnIndex = resourceConfig.columns.findIndex(col => col.name === beforeColumnName);
120
+ resourceConfig.columns.splice(beforeColumnIndex + 1, 0, newColumn);
121
+ columnAdded = true;
122
+ }
123
+ targetGroup.columns.splice(this.options.placeInGroup.position, 0, newColumn.name);
124
+ }
125
+ }
126
+ }
127
+ else {
128
+ resourceConfig.columns.push(newColumn);
129
+ }
130
+ });
131
+ }
132
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,171 @@
1
+ import type {
2
+ AdminForthResource,
3
+ IAdminForth,
4
+ IHttpServer,
5
+ } from "adminforth";
6
+ import clone from 'clone';
7
+
8
+ import { AdminForthPlugin, AdminForthResourcePages, suggestIfTypo } from "adminforth";
9
+ import { PluginOptions } from "./types.js";
10
+ import { interpretResource, ActionCheckSource } from "adminforth";
11
+
12
+ export default class ForeignInlineShowPlugin extends AdminForthPlugin {
13
+ foreignResource: AdminForthResource;
14
+ options: PluginOptions;
15
+ adminforth: IAdminForth;
16
+
17
+ constructor(options: PluginOptions) {
18
+ super(options, import.meta.url);
19
+ this.options = options;
20
+ }
21
+
22
+ instanceUniqueRepresentation(pluginOptions: any) : string {
23
+ return `${pluginOptions.foreignResourceId}`;
24
+ }
25
+
26
+ setupEndpoints(server: IHttpServer) {
27
+ process.env.HEAVY_DEBUG && console.log(`🪲 ForeignInlineShowPlugin.setupEndpoints, registering: '/plugin/${this.pluginInstanceId}/get_resource'`);
28
+ server.endpoint({
29
+ method: 'POST',
30
+ path: `/plugin/${this.pluginInstanceId}/get_resource`,
31
+ handler: async ({ body, adminUser }) => {
32
+ const resource = this.adminforth.config.resources.find((res) => this.options.foreignResourceId === res.resourceId);
33
+ if (!resource) {
34
+ return { error: `Resource ${this.options.foreignResourceId} not found` };
35
+ }
36
+ const resourceCopy = clone({ ...resource, plugins: undefined });
37
+
38
+ if (this.options.modifyTableResourceConfig) {
39
+ this.options.modifyTableResourceConfig(resourceCopy);
40
+ }
41
+
42
+ const { allowedActions } = await interpretResource(adminUser, resourceCopy, {}, ActionCheckSource.DisplayButtons, this.adminforth);
43
+
44
+ return {
45
+ resource: {
46
+ ...resourceCopy,
47
+ options: {
48
+ ...resourceCopy.options,
49
+ allowedActions,
50
+ },
51
+ }
52
+ };
53
+ }
54
+ });
55
+ server.endpoint({
56
+ method: 'POST',
57
+ path: `/plugin/${this.pluginInstanceId}/start_bulk_action`,
58
+ handler: async ({ body, adminUser, tr }) => {
59
+ const { resourceId, actionId, recordIds } = body;
60
+ const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
61
+ if (!resource) {
62
+ return { error: await tr(`Resource {resourceId} not found`, 'errors', { resourceId }) };
63
+ }
64
+
65
+ const resourceCopy = JSON.parse(JSON.stringify({ ...resource, plugins: undefined }));
66
+
67
+
68
+ if (this.options.modifyTableResourceConfig) {
69
+ this.options.modifyTableResourceConfig(resourceCopy);
70
+ }
71
+
72
+ const { allowedActions } = await interpretResource(
73
+ adminUser,
74
+ resourceCopy,
75
+ { requestBody: body },
76
+ ActionCheckSource.BulkActionRequest,
77
+ this.adminforth
78
+ );
79
+
80
+ const action = resourceCopy.options.bulkActions.find((act) => act.id == actionId);
81
+ if (!action) {
82
+ return { error: await tr(`Action {actionId} not found`, 'errors', { actionId }) };
83
+ }
84
+
85
+ if (action.allowed) {
86
+ const execAllowed = await action.allowed({ adminUser, resourceCopy, selectedIds: recordIds, allowedActions });
87
+ if (!execAllowed) {
88
+ return { error: await tr(`Action "{actionId}" not allowed`, 'errors', { actionId: action.label }) };
89
+ }
90
+ }
91
+ const response = await action.action({selectedIds: recordIds, adminUser, resourceCopy, tr});
92
+
93
+ return {
94
+ actionId,
95
+ recordIds,
96
+ resourceId,
97
+ ...response
98
+ }
99
+ }
100
+ })
101
+ }
102
+
103
+ async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
104
+ super.modifyResourceConfig(adminforth, resourceConfig);
105
+ this.adminforth = adminforth;
106
+
107
+ this.foreignResource = adminforth.config.resources.find((resource) => resource.resourceId === this.options.foreignResourceId);
108
+ if (!this.foreignResource) {
109
+ const similar = suggestIfTypo(adminforth.config.resources.map((res) => res.resourceId), this.options.foreignResourceId);
110
+ throw new Error(`ForeignInlineShowPlugin: Resource with ID "${this.options.foreignResourceId}" not found. ${similar ? `Did you mean "${similar}"?` : ''}`);
111
+ }
112
+
113
+ const newColumn = {
114
+ name: `foreignInlineShow_${this.foreignResource.resourceId}`,
115
+ label: 'Foreign Inline Show',
116
+ virtual: true,
117
+ showIn: {
118
+ show: true,
119
+ list: false,
120
+ edit: false,
121
+ create: false,
122
+ filter: false,
123
+ },
124
+ components: {
125
+ showRow: {
126
+ file: this.componentPath('InlineShow.vue'),
127
+ meta: {
128
+ ...this.options,
129
+ pluginInstanceId: this.pluginInstanceId
130
+ }
131
+ }
132
+ },
133
+ };
134
+
135
+ if (this.options.placeInGroup?.name) {
136
+ const fieldGroupTypes = [
137
+ 'fieldGroups',
138
+ 'createFieldGroups',
139
+ 'editFieldGroups',
140
+ 'showFieldGroups'
141
+ ] as const;
142
+
143
+ let columnAdded = false;
144
+
145
+ for (const groupType of fieldGroupTypes) {
146
+ const targetGroup = resourceConfig.options?.[groupType]?.find(
147
+ group => group.groupName === this.options.placeInGroup?.name
148
+ );
149
+
150
+ if (targetGroup) {
151
+ if (this.options.placeInGroup.position < 0 || this.options.placeInGroup.position > targetGroup.columns.length) {
152
+ throw new Error(`ForeignInlineShowPlugin: Invalid position ${this.options.placeInGroup?.position}. Must be between 0 and ${targetGroup.columns.length} for group "${this.options.placeInGroup?.name}"`);
153
+ }
154
+
155
+ if (!columnAdded) {
156
+ const beforeColumnName = targetGroup.columns[this.options.placeInGroup.position - 1];
157
+ const beforeColumnIndex = resourceConfig.columns.findIndex(
158
+ col => col.name === beforeColumnName
159
+ );
160
+ resourceConfig.columns.splice(beforeColumnIndex + 1, 0, newColumn);
161
+ columnAdded = true;
162
+ }
163
+
164
+ targetGroup.columns.splice(this.options.placeInGroup.position, 0, newColumn.name);
165
+ }
166
+ }
167
+ } else {
168
+ resourceConfig.columns.push(newColumn);
169
+ }
170
+ }
171
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@adminforth/foreign-inline-show",
3
+ "version": "1.0.1",
4
+ "description": "AdminForth plugin for adding show of parent item to the child items show page",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "homepage": "https://adminforth.dev/docs/tutorial/Plugins/ForeignInlineShow/",
9
+ "scripts": {
10
+ "build": "tsc && rsync -av --exclude 'node_modules' custom dist/",
11
+ "prepare": "npm link adminforth"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/devforth/adminforth-foreign-inline-show.git"
16
+ },
17
+ "author": "devforth",
18
+ "keywords": [
19
+ "adminforth",
20
+ "show foreign items"
21
+ ],
22
+ "license": "ISC",
23
+ "devDependencies": {
24
+ "@types/node": "^22.10.7",
25
+ "semantic-release": "^24.2.1",
26
+ "semantic-release-slack-bot": "^4.0.2",
27
+ "typescript": "^5.7.3"
28
+ },
29
+ "release": {
30
+ "plugins": [
31
+ "@semantic-release/commit-analyzer",
32
+ "@semantic-release/release-notes-generator",
33
+ "@semantic-release/npm",
34
+ "@semantic-release/github",
35
+ [
36
+ "semantic-release-slack-bot",
37
+ {
38
+ "notifyOnSuccess": true,
39
+ "notifyOnFail": true,
40
+ "slackIcon": ":package:",
41
+ "markdownReleaseNotes": true
42
+ }
43
+ ]
44
+ ],
45
+ "branches": [
46
+ "main",
47
+ {
48
+ "name": "next",
49
+ "prerelease": true
50
+ }
51
+ ]
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "dependencies": {
57
+ "clone": "^2.1.2"
58
+ }
59
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+
14
+ /* Language and Environment */
15
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
16
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
17
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
18
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
+
28
+ /* Modules */
29
+ // changed from commmonjs to node16 because The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.
30
+ "module": "node16", /* Specify what module code is generated. */
31
+ // "rootDir": "./", /* Specify the root folder within your source files. */
32
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
33
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
34
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
35
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
36
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
37
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
38
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
39
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
40
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
41
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
+ // "resolveJsonModule": true, /* Enable importing .json files. */
45
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
46
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
47
+
48
+ /* JavaScript Support */
49
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
50
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
51
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
52
+
53
+ /* Emit */
54
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
55
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
56
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
57
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
60
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
61
+ // "removeComments": true, /* Disable emitting comments. */
62
+ // "noEmit": true, /* Disable emitting files from a compilation. */
63
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
64
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
65
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
71
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
77
+
78
+ /* Interop Constraints */
79
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
80
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
81
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
82
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
83
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
84
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
85
+
86
+ /* Type Checking */
87
+ "strict": false, /* TODO */ /* Enable all strict type-checking options. */
88
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
89
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
90
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
91
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
92
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
93
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
94
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
95
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
96
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
97
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
98
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
99
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
100
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
101
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
102
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
103
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
104
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
105
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
106
+
107
+ /* Completeness */
108
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
109
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
110
+ },
111
+ "exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
112
+ }
package/types.ts ADDED
@@ -0,0 +1,32 @@
1
+
2
+ import { AdminForthResource } from 'adminforth';
3
+
4
+ export type PluginOptions = {
5
+
6
+ /**
7
+ * Id of the resource to be displayed in the inline list.
8
+ *
9
+ * Resource mandatory should have one columns which defined {@link AdminForthResourceColumn.foreignResource} which
10
+ * should be equal to the resourceId of the resource where plugin is used.
11
+ */
12
+ foreignResourceId: string;
13
+
14
+ /**
15
+ * Function to modify the resource config of the table.
16
+ * Can be used to define list of columns visible in the inline list.
17
+ * Or modify listPageSize
18
+ *
19
+ * @param resourceConfig - Resource config of the table.
20
+ */
21
+ modifyTableResourceConfig?: (resourceConfig: AdminForthResource) => void;
22
+
23
+ /**
24
+ * Place the component in a specific group.
25
+ *
26
+ * @param group - Group to place the component in.
27
+ */
28
+ placeInGroup?: {
29
+ name: string;
30
+ position: number;
31
+ };
32
+ }