textchecker-element
Version:
Overlay text checker web compoentns.
307 lines • 14.9 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextCheckerElement = void 0;
const text_caret_pos_1 = require("./util/text-caret-pos");
const lit_html_1 = require("lit-html");
const text_checker_store_1 = require("./text-checker-store");
// @ts-ignore
const to_px_1 = __importDefault(require("to-px"));
const Marker = (rect, isHighLight = false) => {
if (isHighLight) {
return (0, lit_html_1.html) `<span
style="pointer-events: none; border: 2px dotted red; position: absolute; left: ${rect.left}px; top: ${rect.top}px; width: ${rect.width}px; height: ${rect.height}px;"
></span>`;
}
else {
return (0, lit_html_1.html) `<span
style="pointer-events: none; border-bottom: 2px dotted red; position: absolute; left: ${rect.left}px; top: ${rect.top}px; width: ${rect.width}px; height: ${rect.height}px;"
></span>`;
}
};
class TextCheckerElement extends HTMLElement {
constructor(args) {
var _a;
super();
this.hoverPadding = 8;
this.isFocus = false;
this.isHovering = false;
this.attributeChangedCallback = (name, _oldValue, newValue) => {
if (this[name]) {
// @ts-ignore
this[name] = newValue;
if (name === "target") {
this.targetElement = document.querySelector(newValue);
}
}
};
this.onMouseEnter = () => {
var _a;
this.isHovering = true;
(_a = this.onEnter) === null || _a === void 0 ? void 0 : _a.call(this);
};
this.onMouseLeave = () => {
var _a;
this.isHovering = false;
(_a = this.onLeave) === null || _a === void 0 ? void 0 : _a.call(this);
this.resetHoverState();
};
this.renderAnnotationMarkers = (state) => {
const items = state.rectItems.map((rect) => Marker(rect, state.highlightRectIdSet.has(rect.id)));
(0, lit_html_1.render)(items, this.annotationBox);
};
this.onFocus = () => {
this.isFocus = true;
};
this.onBlur = () => {
this.isFocus = false;
};
this.isHoverRectItem = (rectItem) => {
const state = this.store.get();
return Boolean(state.mouseHoverRectIdMap.get(rectItem.id));
};
this.onMouseUpdate = (event) => {
const state = this.store.get();
const hoverPadding = this.hoverPadding;
const isIncludedIndexes = state.rectItems
.filter((rect) => {
const point = {
x: event.clientX - rect.boxAbsoluteX,
y: event.clientY - rect.boxAbsoluteY
};
return (rect.left - hoverPadding <= point.x &&
rect.left + rect.width + hoverPadding >= point.x &&
rect.top - hoverPadding <= point.y &&
rect.top + rect.height + hoverPadding >= point.y);
})
.map((item) => item.id);
// call mouseover
// naive implementation
// TODO: https://github.com/mourner/flatbush is useful for search
state.rectItems.forEach((rectItem) => {
var _a, _b;
const isHoverRect = state.mouseHoverRectIdMap.get(rectItem.id);
const isIncludedMouse = isIncludedIndexes.includes(rectItem.id);
if (!isHoverRect && isIncludedMouse) {
(_a = state.annotationItems
.find((item) => item.id === rectItem.id)) === null || _a === void 0 ? void 0 : _a.onMouseEnter({
rectItem: rectItem
});
}
else if (isHoverRect && !isIncludedMouse) {
(_b = state.annotationItems
.find((item) => item.id === rectItem.id)) === null || _b === void 0 ? void 0 : _b.onMouseLeave({
rectItem: rectItem
});
}
state.mouseHoverRectIdMap.set(rectItem.id, isIncludedMouse);
});
// update highlight
this.store.highlightRectIndexes(isIncludedIndexes);
};
this.store = (0, text_checker_store_1.createTextCheckerStore)();
this.targetElement = args === null || args === void 0 ? void 0 : args.targetElement;
this.onEnter = args === null || args === void 0 ? void 0 : args.onEnter;
this.onLeave = args === null || args === void 0 ? void 0 : args.onLeave;
this.hoverPadding = (_a = args === null || args === void 0 ? void 0 : args.hoverPadding) !== null && _a !== void 0 ? _a : 8;
}
static get observedAttributes() {
return ["target", "hoverPadding"];
}
connectedCallback() {
const target = this.targetElement;
if (!target) {
throw new Error("target element is not found");
}
const shadow = this.attachShadow({ mode: "closed" });
const overlay = document.createElement("div");
overlay.className = "overlay";
overlay.setAttribute("style", "color: transparent; border: position: absolute; top: 0px; left: 0px; pointer-events: none;");
const annotationBox = document.createElement("div");
annotationBox.className = "annotationBox";
overlay.append(annotationBox);
shadow.append(overlay);
this.annotationBox = annotationBox;
// we need to capture over textarea
this.targetElement.dataset.attachedTextCheckerElement = "true";
this.targetElement.addEventListener("mousemove", this.onMouseUpdate);
this.targetElement.addEventListener("focus", this.onFocus);
this.targetElement.addEventListener("blur", this.onBlur);
this.targetElement.addEventListener("mouseenter", this.onMouseEnter);
this.targetElement.addEventListener("mouseleave", this.onMouseLeave);
this.store.onChange(() => {
this.renderAnnotationMarkers(this.store.get());
});
}
disconnectedCallback() {
this.targetElement.removeEventListener("mousemove", this.onMouseUpdate);
this.targetElement.removeEventListener("focus", this.onFocus);
this.targetElement.removeEventListener("blur", this.onBlur);
this.targetElement.removeEventListener("mouseenter", this.onMouseEnter);
this.targetElement.removeEventListener("mouseleave", this.onMouseLeave);
}
resetAnnotations() {
this.store.clear();
}
resetHoverState() {
this.store.clearHoverState();
}
updateAnnotations(annotationItems) {
var _a, _b, _c, _d, _e, _f;
const target = this.targetElement;
const targetStyle = window.getComputedStyle(target);
const copyAttributes = ["box-sizing"];
const copyStyle = copyAttributes
.map((attr) => {
return `${attr}: ${targetStyle.getPropertyValue(attr)};`;
})
.join("");
this.annotationBox.setAttribute("style", `color: transparent; overflow:hidden; position: absolute; pointer-events: none; ${copyStyle}`);
// Ref: https://github.com/yuku/textoverlay
// Outer position
// update annotation box that align with target textarea
// top-left (0,0)
// read styles form target element
const offsetTop = target.offsetTop;
const offsetLeft = target.offsetLeft;
const offsetHeight = target.offsetHeight;
const offsetWidth = target.clientWidth +
parseInt(targetStyle.borderLeftWidth || "0", 10) +
parseInt(targetStyle.borderRightWidth || "0", 10);
// const textareaScrollTop = target.scrollTop;
const textareaZIndex = targetStyle.zIndex !== null && targetStyle.zIndex !== "auto" ? +targetStyle.zIndex : 0;
// updates style
this.annotationBox.style.zIndex = `${textareaZIndex + 1}`;
this.annotationBox.style.left = `${offsetLeft}px`;
this.annotationBox.style.top = `${offsetTop}px`;
this.annotationBox.style.height = `${offsetHeight}px`;
this.annotationBox.style.width = `${offsetWidth}px`;
// box
const fontSize = (_a = (0, to_px_1.default)(targetStyle.getPropertyValue("font-size"))) !== null && _a !== void 0 ? _a : 16.123;
const boxMarginTop = (_b = (0, to_px_1.default)(targetStyle.getPropertyValue("margin-top"))) !== null && _b !== void 0 ? _b : 0;
const boxMarginBottom = (_c = (0, to_px_1.default)(targetStyle.getPropertyValue("margin-bottom"))) !== null && _c !== void 0 ? _c : 0;
const boxBorderWidth = (_d = (0, to_px_1.default)(targetStyle.getPropertyValue("border-width"))) !== null && _d !== void 0 ? _d : 0;
const boxPaddingTop = (_e = (0, to_px_1.default)(targetStyle.getPropertyValue("padding-top"))) !== null && _e !== void 0 ? _e : 0;
const boxPaddingBottom = (_f = (0, to_px_1.default)(targetStyle.getPropertyValue("padding-bottom"))) !== null && _f !== void 0 ? _f : 0;
const boundingClientRect = target.getBoundingClientRect();
const boxAbsoluteX = boundingClientRect.x;
const boxAbsoluteY = boundingClientRect.y;
const boxWidth = boundingClientRect.width;
const boxHeight = boundingClientRect.height;
// Inner position
// textarea is scrollable element
const visibleArea = {
top: target.scrollTop,
left: target.scrollLeft,
width: boxWidth,
height: boxHeight
};
this.annotationBox.scrollTop = target.scrollTop;
this.annotationBox.scrollLeft = target.scrollLeft;
// FIXME: more correct way
// AnnotationItems should be sorted by range.
// Because, drop non-visible rect items for performance.
// Example)
// ZYXWVUTSRQPONMLKJIHGFEDCBA
// ^^^^^^^--------------------
// visible ^^^^^
// non-visible = drop from `rectItems`
const annotationItemsByDescendingOrder = annotationItems.slice().reverse();
let stopSearchAboveIsNotVisible = false;
const rectItems = annotationItemsByDescendingOrder.flatMap((annotation) => {
var _a, _b, _c, _d, _e, _f;
// already the annotation is not visible, skip it
if (stopSearchAboveIsNotVisible) {
return [];
}
const start = annotation.start;
const end = annotation.end;
// 0 start
const startCoordinate = (0, text_caret_pos_1.getCoordinates)(this.targetElement, start, {
reuse: true,
returnHeight: true,
returnDiv: false,
debug: false
});
// Stop to search if out of visible
if (startCoordinate.top + fontSize < visibleArea.top) {
stopSearchAboveIsNotVisible = true;
return [];
}
const endCoordinate = (0, text_caret_pos_1.getCoordinates)(this.targetElement, end, {
reuse: true,
returnHeight: true,
returnDiv: true,
debug: false
});
const rectItems = startCoordinate.top === endCoordinate.top
? [
{
id: annotation.id,
// left and top is visible position
// annotationBox(textarea) also scroll with same position of actual textarea
left: startCoordinate.left - visibleArea.left,
top: startCoordinate.top - visibleArea.top,
height: fontSize, //startCoordinate.height,
width: endCoordinate.left - startCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
}
]
: // two line
[
{
id: annotation.id,
left: startCoordinate.left - visibleArea.left,
top: startCoordinate.top - visibleArea.top,
height: fontSize, //startCoordinate.height,
width: ((_c = (_b = (_a = startCoordinate === null || startCoordinate === void 0 ? void 0 : startCoordinate._div) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect()) === null || _b === void 0 ? void 0 : _b.width) !== null && _c !== void 0 ? _c : 0) - startCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
},
{
id: annotation.id,
left: -visibleArea.left,
top: endCoordinate.top - visibleArea.top,
height: fontSize,
width: ((_f = (_e = (_d = startCoordinate === null || startCoordinate === void 0 ? void 0 : startCoordinate._div) === null || _d === void 0 ? void 0 : _d.getBoundingClientRect()) === null || _e === void 0 ? void 0 : _e.left) !== null && _f !== void 0 ? _f : 0) + endCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
}
];
return rectItems;
});
this.store.update({
annotationItems,
rectItems
});
}
}
exports.TextCheckerElement = TextCheckerElement;
if (!window.customElements.get("text-checker-element")) {
window.customElements.define("text-checker-element", TextCheckerElement);
}
//# sourceMappingURL=text-checker-element.js.map