Skip to content

Commit

Permalink
ENH Simplify APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Sep 25, 2023
1 parent 7a16b8b commit 9186d20
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 212 deletions.
1 change: 0 additions & 1 deletion _config.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@

// Avoid creating global variables
call_user_func(function () {

});
8 changes: 0 additions & 8 deletions _config/graphql.yml

This file was deleted.

6 changes: 0 additions & 6 deletions _graphql/queries.yml

This file was deleted.

11 changes: 0 additions & 11 deletions _graphql/types.yml

This file was deleted.

2 changes: 1 addition & 1 deletion client/dist/js/bundle.js

Large diffs are not rendered by default.

5 changes: 0 additions & 5 deletions client/src/boot/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
/* global document */
/* eslint-disable */
import Config from 'lib/Config';
import registerReducers from './registerReducers';
import registerComponents from './registerComponents';
import registerQueries from './registerQueries';

document.addEventListener('DOMContentLoaded', () => {
registerComponents();

registerQueries();

registerReducers();
});
10 changes: 0 additions & 10 deletions client/src/boot/registerQueries.js

This file was deleted.

50 changes: 35 additions & 15 deletions client/src/components/LinkField/LinkField.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,62 @@
import React, { Fragment, useState } from 'react';
import React, { Fragment, useState, useEffect } from 'react';
import { compose } from 'redux';
import { inject, injectGraphql, loadComponent } from 'lib/Injector';
import { inject, loadComponent } from 'lib/Injector';
import fieldHolder from 'components/FieldHolder/FieldHolder';

const LinkField = ({ id, loading, Loading, data, LinkPicker, onChange, types, linkDescription, ...props }) => {
if (loading) {
return <Loading />;
}

// id, onChange, dataStr - come from entwine/JsonField.js
// LinkPicker, Loading - come from inject(['LinkPicker', 'Loading']),
const LinkField = ({ id, onChange, dataStr, Loading, LinkPicker }) => {
const [types, setTypes] = useState([]);
const [description, setDescription] = useState(null);
const [editing, setEditing] = useState(false);
const [newTypeKey, setNewTypeKey] = useState('');

const onClear = (event) => {
if (typeof onChange !== 'function') {
return;
}

onChange(event, { id, value: {} });
};

// Utility function to make a GET request to the server
const fetchData = (path, onFetched) => {
(async () => fetch(path))()
.then(response => response.json())
.then(onFetched);
};

// Request of types data from server only on the initial load of the component
useEffect(() => {
fetchData('/admin/linkfield/types', (responseJson) => setTypes(responseJson));
}, []);

// Make a request to the server for the description of the link when editing changes to false
// and on the initial load of the component
useEffect(() => {
if (!editing) {
const path = `/admin/linkfield/description?data=${encodeURI(dataStr)}`;
fetchData(path, (responseJson) => setDescription(responseJson.description));
}
}, [editing]);

if (types.length === 0 || description === null) {
return <Loading />;
}

const data = JSON.parse(dataStr);
const { typeKey } = data;
const type = types[typeKey];
const modalType = newTypeKey ? types[newTypeKey] : type;

let title = data ? data.Title : '';

if (!title) {
title = data ? data.TitleRelField : '';
}

const linkProps = {
title,
link: type ? { type, title, description: linkDescription } : undefined,
// link: type ? { type, title, description: linkDescription } : undefined,
link: type ? { type, title, description } : undefined,
onEdit: () => { setEditing(true); },
onClear,
onSelect: (key) => {
Expand All @@ -43,14 +68,11 @@ const LinkField = ({ id, loading, Loading, data, LinkPicker, onChange, types, li

const onModalSubmit = (modalData, action, submitFn) => {
const { SecurityID, action_insert: actionInsert, ...value } = modalData;

if (typeof onChange === 'function') {
onChange(event, { id, value });
}

setEditing(false);
setNewTypeKey('');

return Promise.resolve();
};

Expand Down Expand Up @@ -83,8 +105,6 @@ const stringifyData = (Component) => (({ data, value, ...props }) => {

export default compose(
inject(['LinkPicker', 'Loading']),
injectGraphql('readLinkTypes'),
stringifyData,
injectGraphql('readLinkDescription'),
fieldHolder
)(LinkField);
43 changes: 0 additions & 43 deletions client/src/state/linkDescription/readLinkDescription.js

This file was deleted.

48 changes: 0 additions & 48 deletions client/src/state/linkTypes/readLinkTypes.js

This file was deleted.

79 changes: 79 additions & 0 deletions src/Extensions/LeftAndMain.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@

namespace SilverStripe\LinkField\Extensions;

use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Extension;
use SilverStripe\LinkField\Type\Registry;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Control\HTTPRequest;

/**
* Register a new Form Schema in LeftAndMain.
*/
class LeftAndMain extends Extension
{
private static $allowed_actions = [
'linkfield',
];

public function init()
{
// Get the Link Registry to load all the JS requirements for managing Links.
Expand All @@ -22,4 +29,76 @@ public function updateClientConfig(&$clientConfig)
'schemaUrl' => $this->getOwner()->Link('methodSchema/Modals/DynamicLink'),
];
}

/**
* Endoint for /admin/linkfield/*
*/
public function linkfield(): HTTPResponse
{
$request = $this->getOwner()->getRequest();
if (!$request->isGET()) {
throw new HTTPResponse_Exception('Only GET requests are allowed');
}
$action = $request->param('ID');
if ($action === 'description') {
return $this->description();
} elseif ($action === 'types') {
return $this->types();
}
throw new HTTPResponse_Exception('Invalid action');
}

/**
* /admin/linkfield/description/{json}
*/
private function description(): HTTPResponse
{
/** @var HTTPRequest $request */
$request = $this->getOwner()->getRequest();
$jsonStr = $request->getVar('data');
// data will be an empty array if there is no existing link
$data = json_decode($jsonStr, true);
$description = '';
if (json_last_error() !== JSON_ERROR_NONE) {
throw new HTTPResponse_Exception('data is not a valid JSON string');
}
if (array_key_exists('typeKey', $data)) {
$typeKey = $data['typeKey'];
/** @var Type $type */
$type = Registry::singleton()->byKey($typeKey);
if (!$type) {
throw new HTTPResponse_Exception('typeKey is not allowed');
}
$description = $type->generateLinkDescription($data);
}
return $this->jsonResponse([
'description' => $description
]);
}

/**
* /admin/linkfield/types
*/
private function types(): HTTPResponse
{
$data = [];
/** @var Type $type */
foreach (Registry::singleton()->list() as $key => $type) {
$data[$key] = [
'key' => $key,
'handlerName' => $type->LinkTypeHandlerName(),
'title' => $type->LinkTypeTile()
];
}
return $this->jsonResponse($data);
}

private function jsonResponse(array $data)
{
$response = $this->getOwner()->getResponse();
$jsonStr = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$response->setBody($jsonStr);
$response->addHeader('Content-type', 'application/json');
return $response;
}
}
34 changes: 0 additions & 34 deletions src/GraphQL/LinkDescriptionResolver.php

This file was deleted.

Loading

0 comments on commit 9186d20

Please sign in to comment.