Skip to content

Commit

Permalink
Merge pull request #127 from contentstack/EB-1848
Browse files Browse the repository at this point in the history
Eb 1848: Release Preview Compare utility
  • Loading branch information
RavenColEvol committed May 17, 2024
2 parents 6f41203 + 5e8deb1 commit ebd942e
Show file tree
Hide file tree
Showing 11 changed files with 4,113 additions and 2,799 deletions.
11 changes: 6 additions & 5 deletions jest.config.mjs → jest.config.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default {
module.exports = {
testEnvironment: "jsdom",
roots: ["<rootDir>/src"],
testMatch: [
Expand All @@ -7,10 +7,11 @@ export default {
],
automock: false,
setupFiles: ["<rootDir>/setupJest.ts"],
transform: {
"^.+\\.(ts|tsx)$": 'ts-jest',
preset: "ts-jest",
moduleNameMapper: {
uuid: require.resolve("uuid"),
},
coveragePathIgnorePatterns: ["__test__/"],
"collectCoverage": true,
"coverageReporters": ["html"],
collectCoverage: true,
coverageReporters: ["html"],
};
6,726 changes: 3,963 additions & 2,763 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"scripts": {
"build": "rimraf dist && tsup",
"build-webpack": "rimraf dist && webpack --config webpack.prod.js",
"test": "jest",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"test:watch": "jest --watch",
"test:coverage": "jest src --coverage --watchAll --coverageDirectory=\"coverage\"",
"dev": "webpack --config webpack.dev.js",
Expand All @@ -49,6 +49,7 @@
"@testing-library/jest-dom": "^5.14.1",
"@types/jest": "^27.0.1",
"@types/mustache": "^4.2.2",
"@types/post-robot": "^10.0.6",
"@types/uuid": "^8.3.1",
"@typescript-eslint/eslint-plugin": "^4.31.1",
"@typescript-eslint/parser": "^4.31.1",
Expand All @@ -58,17 +59,18 @@
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.6.0",
"husky": "^8.0.0",
"jest": "^27.2.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-fetch-mock": "^3.0.3",
"mini-css-extract-plugin": "^2.3.0",
"prettier": "^2.8.4",
"prettier-eslint": "^15.0.1",
"style-loader": "^2.0.0",
"ts-jest": "^27.0.5",
"ts-jest": "^29.1.2",
"ts-loader": "^9.4.2",
"ts-node": "^10.9.2",
"tsup": "^8.0.1",
"typedoc": "^0.23.25",
"typedoc": "^0.25.13",
"typescript": "^5.4.5",
"webpack": "^5.91.0",
"webpack-cli": "^4.8.0",
Expand All @@ -84,6 +86,7 @@
"just-camel-case": "^4.0.2",
"morphdom": "^2.6.1",
"mustache": "^4.2.0",
"post-robot": "^8.0.31",
"uuid": "^8.3.2"
},
"lint-staged": {
Expand Down
5 changes: 5 additions & 0 deletions src/__test__/contentstack-live-preview-HOC.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { IInitData } from "../utils/types";
import { sendPostmessageToWindow } from "./utils";
import packageJson from "../../package.json";

jest.mock("post-robot", () => ({
on: jest.fn(),
send: jest.fn(),
}));

describe("Live preview HOC Callback Pub Sub", () => {
afterEach(() => {
ContentstackLivePreview.subscribers = {};
Expand Down
76 changes: 76 additions & 0 deletions src/compare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import postRobot from "post-robot";
import { loadCompareGlobalStyle } from "./styles/compare";

const voidElements = new Set([
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);

export function handleWebCompare() {
loadCompareGlobalStyle();
postRobot.on("send-current-base-route", async () => {
return { url: window.location.href.split("?")[0] };
});

postRobot.on("send-cslp-data", async () => {
const elements = Array.from(document.querySelectorAll("[data-cslp]"));
const map: Record<string, string> = {};
for (const element of elements) {
const cslp = element.getAttribute("data-cslp")!;
if (
element.hasAttributes() &&
voidElements.has(element.tagName.toLowerCase())
) {
let attributes = "";
for (const attr of element.attributes) {
attributes += `${attr.name} -> ${attr.value}\n`;
}
map[cslp] = attributes;
} else {
map[cslp] = element.innerHTML;
}
}
return map;
});

const mergeColors = (className = ".cs-compare--added") => {
const elements = Array.from(document.querySelectorAll(className));
for (let i = 1; i < elements.length; i++) {
const prev = elements[i - 1];
const next = elements[i];
if (prev.nextElementSibling === next)
prev.appendChild(prev.nextSibling!);
}
};

postRobot.on("diff-value", async ({ data }) => {
const { diff, type } = data;
const operation = type === "base" ? "removed" : "added";
const elements = Array.from(document.querySelectorAll("[data-cslp]"));
for (const element of elements) {
const path = element.getAttribute("data-cslp")!;
if (!diff[path]) continue;

if (voidElements.has(element.tagName.toLowerCase())) {
element.classList.add(`cs-compare__void--${operation}`);
} else {
element.innerHTML = diff[path];
}
}

mergeColors(`.cs-compare--${operation}`);
});
}
7 changes: 5 additions & 2 deletions src/contentstack-live-preview-HOC.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { v4 as uuidv4 } from "uuid";
import { v4 } from "uuid";
import camelCase from "./utils/camelCase";

import {
Expand All @@ -11,6 +11,7 @@ import {
import LivePreview from "./live-preview";
import { userInitData } from "./utils/defaults";
import { PublicLogger } from "./utils/public-logger";
import { handleWebCompare } from "./compare";

export interface ICSLivePreview {
livePreview: LivePreview | null;
Expand Down Expand Up @@ -56,6 +57,8 @@ const ContentstackLivePreview: ICSLivePreview = {
);
return Promise.resolve(ContentstackLivePreview.livePreview);
} else {
handleWebCompare();

ContentstackLivePreview.livePreview = new LivePreview(
userConfig
);
Expand Down Expand Up @@ -110,7 +113,7 @@ const ContentstackLivePreview: ICSLivePreview = {
});
},
subscribe(callback: OnEntryChangeCallback): OnEntryChangeCallbackUID {
const callbackUid = uuidv4();
const callbackUid = v4();
ContentstackLivePreview.subscribers[callbackUid] = callback;
return callbackUid;
},
Expand Down
11 changes: 4 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import ContentstackLivePreviewHOC, {
ICSLivePreview,
} from "./contentstack-live-preview-HOC";

const SHOULD_KEEP_SDK = !(
process.env.PURGE_PREVIEW_SDK || process.env.REACT_APP_PURGE_PREVIEW_SDK
);

const LightLivePreviewHoC = {
init() {},
onLiveEdit() {},
Expand All @@ -18,8 +14,9 @@ const LightLivePreviewHoC = {
setConfigFromParams() {},
};

export const ContentstackLivePreview = SHOULD_KEEP_SDK
? ContentstackLivePreviewHOC
: (LightLivePreviewHoC as unknown as ICSLivePreview);
export const ContentstackLivePreview =
process.env.PURGE_PREVIEW_SDK || process.env.REACT_APP_PURGE_PREVIEW_SDK
? (LightLivePreviewHoC as unknown as ICSLivePreview)
: ContentstackLivePreviewHOC;

export default ContentstackLivePreview;
26 changes: 26 additions & 0 deletions src/styles/compare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { glob } from "goober";

export const loadCompareGlobalStyle = () => {
const css = glob;
css`
.cs-compare--added {
background: rgba(0, 122, 82, 0.2);
border-bottom: 2px solid rgba(0, 122, 82);
}
.cs-compare--removed {
background: rgba(214, 36, 0, 0.2);
text-decoration: line-through 2px solid rgba(214, 36, 0, 1);
}
.cs-compare__void--added {
background: rgba(0, 122, 82, 0.2);
outline: 2px solid rgba(0, 122, 82);
}
.cs-compare__void--removed {
background: rgba(214, 36, 0, 0.2);
outline: 2px solid rgba(214, 36, 0, 1);
}
`;
};
23 changes: 13 additions & 10 deletions webpack.common.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
import path from 'path';
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

module.exports = {
export default {
entry: path.resolve(__dirname, "src", "index.ts"),
output: {
globalObject: "this",
Expand All @@ -11,19 +15,18 @@ module.exports = {
filename: "index.js",
chunkFilename: "[name].js",
},
plugins: [new MiniCssExtractPlugin()],
optimization: {
sideEffects: true,
usedExports: false,
},
plugins: [],
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
include: [path.resolve(__dirname, "src")],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
include: [path.resolve(__dirname, "src")],
},
}
],
},
resolve: {
Expand Down
6 changes: 3 additions & 3 deletions webpack.dev.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
import { merge } from "webpack-merge";
import common from "./webpack.common.js";

module.exports = merge(common, {
export default merge(common, {
mode: "development",
watch: true,
devtool: "inline-source-map",
Expand Down
10 changes: 5 additions & 5 deletions webpack.prod.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
const { DefinePlugin } = require("webpack");
import { merge } from "webpack-merge";
import common from "./webpack.common.js";
import * as webpack from "webpack";

module.exports = merge(common, {
export default merge(common, {
mode: "production",
plugins: [
new DefinePlugin({
new webpack.default.DefinePlugin({
'process.env.PURGE_PREVIEW_SDK': true,
})
]
Expand Down

0 comments on commit ebd942e

Please sign in to comment.