Skip to content

Commit

Permalink
feat: observer works inside shadowDom (#3163)
Browse files Browse the repository at this point in the history
  • Loading branch information
stepan662 authored Feb 22, 2023
1 parent 7ba5644 commit b9d61c4
Show file tree
Hide file tree
Showing 14 changed files with 227 additions and 208 deletions.
38 changes: 17 additions & 21 deletions packages/core/src/Controller/Plugins/Plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export const Plugins = (
) => {
const plugins = {
ui: undefined as UiMiddleware | undefined,
observer: undefined as ObserverMiddleware | undefined,
};

const instances = {
Expand Down Expand Up @@ -83,11 +82,11 @@ export const Plugins = (
};

const setObserver = (observer: ObserverMiddleware | undefined) => {
plugins.observer = observer;
instances.observer = observer?.();
};

const hasObserver = () => {
return Boolean(plugins.observer);
return Boolean(instances.observer);
};

const addFormatter = (formatter: FormatterMiddleware | undefined) => {
Expand Down Expand Up @@ -172,24 +171,21 @@ export const Plugins = (
};

const run = () => {
if (!instances.ui) {
const { apiKey, apiUrl, projectId } = getInitialOptions();
instances.ui = plugins.ui?.({
apiKey: apiKey!,
apiUrl: apiUrl!,
projectId,
highlight,
changeTranslation,
});
}
if (!instances.observer) {
instances.observer = plugins.observer?.({
translate,
onClick,
options: getInitialOptions().observerOptions,
});
}
instances.observer?.run({ mouseHighlight: true });
const { apiKey, apiUrl, projectId, observerOptions } = getInitialOptions();
instances.ui = plugins.ui?.({
apiKey: apiKey!,
apiUrl: apiUrl!,
projectId,
highlight,
changeTranslation,
});

instances.observer?.run({
mouseHighlight: true,
options: observerOptions,
translate,
onClick,
});
};

const getDevBackend = () => {
Expand Down
11 changes: 0 additions & 11 deletions packages/core/src/__test/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,4 @@ describe('plugins', () => {
expect(tolgee.t({ key: 'hello' })).toEqual('hello|world');
tolgee.stop();
});

it("won't wrap before run", () => {
const tolgee = TolgeeCore().init({
language: 'en',
staticData: { en: { hello: 'world' } },
});
tolgee.addPlugin(observerPlugin(false));
expect(tolgee.t({ key: 'hello' })).toEqual('world');
tolgee.run();
expect(tolgee.t({ key: 'hello' })).toEqual('hello|world');
});
});
11 changes: 4 additions & 7 deletions packages/core/src/types/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,12 @@ export type HighlightInterface = (key?: string, ns?: NsFallback) => Highlighter;

export type ObserverRunProps = {
mouseHighlight: boolean;
options: ObserverOptionsInternal;
translate: (params: TranslatePropsInternal) => string;
onClick: TranslationOnClick;
};

export type ObserverMiddleware = (props: ObserverProps) => {
export type ObserverMiddleware = () => {
unwrap: (text: string) => Unwrapped;
wrap: WrapperWrapFunction;
retranslate: () => void;
Expand Down Expand Up @@ -116,12 +119,6 @@ export type TranslationOnClick = (data: {
event: any;
}) => void;

export type ObserverProps = {
translate: (params: TranslatePropsInternal) => string;
onClick: TranslationOnClick;
options: ObserverOptionsInternal;
};

export type Highlighter = {
unhighlight(): void;
};
Expand Down
2 changes: 1 addition & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"build": "rollup -c rollup.config.js && tsc --project tsconfig.prod.json",
"clean": "rm -rf build build-e2e dist dist-e2e lib",
"test": "jest --config ./jest.config.js --collect-coverage",
"develop": "concurrently \"rollup -c rollup.config.js -w\" \"tsc --watch --preserveWatchOutput --project tsconfig.prod.json\" ",
"develop": "concurrently \"rollup -c rollup.dev.js -w\" \"tsc --watch --preserveWatchOutput --project tsconfig.prod.json\" ",
"schema": "openapi-typescript http://localhost:8202/v3/api-docs/Accessible%20with%20API%20key --output ./src/ui/client/apiSchema.generated.ts"
},
"author": "Tolgee",
Expand Down
8 changes: 8 additions & 0 deletions packages/web/rollup.dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { buildPackage } from './rollup.common';

export default [
buildPackage({
input: 'src/entry-development.ts',
name: 'web.development',
}),
];
23 changes: 15 additions & 8 deletions packages/web/src/InvisibleObserver.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type { ObserverMiddleware } from '@tolgee/core';
import type { ObserverMiddleware, ObserverRunProps } from '@tolgee/core';
import { GeneralObserver } from './observers/general/GeneralObserver';
import { InvisibleWrapper } from './observers/invisible/InvisibleWrapper';

export const InvisibleObserver =
(): ObserverMiddleware =>
({ onClick, options }) => {
const wrapper = InvisibleWrapper();
const observer = GeneralObserver(wrapper, options, onClick);
return { ...observer, retranslate: () => {}, outputNotFormattable: false };
};
export const InvisibleObserver = (): ObserverMiddleware => () => {
const observer = GeneralObserver();

const self = Object.freeze({
...observer,
run(props: ObserverRunProps) {
const wrapper = InvisibleWrapper();
observer.run({ ...props, wrapper });
},
retranslate() {},
outputNotFormattable: false,
});
return self;
};
47 changes: 21 additions & 26 deletions packages/web/src/TextObserver.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,35 @@
import type { ObserverMiddleware } from '@tolgee/core';
import type { ObserverMiddleware, ObserverRunProps } from '@tolgee/core';
import { GeneralObserver } from './observers/general/GeneralObserver';
import { setNodeText } from './observers/general/helpers';
import { TextWrapper } from './observers/text/TextWrapper';

export const TextObserver =
(): ObserverMiddleware =>
({ translate, onClick, options }) => {
const wrapper = TextWrapper({
inputPrefix: options.inputPrefix,
inputSuffix: options.inputSuffix,
translate,
});
const { wrap, unwrap, stop, forEachElement, highlight, run } =
GeneralObserver(wrapper, options, onClick);
export const TextObserver = (): ObserverMiddleware => () => {
const observer = GeneralObserver();

const retranslate = () => {
forEachElement((_, elMeta) => {
const self = Object.freeze({
...observer,
run(props: ObserverRunProps) {
const wrapper = TextWrapper({
inputPrefix: props.options.inputPrefix,
inputSuffix: props.options.inputSuffix,
translate: props.translate,
});
observer.run({ ...props, wrapper });
},
retranslate() {
observer.forEachElement((_, elMeta) => {
for (const [node, nodeMeta] of elMeta.nodes.entries()) {
if (nodeMeta.keyAttributeOnly) {
return;
}
const result = wrapper.unwrap(nodeMeta.oldTextContent);
const result = observer.unwrap(nodeMeta.oldTextContent);
if (result) {
setNodeText(node, result.text);
}
}
});
};

return {
wrap,
unwrap,
stop,
run,
retranslate,
highlight,
outputNotFormattable: true,
};
};
},
outputNotFormattable: true,
});
return self;
};
12 changes: 10 additions & 2 deletions packages/web/src/observers/general/ElementRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import { ElementMeta, NodeMeta, TolgeeElement } from '../../types';

import { ElementHighlighter } from './ElementHighlighter';
import { initElementMeta } from './ElementMeta';
import { ElementStore } from './ElementStore';
import { ElementStoreType } from './ElementStore';
import { compareDescriptors, nodeContains } from './helpers';
import { MouseEventHandler } from './MouseEventHandler';

export const ElementRegistry = (
options: ObserverOptionsInternal,
elementStore: ElementStoreType,
onClick: TranslationOnClick
) => {
const elementStore = ElementStore();
const elementHighlighter = ElementHighlighter({
highlightColor: options.highlightColor,
highlightWidth: options.highlightWidth,
Expand All @@ -31,6 +31,7 @@ export const ElementRegistry = (
keysAndDefaults: getKeysAndDefaults(meta),
});
},
options,
});

function register(element: Element, node: Node, nodeMeta: NodeMeta) {
Expand All @@ -56,6 +57,11 @@ export const ElementRegistry = (

function stop() {
eventHandler.stop();
elementStore.forEachElement((_, meta) => {
if (meta.highlightEl) {
meta.unhighlight?.();
}
});
}

function isRestricted(element: Element) {
Expand Down Expand Up @@ -149,3 +155,5 @@ export const ElementRegistry = (
stop,
});
};

export type ElementRegistryInstance = ReturnType<typeof ElementRegistry>;
Loading

0 comments on commit b9d61c4

Please sign in to comment.