From 78c4b21d58cc84eda8495841155eef54525d7a50 Mon Sep 17 00:00:00 2001 From: Rafael Horvat Date: Wed, 15 Nov 2023 15:36:35 +0100 Subject: [PATCH] Add deepEqual utility function for comparing (#96) objects --- js/src/forum/index.js | 6 +++++- js/src/forum/utils/deepEqual.js | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 js/src/forum/utils/deepEqual.js diff --git a/js/src/forum/index.js b/js/src/forum/index.js index 13222e5..39e71d7 100644 --- a/js/src/forum/index.js +++ b/js/src/forum/index.js @@ -25,6 +25,7 @@ import ComposerState from 'flarum/forum/states/ComposerState'; import fillRelationship from './utils/fillRelationship'; import DraftsListState from './states/DraftsListState'; import app from 'flarum/forum/app'; +import deepEqual from './utils/deepEqual'; export * from './components'; export * from './models'; @@ -61,7 +62,10 @@ app.initializers.add('fof-drafts', () => { const getData = (field) => (field === 'content' ? this.fields.content() : data[field]) || ''; for (const field of fields) { - if ((!draft && getData(field)) || (draft && getData(field) != draft.data.attributes[field])) { + const fieldValue = getData(field); + const draftFieldValue = draft && draft.data.attributes[field]; + + if ((!draft && fieldValue) || (draft && !deepEqual(fieldValue, draftFieldValue))) { return true; } } diff --git a/js/src/forum/utils/deepEqual.js b/js/src/forum/utils/deepEqual.js new file mode 100644 index 0000000..4584ee1 --- /dev/null +++ b/js/src/forum/utils/deepEqual.js @@ -0,0 +1,20 @@ +// Deep comparison function +export default function deepEqual(obj1, obj2) { + if (obj1 === obj2) { + return true; + } + if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 == null || obj2 == null) { + return false; + } + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + for (let key of keys1) { + if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) { + return false; + } + } + return true; +}