-
Notifications
You must be signed in to change notification settings - Fork 42
/
sagas.js
282 lines (232 loc) · 9.55 KB
/
sagas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
* External dependencies
*/
import { call, put, select, takeEvery, takeLatest } from "redux-saga/effects";
/**
* WordPress dependencies
*/
import apiFetch from "@wordpress/api-fetch";
import * as data from "@wordpress/data";
/**
* Internal dependencies
*/
import { receiveAnalysisResults, toggleLinkSuccess, updateOccurrencesForEntity } from "../../Edit/actions";
import {
ADD_ENTITY,
ANNOTATION,
SET_CURRENT_ENTITY,
TOGGLE_ENTITY,
TOGGLE_LINK
} from "../../Edit/constants/ActionTypes";
import { requestAnalysis } from "./actions";
import parseAnalysisResponse from "./compat";
import { EDITOR_STORE } from "../../common/constants";
import EditorOps from "../api/editor-ops";
import { makeEntityAnnotationsSelector, mergeArray } from "../api/utils";
import { Blocks } from "../api/blocks";
import { getAnnotationFilter, getBlockEditorFormat, getClassificationBlock, getSelectedEntities } from "./selectors";
import { addEntityRequest, addEntitySuccess } from "../../Edit/components/AddEntity/actions";
import { applyFormat } from "@wordpress/rich-text";
import { doAction } from "@wordpress/hooks";
import { createEntityRequest } from "../../common/containers/create-entity-form/actions";
import createEntity from "../api/create-entity";
import { relatedPostsRequest, relatedPostsSuccess } from "../../common/containers/related-posts/actions";
import getRelatedPosts from "../../common/api/get-related-posts";
function* handleRequestAnalysis() {
const editorOps = new EditorOps(EDITOR_STORE);
const request = editorOps.buildAnalysisRequest(window["wlSettings"]["language"], [
window["wordlift"]["currentPostUri"]
]);
const response = yield call(apiFetch, {
url: `${window["wlSettings"]["ajax_url"]}?action=wordlift_analyze`,
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request)
});
embedAnalysis(editorOps, response);
const parsed = parseAnalysisResponse(response);
yield put(receiveAnalysisResults(parsed));
}
function embedAnalysis(editorOps, response) {
// Bail out if the response doesn't contain results.
if ("undefined" === typeof response || "undefined" === typeof response.annotations) return;
const annotations = Object.values(response.annotations).sort(function(a1, a2) {
if (a1.end > a2.end) return -1;
if (a1.end < a2.end) return 1;
return 0;
});
annotations.forEach(annotation =>
editorOps.insertAnnotation(annotation.annotationId, annotation.start, annotation.end)
);
editorOps.applyChanges();
}
function* toggleEntity({ entity }) {
// Get the supported blocks.
const blocks = Blocks.create(data.select(EDITOR_STORE).getBlocks(), data.dispatch(EDITOR_STORE));
const mainType = entity.mainType || "thing";
const onClassNames = ["disambiguated", `wl-${mainType.replace(/\s/, "-")}`];
// Build a css selector to select all the annotations for the provided entity.
const annotationSelector = makeEntityAnnotationsSelector(entity);
// Collect the annotations that have been switch on/off.
const occurrences = [];
if (0 === entity.occurrences.length) {
// Switch on.
blocks.replace(
new RegExp(`<span\\s+id="(${annotationSelector})"\\sclass="([^"]*)">`, "gi"),
(match, annotationId, classNames) => {
const newClassNames = mergeArray(classNames.split(/\s+/), onClassNames);
occurrences.push(annotationId);
return `<span id="${annotationId}" class="${newClassNames.join(" ")}" itemid="${entity.id}">`;
}
);
} else {
console.debug(`Looking for "<span\\s+id="(${annotationSelector})"\\sclass="([^"]*)"\\sitemid="[^"]*">"...`);
// Switch off.
blocks.replace(
new RegExp(`<span\\s+id="(${annotationSelector})"\\sclass="([^"]*)"\\sitemid="[^"]*">`, "gi"),
(match, annotationId, classNames) => {
const newClassNames = classNames.split(/\s+/).filter(x => -1 === onClassNames.indexOf(x));
return `<span id="${annotationId}" class="${newClassNames.join(" ")}">`;
}
);
}
yield put(updateOccurrencesForEntity(entity.id, occurrences));
// Send the selected entities to the WordLift Classification box.
data.dispatch(EDITOR_STORE).updateBlockAttributes(getClassificationBlock().clientId, {
entities: yield select(getSelectedEntities)
});
// Apply the changes.
blocks.apply();
}
function* toggleLink({ entity }) {
// Get the supported blocks.
const blocks = Blocks.create(data.select(EDITOR_STORE).getBlocks(), data.dispatch(EDITOR_STORE));
// Build a css selector to select all the annotations for the provided entity.
const annotationSelector = makeEntityAnnotationsSelector(entity);
const cssClasses = ["wl-link", "wl-no-link"];
const link = !entity.link;
blocks.replace(
new RegExp(`<span\\s+id="(${annotationSelector})"\\sclass="([^"]*)"\\sitemid="([^"]*)">`, "gi"),
(match, annotationId, classNames) => {
// Remove existing `wl-link` / `wl-no-link` classes.
const newClassNames = classNames.split(/\s+/).filter(x => -1 === cssClasses.indexOf(x));
// Add the `wl-link` / `wl-no-link` class according to the desired outcome.
newClassNames.push(link ? "wl-link" : "wl-no-link");
return `<span id="${annotationId}" class="${newClassNames.join(" ")}" itemid="${entity.id}">`;
}
);
// Apply the changes.
blocks.apply();
yield put(toggleLinkSuccess({ id: entity.id, link }));
}
/**
* Handle `ANNOTATION` actions.
*
* When the `ANNOTATION` action is fired, the `selected` css class will be added
* to the selected annotation and removed from the others.
*
* The annotation id should match the element id.
*
* @since 3.23.0
* @param {string|undefined} annotationId The annotation id.
*/
function* toggleAnnotation({ annotation }) {
// Bail out if the annotation didn't change.
const selectedAnnotation = yield select(getAnnotationFilter);
if (annotation === selectedAnnotation) return null;
// Get the supported blocks.
const blocks = Blocks.create(data.select(EDITOR_STORE).getBlocks(), data.dispatch(EDITOR_STORE));
blocks.replace(
new RegExp(`<span\\s+id="([^"]+)"\\sclass="(textannotation(?:\\s[^"]*)?)"`, "gi"),
(match, annotationId, classNames) => {
// Get the class names removing any potential `selected` class.
const newClassNames = classNames.split(/\s+/).filter(x => "selected" !== x);
// Add the `selected` class if the annotation match.
if (annotation === annotationId) newClassNames.push("selected");
// Return the new span.
return `<span id="${annotationId}" class="${newClassNames.join(" ")}"`;
}
);
// Apply the changes.
blocks.apply();
}
/**
* Handles the request to add an entity.
*
* First we toggle the wordlift/annotation in Block Editor to create the annotation.
*/
function* handleAddEntityRequest({ payload }) {
// See https://developer.wordpress.org/block-editor/packages/packages-rich-text/#applyFormat
const { onChange, value } = yield select(getBlockEditorFormat);
const annotationId = "urn:local-annotation-" + Math.floor(Math.random() * 999999);
// Create the entity if the `id` isn't defined.
const id =
payload.id ||
(yield call(createEntity, {
title: payload.label,
status: "draft",
description: payload.description,
excerpt: ""
}))["wl:entity_url"];
const entityToAdd = {
id,
...payload,
annotations: { [annotationId]: { annotationId, start: value.start, end: value.end } },
occurrences: [annotationId]
};
console.debug("Adding Entity", entityToAdd);
const format = {
type: "wordlift/annotation",
attributes: { id: annotationId, class: "disambiguated", itemid: entityToAdd.id }
};
yield call(onChange, applyFormat(value, format));
yield put({ type: ADD_ENTITY, payload: entityToAdd });
// Send the selected entities to the WordLift Classification box.
data.dispatch(EDITOR_STORE).updateBlockAttributes(getClassificationBlock().clientId, {
entities: yield select(getSelectedEntities)
});
yield put(addEntitySuccess());
}
/**
* Broadcast the `wordlift.addEntitySuccess` action in order to have the AddEntity local store capture it.
*/
function* handleAddEntitySuccess() {
yield call(doAction, "wordlift.addEntitySuccess");
}
/**
* Handles the action when the entity edit link is clicked in the Classification Box.
*
* Within the Block Editor we open a new window to the WordPress edit post screen.
*
* @since 3.23.0
* @param Object entity The entity object.
*/
function* handleSetCurrentEntity({ entity }) {
const url = `${window["wp"].ajax.settings.url}?action=wordlift_redirect&uri=${encodeURIComponent(entity.id)}&to=edit`;
window.open(url, "_blank");
}
/**
* Handle the Create Entity Request, which is supposed to open a form in the sidebar.
*/
function* handleCreateEntityRequest() {
// Call the WP hook to close the entity select (see ../../Edit/components/AddEntity/index.js).
doAction("unstable_wordlift.closeEntitySelect");
}
/**
* Handles the request to load the related posts.
*/
function* handleRelatedPostsRequest() {
const posts = yield call(getRelatedPosts);
yield put(relatedPostsSuccess(posts));
}
export default function* saga() {
yield takeLatest(requestAnalysis, handleRequestAnalysis);
yield takeEvery(TOGGLE_ENTITY, toggleEntity);
yield takeEvery(TOGGLE_LINK, toggleLink);
yield takeLatest(ANNOTATION, toggleAnnotation);
yield takeEvery(addEntityRequest, handleAddEntityRequest);
yield takeEvery(addEntitySuccess, handleAddEntitySuccess);
yield takeEvery(SET_CURRENT_ENTITY, handleSetCurrentEntity);
yield takeEvery(createEntityRequest, handleCreateEntityRequest);
yield takeEvery(relatedPostsRequest, handleRelatedPostsRequest);
}