annotation_layer.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  1. /* Copyright 2014 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /** @typedef {import("./api").PDFPageProxy} PDFPageProxy */
  16. /** @typedef {import("./display_utils").PageViewport} PageViewport */
  17. /** @typedef {import("./interfaces").IDownloadManager} IDownloadManager */
  18. /** @typedef {import("../../web/interfaces").IPDFLinkService} IPDFLinkService */
  19. import {
  20. AnnotationBorderStyleType,
  21. AnnotationType,
  22. assert,
  23. FeatureTest,
  24. LINE_FACTOR,
  25. shadow,
  26. unreachable,
  27. Util,
  28. warn,
  29. } from "../shared/util.js";
  30. import {
  31. AnnotationPrefix,
  32. DOMSVGFactory,
  33. getFilenameFromUrl,
  34. PDFDateString,
  35. setLayerDimensions,
  36. } from "./display_utils.js";
  37. import { AnnotationStorage } from "./annotation_storage.js";
  38. import { ColorConverters } from "../shared/scripting_utils.js";
  39. import { XfaLayer } from "./xfa_layer.js";
  40. const DEFAULT_TAB_INDEX = 1000;
  41. const DEFAULT_FONT_SIZE = 9;
  42. const GetElementsByNameSet = new WeakSet();
  43. function getRectDims(rect) {
  44. return {
  45. width: rect[2] - rect[0],
  46. height: rect[3] - rect[1],
  47. };
  48. }
  49. /**
  50. * @typedef {Object} AnnotationElementParameters
  51. * @property {Object} data
  52. * @property {HTMLDivElement} layer
  53. * @property {PDFPageProxy} page
  54. * @property {PageViewport} viewport
  55. * @property {IPDFLinkService} linkService
  56. * @property {IDownloadManager} downloadManager
  57. * @property {AnnotationStorage} [annotationStorage]
  58. * @property {string} [imageResourcesPath] - Path for image resources, mainly
  59. * for annotation icons. Include trailing slash.
  60. * @property {boolean} renderForms
  61. * @property {Object} svgFactory
  62. * @property {boolean} [enableScripting]
  63. * @property {boolean} [hasJSActions]
  64. * @property {Object} [fieldObjects]
  65. */
  66. class AnnotationElementFactory {
  67. /**
  68. * @param {AnnotationElementParameters} parameters
  69. * @returns {AnnotationElement}
  70. */
  71. static create(parameters) {
  72. const subtype = parameters.data.annotationType;
  73. switch (subtype) {
  74. case AnnotationType.LINK:
  75. return new LinkAnnotationElement(parameters);
  76. case AnnotationType.TEXT:
  77. return new TextAnnotationElement(parameters);
  78. case AnnotationType.WIDGET:
  79. const fieldType = parameters.data.fieldType;
  80. switch (fieldType) {
  81. case "Tx":
  82. return new TextWidgetAnnotationElement(parameters);
  83. case "Btn":
  84. if (parameters.data.radioButton) {
  85. return new RadioButtonWidgetAnnotationElement(parameters);
  86. } else if (parameters.data.checkBox) {
  87. return new CheckboxWidgetAnnotationElement(parameters);
  88. }
  89. return new PushButtonWidgetAnnotationElement(parameters);
  90. case "Ch":
  91. return new ChoiceWidgetAnnotationElement(parameters);
  92. }
  93. return new WidgetAnnotationElement(parameters);
  94. case AnnotationType.POPUP:
  95. return new PopupAnnotationElement(parameters);
  96. case AnnotationType.FREETEXT:
  97. return new FreeTextAnnotationElement(parameters);
  98. case AnnotationType.LINE:
  99. return new LineAnnotationElement(parameters);
  100. case AnnotationType.SQUARE:
  101. return new SquareAnnotationElement(parameters);
  102. case AnnotationType.CIRCLE:
  103. return new CircleAnnotationElement(parameters);
  104. case AnnotationType.POLYLINE:
  105. return new PolylineAnnotationElement(parameters);
  106. case AnnotationType.CARET:
  107. return new CaretAnnotationElement(parameters);
  108. case AnnotationType.INK:
  109. return new InkAnnotationElement(parameters);
  110. case AnnotationType.POLYGON:
  111. return new PolygonAnnotationElement(parameters);
  112. case AnnotationType.HIGHLIGHT:
  113. return new HighlightAnnotationElement(parameters);
  114. case AnnotationType.UNDERLINE:
  115. return new UnderlineAnnotationElement(parameters);
  116. case AnnotationType.SQUIGGLY:
  117. return new SquigglyAnnotationElement(parameters);
  118. case AnnotationType.STRIKEOUT:
  119. return new StrikeOutAnnotationElement(parameters);
  120. case AnnotationType.STAMP:
  121. return new StampAnnotationElement(parameters);
  122. case AnnotationType.FILEATTACHMENT:
  123. return new FileAttachmentAnnotationElement(parameters);
  124. default:
  125. return new AnnotationElement(parameters);
  126. }
  127. }
  128. }
  129. class AnnotationElement {
  130. constructor(
  131. parameters,
  132. {
  133. isRenderable = false,
  134. ignoreBorder = false,
  135. createQuadrilaterals = false,
  136. } = {}
  137. ) {
  138. this.isRenderable = isRenderable;
  139. this.data = parameters.data;
  140. this.layer = parameters.layer;
  141. this.page = parameters.page;
  142. this.viewport = parameters.viewport;
  143. this.linkService = parameters.linkService;
  144. this.downloadManager = parameters.downloadManager;
  145. this.imageResourcesPath = parameters.imageResourcesPath;
  146. this.renderForms = parameters.renderForms;
  147. this.svgFactory = parameters.svgFactory;
  148. this.annotationStorage = parameters.annotationStorage;
  149. this.enableScripting = parameters.enableScripting;
  150. this.hasJSActions = parameters.hasJSActions;
  151. this._fieldObjects = parameters.fieldObjects;
  152. if (isRenderable) {
  153. this.container = this._createContainer(ignoreBorder);
  154. }
  155. if (createQuadrilaterals) {
  156. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  157. }
  158. }
  159. /**
  160. * Create an empty container for the annotation's HTML element.
  161. *
  162. * @private
  163. * @param {boolean} ignoreBorder
  164. * @memberof AnnotationElement
  165. * @returns {HTMLElement} A section element.
  166. */
  167. _createContainer(ignoreBorder = false) {
  168. const { data, page, viewport } = this;
  169. const container = document.createElement("section");
  170. container.setAttribute("data-annotation-id", data.id);
  171. const { pageWidth, pageHeight, pageX, pageY } = viewport.rawDims;
  172. const { width, height } = getRectDims(data.rect);
  173. // Do *not* modify `data.rect`, since that will corrupt the annotation
  174. // position on subsequent calls to `_createContainer` (see issue 6804).
  175. const rect = Util.normalizeRect([
  176. data.rect[0],
  177. page.view[3] - data.rect[1] + page.view[1],
  178. data.rect[2],
  179. page.view[3] - data.rect[3] + page.view[1],
  180. ]);
  181. if (!ignoreBorder && data.borderStyle.width > 0) {
  182. container.style.borderWidth = `${data.borderStyle.width}px`;
  183. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  184. const verticalRadius = data.borderStyle.verticalCornerRadius;
  185. if (horizontalRadius > 0 || verticalRadius > 0) {
  186. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  187. container.style.borderRadius = radius;
  188. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  189. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  190. container.style.borderRadius = radius;
  191. }
  192. switch (data.borderStyle.style) {
  193. case AnnotationBorderStyleType.SOLID:
  194. container.style.borderStyle = "solid";
  195. break;
  196. case AnnotationBorderStyleType.DASHED:
  197. container.style.borderStyle = "dashed";
  198. break;
  199. case AnnotationBorderStyleType.BEVELED:
  200. warn("Unimplemented border style: beveled");
  201. break;
  202. case AnnotationBorderStyleType.INSET:
  203. warn("Unimplemented border style: inset");
  204. break;
  205. case AnnotationBorderStyleType.UNDERLINE:
  206. container.style.borderBottomStyle = "solid";
  207. break;
  208. default:
  209. break;
  210. }
  211. const borderColor = data.borderColor || null;
  212. if (borderColor) {
  213. container.style.borderColor = Util.makeHexColor(
  214. borderColor[0] | 0,
  215. borderColor[1] | 0,
  216. borderColor[2] | 0
  217. );
  218. } else {
  219. // Transparent (invisible) border, so do not draw it at all.
  220. container.style.borderWidth = 0;
  221. }
  222. }
  223. container.style.left = `${(100 * (rect[0] - pageX)) / pageWidth}%`;
  224. container.style.top = `${(100 * (rect[1] - pageY)) / pageHeight}%`;
  225. const { rotation } = data;
  226. if (data.hasOwnCanvas || rotation === 0) {
  227. container.style.width = `${(100 * width) / pageWidth}%`;
  228. container.style.height = `${(100 * height) / pageHeight}%`;
  229. } else {
  230. this.setRotation(rotation, container);
  231. }
  232. return container;
  233. }
  234. setRotation(angle, container = this.container) {
  235. const { pageWidth, pageHeight } = this.viewport.rawDims;
  236. const { width, height } = getRectDims(this.data.rect);
  237. let elementWidth, elementHeight;
  238. if (angle % 180 === 0) {
  239. elementWidth = (100 * width) / pageWidth;
  240. elementHeight = (100 * height) / pageHeight;
  241. } else {
  242. elementWidth = (100 * height) / pageWidth;
  243. elementHeight = (100 * width) / pageHeight;
  244. }
  245. container.style.width = `${elementWidth}%`;
  246. container.style.height = `${elementHeight}%`;
  247. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  248. }
  249. get _commonActions() {
  250. const setColor = (jsName, styleName, event) => {
  251. const color = event.detail[jsName];
  252. event.target.style[styleName] = ColorConverters[`${color[0]}_HTML`](
  253. color.slice(1)
  254. );
  255. };
  256. return shadow(this, "_commonActions", {
  257. display: event => {
  258. const hidden = event.detail.display % 2 === 1;
  259. this.container.style.visibility = hidden ? "hidden" : "visible";
  260. this.annotationStorage.setValue(this.data.id, {
  261. hidden,
  262. print: event.detail.display === 0 || event.detail.display === 3,
  263. });
  264. },
  265. print: event => {
  266. this.annotationStorage.setValue(this.data.id, {
  267. print: event.detail.print,
  268. });
  269. },
  270. hidden: event => {
  271. this.container.style.visibility = event.detail.hidden
  272. ? "hidden"
  273. : "visible";
  274. this.annotationStorage.setValue(this.data.id, {
  275. hidden: event.detail.hidden,
  276. });
  277. },
  278. focus: event => {
  279. setTimeout(() => event.target.focus({ preventScroll: false }), 0);
  280. },
  281. userName: event => {
  282. // tooltip
  283. event.target.title = event.detail.userName;
  284. },
  285. readonly: event => {
  286. if (event.detail.readonly) {
  287. event.target.setAttribute("readonly", "");
  288. } else {
  289. event.target.removeAttribute("readonly");
  290. }
  291. },
  292. required: event => {
  293. this._setRequired(event.target, event.detail.required);
  294. },
  295. bgColor: event => {
  296. setColor("bgColor", "backgroundColor", event);
  297. },
  298. fillColor: event => {
  299. setColor("fillColor", "backgroundColor", event);
  300. },
  301. fgColor: event => {
  302. setColor("fgColor", "color", event);
  303. },
  304. textColor: event => {
  305. setColor("textColor", "color", event);
  306. },
  307. borderColor: event => {
  308. setColor("borderColor", "borderColor", event);
  309. },
  310. strokeColor: event => {
  311. setColor("strokeColor", "borderColor", event);
  312. },
  313. rotation: event => {
  314. const angle = event.detail.rotation;
  315. this.setRotation(angle);
  316. this.annotationStorage.setValue(this.data.id, {
  317. rotation: angle,
  318. });
  319. },
  320. });
  321. }
  322. _dispatchEventFromSandbox(actions, jsEvent) {
  323. const commonActions = this._commonActions;
  324. for (const name of Object.keys(jsEvent.detail)) {
  325. const action = actions[name] || commonActions[name];
  326. action?.(jsEvent);
  327. }
  328. }
  329. _setDefaultPropertiesFromJS(element) {
  330. if (!this.enableScripting) {
  331. return;
  332. }
  333. // Some properties may have been updated thanks to JS.
  334. const storedData = this.annotationStorage.getRawValue(this.data.id);
  335. if (!storedData) {
  336. return;
  337. }
  338. const commonActions = this._commonActions;
  339. for (const [actionName, detail] of Object.entries(storedData)) {
  340. const action = commonActions[actionName];
  341. if (action) {
  342. const eventProxy = {
  343. detail: {
  344. [actionName]: detail,
  345. },
  346. target: element,
  347. };
  348. action(eventProxy);
  349. // The action has been consumed: no need to keep it.
  350. delete storedData[actionName];
  351. }
  352. }
  353. }
  354. /**
  355. * Create quadrilaterals from the annotation's quadpoints.
  356. *
  357. * @private
  358. * @param {boolean} ignoreBorder
  359. * @memberof AnnotationElement
  360. * @returns {Array<HTMLElement>} An array of section elements.
  361. */
  362. _createQuadrilaterals(ignoreBorder = false) {
  363. if (!this.data.quadPoints) {
  364. return null;
  365. }
  366. const quadrilaterals = [];
  367. const savedRect = this.data.rect;
  368. for (const quadPoint of this.data.quadPoints) {
  369. this.data.rect = [
  370. quadPoint[2].x,
  371. quadPoint[2].y,
  372. quadPoint[1].x,
  373. quadPoint[1].y,
  374. ];
  375. quadrilaterals.push(this._createContainer(ignoreBorder));
  376. }
  377. this.data.rect = savedRect;
  378. return quadrilaterals;
  379. }
  380. /**
  381. * Create a popup for the annotation's HTML element. This is used for
  382. * annotations that do not have a Popup entry in the dictionary, but
  383. * are of a type that works with popups (such as Highlight annotations).
  384. *
  385. * @private
  386. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  387. * @param {Object} data
  388. * @memberof AnnotationElement
  389. */
  390. _createPopup(trigger, data) {
  391. let container = this.container;
  392. if (this.quadrilaterals) {
  393. trigger = trigger || this.quadrilaterals;
  394. container = this.quadrilaterals[0];
  395. }
  396. // If no trigger element is specified, create it.
  397. if (!trigger) {
  398. trigger = document.createElement("div");
  399. trigger.className = "popupTriggerArea";
  400. container.append(trigger);
  401. }
  402. const popupElement = new PopupElement({
  403. container,
  404. trigger,
  405. color: data.color,
  406. titleObj: data.titleObj,
  407. modificationDate: data.modificationDate,
  408. contentsObj: data.contentsObj,
  409. richText: data.richText,
  410. hideWrapper: true,
  411. });
  412. const popup = popupElement.render();
  413. // Position the popup next to the annotation's container.
  414. popup.style.left = "100%";
  415. container.append(popup);
  416. }
  417. /**
  418. * Render the quadrilaterals of the annotation.
  419. *
  420. * @private
  421. * @param {string} className
  422. * @memberof AnnotationElement
  423. * @returns {Array<HTMLElement>} An array of section elements.
  424. */
  425. _renderQuadrilaterals(className) {
  426. if (
  427. typeof PDFJSDev === "undefined" ||
  428. PDFJSDev.test("!PRODUCTION || TESTING")
  429. ) {
  430. assert(this.quadrilaterals, "Missing quadrilaterals during rendering");
  431. }
  432. for (const quadrilateral of this.quadrilaterals) {
  433. quadrilateral.className = className;
  434. }
  435. return this.quadrilaterals;
  436. }
  437. /**
  438. * Render the annotation's HTML element(s).
  439. *
  440. * @public
  441. * @memberof AnnotationElement
  442. * @returns {HTMLElement|Array<HTMLElement>} A section element or
  443. * an array of section elements.
  444. */
  445. render() {
  446. unreachable("Abstract method `AnnotationElement.render` called");
  447. }
  448. /**
  449. * @private
  450. * @returns {Array}
  451. */
  452. _getElementsByName(name, skipId = null) {
  453. const fields = [];
  454. if (this._fieldObjects) {
  455. const fieldObj = this._fieldObjects[name];
  456. if (fieldObj) {
  457. for (const { page, id, exportValues } of fieldObj) {
  458. if (page === -1) {
  459. continue;
  460. }
  461. if (id === skipId) {
  462. continue;
  463. }
  464. const exportValue =
  465. typeof exportValues === "string" ? exportValues : null;
  466. const domElement = document.querySelector(
  467. `[data-element-id="${id}"]`
  468. );
  469. if (domElement && !GetElementsByNameSet.has(domElement)) {
  470. warn(`_getElementsByName - element not allowed: ${id}`);
  471. continue;
  472. }
  473. fields.push({ id, exportValue, domElement });
  474. }
  475. }
  476. return fields;
  477. }
  478. // Fallback to a regular DOM lookup, to ensure that the standalone
  479. // viewer components won't break.
  480. for (const domElement of document.getElementsByName(name)) {
  481. const { exportValue } = domElement;
  482. const id = domElement.getAttribute("data-element-id");
  483. if (id === skipId) {
  484. continue;
  485. }
  486. if (!GetElementsByNameSet.has(domElement)) {
  487. continue;
  488. }
  489. fields.push({ id, exportValue, domElement });
  490. }
  491. return fields;
  492. }
  493. }
  494. class LinkAnnotationElement extends AnnotationElement {
  495. constructor(parameters, options = null) {
  496. super(parameters, {
  497. isRenderable: true,
  498. ignoreBorder: !!options?.ignoreBorder,
  499. createQuadrilaterals: true,
  500. });
  501. this.isTooltipOnly = parameters.data.isTooltipOnly;
  502. }
  503. render() {
  504. const { data, linkService } = this;
  505. const link = document.createElement("a");
  506. link.setAttribute("data-element-id", data.id);
  507. let isBound = false;
  508. if (data.url) {
  509. linkService.addLinkAttributes(link, data.url, data.newWindow);
  510. isBound = true;
  511. } else if (data.action) {
  512. this._bindNamedAction(link, data.action);
  513. isBound = true;
  514. } else if (data.attachment) {
  515. this._bindAttachment(link, data.attachment);
  516. isBound = true;
  517. } else if (data.setOCGState) {
  518. this.#bindSetOCGState(link, data.setOCGState);
  519. isBound = true;
  520. } else if (data.dest) {
  521. this._bindLink(link, data.dest);
  522. isBound = true;
  523. } else {
  524. if (
  525. data.actions &&
  526. (data.actions.Action ||
  527. data.actions["Mouse Up"] ||
  528. data.actions["Mouse Down"]) &&
  529. this.enableScripting &&
  530. this.hasJSActions
  531. ) {
  532. this._bindJSAction(link, data);
  533. isBound = true;
  534. }
  535. if (data.resetForm) {
  536. this._bindResetFormAction(link, data.resetForm);
  537. isBound = true;
  538. } else if (this.isTooltipOnly && !isBound) {
  539. this._bindLink(link, "");
  540. isBound = true;
  541. }
  542. }
  543. if (this.quadrilaterals) {
  544. return this._renderQuadrilaterals("linkAnnotation").map(
  545. (quadrilateral, index) => {
  546. const linkElement = index === 0 ? link : link.cloneNode();
  547. quadrilateral.append(linkElement);
  548. return quadrilateral;
  549. }
  550. );
  551. }
  552. this.container.className = "linkAnnotation";
  553. if (isBound) {
  554. this.container.append(link);
  555. }
  556. return this.container;
  557. }
  558. #setInternalLink() {
  559. this.container.setAttribute("data-internal-link", "");
  560. }
  561. /**
  562. * Bind internal links to the link element.
  563. *
  564. * @private
  565. * @param {Object} link
  566. * @param {Object} destination
  567. * @memberof LinkAnnotationElement
  568. */
  569. _bindLink(link, destination) {
  570. link.href = this.linkService.getDestinationHash(destination);
  571. link.onclick = () => {
  572. if (destination) {
  573. this.linkService.goToDestination(destination);
  574. }
  575. return false;
  576. };
  577. if (destination || destination === /* isTooltipOnly = */ "") {
  578. this.#setInternalLink();
  579. }
  580. }
  581. /**
  582. * Bind named actions to the link element.
  583. *
  584. * @private
  585. * @param {Object} link
  586. * @param {Object} action
  587. * @memberof LinkAnnotationElement
  588. */
  589. _bindNamedAction(link, action) {
  590. link.href = this.linkService.getAnchorUrl("");
  591. link.onclick = () => {
  592. this.linkService.executeNamedAction(action);
  593. return false;
  594. };
  595. this.#setInternalLink();
  596. }
  597. /**
  598. * Bind attachments to the link element.
  599. * @param {Object} link
  600. * @param {Object} attachment
  601. */
  602. _bindAttachment(link, attachment) {
  603. link.href = this.linkService.getAnchorUrl("");
  604. link.onclick = () => {
  605. this.downloadManager?.openOrDownloadData(
  606. this.container,
  607. attachment.content,
  608. attachment.filename
  609. );
  610. return false;
  611. };
  612. this.#setInternalLink();
  613. }
  614. /**
  615. * Bind SetOCGState actions to the link element.
  616. * @param {Object} link
  617. * @param {Object} action
  618. */
  619. #bindSetOCGState(link, action) {
  620. link.href = this.linkService.getAnchorUrl("");
  621. link.onclick = () => {
  622. this.linkService.executeSetOCGState(action);
  623. return false;
  624. };
  625. this.#setInternalLink();
  626. }
  627. /**
  628. * Bind JS actions to the link element.
  629. *
  630. * @private
  631. * @param {Object} link
  632. * @param {Object} data
  633. * @memberof LinkAnnotationElement
  634. */
  635. _bindJSAction(link, data) {
  636. link.href = this.linkService.getAnchorUrl("");
  637. const map = new Map([
  638. ["Action", "onclick"],
  639. ["Mouse Up", "onmouseup"],
  640. ["Mouse Down", "onmousedown"],
  641. ]);
  642. for (const name of Object.keys(data.actions)) {
  643. const jsName = map.get(name);
  644. if (!jsName) {
  645. continue;
  646. }
  647. link[jsName] = () => {
  648. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  649. source: this,
  650. detail: {
  651. id: data.id,
  652. name,
  653. },
  654. });
  655. return false;
  656. };
  657. }
  658. if (!link.onclick) {
  659. link.onclick = () => false;
  660. }
  661. this.#setInternalLink();
  662. }
  663. _bindResetFormAction(link, resetForm) {
  664. const otherClickAction = link.onclick;
  665. if (!otherClickAction) {
  666. link.href = this.linkService.getAnchorUrl("");
  667. }
  668. this.#setInternalLink();
  669. if (!this._fieldObjects) {
  670. warn(
  671. `_bindResetFormAction - "resetForm" action not supported, ` +
  672. "ensure that the `fieldObjects` parameter is provided."
  673. );
  674. if (!otherClickAction) {
  675. link.onclick = () => false;
  676. }
  677. return;
  678. }
  679. link.onclick = () => {
  680. otherClickAction?.();
  681. const {
  682. fields: resetFormFields,
  683. refs: resetFormRefs,
  684. include,
  685. } = resetForm;
  686. const allFields = [];
  687. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  688. const fieldIds = new Set(resetFormRefs);
  689. for (const fieldName of resetFormFields) {
  690. const fields = this._fieldObjects[fieldName] || [];
  691. for (const { id } of fields) {
  692. fieldIds.add(id);
  693. }
  694. }
  695. for (const fields of Object.values(this._fieldObjects)) {
  696. for (const field of fields) {
  697. if (fieldIds.has(field.id) === include) {
  698. allFields.push(field);
  699. }
  700. }
  701. }
  702. } else {
  703. for (const fields of Object.values(this._fieldObjects)) {
  704. allFields.push(...fields);
  705. }
  706. }
  707. const storage = this.annotationStorage;
  708. const allIds = [];
  709. for (const field of allFields) {
  710. const { id } = field;
  711. allIds.push(id);
  712. switch (field.type) {
  713. case "text": {
  714. const value = field.defaultValue || "";
  715. storage.setValue(id, { value });
  716. break;
  717. }
  718. case "checkbox":
  719. case "radiobutton": {
  720. const value = field.defaultValue === field.exportValues;
  721. storage.setValue(id, { value });
  722. break;
  723. }
  724. case "combobox":
  725. case "listbox": {
  726. const value = field.defaultValue || "";
  727. storage.setValue(id, { value });
  728. break;
  729. }
  730. default:
  731. continue;
  732. }
  733. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  734. if (!domElement) {
  735. continue;
  736. } else if (!GetElementsByNameSet.has(domElement)) {
  737. warn(`_bindResetFormAction - element not allowed: ${id}`);
  738. continue;
  739. }
  740. domElement.dispatchEvent(new Event("resetform"));
  741. }
  742. if (this.enableScripting) {
  743. // Update the values in the sandbox.
  744. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  745. source: this,
  746. detail: {
  747. id: "app",
  748. ids: allIds,
  749. name: "ResetForm",
  750. },
  751. });
  752. }
  753. return false;
  754. };
  755. }
  756. }
  757. class TextAnnotationElement extends AnnotationElement {
  758. constructor(parameters) {
  759. const isRenderable = !!(
  760. parameters.data.hasPopup ||
  761. parameters.data.titleObj?.str ||
  762. parameters.data.contentsObj?.str ||
  763. parameters.data.richText?.str
  764. );
  765. super(parameters, { isRenderable });
  766. }
  767. render() {
  768. this.container.className = "textAnnotation";
  769. const image = document.createElement("img");
  770. image.src =
  771. this.imageResourcesPath +
  772. "annotation-" +
  773. this.data.name.toLowerCase() +
  774. ".svg";
  775. image.alt = "[{{type}} Annotation]";
  776. image.dataset.l10nId = "text_annotation_type";
  777. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  778. if (!this.data.hasPopup) {
  779. this._createPopup(image, this.data);
  780. }
  781. this.container.append(image);
  782. return this.container;
  783. }
  784. }
  785. class WidgetAnnotationElement extends AnnotationElement {
  786. render() {
  787. // Show only the container for unsupported field types.
  788. if (this.data.alternativeText) {
  789. this.container.title = this.data.alternativeText;
  790. }
  791. return this.container;
  792. }
  793. _getKeyModifier(event) {
  794. const { isWin, isMac } = FeatureTest.platform;
  795. return (isWin && event.ctrlKey) || (isMac && event.metaKey);
  796. }
  797. _setEventListener(element, baseName, eventName, valueGetter) {
  798. if (baseName.includes("mouse")) {
  799. // Mouse events
  800. element.addEventListener(baseName, event => {
  801. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  802. source: this,
  803. detail: {
  804. id: this.data.id,
  805. name: eventName,
  806. value: valueGetter(event),
  807. shift: event.shiftKey,
  808. modifier: this._getKeyModifier(event),
  809. },
  810. });
  811. });
  812. } else {
  813. // Non mouse event
  814. element.addEventListener(baseName, event => {
  815. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  816. source: this,
  817. detail: {
  818. id: this.data.id,
  819. name: eventName,
  820. value: valueGetter(event),
  821. },
  822. });
  823. });
  824. }
  825. }
  826. _setEventListeners(element, names, getter) {
  827. for (const [baseName, eventName] of names) {
  828. if (eventName === "Action" || this.data.actions?.[eventName]) {
  829. this._setEventListener(element, baseName, eventName, getter);
  830. }
  831. }
  832. }
  833. _setBackgroundColor(element) {
  834. const color = this.data.backgroundColor || null;
  835. element.style.backgroundColor =
  836. color === null
  837. ? "transparent"
  838. : Util.makeHexColor(color[0], color[1], color[2]);
  839. }
  840. /**
  841. * Apply text styles to the text in the element.
  842. *
  843. * @private
  844. * @param {HTMLDivElement} element
  845. * @memberof TextWidgetAnnotationElement
  846. */
  847. _setTextStyle(element) {
  848. const TEXT_ALIGNMENT = ["left", "center", "right"];
  849. const { fontColor } = this.data.defaultAppearanceData;
  850. const fontSize =
  851. this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  852. const style = element.style;
  853. // TODO: If the font-size is zero, calculate it based on the height and
  854. // width of the element.
  855. // Not setting `style.fontSize` will use the default font-size for now.
  856. // We don't use the font, as specified in the PDF document, for the <input>
  857. // element. Hence using the original `fontSize` could look bad, which is why
  858. // it's instead based on the field height.
  859. // If the height is "big" then it could lead to a too big font size
  860. // so in this case use the one we've in the pdf (hence the min).
  861. let computedFontSize;
  862. const BORDER_SIZE = 2;
  863. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  864. if (this.data.multiLine) {
  865. const height = Math.abs(
  866. this.data.rect[3] - this.data.rect[1] - BORDER_SIZE
  867. );
  868. const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
  869. const lineHeight = height / numberOfLines;
  870. computedFontSize = Math.min(
  871. fontSize,
  872. roundToOneDecimal(lineHeight / LINE_FACTOR)
  873. );
  874. } else {
  875. const height = Math.abs(
  876. this.data.rect[3] - this.data.rect[1] - BORDER_SIZE
  877. );
  878. computedFontSize = Math.min(
  879. fontSize,
  880. roundToOneDecimal(height / LINE_FACTOR)
  881. );
  882. }
  883. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  884. style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  885. if (this.data.textAlignment !== null) {
  886. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  887. }
  888. }
  889. _setRequired(element, isRequired) {
  890. if (isRequired) {
  891. element.setAttribute("required", true);
  892. } else {
  893. element.removeAttribute("required");
  894. }
  895. element.setAttribute("aria-required", isRequired);
  896. }
  897. }
  898. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  899. constructor(parameters) {
  900. const isRenderable =
  901. parameters.renderForms ||
  902. (!parameters.data.hasAppearance && !!parameters.data.fieldValue);
  903. super(parameters, { isRenderable });
  904. }
  905. setPropertyOnSiblings(base, key, value, keyInStorage) {
  906. const storage = this.annotationStorage;
  907. for (const element of this._getElementsByName(
  908. base.name,
  909. /* skipId = */ base.id
  910. )) {
  911. if (element.domElement) {
  912. element.domElement[key] = value;
  913. }
  914. storage.setValue(element.id, { [keyInStorage]: value });
  915. }
  916. }
  917. render() {
  918. const storage = this.annotationStorage;
  919. const id = this.data.id;
  920. this.container.className = "textWidgetAnnotation";
  921. let element = null;
  922. if (this.renderForms) {
  923. // NOTE: We cannot set the values using `element.value` below, since it
  924. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  925. // from parsing the elements correctly for the reference tests.
  926. const storedData = storage.getValue(id, {
  927. value: this.data.fieldValue,
  928. });
  929. let textContent = storedData.formattedValue || storedData.value || "";
  930. const maxLen = storage.getValue(id, {
  931. charLimit: this.data.maxLen,
  932. }).charLimit;
  933. if (maxLen && textContent.length > maxLen) {
  934. textContent = textContent.slice(0, maxLen);
  935. }
  936. const elementData = {
  937. userValue: textContent,
  938. formattedValue: null,
  939. lastCommittedValue: null,
  940. commitKey: 1,
  941. };
  942. if (this.data.multiLine) {
  943. element = document.createElement("textarea");
  944. element.textContent = textContent;
  945. if (this.data.doNotScroll) {
  946. element.style.overflowY = "hidden";
  947. }
  948. } else {
  949. element = document.createElement("input");
  950. element.type = "text";
  951. element.setAttribute("value", textContent);
  952. if (this.data.doNotScroll) {
  953. element.style.overflowX = "hidden";
  954. }
  955. }
  956. GetElementsByNameSet.add(element);
  957. element.setAttribute("data-element-id", id);
  958. element.disabled = this.data.readOnly;
  959. element.name = this.data.fieldName;
  960. element.tabIndex = DEFAULT_TAB_INDEX;
  961. this._setRequired(element, this.data.required);
  962. if (maxLen) {
  963. element.maxLength = maxLen;
  964. }
  965. element.addEventListener("input", event => {
  966. storage.setValue(id, { value: event.target.value });
  967. this.setPropertyOnSiblings(
  968. element,
  969. "value",
  970. event.target.value,
  971. "value"
  972. );
  973. });
  974. element.addEventListener("resetform", event => {
  975. const defaultValue = this.data.defaultFieldValue ?? "";
  976. element.value = elementData.userValue = defaultValue;
  977. elementData.formattedValue = null;
  978. });
  979. let blurListener = event => {
  980. const { formattedValue } = elementData;
  981. if (formattedValue !== null && formattedValue !== undefined) {
  982. event.target.value = formattedValue;
  983. }
  984. // Reset the cursor position to the start of the field (issue 12359).
  985. event.target.scrollLeft = 0;
  986. };
  987. if (this.enableScripting && this.hasJSActions) {
  988. element.addEventListener("focus", event => {
  989. const { target } = event;
  990. if (elementData.userValue) {
  991. target.value = elementData.userValue;
  992. }
  993. elementData.lastCommittedValue = target.value;
  994. elementData.commitKey = 1;
  995. });
  996. element.addEventListener("updatefromsandbox", jsEvent => {
  997. const actions = {
  998. value(event) {
  999. elementData.userValue = event.detail.value ?? "";
  1000. storage.setValue(id, { value: elementData.userValue.toString() });
  1001. event.target.value = elementData.userValue;
  1002. },
  1003. formattedValue(event) {
  1004. const { formattedValue } = event.detail;
  1005. elementData.formattedValue = formattedValue;
  1006. if (
  1007. formattedValue !== null &&
  1008. formattedValue !== undefined &&
  1009. event.target !== document.activeElement
  1010. ) {
  1011. // Input hasn't the focus so display formatted string
  1012. event.target.value = formattedValue;
  1013. }
  1014. storage.setValue(id, {
  1015. formattedValue,
  1016. });
  1017. },
  1018. selRange(event) {
  1019. event.target.setSelectionRange(...event.detail.selRange);
  1020. },
  1021. charLimit: event => {
  1022. const { charLimit } = event.detail;
  1023. const { target } = event;
  1024. if (charLimit === 0) {
  1025. target.removeAttribute("maxLength");
  1026. return;
  1027. }
  1028. target.setAttribute("maxLength", charLimit);
  1029. let value = elementData.userValue;
  1030. if (!value || value.length <= charLimit) {
  1031. return;
  1032. }
  1033. value = value.slice(0, charLimit);
  1034. target.value = elementData.userValue = value;
  1035. storage.setValue(id, { value });
  1036. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  1037. source: this,
  1038. detail: {
  1039. id,
  1040. name: "Keystroke",
  1041. value,
  1042. willCommit: true,
  1043. commitKey: 1,
  1044. selStart: target.selectionStart,
  1045. selEnd: target.selectionEnd,
  1046. },
  1047. });
  1048. },
  1049. };
  1050. this._dispatchEventFromSandbox(actions, jsEvent);
  1051. });
  1052. // Even if the field hasn't any actions
  1053. // leaving it can still trigger some actions with Calculate
  1054. element.addEventListener("keydown", event => {
  1055. elementData.commitKey = 1;
  1056. // If the key is one of Escape, Enter then the data are committed.
  1057. // If we've a Tab then data will be committed on blur.
  1058. let commitKey = -1;
  1059. if (event.key === "Escape") {
  1060. commitKey = 0;
  1061. } else if (event.key === "Enter" && !this.data.multiLine) {
  1062. // When we've a multiline field, "Enter" key is a key as the other
  1063. // hence we don't commit the data (Acrobat behaves the same way)
  1064. // (see issue #15627).
  1065. commitKey = 2;
  1066. } else if (event.key === "Tab") {
  1067. elementData.commitKey = 3;
  1068. }
  1069. if (commitKey === -1) {
  1070. return;
  1071. }
  1072. const { value } = event.target;
  1073. if (elementData.lastCommittedValue === value) {
  1074. return;
  1075. }
  1076. elementData.lastCommittedValue = value;
  1077. // Save the entered value
  1078. elementData.userValue = value;
  1079. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  1080. source: this,
  1081. detail: {
  1082. id,
  1083. name: "Keystroke",
  1084. value,
  1085. willCommit: true,
  1086. commitKey,
  1087. selStart: event.target.selectionStart,
  1088. selEnd: event.target.selectionEnd,
  1089. },
  1090. });
  1091. });
  1092. const _blurListener = blurListener;
  1093. blurListener = null;
  1094. element.addEventListener("blur", event => {
  1095. if (!event.relatedTarget) {
  1096. return;
  1097. }
  1098. const { value } = event.target;
  1099. elementData.userValue = value;
  1100. if (elementData.lastCommittedValue !== value) {
  1101. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  1102. source: this,
  1103. detail: {
  1104. id,
  1105. name: "Keystroke",
  1106. value,
  1107. willCommit: true,
  1108. commitKey: elementData.commitKey,
  1109. selStart: event.target.selectionStart,
  1110. selEnd: event.target.selectionEnd,
  1111. },
  1112. });
  1113. }
  1114. _blurListener(event);
  1115. });
  1116. if (this.data.actions?.Keystroke) {
  1117. element.addEventListener("beforeinput", event => {
  1118. elementData.lastCommittedValue = null;
  1119. const { data, target } = event;
  1120. const { value, selectionStart, selectionEnd } = target;
  1121. let selStart = selectionStart,
  1122. selEnd = selectionEnd;
  1123. switch (event.inputType) {
  1124. // https://rawgit.com/w3c/input-events/v1/index.html#interface-InputEvent-Attributes
  1125. case "deleteWordBackward": {
  1126. const match = value
  1127. .substring(0, selectionStart)
  1128. .match(/\w*[^\w]*$/);
  1129. if (match) {
  1130. selStart -= match[0].length;
  1131. }
  1132. break;
  1133. }
  1134. case "deleteWordForward": {
  1135. const match = value
  1136. .substring(selectionStart)
  1137. .match(/^[^\w]*\w*/);
  1138. if (match) {
  1139. selEnd += match[0].length;
  1140. }
  1141. break;
  1142. }
  1143. case "deleteContentBackward":
  1144. if (selectionStart === selectionEnd) {
  1145. selStart -= 1;
  1146. }
  1147. break;
  1148. case "deleteContentForward":
  1149. if (selectionStart === selectionEnd) {
  1150. selEnd += 1;
  1151. }
  1152. break;
  1153. }
  1154. // We handle the event ourselves.
  1155. event.preventDefault();
  1156. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  1157. source: this,
  1158. detail: {
  1159. id,
  1160. name: "Keystroke",
  1161. value,
  1162. change: data || "",
  1163. willCommit: false,
  1164. selStart,
  1165. selEnd,
  1166. },
  1167. });
  1168. });
  1169. }
  1170. this._setEventListeners(
  1171. element,
  1172. [
  1173. ["focus", "Focus"],
  1174. ["blur", "Blur"],
  1175. ["mousedown", "Mouse Down"],
  1176. ["mouseenter", "Mouse Enter"],
  1177. ["mouseleave", "Mouse Exit"],
  1178. ["mouseup", "Mouse Up"],
  1179. ],
  1180. event => event.target.value
  1181. );
  1182. }
  1183. if (blurListener) {
  1184. element.addEventListener("blur", blurListener);
  1185. }
  1186. if (this.data.comb) {
  1187. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  1188. const combWidth = fieldWidth / maxLen;
  1189. element.classList.add("comb");
  1190. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  1191. }
  1192. } else {
  1193. element = document.createElement("div");
  1194. element.textContent = this.data.fieldValue;
  1195. element.style.verticalAlign = "middle";
  1196. element.style.display = "table-cell";
  1197. }
  1198. this._setTextStyle(element);
  1199. this._setBackgroundColor(element);
  1200. this._setDefaultPropertiesFromJS(element);
  1201. this.container.append(element);
  1202. return this.container;
  1203. }
  1204. }
  1205. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  1206. constructor(parameters) {
  1207. super(parameters, { isRenderable: parameters.renderForms });
  1208. }
  1209. render() {
  1210. const storage = this.annotationStorage;
  1211. const data = this.data;
  1212. const id = data.id;
  1213. let value = storage.getValue(id, {
  1214. value: data.exportValue === data.fieldValue,
  1215. }).value;
  1216. if (typeof value === "string") {
  1217. // The value has been changed through js and set in annotationStorage.
  1218. value = value !== "Off";
  1219. storage.setValue(id, { value });
  1220. }
  1221. this.container.className = "buttonWidgetAnnotation checkBox";
  1222. const element = document.createElement("input");
  1223. GetElementsByNameSet.add(element);
  1224. element.setAttribute("data-element-id", id);
  1225. element.disabled = data.readOnly;
  1226. this._setRequired(element, this.data.required);
  1227. element.type = "checkbox";
  1228. element.name = data.fieldName;
  1229. if (value) {
  1230. element.setAttribute("checked", true);
  1231. }
  1232. element.setAttribute("exportValue", data.exportValue);
  1233. element.tabIndex = DEFAULT_TAB_INDEX;
  1234. element.addEventListener("change", event => {
  1235. const { name, checked } = event.target;
  1236. for (const checkbox of this._getElementsByName(name, /* skipId = */ id)) {
  1237. const curChecked = checked && checkbox.exportValue === data.exportValue;
  1238. if (checkbox.domElement) {
  1239. checkbox.domElement.checked = curChecked;
  1240. }
  1241. storage.setValue(checkbox.id, { value: curChecked });
  1242. }
  1243. storage.setValue(id, { value: checked });
  1244. });
  1245. element.addEventListener("resetform", event => {
  1246. const defaultValue = data.defaultFieldValue || "Off";
  1247. event.target.checked = defaultValue === data.exportValue;
  1248. });
  1249. if (this.enableScripting && this.hasJSActions) {
  1250. element.addEventListener("updatefromsandbox", jsEvent => {
  1251. const actions = {
  1252. value(event) {
  1253. event.target.checked = event.detail.value !== "Off";
  1254. storage.setValue(id, { value: event.target.checked });
  1255. },
  1256. };
  1257. this._dispatchEventFromSandbox(actions, jsEvent);
  1258. });
  1259. this._setEventListeners(
  1260. element,
  1261. [
  1262. ["change", "Validate"],
  1263. ["change", "Action"],
  1264. ["focus", "Focus"],
  1265. ["blur", "Blur"],
  1266. ["mousedown", "Mouse Down"],
  1267. ["mouseenter", "Mouse Enter"],
  1268. ["mouseleave", "Mouse Exit"],
  1269. ["mouseup", "Mouse Up"],
  1270. ],
  1271. event => event.target.checked
  1272. );
  1273. }
  1274. this._setBackgroundColor(element);
  1275. this._setDefaultPropertiesFromJS(element);
  1276. this.container.append(element);
  1277. return this.container;
  1278. }
  1279. }
  1280. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  1281. constructor(parameters) {
  1282. super(parameters, { isRenderable: parameters.renderForms });
  1283. }
  1284. render() {
  1285. this.container.className = "buttonWidgetAnnotation radioButton";
  1286. const storage = this.annotationStorage;
  1287. const data = this.data;
  1288. const id = data.id;
  1289. let value = storage.getValue(id, {
  1290. value: data.fieldValue === data.buttonValue,
  1291. }).value;
  1292. if (typeof value === "string") {
  1293. // The value has been changed through js and set in annotationStorage.
  1294. value = value !== data.buttonValue;
  1295. storage.setValue(id, { value });
  1296. }
  1297. const element = document.createElement("input");
  1298. GetElementsByNameSet.add(element);
  1299. element.setAttribute("data-element-id", id);
  1300. element.disabled = data.readOnly;
  1301. this._setRequired(element, this.data.required);
  1302. element.type = "radio";
  1303. element.name = data.fieldName;
  1304. if (value) {
  1305. element.setAttribute("checked", true);
  1306. }
  1307. element.tabIndex = DEFAULT_TAB_INDEX;
  1308. element.addEventListener("change", event => {
  1309. const { name, checked } = event.target;
  1310. for (const radio of this._getElementsByName(name, /* skipId = */ id)) {
  1311. storage.setValue(radio.id, { value: false });
  1312. }
  1313. storage.setValue(id, { value: checked });
  1314. });
  1315. element.addEventListener("resetform", event => {
  1316. const defaultValue = data.defaultFieldValue;
  1317. event.target.checked =
  1318. defaultValue !== null &&
  1319. defaultValue !== undefined &&
  1320. defaultValue === data.buttonValue;
  1321. });
  1322. if (this.enableScripting && this.hasJSActions) {
  1323. const pdfButtonValue = data.buttonValue;
  1324. element.addEventListener("updatefromsandbox", jsEvent => {
  1325. const actions = {
  1326. value: event => {
  1327. const checked = pdfButtonValue === event.detail.value;
  1328. for (const radio of this._getElementsByName(event.target.name)) {
  1329. const curChecked = checked && radio.id === id;
  1330. if (radio.domElement) {
  1331. radio.domElement.checked = curChecked;
  1332. }
  1333. storage.setValue(radio.id, { value: curChecked });
  1334. }
  1335. },
  1336. };
  1337. this._dispatchEventFromSandbox(actions, jsEvent);
  1338. });
  1339. this._setEventListeners(
  1340. element,
  1341. [
  1342. ["change", "Validate"],
  1343. ["change", "Action"],
  1344. ["focus", "Focus"],
  1345. ["blur", "Blur"],
  1346. ["mousedown", "Mouse Down"],
  1347. ["mouseenter", "Mouse Enter"],
  1348. ["mouseleave", "Mouse Exit"],
  1349. ["mouseup", "Mouse Up"],
  1350. ],
  1351. event => event.target.checked
  1352. );
  1353. }
  1354. this._setBackgroundColor(element);
  1355. this._setDefaultPropertiesFromJS(element);
  1356. this.container.append(element);
  1357. return this.container;
  1358. }
  1359. }
  1360. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  1361. constructor(parameters) {
  1362. super(parameters, { ignoreBorder: parameters.data.hasAppearance });
  1363. }
  1364. render() {
  1365. // The rendering and functionality of a push button widget annotation is
  1366. // equal to that of a link annotation, but may have more functionality, such
  1367. // as performing actions on form fields (resetting, submitting, et cetera).
  1368. const container = super.render();
  1369. container.className = "buttonWidgetAnnotation pushButton";
  1370. if (this.data.alternativeText) {
  1371. container.title = this.data.alternativeText;
  1372. }
  1373. const linkElement = container.lastChild;
  1374. if (this.enableScripting && this.hasJSActions && linkElement) {
  1375. this._setDefaultPropertiesFromJS(linkElement);
  1376. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  1377. this._dispatchEventFromSandbox({}, jsEvent);
  1378. });
  1379. }
  1380. return container;
  1381. }
  1382. }
  1383. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  1384. constructor(parameters) {
  1385. super(parameters, { isRenderable: parameters.renderForms });
  1386. }
  1387. render() {
  1388. this.container.className = "choiceWidgetAnnotation";
  1389. const storage = this.annotationStorage;
  1390. const id = this.data.id;
  1391. const storedData = storage.getValue(id, {
  1392. value: this.data.fieldValue,
  1393. });
  1394. const selectElement = document.createElement("select");
  1395. GetElementsByNameSet.add(selectElement);
  1396. selectElement.setAttribute("data-element-id", id);
  1397. selectElement.disabled = this.data.readOnly;
  1398. this._setRequired(selectElement, this.data.required);
  1399. selectElement.name = this.data.fieldName;
  1400. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  1401. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  1402. if (!this.data.combo) {
  1403. // List boxes have a size and (optionally) multiple selection.
  1404. selectElement.size = this.data.options.length;
  1405. if (this.data.multiSelect) {
  1406. selectElement.multiple = true;
  1407. }
  1408. }
  1409. selectElement.addEventListener("resetform", event => {
  1410. const defaultValue = this.data.defaultFieldValue;
  1411. for (const option of selectElement.options) {
  1412. option.selected = option.value === defaultValue;
  1413. }
  1414. });
  1415. // Insert the options into the choice field.
  1416. for (const option of this.data.options) {
  1417. const optionElement = document.createElement("option");
  1418. optionElement.textContent = option.displayValue;
  1419. optionElement.value = option.exportValue;
  1420. if (storedData.value.includes(option.exportValue)) {
  1421. optionElement.setAttribute("selected", true);
  1422. addAnEmptyEntry = false;
  1423. }
  1424. selectElement.append(optionElement);
  1425. }
  1426. let removeEmptyEntry = null;
  1427. if (addAnEmptyEntry) {
  1428. const noneOptionElement = document.createElement("option");
  1429. noneOptionElement.value = " ";
  1430. noneOptionElement.setAttribute("hidden", true);
  1431. noneOptionElement.setAttribute("selected", true);
  1432. selectElement.prepend(noneOptionElement);
  1433. removeEmptyEntry = () => {
  1434. noneOptionElement.remove();
  1435. selectElement.removeEventListener("input", removeEmptyEntry);
  1436. removeEmptyEntry = null;
  1437. };
  1438. selectElement.addEventListener("input", removeEmptyEntry);
  1439. }
  1440. const getValue = isExport => {
  1441. const name = isExport ? "value" : "textContent";
  1442. const { options, multiple } = selectElement;
  1443. if (!multiple) {
  1444. return options.selectedIndex === -1
  1445. ? null
  1446. : options[options.selectedIndex][name];
  1447. }
  1448. return Array.prototype.filter
  1449. .call(options, option => option.selected)
  1450. .map(option => option[name]);
  1451. };
  1452. let selectedValues = getValue(/* isExport */ false);
  1453. const getItems = event => {
  1454. const options = event.target.options;
  1455. return Array.prototype.map.call(options, option => {
  1456. return { displayValue: option.textContent, exportValue: option.value };
  1457. });
  1458. };
  1459. if (this.enableScripting && this.hasJSActions) {
  1460. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  1461. const actions = {
  1462. value(event) {
  1463. removeEmptyEntry?.();
  1464. const value = event.detail.value;
  1465. const values = new Set(Array.isArray(value) ? value : [value]);
  1466. for (const option of selectElement.options) {
  1467. option.selected = values.has(option.value);
  1468. }
  1469. storage.setValue(id, {
  1470. value: getValue(/* isExport */ true),
  1471. });
  1472. selectedValues = getValue(/* isExport */ false);
  1473. },
  1474. multipleSelection(event) {
  1475. selectElement.multiple = true;
  1476. },
  1477. remove(event) {
  1478. const options = selectElement.options;
  1479. const index = event.detail.remove;
  1480. options[index].selected = false;
  1481. selectElement.remove(index);
  1482. if (options.length > 0) {
  1483. const i = Array.prototype.findIndex.call(
  1484. options,
  1485. option => option.selected
  1486. );
  1487. if (i === -1) {
  1488. options[0].selected = true;
  1489. }
  1490. }
  1491. storage.setValue(id, {
  1492. value: getValue(/* isExport */ true),
  1493. items: getItems(event),
  1494. });
  1495. selectedValues = getValue(/* isExport */ false);
  1496. },
  1497. clear(event) {
  1498. while (selectElement.length !== 0) {
  1499. selectElement.remove(0);
  1500. }
  1501. storage.setValue(id, { value: null, items: [] });
  1502. selectedValues = getValue(/* isExport */ false);
  1503. },
  1504. insert(event) {
  1505. const { index, displayValue, exportValue } = event.detail.insert;
  1506. const selectChild = selectElement.children[index];
  1507. const optionElement = document.createElement("option");
  1508. optionElement.textContent = displayValue;
  1509. optionElement.value = exportValue;
  1510. if (selectChild) {
  1511. selectChild.before(optionElement);
  1512. } else {
  1513. selectElement.append(optionElement);
  1514. }
  1515. storage.setValue(id, {
  1516. value: getValue(/* isExport */ true),
  1517. items: getItems(event),
  1518. });
  1519. selectedValues = getValue(/* isExport */ false);
  1520. },
  1521. items(event) {
  1522. const { items } = event.detail;
  1523. while (selectElement.length !== 0) {
  1524. selectElement.remove(0);
  1525. }
  1526. for (const item of items) {
  1527. const { displayValue, exportValue } = item;
  1528. const optionElement = document.createElement("option");
  1529. optionElement.textContent = displayValue;
  1530. optionElement.value = exportValue;
  1531. selectElement.append(optionElement);
  1532. }
  1533. if (selectElement.options.length > 0) {
  1534. selectElement.options[0].selected = true;
  1535. }
  1536. storage.setValue(id, {
  1537. value: getValue(/* isExport */ true),
  1538. items: getItems(event),
  1539. });
  1540. selectedValues = getValue(/* isExport */ false);
  1541. },
  1542. indices(event) {
  1543. const indices = new Set(event.detail.indices);
  1544. for (const option of event.target.options) {
  1545. option.selected = indices.has(option.index);
  1546. }
  1547. storage.setValue(id, {
  1548. value: getValue(/* isExport */ true),
  1549. });
  1550. selectedValues = getValue(/* isExport */ false);
  1551. },
  1552. editable(event) {
  1553. event.target.disabled = !event.detail.editable;
  1554. },
  1555. };
  1556. this._dispatchEventFromSandbox(actions, jsEvent);
  1557. });
  1558. selectElement.addEventListener("input", event => {
  1559. const exportValue = getValue(/* isExport */ true);
  1560. storage.setValue(id, { value: exportValue });
  1561. event.preventDefault();
  1562. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  1563. source: this,
  1564. detail: {
  1565. id,
  1566. name: "Keystroke",
  1567. value: selectedValues,
  1568. changeEx: exportValue,
  1569. willCommit: false,
  1570. commitKey: 1,
  1571. keyDown: false,
  1572. },
  1573. });
  1574. });
  1575. this._setEventListeners(
  1576. selectElement,
  1577. [
  1578. ["focus", "Focus"],
  1579. ["blur", "Blur"],
  1580. ["mousedown", "Mouse Down"],
  1581. ["mouseenter", "Mouse Enter"],
  1582. ["mouseleave", "Mouse Exit"],
  1583. ["mouseup", "Mouse Up"],
  1584. ["input", "Action"],
  1585. ],
  1586. event => event.target.checked
  1587. );
  1588. } else {
  1589. selectElement.addEventListener("input", function (event) {
  1590. storage.setValue(id, { value: getValue(/* isExport */ true) });
  1591. });
  1592. }
  1593. if (this.data.combo) {
  1594. this._setTextStyle(selectElement);
  1595. } else {
  1596. // Just use the default font size...
  1597. // it's a bit hard to guess what is a good size.
  1598. }
  1599. this._setBackgroundColor(selectElement);
  1600. this._setDefaultPropertiesFromJS(selectElement);
  1601. this.container.append(selectElement);
  1602. return this.container;
  1603. }
  1604. }
  1605. class PopupAnnotationElement extends AnnotationElement {
  1606. // Do not render popup annotations for parent elements with these types as
  1607. // they create the popups themselves (because of custom trigger divs).
  1608. static IGNORE_TYPES = new Set([
  1609. "Line",
  1610. "Square",
  1611. "Circle",
  1612. "PolyLine",
  1613. "Polygon",
  1614. "Ink",
  1615. ]);
  1616. constructor(parameters) {
  1617. const { data } = parameters;
  1618. const isRenderable =
  1619. !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) &&
  1620. !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  1621. super(parameters, { isRenderable });
  1622. }
  1623. render() {
  1624. this.container.className = "popupAnnotation";
  1625. const parentElements = this.layer.querySelectorAll(
  1626. `[data-annotation-id="${this.data.parentId}"]`
  1627. );
  1628. if (parentElements.length === 0) {
  1629. return this.container;
  1630. }
  1631. const popup = new PopupElement({
  1632. container: this.container,
  1633. trigger: Array.from(parentElements),
  1634. color: this.data.color,
  1635. titleObj: this.data.titleObj,
  1636. modificationDate: this.data.modificationDate,
  1637. contentsObj: this.data.contentsObj,
  1638. richText: this.data.richText,
  1639. });
  1640. // Position the popup next to the parent annotation's container.
  1641. // PDF viewers ignore a popup annotation's rectangle.
  1642. const page = this.page;
  1643. const rect = Util.normalizeRect([
  1644. this.data.parentRect[0],
  1645. page.view[3] - this.data.parentRect[1] + page.view[1],
  1646. this.data.parentRect[2],
  1647. page.view[3] - this.data.parentRect[3] + page.view[1],
  1648. ]);
  1649. const popupLeft =
  1650. rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  1651. const popupTop = rect[1];
  1652. const { pageWidth, pageHeight, pageX, pageY } = this.viewport.rawDims;
  1653. this.container.style.left = `${(100 * (popupLeft - pageX)) / pageWidth}%`;
  1654. this.container.style.top = `${(100 * (popupTop - pageY)) / pageHeight}%`;
  1655. this.container.append(popup.render());
  1656. return this.container;
  1657. }
  1658. }
  1659. class PopupElement {
  1660. constructor(parameters) {
  1661. this.container = parameters.container;
  1662. this.trigger = parameters.trigger;
  1663. this.color = parameters.color;
  1664. this.titleObj = parameters.titleObj;
  1665. this.modificationDate = parameters.modificationDate;
  1666. this.contentsObj = parameters.contentsObj;
  1667. this.richText = parameters.richText;
  1668. this.hideWrapper = parameters.hideWrapper || false;
  1669. this.pinned = false;
  1670. }
  1671. render() {
  1672. const BACKGROUND_ENLIGHT = 0.7;
  1673. const wrapper = document.createElement("div");
  1674. wrapper.className = "popupWrapper";
  1675. // For Popup annotations we hide the entire section because it contains
  1676. // only the popup. However, for Text annotations without a separate Popup
  1677. // annotation, we cannot hide the entire container as the image would
  1678. // disappear too. In that special case, hiding the wrapper suffices.
  1679. this.hideElement = this.hideWrapper ? wrapper : this.container;
  1680. this.hideElement.hidden = true;
  1681. const popup = document.createElement("div");
  1682. popup.className = "popup";
  1683. const color = this.color;
  1684. if (color) {
  1685. // Enlighten the color.
  1686. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  1687. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  1688. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  1689. popup.style.backgroundColor = Util.makeHexColor(r | 0, g | 0, b | 0);
  1690. }
  1691. const title = document.createElement("h1");
  1692. title.dir = this.titleObj.dir;
  1693. title.textContent = this.titleObj.str;
  1694. popup.append(title);
  1695. // The modification date is shown in the popup instead of the creation
  1696. // date if it is available and can be parsed correctly, which is
  1697. // consistent with other viewers such as Adobe Acrobat.
  1698. const dateObject = PDFDateString.toDateObject(this.modificationDate);
  1699. if (dateObject) {
  1700. const modificationDate = document.createElement("span");
  1701. modificationDate.className = "popupDate";
  1702. modificationDate.textContent = "{{date}}, {{time}}";
  1703. modificationDate.dataset.l10nId = "annotation_date_string";
  1704. modificationDate.dataset.l10nArgs = JSON.stringify({
  1705. date: dateObject.toLocaleDateString(),
  1706. time: dateObject.toLocaleTimeString(),
  1707. });
  1708. popup.append(modificationDate);
  1709. }
  1710. if (
  1711. this.richText?.str &&
  1712. (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)
  1713. ) {
  1714. XfaLayer.render({
  1715. xfaHtml: this.richText.html,
  1716. intent: "richText",
  1717. div: popup,
  1718. });
  1719. popup.lastChild.className = "richText popupContent";
  1720. } else {
  1721. const contents = this._formatContents(this.contentsObj);
  1722. popup.append(contents);
  1723. }
  1724. if (!Array.isArray(this.trigger)) {
  1725. this.trigger = [this.trigger];
  1726. }
  1727. // Attach the event listeners to the trigger element.
  1728. for (const element of this.trigger) {
  1729. element.addEventListener("click", this._toggle.bind(this));
  1730. element.addEventListener("mouseover", this._show.bind(this, false));
  1731. element.addEventListener("mouseout", this._hide.bind(this, false));
  1732. }
  1733. popup.addEventListener("click", this._hide.bind(this, true));
  1734. wrapper.append(popup);
  1735. return wrapper;
  1736. }
  1737. /**
  1738. * Format the contents of the popup by adding newlines where necessary.
  1739. *
  1740. * @private
  1741. * @param {Object<string, string>} contentsObj
  1742. * @memberof PopupElement
  1743. * @returns {HTMLParagraphElement}
  1744. */
  1745. _formatContents({ str, dir }) {
  1746. const p = document.createElement("p");
  1747. p.className = "popupContent";
  1748. p.dir = dir;
  1749. const lines = str.split(/(?:\r\n?|\n)/);
  1750. for (let i = 0, ii = lines.length; i < ii; ++i) {
  1751. const line = lines[i];
  1752. p.append(document.createTextNode(line));
  1753. if (i < ii - 1) {
  1754. p.append(document.createElement("br"));
  1755. }
  1756. }
  1757. return p;
  1758. }
  1759. /**
  1760. * Toggle the visibility of the popup.
  1761. *
  1762. * @private
  1763. * @memberof PopupElement
  1764. */
  1765. _toggle() {
  1766. if (this.pinned) {
  1767. this._hide(true);
  1768. } else {
  1769. this._show(true);
  1770. }
  1771. }
  1772. /**
  1773. * Show the popup.
  1774. *
  1775. * @private
  1776. * @param {boolean} pin
  1777. * @memberof PopupElement
  1778. */
  1779. _show(pin = false) {
  1780. if (pin) {
  1781. this.pinned = true;
  1782. }
  1783. if (this.hideElement.hidden) {
  1784. this.hideElement.hidden = false;
  1785. this.container.style.zIndex =
  1786. parseInt(this.container.style.zIndex) + 1000;
  1787. }
  1788. }
  1789. /**
  1790. * Hide the popup.
  1791. *
  1792. * @private
  1793. * @param {boolean} unpin
  1794. * @memberof PopupElement
  1795. */
  1796. _hide(unpin = true) {
  1797. if (unpin) {
  1798. this.pinned = false;
  1799. }
  1800. if (!this.hideElement.hidden && !this.pinned) {
  1801. this.hideElement.hidden = true;
  1802. this.container.style.zIndex =
  1803. parseInt(this.container.style.zIndex) - 1000;
  1804. }
  1805. }
  1806. }
  1807. class FreeTextAnnotationElement extends AnnotationElement {
  1808. constructor(parameters) {
  1809. const isRenderable = !!(
  1810. parameters.data.hasPopup ||
  1811. parameters.data.titleObj?.str ||
  1812. parameters.data.contentsObj?.str ||
  1813. parameters.data.richText?.str
  1814. );
  1815. super(parameters, { isRenderable, ignoreBorder: true });
  1816. this.textContent = parameters.data.textContent;
  1817. }
  1818. render() {
  1819. this.container.className = "freeTextAnnotation";
  1820. if (this.textContent) {
  1821. const content = document.createElement("div");
  1822. content.className = "annotationTextContent";
  1823. content.setAttribute("role", "comment");
  1824. for (const line of this.textContent) {
  1825. const lineSpan = document.createElement("span");
  1826. lineSpan.textContent = line;
  1827. content.append(lineSpan);
  1828. }
  1829. this.container.append(content);
  1830. }
  1831. if (!this.data.hasPopup) {
  1832. this._createPopup(null, this.data);
  1833. }
  1834. return this.container;
  1835. }
  1836. }
  1837. class LineAnnotationElement extends AnnotationElement {
  1838. constructor(parameters) {
  1839. const isRenderable = !!(
  1840. parameters.data.hasPopup ||
  1841. parameters.data.titleObj?.str ||
  1842. parameters.data.contentsObj?.str ||
  1843. parameters.data.richText?.str
  1844. );
  1845. super(parameters, { isRenderable, ignoreBorder: true });
  1846. }
  1847. render() {
  1848. this.container.className = "lineAnnotation";
  1849. // Create an invisible line with the same starting and ending coordinates
  1850. // that acts as the trigger for the popup. Only the line itself should
  1851. // trigger the popup, not the entire container.
  1852. const data = this.data;
  1853. const { width, height } = getRectDims(data.rect);
  1854. const svg = this.svgFactory.create(
  1855. width,
  1856. height,
  1857. /* skipDimensions = */ true
  1858. );
  1859. // PDF coordinates are calculated from a bottom left origin, so transform
  1860. // the line coordinates to a top left origin for the SVG element.
  1861. const line = this.svgFactory.createElement("svg:line");
  1862. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  1863. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  1864. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  1865. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  1866. // Ensure that the 'stroke-width' is always non-zero, since otherwise it
  1867. // won't be possible to open/close the popup (note e.g. issue 11122).
  1868. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  1869. line.setAttribute("stroke", "transparent");
  1870. line.setAttribute("fill", "transparent");
  1871. svg.append(line);
  1872. this.container.append(svg);
  1873. // Create the popup ourselves so that we can bind it to the line instead
  1874. // of to the entire container (which is the default).
  1875. this._createPopup(line, data);
  1876. return this.container;
  1877. }
  1878. }
  1879. class SquareAnnotationElement extends AnnotationElement {
  1880. constructor(parameters) {
  1881. const isRenderable = !!(
  1882. parameters.data.hasPopup ||
  1883. parameters.data.titleObj?.str ||
  1884. parameters.data.contentsObj?.str ||
  1885. parameters.data.richText?.str
  1886. );
  1887. super(parameters, { isRenderable, ignoreBorder: true });
  1888. }
  1889. render() {
  1890. this.container.className = "squareAnnotation";
  1891. // Create an invisible square with the same rectangle that acts as the
  1892. // trigger for the popup. Only the square itself should trigger the
  1893. // popup, not the entire container.
  1894. const data = this.data;
  1895. const { width, height } = getRectDims(data.rect);
  1896. const svg = this.svgFactory.create(
  1897. width,
  1898. height,
  1899. /* skipDimensions = */ true
  1900. );
  1901. // The browser draws half of the borders inside the square and half of
  1902. // the borders outside the square by default. This behavior cannot be
  1903. // changed programmatically, so correct for that here.
  1904. const borderWidth = data.borderStyle.width;
  1905. const square = this.svgFactory.createElement("svg:rect");
  1906. square.setAttribute("x", borderWidth / 2);
  1907. square.setAttribute("y", borderWidth / 2);
  1908. square.setAttribute("width", width - borderWidth);
  1909. square.setAttribute("height", height - borderWidth);
  1910. // Ensure that the 'stroke-width' is always non-zero, since otherwise it
  1911. // won't be possible to open/close the popup (note e.g. issue 11122).
  1912. square.setAttribute("stroke-width", borderWidth || 1);
  1913. square.setAttribute("stroke", "transparent");
  1914. square.setAttribute("fill", "transparent");
  1915. svg.append(square);
  1916. this.container.append(svg);
  1917. // Create the popup ourselves so that we can bind it to the square instead
  1918. // of to the entire container (which is the default).
  1919. this._createPopup(square, data);
  1920. return this.container;
  1921. }
  1922. }
  1923. class CircleAnnotationElement extends AnnotationElement {
  1924. constructor(parameters) {
  1925. const isRenderable = !!(
  1926. parameters.data.hasPopup ||
  1927. parameters.data.titleObj?.str ||
  1928. parameters.data.contentsObj?.str ||
  1929. parameters.data.richText?.str
  1930. );
  1931. super(parameters, { isRenderable, ignoreBorder: true });
  1932. }
  1933. render() {
  1934. this.container.className = "circleAnnotation";
  1935. // Create an invisible circle with the same ellipse that acts as the
  1936. // trigger for the popup. Only the circle itself should trigger the
  1937. // popup, not the entire container.
  1938. const data = this.data;
  1939. const { width, height } = getRectDims(data.rect);
  1940. const svg = this.svgFactory.create(
  1941. width,
  1942. height,
  1943. /* skipDimensions = */ true
  1944. );
  1945. // The browser draws half of the borders inside the circle and half of
  1946. // the borders outside the circle by default. This behavior cannot be
  1947. // changed programmatically, so correct for that here.
  1948. const borderWidth = data.borderStyle.width;
  1949. const circle = this.svgFactory.createElement("svg:ellipse");
  1950. circle.setAttribute("cx", width / 2);
  1951. circle.setAttribute("cy", height / 2);
  1952. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  1953. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  1954. // Ensure that the 'stroke-width' is always non-zero, since otherwise it
  1955. // won't be possible to open/close the popup (note e.g. issue 11122).
  1956. circle.setAttribute("stroke-width", borderWidth || 1);
  1957. circle.setAttribute("stroke", "transparent");
  1958. circle.setAttribute("fill", "transparent");
  1959. svg.append(circle);
  1960. this.container.append(svg);
  1961. // Create the popup ourselves so that we can bind it to the circle instead
  1962. // of to the entire container (which is the default).
  1963. this._createPopup(circle, data);
  1964. return this.container;
  1965. }
  1966. }
  1967. class PolylineAnnotationElement extends AnnotationElement {
  1968. constructor(parameters) {
  1969. const isRenderable = !!(
  1970. parameters.data.hasPopup ||
  1971. parameters.data.titleObj?.str ||
  1972. parameters.data.contentsObj?.str ||
  1973. parameters.data.richText?.str
  1974. );
  1975. super(parameters, { isRenderable, ignoreBorder: true });
  1976. this.containerClassName = "polylineAnnotation";
  1977. this.svgElementName = "svg:polyline";
  1978. }
  1979. render() {
  1980. this.container.className = this.containerClassName;
  1981. // Create an invisible polyline with the same points that acts as the
  1982. // trigger for the popup. Only the polyline itself should trigger the
  1983. // popup, not the entire container.
  1984. const data = this.data;
  1985. const { width, height } = getRectDims(data.rect);
  1986. const svg = this.svgFactory.create(
  1987. width,
  1988. height,
  1989. /* skipDimensions = */ true
  1990. );
  1991. // Convert the vertices array to a single points string that the SVG
  1992. // polyline element expects ("x1,y1 x2,y2 ..."). PDF coordinates are
  1993. // calculated from a bottom left origin, so transform the polyline
  1994. // coordinates to a top left origin for the SVG element.
  1995. let points = [];
  1996. for (const coordinate of data.vertices) {
  1997. const x = coordinate.x - data.rect[0];
  1998. const y = data.rect[3] - coordinate.y;
  1999. points.push(x + "," + y);
  2000. }
  2001. points = points.join(" ");
  2002. const polyline = this.svgFactory.createElement(this.svgElementName);
  2003. polyline.setAttribute("points", points);
  2004. // Ensure that the 'stroke-width' is always non-zero, since otherwise it
  2005. // won't be possible to open/close the popup (note e.g. issue 11122).
  2006. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  2007. polyline.setAttribute("stroke", "transparent");
  2008. polyline.setAttribute("fill", "transparent");
  2009. svg.append(polyline);
  2010. this.container.append(svg);
  2011. // Create the popup ourselves so that we can bind it to the polyline
  2012. // instead of to the entire container (which is the default).
  2013. this._createPopup(polyline, data);
  2014. return this.container;
  2015. }
  2016. }
  2017. class PolygonAnnotationElement extends PolylineAnnotationElement {
  2018. constructor(parameters) {
  2019. // Polygons are specific forms of polylines, so reuse their logic.
  2020. super(parameters);
  2021. this.containerClassName = "polygonAnnotation";
  2022. this.svgElementName = "svg:polygon";
  2023. }
  2024. }
  2025. class CaretAnnotationElement extends AnnotationElement {
  2026. constructor(parameters) {
  2027. const isRenderable = !!(
  2028. parameters.data.hasPopup ||
  2029. parameters.data.titleObj?.str ||
  2030. parameters.data.contentsObj?.str ||
  2031. parameters.data.richText?.str
  2032. );
  2033. super(parameters, { isRenderable, ignoreBorder: true });
  2034. }
  2035. render() {
  2036. this.container.className = "caretAnnotation";
  2037. if (!this.data.hasPopup) {
  2038. this._createPopup(null, this.data);
  2039. }
  2040. return this.container;
  2041. }
  2042. }
  2043. class InkAnnotationElement extends AnnotationElement {
  2044. constructor(parameters) {
  2045. const isRenderable = !!(
  2046. parameters.data.hasPopup ||
  2047. parameters.data.titleObj?.str ||
  2048. parameters.data.contentsObj?.str ||
  2049. parameters.data.richText?.str
  2050. );
  2051. super(parameters, { isRenderable, ignoreBorder: true });
  2052. this.containerClassName = "inkAnnotation";
  2053. // Use the polyline SVG element since it allows us to use coordinates
  2054. // directly and to draw both straight lines and curves.
  2055. this.svgElementName = "svg:polyline";
  2056. }
  2057. render() {
  2058. this.container.className = this.containerClassName;
  2059. // Create an invisible polyline with the same points that acts as the
  2060. // trigger for the popup.
  2061. const data = this.data;
  2062. const { width, height } = getRectDims(data.rect);
  2063. const svg = this.svgFactory.create(
  2064. width,
  2065. height,
  2066. /* skipDimensions = */ true
  2067. );
  2068. for (const inkList of data.inkLists) {
  2069. // Convert the ink list to a single points string that the SVG
  2070. // polyline element expects ("x1,y1 x2,y2 ..."). PDF coordinates are
  2071. // calculated from a bottom left origin, so transform the polyline
  2072. // coordinates to a top left origin for the SVG element.
  2073. let points = [];
  2074. for (const coordinate of inkList) {
  2075. const x = coordinate.x - data.rect[0];
  2076. const y = data.rect[3] - coordinate.y;
  2077. points.push(`${x},${y}`);
  2078. }
  2079. points = points.join(" ");
  2080. const polyline = this.svgFactory.createElement(this.svgElementName);
  2081. polyline.setAttribute("points", points);
  2082. // Ensure that the 'stroke-width' is always non-zero, since otherwise it
  2083. // won't be possible to open/close the popup (note e.g. issue 11122).
  2084. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  2085. polyline.setAttribute("stroke", "transparent");
  2086. polyline.setAttribute("fill", "transparent");
  2087. // Create the popup ourselves so that we can bind it to the polyline
  2088. // instead of to the entire container (which is the default).
  2089. this._createPopup(polyline, data);
  2090. svg.append(polyline);
  2091. }
  2092. this.container.append(svg);
  2093. return this.container;
  2094. }
  2095. }
  2096. class HighlightAnnotationElement extends AnnotationElement {
  2097. constructor(parameters) {
  2098. const isRenderable = !!(
  2099. parameters.data.hasPopup ||
  2100. parameters.data.titleObj?.str ||
  2101. parameters.data.contentsObj?.str ||
  2102. parameters.data.richText?.str
  2103. );
  2104. super(parameters, {
  2105. isRenderable,
  2106. ignoreBorder: true,
  2107. createQuadrilaterals: true,
  2108. });
  2109. }
  2110. render() {
  2111. if (!this.data.hasPopup) {
  2112. this._createPopup(null, this.data);
  2113. }
  2114. if (this.quadrilaterals) {
  2115. return this._renderQuadrilaterals("highlightAnnotation");
  2116. }
  2117. this.container.className = "highlightAnnotation";
  2118. return this.container;
  2119. }
  2120. }
  2121. class UnderlineAnnotationElement extends AnnotationElement {
  2122. constructor(parameters) {
  2123. const isRenderable = !!(
  2124. parameters.data.hasPopup ||
  2125. parameters.data.titleObj?.str ||
  2126. parameters.data.contentsObj?.str ||
  2127. parameters.data.richText?.str
  2128. );
  2129. super(parameters, {
  2130. isRenderable,
  2131. ignoreBorder: true,
  2132. createQuadrilaterals: true,
  2133. });
  2134. }
  2135. render() {
  2136. if (!this.data.hasPopup) {
  2137. this._createPopup(null, this.data);
  2138. }
  2139. if (this.quadrilaterals) {
  2140. return this._renderQuadrilaterals("underlineAnnotation");
  2141. }
  2142. this.container.className = "underlineAnnotation";
  2143. return this.container;
  2144. }
  2145. }
  2146. class SquigglyAnnotationElement extends AnnotationElement {
  2147. constructor(parameters) {
  2148. const isRenderable = !!(
  2149. parameters.data.hasPopup ||
  2150. parameters.data.titleObj?.str ||
  2151. parameters.data.contentsObj?.str ||
  2152. parameters.data.richText?.str
  2153. );
  2154. super(parameters, {
  2155. isRenderable,
  2156. ignoreBorder: true,
  2157. createQuadrilaterals: true,
  2158. });
  2159. }
  2160. render() {
  2161. if (!this.data.hasPopup) {
  2162. this._createPopup(null, this.data);
  2163. }
  2164. if (this.quadrilaterals) {
  2165. return this._renderQuadrilaterals("squigglyAnnotation");
  2166. }
  2167. this.container.className = "squigglyAnnotation";
  2168. return this.container;
  2169. }
  2170. }
  2171. class StrikeOutAnnotationElement extends AnnotationElement {
  2172. constructor(parameters) {
  2173. const isRenderable = !!(
  2174. parameters.data.hasPopup ||
  2175. parameters.data.titleObj?.str ||
  2176. parameters.data.contentsObj?.str ||
  2177. parameters.data.richText?.str
  2178. );
  2179. super(parameters, {
  2180. isRenderable,
  2181. ignoreBorder: true,
  2182. createQuadrilaterals: true,
  2183. });
  2184. }
  2185. render() {
  2186. if (!this.data.hasPopup) {
  2187. this._createPopup(null, this.data);
  2188. }
  2189. if (this.quadrilaterals) {
  2190. return this._renderQuadrilaterals("strikeoutAnnotation");
  2191. }
  2192. this.container.className = "strikeoutAnnotation";
  2193. return this.container;
  2194. }
  2195. }
  2196. class StampAnnotationElement extends AnnotationElement {
  2197. constructor(parameters) {
  2198. const isRenderable = !!(
  2199. parameters.data.hasPopup ||
  2200. parameters.data.titleObj?.str ||
  2201. parameters.data.contentsObj?.str ||
  2202. parameters.data.richText?.str
  2203. );
  2204. super(parameters, { isRenderable, ignoreBorder: true });
  2205. }
  2206. render() {
  2207. this.container.className = "stampAnnotation";
  2208. if (!this.data.hasPopup) {
  2209. this._createPopup(null, this.data);
  2210. }
  2211. return this.container;
  2212. }
  2213. }
  2214. class FileAttachmentAnnotationElement extends AnnotationElement {
  2215. constructor(parameters) {
  2216. super(parameters, { isRenderable: true });
  2217. const { filename, content } = this.data.file;
  2218. this.filename = getFilenameFromUrl(filename, /* onlyStripPath = */ true);
  2219. this.content = content;
  2220. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  2221. source: this,
  2222. filename,
  2223. content,
  2224. });
  2225. }
  2226. render() {
  2227. this.container.className = "fileAttachmentAnnotation";
  2228. let trigger;
  2229. if (this.data.hasAppearance) {
  2230. trigger = document.createElement("div");
  2231. } else {
  2232. // Unfortunately it seems that it's not clearly specified exactly what
  2233. // names are actually valid, since Table 184 contains:
  2234. // Conforming readers shall provide predefined icon appearances for at
  2235. // least the following standard names: GraphPushPin, PaperclipTag.
  2236. // Additional names may be supported as well. Default value: PushPin.
  2237. trigger = document.createElement("img");
  2238. trigger.src = `${this.imageResourcesPath}annotation-${
  2239. /paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"
  2240. }.svg`;
  2241. }
  2242. trigger.className = "popupTriggerArea";
  2243. trigger.addEventListener("dblclick", this._download.bind(this));
  2244. if (
  2245. !this.data.hasPopup &&
  2246. (this.data.titleObj?.str ||
  2247. this.data.contentsObj?.str ||
  2248. this.data.richText)
  2249. ) {
  2250. this._createPopup(trigger, this.data);
  2251. }
  2252. this.container.append(trigger);
  2253. return this.container;
  2254. }
  2255. /**
  2256. * Download the file attachment associated with this annotation.
  2257. *
  2258. * @private
  2259. * @memberof FileAttachmentAnnotationElement
  2260. */
  2261. _download() {
  2262. this.downloadManager?.openOrDownloadData(
  2263. this.container,
  2264. this.content,
  2265. this.filename
  2266. );
  2267. }
  2268. }
  2269. /**
  2270. * @typedef {Object} AnnotationLayerParameters
  2271. * @property {PageViewport} viewport
  2272. * @property {HTMLDivElement} div
  2273. * @property {Array} annotations
  2274. * @property {PDFPageProxy} page
  2275. * @property {IPDFLinkService} linkService
  2276. * @property {IDownloadManager} downloadManager
  2277. * @property {AnnotationStorage} [annotationStorage]
  2278. * @property {string} [imageResourcesPath] - Path for image resources, mainly
  2279. * for annotation icons. Include trailing slash.
  2280. * @property {boolean} renderForms
  2281. * @property {boolean} [enableScripting] - Enable embedded script execution.
  2282. * @property {boolean} [hasJSActions] - Some fields have JS actions.
  2283. * The default value is `false`.
  2284. * @property {Object<string, Array<Object>> | null} [fieldObjects]
  2285. * @property {Map<string, HTMLCanvasElement>} [annotationCanvasMap]
  2286. * @property {TextAccessibilityManager} [accessibilityManager]
  2287. */
  2288. class AnnotationLayer {
  2289. static #appendElement(element, id, div, accessibilityManager) {
  2290. const contentElement = element.firstChild || element;
  2291. contentElement.id = `${AnnotationPrefix}${id}`;
  2292. div.append(element);
  2293. accessibilityManager?.moveElementInDOM(
  2294. div,
  2295. element,
  2296. contentElement,
  2297. /* isRemovable = */ false
  2298. );
  2299. }
  2300. /**
  2301. * Render a new annotation layer with all annotation elements.
  2302. *
  2303. * @param {AnnotationLayerParameters} params
  2304. * @memberof AnnotationLayer
  2305. */
  2306. static render(params) {
  2307. const { annotations, div, viewport, accessibilityManager } = params;
  2308. setLayerDimensions(div, viewport);
  2309. const elementParams = {
  2310. data: null,
  2311. layer: div,
  2312. page: params.page,
  2313. viewport,
  2314. linkService: params.linkService,
  2315. downloadManager: params.downloadManager,
  2316. imageResourcesPath: params.imageResourcesPath || "",
  2317. renderForms: params.renderForms !== false,
  2318. svgFactory: new DOMSVGFactory(),
  2319. annotationStorage: params.annotationStorage || new AnnotationStorage(),
  2320. enableScripting: params.enableScripting === true,
  2321. hasJSActions: params.hasJSActions,
  2322. fieldObjects: params.fieldObjects,
  2323. };
  2324. let zIndex = 0;
  2325. for (const data of annotations) {
  2326. if (data.annotationType !== AnnotationType.POPUP) {
  2327. const { width, height } = getRectDims(data.rect);
  2328. if (width <= 0 || height <= 0) {
  2329. continue; // Ignore empty annotations.
  2330. }
  2331. }
  2332. elementParams.data = data;
  2333. const element = AnnotationElementFactory.create(elementParams);
  2334. if (!element.isRenderable) {
  2335. continue;
  2336. }
  2337. const rendered = element.render();
  2338. if (data.hidden) {
  2339. rendered.style.visibility = "hidden";
  2340. }
  2341. if (Array.isArray(rendered)) {
  2342. for (const renderedElement of rendered) {
  2343. renderedElement.style.zIndex = zIndex++;
  2344. AnnotationLayer.#appendElement(
  2345. renderedElement,
  2346. data.id,
  2347. div,
  2348. accessibilityManager
  2349. );
  2350. }
  2351. } else {
  2352. // The accessibility manager will move the annotation in the DOM in
  2353. // order to match the visual ordering.
  2354. // But if an annotation is above an other one, then we must draw it
  2355. // after the other one whatever the order is in the DOM, hence the
  2356. // use of the z-index.
  2357. rendered.style.zIndex = zIndex++;
  2358. if (element instanceof PopupAnnotationElement) {
  2359. // Popup annotation elements should not be on top of other
  2360. // annotation elements to prevent interfering with mouse events.
  2361. div.prepend(rendered);
  2362. } else {
  2363. AnnotationLayer.#appendElement(
  2364. rendered,
  2365. data.id,
  2366. div,
  2367. accessibilityManager
  2368. );
  2369. }
  2370. }
  2371. }
  2372. this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
  2373. }
  2374. /**
  2375. * Update the annotation elements on existing annotation layer.
  2376. *
  2377. * @param {AnnotationLayerParameters} params
  2378. * @memberof AnnotationLayer
  2379. */
  2380. static update(params) {
  2381. const { annotationCanvasMap, div, viewport } = params;
  2382. setLayerDimensions(div, { rotation: viewport.rotation });
  2383. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  2384. div.hidden = false;
  2385. }
  2386. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  2387. if (!annotationCanvasMap) {
  2388. return;
  2389. }
  2390. for (const [id, canvas] of annotationCanvasMap) {
  2391. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  2392. if (!element) {
  2393. continue;
  2394. }
  2395. const { firstChild } = element;
  2396. if (!firstChild) {
  2397. element.append(canvas);
  2398. } else if (firstChild.nodeName === "CANVAS") {
  2399. firstChild.replaceWith(canvas);
  2400. } else {
  2401. firstChild.before(canvas);
  2402. }
  2403. }
  2404. annotationCanvasMap.clear();
  2405. }
  2406. }
  2407. export { AnnotationLayer };