index.esm.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756
  1. /**
  2. * Hanzi Writer v3.6.0 | https://chanind.github.io/hanzi-writer
  3. */
  4. var _globalObj$navigator; // hacky way to get around rollup not properly setting `global` to `window` in browser
  5. const globalObj = typeof window === 'undefined' ? global : window;
  6. const performanceNow = globalObj.performance && (() => globalObj.performance.now()) || (() => Date.now());
  7. const requestAnimationFrame = globalObj.requestAnimationFrame || (callback => setTimeout(() => callback(performanceNow()), 1000 / 60));
  8. const cancelAnimationFrame = globalObj.cancelAnimationFrame || clearTimeout; // Object.assign polyfill, because IE :/
  9. function arrLast(arr) {
  10. return arr[arr.length - 1];
  11. }
  12. const fixIndex = (index, length) => {
  13. // helper to handle negative indexes in array indices
  14. if (index < 0) {
  15. return length + index;
  16. }
  17. return index;
  18. };
  19. const selectIndex = (arr, index) => {
  20. // helper to select item from array at index, supporting negative indexes
  21. return arr[fixIndex(index, arr.length)];
  22. };
  23. function copyAndMergeDeep(base, override) {
  24. const output = { ...base
  25. };
  26. for (const key in override) {
  27. const baseVal = base[key];
  28. const overrideVal = override[key];
  29. if (baseVal === overrideVal) {
  30. continue;
  31. }
  32. if (baseVal && overrideVal && typeof baseVal === 'object' && typeof overrideVal === 'object' && !Array.isArray(overrideVal)) {
  33. output[key] = copyAndMergeDeep(baseVal, overrideVal);
  34. } else {
  35. // @ts-ignore
  36. output[key] = overrideVal;
  37. }
  38. }
  39. return output;
  40. }
  41. /** basically a simplified version of lodash.get, selects a key out of an object like 'a.b' from {a: {b: 7}} */
  42. function inflate(scope, obj) {
  43. const parts = scope.split('.');
  44. const final = {};
  45. let current = final;
  46. for (let i = 0; i < parts.length; i++) {
  47. const cap = i === parts.length - 1 ? obj : {};
  48. current[parts[i]] = cap;
  49. current = cap;
  50. }
  51. return final;
  52. }
  53. let count = 0;
  54. function counter() {
  55. count++;
  56. return count;
  57. }
  58. function average(arr) {
  59. const sum = arr.reduce((acc, val) => val + acc, 0);
  60. return sum / arr.length;
  61. }
  62. function colorStringToVals(colorString) {
  63. const normalizedColor = colorString.toUpperCase().trim(); // based on https://stackoverflow.com/a/21648508
  64. if (/^#([A-F0-9]{3}){1,2}$/.test(normalizedColor)) {
  65. let hexParts = normalizedColor.substring(1).split('');
  66. if (hexParts.length === 3) {
  67. hexParts = [hexParts[0], hexParts[0], hexParts[1], hexParts[1], hexParts[2], hexParts[2]];
  68. }
  69. const hexStr = `${hexParts.join('')}`;
  70. return {
  71. r: parseInt(hexStr.slice(0, 2), 16),
  72. g: parseInt(hexStr.slice(2, 4), 16),
  73. b: parseInt(hexStr.slice(4, 6), 16),
  74. a: 1
  75. };
  76. }
  77. const rgbMatch = normalizedColor.match(/^RGBA?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d*\.?\d+))?\)$/);
  78. if (rgbMatch) {
  79. return {
  80. r: parseInt(rgbMatch[1], 10),
  81. g: parseInt(rgbMatch[2], 10),
  82. b: parseInt(rgbMatch[3], 10),
  83. // @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 2.
  84. a: parseFloat(rgbMatch[4] || 1, 10)
  85. };
  86. }
  87. throw new Error(`Invalid color: ${colorString}`);
  88. }
  89. const trim = string => string.replace(/^\s+/, '').replace(/\s+$/, ''); // return a new array-like object with int keys where each key is item
  90. // ex: objRepeat({x: 8}, 3) === {0: {x: 8}, 1: {x: 8}, 2: {x: 8}}
  91. function objRepeat(item, times) {
  92. const obj = {};
  93. for (let i = 0; i < times; i++) {
  94. obj[i] = item;
  95. }
  96. return obj;
  97. } // similar to objRepeat, but takes in a callback which is called for each index in the object
  98. function objRepeatCb(times, cb) {
  99. const obj = {};
  100. for (let i = 0; i < times; i++) {
  101. obj[i] = cb(i);
  102. }
  103. return obj;
  104. }
  105. const ua = ((_globalObj$navigator = globalObj.navigator) === null || _globalObj$navigator === void 0 ? void 0 : _globalObj$navigator.userAgent) || '';
  106. const isMsBrowser = ua.indexOf('MSIE ') > 0 || ua.indexOf('Trident/') > 0 || ua.indexOf('Edge/') > 0; // eslint-disable-next-line @typescript-eslint/no-empty-function
  107. const noop = () => {};
  108. class RenderState {
  109. constructor(character, options, onStateChange = noop) {
  110. this._mutationChains = [];
  111. this._onStateChange = onStateChange;
  112. this.state = {
  113. options: {
  114. drawingFadeDuration: options.drawingFadeDuration,
  115. drawingWidth: options.drawingWidth,
  116. drawingColor: colorStringToVals(options.drawingColor),
  117. strokeColor: colorStringToVals(options.strokeColor),
  118. outlineColor: colorStringToVals(options.outlineColor),
  119. radicalColor: colorStringToVals(options.radicalColor || options.strokeColor),
  120. highlightColor: colorStringToVals(options.highlightColor)
  121. },
  122. character: {
  123. main: {
  124. opacity: options.showCharacter ? 1 : 0,
  125. strokes: {}
  126. },
  127. outline: {
  128. opacity: options.showOutline ? 1 : 0,
  129. strokes: {}
  130. },
  131. highlight: {
  132. opacity: 1,
  133. strokes: {}
  134. }
  135. },
  136. userStrokes: null
  137. };
  138. for (let i = 0; i < character.strokes.length; i++) {
  139. this.state.character.main.strokes[i] = {
  140. opacity: 1,
  141. displayPortion: 1
  142. };
  143. this.state.character.outline.strokes[i] = {
  144. opacity: 1,
  145. displayPortion: 1
  146. };
  147. this.state.character.highlight.strokes[i] = {
  148. opacity: 0,
  149. displayPortion: 1
  150. };
  151. }
  152. }
  153. overwriteOnStateChange(onStateChange) {
  154. this._onStateChange = onStateChange;
  155. }
  156. updateState(stateChanges) {
  157. const nextState = copyAndMergeDeep(this.state, stateChanges);
  158. this._onStateChange(nextState, this.state);
  159. this.state = nextState;
  160. }
  161. run(mutations, options = {}) {
  162. const scopes = mutations.map(mut => mut.scope);
  163. this.cancelMutations(scopes);
  164. return new Promise(resolve => {
  165. const mutationChain = {
  166. _isActive: true,
  167. _index: 0,
  168. _resolve: resolve,
  169. _mutations: mutations,
  170. _loop: options.loop,
  171. _scopes: scopes
  172. };
  173. this._mutationChains.push(mutationChain);
  174. this._run(mutationChain);
  175. });
  176. }
  177. _run(mutationChain) {
  178. if (!mutationChain._isActive) {
  179. return;
  180. }
  181. const mutations = mutationChain._mutations;
  182. if (mutationChain._index >= mutations.length) {
  183. if (mutationChain._loop) {
  184. mutationChain._index = 0; // eslint-disable-line no-param-reassign
  185. } else {
  186. mutationChain._isActive = false; // eslint-disable-line no-param-reassign
  187. this._mutationChains = this._mutationChains.filter(chain => chain !== mutationChain); // The chain is done - resolve the promise to signal it finished successfully
  188. mutationChain._resolve({
  189. canceled: false
  190. });
  191. return;
  192. }
  193. }
  194. const activeMutation = mutationChain._mutations[mutationChain._index];
  195. activeMutation.run(this).then(() => {
  196. if (mutationChain._isActive) {
  197. mutationChain._index++; // eslint-disable-line no-param-reassign
  198. this._run(mutationChain);
  199. }
  200. });
  201. }
  202. _getActiveMutations() {
  203. return this._mutationChains.map(chain => chain._mutations[chain._index]);
  204. }
  205. pauseAll() {
  206. this._getActiveMutations().forEach(mutation => mutation.pause());
  207. }
  208. resumeAll() {
  209. this._getActiveMutations().forEach(mutation => mutation.resume());
  210. }
  211. cancelMutations(scopesToCancel) {
  212. for (const chain of this._mutationChains) {
  213. for (const chainId of chain._scopes) {
  214. for (const scopeToCancel of scopesToCancel) {
  215. if (chainId.startsWith(scopeToCancel) || scopeToCancel.startsWith(chainId)) {
  216. this._cancelMutationChain(chain);
  217. }
  218. }
  219. }
  220. }
  221. }
  222. cancelAll() {
  223. this.cancelMutations(['']);
  224. }
  225. _cancelMutationChain(mutationChain) {
  226. var _mutationChain$_resol;
  227. mutationChain._isActive = false;
  228. for (let i = mutationChain._index; i < mutationChain._mutations.length; i++) {
  229. mutationChain._mutations[i].cancel(this);
  230. }
  231. (_mutationChain$_resol = mutationChain._resolve) === null || _mutationChain$_resol === void 0 ? void 0 : _mutationChain$_resol.call(mutationChain, {
  232. canceled: true
  233. });
  234. this._mutationChains = this._mutationChains.filter(chain => chain !== mutationChain);
  235. }
  236. }
  237. const subtract = (p1, p2) => ({
  238. x: p1.x - p2.x,
  239. y: p1.y - p2.y
  240. });
  241. const magnitude = point => Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
  242. const distance = (point1, point2) => magnitude(subtract(point1, point2));
  243. const equals = (point1, point2) => point1.x === point2.x && point1.y === point2.y;
  244. const round = (point, precision = 1) => {
  245. const multiplier = precision * 10;
  246. return {
  247. x: Math.round(multiplier * point.x) / multiplier,
  248. y: Math.round(multiplier * point.y) / multiplier
  249. };
  250. };
  251. const length = points => {
  252. let lastPoint = points[0];
  253. const pointsSansFirst = points.slice(1);
  254. return pointsSansFirst.reduce((acc, point) => {
  255. const dist = distance(point, lastPoint);
  256. lastPoint = point;
  257. return acc + dist;
  258. }, 0);
  259. };
  260. const cosineSimilarity = (point1, point2) => {
  261. const rawDotProduct = point1.x * point2.x + point1.y * point2.y;
  262. return rawDotProduct / magnitude(point1) / magnitude(point2);
  263. };
  264. /**
  265. * return a new point, p3, which is on the same line as p1 and p2, but distance away
  266. * from p2. p1, p2, p3 will always lie on the line in that order
  267. */
  268. const _extendPointOnLine = (p1, p2, dist) => {
  269. const vect = subtract(p2, p1);
  270. const norm = dist / magnitude(vect);
  271. return {
  272. x: p2.x + norm * vect.x,
  273. y: p2.y + norm * vect.y
  274. };
  275. };
  276. /** based on http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf */
  277. const frechetDist = (curve1, curve2) => {
  278. const longCurve = curve1.length >= curve2.length ? curve1 : curve2;
  279. const shortCurve = curve1.length >= curve2.length ? curve2 : curve1;
  280. const calcVal = (i, j, prevResultsCol, curResultsCol) => {
  281. if (i === 0 && j === 0) {
  282. return distance(longCurve[0], shortCurve[0]);
  283. }
  284. if (i > 0 && j === 0) {
  285. return Math.max(prevResultsCol[0], distance(longCurve[i], shortCurve[0]));
  286. }
  287. const lastResult = curResultsCol[curResultsCol.length - 1];
  288. if (i === 0 && j > 0) {
  289. return Math.max(lastResult, distance(longCurve[0], shortCurve[j]));
  290. }
  291. return Math.max(Math.min(prevResultsCol[j], prevResultsCol[j - 1], lastResult), distance(longCurve[i], shortCurve[j]));
  292. };
  293. let prevResultsCol = [];
  294. for (let i = 0; i < longCurve.length; i++) {
  295. const curResultsCol = [];
  296. for (let j = 0; j < shortCurve.length; j++) {
  297. // we only need the results from i - 1 and j - 1 to continue the calculation
  298. // so we only need to hold onto the last column of calculated results
  299. // prevResultsCol is results[i-1][:] in the original algorithm
  300. // curResultsCol is results[i][:j-1] in the original algorithm
  301. curResultsCol.push(calcVal(i, j, prevResultsCol, curResultsCol));
  302. }
  303. prevResultsCol = curResultsCol;
  304. }
  305. return prevResultsCol[shortCurve.length - 1];
  306. };
  307. /** break up long segments in the curve into smaller segments of len maxLen or smaller */
  308. const subdivideCurve = (curve, maxLen = 0.05) => {
  309. const newCurve = curve.slice(0, 1);
  310. for (const point of curve.slice(1)) {
  311. const prevPoint = newCurve[newCurve.length - 1];
  312. const segLen = distance(point, prevPoint);
  313. if (segLen > maxLen) {
  314. const numNewPoints = Math.ceil(segLen / maxLen);
  315. const newSegLen = segLen / numNewPoints;
  316. for (let i = 0; i < numNewPoints; i++) {
  317. newCurve.push(_extendPointOnLine(point, prevPoint, -1 * newSegLen * (i + 1)));
  318. }
  319. } else {
  320. newCurve.push(point);
  321. }
  322. }
  323. return newCurve;
  324. };
  325. /** redraw the curve using numPoints equally spaced out along the length of the curve */
  326. const outlineCurve = (curve, numPoints = 30) => {
  327. const curveLen = length(curve);
  328. const segmentLen = curveLen / (numPoints - 1);
  329. const outlinePoints = [curve[0]];
  330. const endPoint = arrLast(curve);
  331. const remainingCurvePoints = curve.slice(1);
  332. for (let i = 0; i < numPoints - 2; i++) {
  333. let lastPoint = arrLast(outlinePoints);
  334. let remainingDist = segmentLen;
  335. let outlinePointFound = false;
  336. while (!outlinePointFound) {
  337. const nextPointDist = distance(lastPoint, remainingCurvePoints[0]);
  338. if (nextPointDist < remainingDist) {
  339. remainingDist -= nextPointDist;
  340. lastPoint = remainingCurvePoints.shift();
  341. } else {
  342. const nextPoint = _extendPointOnLine(lastPoint, remainingCurvePoints[0], remainingDist - nextPointDist);
  343. outlinePoints.push(nextPoint);
  344. outlinePointFound = true;
  345. }
  346. }
  347. }
  348. outlinePoints.push(endPoint);
  349. return outlinePoints;
  350. };
  351. /** translate and scale from https://en.wikipedia.org/wiki/Procrustes_analysis */
  352. const normalizeCurve = curve => {
  353. const outlinedCurve = outlineCurve(curve);
  354. const meanX = average(outlinedCurve.map(point => point.x));
  355. const meanY = average(outlinedCurve.map(point => point.y));
  356. const mean = {
  357. x: meanX,
  358. y: meanY
  359. };
  360. const translatedCurve = outlinedCurve.map(point => subtract(point, mean));
  361. const scale = Math.sqrt(average([Math.pow(translatedCurve[0].x, 2) + Math.pow(translatedCurve[0].y, 2), Math.pow(arrLast(translatedCurve).x, 2) + Math.pow(arrLast(translatedCurve).y, 2)]));
  362. const scaledCurve = translatedCurve.map(point => ({
  363. x: point.x / scale,
  364. y: point.y / scale
  365. }));
  366. return subdivideCurve(scaledCurve);
  367. }; // rotate around the origin
  368. const rotate = (curve, theta) => {
  369. return curve.map(point => ({
  370. x: Math.cos(theta) * point.x - Math.sin(theta) * point.y,
  371. y: Math.sin(theta) * point.x + Math.cos(theta) * point.y
  372. }));
  373. }; // remove intermediate points that are on the same line as the points to either side
  374. const _filterParallelPoints = points => {
  375. if (points.length < 3) return points;
  376. const filteredPoints = [points[0], points[1]];
  377. points.slice(2).forEach(point => {
  378. const numFilteredPoints = filteredPoints.length;
  379. const curVect = subtract(point, filteredPoints[numFilteredPoints - 1]);
  380. const prevVect = subtract(filteredPoints[numFilteredPoints - 1], filteredPoints[numFilteredPoints - 2]); // this is the z coord of the cross-product. If this is 0 then they're parallel
  381. const isParallel = curVect.y * prevVect.x - curVect.x * prevVect.y === 0;
  382. if (isParallel) {
  383. filteredPoints.pop();
  384. }
  385. filteredPoints.push(point);
  386. });
  387. return filteredPoints;
  388. };
  389. function getPathString(points, close = false) {
  390. const start = round(points[0]);
  391. const remainingPoints = points.slice(1);
  392. let pathString = `M ${start.x} ${start.y}`;
  393. remainingPoints.forEach(point => {
  394. const roundedPoint = round(point);
  395. pathString += ` L ${roundedPoint.x} ${roundedPoint.y}`;
  396. });
  397. if (close) {
  398. pathString += 'Z';
  399. }
  400. return pathString;
  401. }
  402. /** take points on a path and move their start point backwards by distance */
  403. const extendStart = (points, dist) => {
  404. const filteredPoints = _filterParallelPoints(points);
  405. if (filteredPoints.length < 2) return filteredPoints;
  406. const p1 = filteredPoints[1];
  407. const p2 = filteredPoints[0];
  408. const newStart = _extendPointOnLine(p1, p2, dist);
  409. const extendedPoints = filteredPoints.slice(1);
  410. extendedPoints.unshift(newStart);
  411. return extendedPoints;
  412. };
  413. class Stroke {
  414. constructor(path, points, strokeNum, isInRadical = false) {
  415. this.path = path;
  416. this.points = points;
  417. this.strokeNum = strokeNum;
  418. this.isInRadical = isInRadical;
  419. }
  420. getStartingPoint() {
  421. return this.points[0];
  422. }
  423. getEndingPoint() {
  424. return this.points[this.points.length - 1];
  425. }
  426. getLength() {
  427. return length(this.points);
  428. }
  429. getVectors() {
  430. let lastPoint = this.points[0];
  431. const pointsSansFirst = this.points.slice(1);
  432. return pointsSansFirst.map(point => {
  433. const vector = subtract(point, lastPoint);
  434. lastPoint = point;
  435. return vector;
  436. });
  437. }
  438. getDistance(point) {
  439. const distances = this.points.map(strokePoint => distance(strokePoint, point));
  440. return Math.min(...distances);
  441. }
  442. getAverageDistance(points) {
  443. const totalDist = points.reduce((acc, point) => acc + this.getDistance(point), 0);
  444. return totalDist / points.length;
  445. }
  446. }
  447. class Character {
  448. constructor(symbol, strokes) {
  449. this.symbol = symbol;
  450. this.strokes = strokes;
  451. }
  452. }
  453. function generateStrokes({
  454. radStrokes,
  455. strokes,
  456. medians
  457. }) {
  458. const isInRadical = strokeNum => {
  459. var _radStrokes$indexOf;
  460. return ((_radStrokes$indexOf = radStrokes === null || radStrokes === void 0 ? void 0 : radStrokes.indexOf(strokeNum)) !== null && _radStrokes$indexOf !== void 0 ? _radStrokes$indexOf : -1) >= 0;
  461. };
  462. return strokes.map((path, index) => {
  463. const points = medians[index].map(pointData => {
  464. const [x, y] = pointData;
  465. return {
  466. x,
  467. y
  468. };
  469. });
  470. return new Stroke(path, points, index, isInRadical(index));
  471. });
  472. }
  473. function parseCharData(symbol, charJson) {
  474. const strokes = generateStrokes(charJson);
  475. return new Character(symbol, strokes);
  476. }
  477. // All makemeahanzi characters have the same bounding box
  478. const CHARACTER_BOUNDS = [{
  479. x: 0,
  480. y: -124
  481. }, {
  482. x: 1024,
  483. y: 900
  484. }];
  485. const [from, to] = CHARACTER_BOUNDS;
  486. const preScaledWidth = to.x - from.x;
  487. const preScaledHeight = to.y - from.y;
  488. class Positioner {
  489. constructor(options) {
  490. const {
  491. padding,
  492. width,
  493. height
  494. } = options;
  495. this.padding = padding;
  496. this.width = width;
  497. this.height = height;
  498. const effectiveWidth = width - 2 * padding;
  499. const effectiveHeight = height - 2 * padding;
  500. const scaleX = effectiveWidth / preScaledWidth;
  501. const scaleY = effectiveHeight / preScaledHeight;
  502. this.scale = Math.min(scaleX, scaleY);
  503. const xCenteringBuffer = padding + (effectiveWidth - this.scale * preScaledWidth) / 2;
  504. const yCenteringBuffer = padding + (effectiveHeight - this.scale * preScaledHeight) / 2;
  505. this.xOffset = -1 * from.x * this.scale + xCenteringBuffer;
  506. this.yOffset = -1 * from.y * this.scale + yCenteringBuffer;
  507. }
  508. convertExternalPoint(point) {
  509. const x = (point.x - this.xOffset) / this.scale;
  510. const y = (this.height - this.yOffset - point.y) / this.scale;
  511. return {
  512. x,
  513. y
  514. };
  515. }
  516. }
  517. const COSINE_SIMILARITY_THRESHOLD = 0; // -1 to 1, smaller = more lenient
  518. const START_AND_END_DIST_THRESHOLD = 250; // bigger = more lenient
  519. const FRECHET_THRESHOLD = 0.4; // bigger = more lenient
  520. const MIN_LEN_THRESHOLD = 0.35; // smaller = more lenient
  521. function strokeMatches(userStroke, character, strokeNum, options = {}) {
  522. const strokes = character.strokes;
  523. const points = stripDuplicates(userStroke.points);
  524. if (points.length < 2) {
  525. return {
  526. isMatch: false,
  527. meta: {
  528. isStrokeBackwards: false
  529. }
  530. };
  531. }
  532. const {
  533. isMatch,
  534. meta,
  535. avgDist
  536. } = getMatchData(points, strokes[strokeNum], options);
  537. if (!isMatch) {
  538. return {
  539. isMatch,
  540. meta
  541. };
  542. } // if there is a better match among strokes the user hasn't drawn yet, the user probably drew the wrong stroke
  543. const laterStrokes = strokes.slice(strokeNum + 1);
  544. let closestMatchDist = avgDist;
  545. for (let i = 0; i < laterStrokes.length; i++) {
  546. const {
  547. isMatch,
  548. avgDist
  549. } = getMatchData(points, laterStrokes[i], { ...options,
  550. checkBackwards: false
  551. });
  552. if (isMatch && avgDist < closestMatchDist) {
  553. closestMatchDist = avgDist;
  554. }
  555. } // if there's a better match, rather that returning false automatically, try reducing leniency instead
  556. // if leniency is already really high we can allow some similar strokes to pass
  557. if (closestMatchDist < avgDist) {
  558. // adjust leniency between 0.3 and 0.6 depending on how much of a better match the new match is
  559. const leniencyAdjustment = 0.6 * (closestMatchDist + avgDist) / (2 * avgDist);
  560. const {
  561. isMatch,
  562. meta
  563. } = getMatchData(points, strokes[strokeNum], { ...options,
  564. leniency: (options.leniency || 1) * leniencyAdjustment
  565. });
  566. return {
  567. isMatch,
  568. meta
  569. };
  570. }
  571. return {
  572. isMatch,
  573. meta
  574. };
  575. }
  576. const startAndEndMatches = (points, closestStroke, leniency) => {
  577. const startingDist = distance(closestStroke.getStartingPoint(), points[0]);
  578. const endingDist = distance(closestStroke.getEndingPoint(), points[points.length - 1]);
  579. return startingDist <= START_AND_END_DIST_THRESHOLD * leniency && endingDist <= START_AND_END_DIST_THRESHOLD * leniency;
  580. }; // returns a list of the direction of all segments in the line connecting the points
  581. const getEdgeVectors = points => {
  582. const vectors = [];
  583. let lastPoint = points[0];
  584. points.slice(1).forEach(point => {
  585. vectors.push(subtract(point, lastPoint));
  586. lastPoint = point;
  587. });
  588. return vectors;
  589. };
  590. const directionMatches = (points, stroke) => {
  591. const edgeVectors = getEdgeVectors(points);
  592. const strokeVectors = stroke.getVectors();
  593. const similarities = edgeVectors.map(edgeVector => {
  594. const strokeSimilarities = strokeVectors.map(strokeVector => cosineSimilarity(strokeVector, edgeVector));
  595. return Math.max(...strokeSimilarities);
  596. });
  597. const avgSimilarity = average(similarities);
  598. return avgSimilarity > COSINE_SIMILARITY_THRESHOLD;
  599. };
  600. const lengthMatches = (points, stroke, leniency) => {
  601. return leniency * (length(points) + 25) / (stroke.getLength() + 25) >= MIN_LEN_THRESHOLD;
  602. };
  603. const stripDuplicates = points => {
  604. if (points.length < 2) return points;
  605. const [firstPoint, ...rest] = points;
  606. const dedupedPoints = [firstPoint];
  607. for (const point of rest) {
  608. if (!equals(point, dedupedPoints[dedupedPoints.length - 1])) {
  609. dedupedPoints.push(point);
  610. }
  611. }
  612. return dedupedPoints;
  613. };
  614. const SHAPE_FIT_ROTATIONS = [Math.PI / 16, Math.PI / 32, 0, -1 * Math.PI / 32, -1 * Math.PI / 16];
  615. const shapeFit = (curve1, curve2, leniency) => {
  616. const normCurve1 = normalizeCurve(curve1);
  617. const normCurve2 = normalizeCurve(curve2);
  618. let minDist = Infinity;
  619. SHAPE_FIT_ROTATIONS.forEach(theta => {
  620. const dist = frechetDist(normCurve1, rotate(normCurve2, theta));
  621. if (dist < minDist) {
  622. minDist = dist;
  623. }
  624. });
  625. return minDist <= FRECHET_THRESHOLD * leniency;
  626. };
  627. const getMatchData = (points, stroke, options) => {
  628. const {
  629. leniency = 1,
  630. isOutlineVisible = false,
  631. checkBackwards = true,
  632. averageDistanceThreshold = 350
  633. } = options;
  634. const avgDist = stroke.getAverageDistance(points);
  635. const distMod = isOutlineVisible || stroke.strokeNum > 0 ? 0.5 : 1;
  636. const withinDistThresh = avgDist <= averageDistanceThreshold * distMod * leniency; // short circuit for faster matching
  637. if (!withinDistThresh) {
  638. return {
  639. isMatch: false,
  640. avgDist,
  641. meta: {
  642. isStrokeBackwards: false
  643. }
  644. };
  645. }
  646. const startAndEndMatch = startAndEndMatches(points, stroke, leniency);
  647. const directionMatch = directionMatches(points, stroke);
  648. const shapeMatch = shapeFit(points, stroke.points, leniency);
  649. const lengthMatch = lengthMatches(points, stroke, leniency);
  650. const isMatch = withinDistThresh && startAndEndMatch && directionMatch && shapeMatch && lengthMatch;
  651. if (checkBackwards && !isMatch) {
  652. const backwardsMatchData = getMatchData([...points].reverse(), stroke, { ...options,
  653. checkBackwards: false
  654. });
  655. if (backwardsMatchData.isMatch) {
  656. return {
  657. isMatch,
  658. avgDist,
  659. meta: {
  660. isStrokeBackwards: true
  661. }
  662. };
  663. }
  664. }
  665. return {
  666. isMatch,
  667. avgDist,
  668. meta: {
  669. isStrokeBackwards: false
  670. }
  671. };
  672. };
  673. class UserStroke {
  674. constructor(id, startingPoint, startingExternalPoint) {
  675. this.id = id;
  676. this.points = [startingPoint];
  677. this.externalPoints = [startingExternalPoint];
  678. }
  679. appendPoint(point, externalPoint) {
  680. this.points.push(point);
  681. this.externalPoints.push(externalPoint);
  682. }
  683. }
  684. class Delay {
  685. constructor(duration) {
  686. this._duration = duration;
  687. this._startTime = null;
  688. this._paused = false;
  689. this.scope = `delay.${duration}`;
  690. }
  691. run() {
  692. this._startTime = performanceNow();
  693. this._runningPromise = new Promise(resolve => {
  694. this._resolve = resolve; // @ts-ignore return type of "setTimeout" in builds is parsed as `number` instead of `Timeout`
  695. this._timeout = setTimeout(() => this.cancel(), this._duration);
  696. });
  697. return this._runningPromise;
  698. }
  699. pause() {
  700. if (this._paused) return; // to pause, clear the timeout and rewrite this._duration with whatever time is remaining
  701. const elapsedDelay = performance.now() - (this._startTime || 0);
  702. this._duration = Math.max(0, this._duration - elapsedDelay);
  703. clearTimeout(this._timeout);
  704. this._paused = true;
  705. }
  706. resume() {
  707. if (!this._paused) return;
  708. this._startTime = performance.now(); // @ts-ignore return type of "setTimeout" in builds is parsed as `number` instead of `Timeout`
  709. this._timeout = setTimeout(() => this.cancel(), this._duration);
  710. this._paused = false;
  711. }
  712. cancel() {
  713. clearTimeout(this._timeout);
  714. if (this._resolve) {
  715. this._resolve();
  716. }
  717. this._resolve = undefined;
  718. }
  719. }
  720. class Mutation {
  721. /**
  722. *
  723. * @param scope a string representation of what fields this mutation affects from the state. This is used to cancel conflicting mutations
  724. * @param valuesOrCallable a thunk containing the value to set, or a callback which will return those values
  725. */
  726. constructor(scope, valuesOrCallable, options = {}) {
  727. this._tick = timing => {
  728. if (this._startPauseTime !== null) {
  729. return;
  730. }
  731. const progress = Math.min(1, (timing - this._startTime - this._pausedDuration) / this._duration);
  732. if (progress === 1) {
  733. this._renderState.updateState(this._values);
  734. this._frameHandle = undefined;
  735. this.cancel(this._renderState);
  736. } else {
  737. const easedProgress = ease(progress);
  738. const stateChanges = getPartialValues(this._startState, this._values, easedProgress);
  739. this._renderState.updateState(stateChanges);
  740. this._frameHandle = requestAnimationFrame(this._tick);
  741. }
  742. };
  743. this.scope = scope;
  744. this._valuesOrCallable = valuesOrCallable;
  745. this._duration = options.duration || 0;
  746. this._force = options.force;
  747. this._pausedDuration = 0;
  748. this._startPauseTime = null;
  749. }
  750. run(renderState) {
  751. if (!this._values) this._inflateValues(renderState);
  752. if (this._duration === 0) renderState.updateState(this._values);
  753. if (this._duration === 0 || isAlreadyAtEnd(renderState.state, this._values)) {
  754. return Promise.resolve();
  755. }
  756. this._renderState = renderState;
  757. this._startState = renderState.state;
  758. this._startTime = performance.now();
  759. this._frameHandle = requestAnimationFrame(this._tick);
  760. return new Promise(resolve => {
  761. this._resolve = resolve;
  762. });
  763. }
  764. _inflateValues(renderState) {
  765. let values = this._valuesOrCallable;
  766. if (typeof this._valuesOrCallable === 'function') {
  767. values = this._valuesOrCallable(renderState.state);
  768. }
  769. this._values = inflate(this.scope, values);
  770. }
  771. pause() {
  772. if (this._startPauseTime !== null) {
  773. return;
  774. }
  775. if (this._frameHandle) {
  776. cancelAnimationFrame(this._frameHandle);
  777. }
  778. this._startPauseTime = performance.now();
  779. }
  780. resume() {
  781. if (this._startPauseTime === null) {
  782. return;
  783. }
  784. this._frameHandle = requestAnimationFrame(this._tick);
  785. this._pausedDuration += performance.now() - this._startPauseTime;
  786. this._startPauseTime = null;
  787. }
  788. cancel(renderState) {
  789. var _this$_resolve;
  790. (_this$_resolve = this._resolve) === null || _this$_resolve === void 0 ? void 0 : _this$_resolve.call(this);
  791. this._resolve = undefined;
  792. cancelAnimationFrame(this._frameHandle || -1);
  793. this._frameHandle = undefined;
  794. if (this._force) {
  795. if (!this._values) this._inflateValues(renderState);
  796. renderState.updateState(this._values);
  797. }
  798. }
  799. }
  800. Mutation.Delay = Delay;
  801. function getPartialValues(startValues, endValues, progress) {
  802. const target = {};
  803. for (const key in endValues) {
  804. const endValue = endValues[key];
  805. const startValue = startValues === null || startValues === void 0 ? void 0 : startValues[key];
  806. if (typeof startValue === 'number' && typeof endValue === 'number' && endValue >= 0) {
  807. target[key] = progress * (endValue - startValue) + startValue;
  808. } else {
  809. target[key] = getPartialValues(startValue, endValue, progress);
  810. }
  811. }
  812. return target;
  813. }
  814. function isAlreadyAtEnd(startValues, endValues) {
  815. for (const key in endValues) {
  816. const endValue = endValues[key];
  817. const startValue = startValues === null || startValues === void 0 ? void 0 : startValues[key];
  818. if (endValue >= 0) {
  819. if (endValue !== startValue) {
  820. return false;
  821. }
  822. } else if (!isAlreadyAtEnd(startValue, endValue)) {
  823. return false;
  824. }
  825. }
  826. return true;
  827. } // from https://github.com/maxwellito/vivus
  828. const ease = x => -Math.cos(x * Math.PI) / 2 + 0.5;
  829. const showStrokes = (charName, character, duration) => {
  830. return [new Mutation(`character.${charName}.strokes`, objRepeat({
  831. opacity: 1,
  832. displayPortion: 1
  833. }, character.strokes.length), {
  834. duration,
  835. force: true
  836. })];
  837. };
  838. const showCharacter = (charName, character, duration) => {
  839. return [new Mutation(`character.${charName}`, {
  840. opacity: 1,
  841. strokes: objRepeat({
  842. opacity: 1,
  843. displayPortion: 1
  844. }, character.strokes.length)
  845. }, {
  846. duration,
  847. force: true
  848. })];
  849. };
  850. const hideCharacter = (charName, character, duration) => {
  851. return [new Mutation(`character.${charName}.opacity`, 0, {
  852. duration,
  853. force: true
  854. }), ...showStrokes(charName, character, 0)];
  855. };
  856. const updateColor = (colorName, colorVal, duration) => {
  857. return [new Mutation(`options.${colorName}`, colorVal, {
  858. duration
  859. })];
  860. };
  861. const highlightStroke = (stroke, color, speed) => {
  862. const strokeNum = stroke.strokeNum;
  863. const duration = (stroke.getLength() + 600) / (3 * speed);
  864. return [new Mutation('options.highlightColor', color), new Mutation('character.highlight', {
  865. opacity: 1,
  866. strokes: {
  867. [strokeNum]: {
  868. displayPortion: 0,
  869. opacity: 0
  870. }
  871. }
  872. }), new Mutation(`character.highlight.strokes.${strokeNum}`, {
  873. displayPortion: 1,
  874. opacity: 1
  875. }, {
  876. duration
  877. }), new Mutation(`character.highlight.strokes.${strokeNum}.opacity`, 0, {
  878. duration,
  879. force: true
  880. })];
  881. };
  882. const animateStroke = (charName, stroke, speed) => {
  883. const strokeNum = stroke.strokeNum;
  884. const duration = (stroke.getLength() + 600) / (3 * speed);
  885. return [new Mutation(`character.${charName}`, {
  886. opacity: 1,
  887. strokes: {
  888. [strokeNum]: {
  889. displayPortion: 0,
  890. opacity: 1
  891. }
  892. }
  893. }), new Mutation(`character.${charName}.strokes.${strokeNum}.displayPortion`, 1, {
  894. duration
  895. })];
  896. };
  897. const animateSingleStroke = (charName, character, strokeNum, speed) => {
  898. const mutationStateFunc = state => {
  899. const curCharState = state.character[charName];
  900. const mutationState = {
  901. opacity: 1,
  902. strokes: {}
  903. };
  904. for (let i = 0; i < character.strokes.length; i++) {
  905. mutationState.strokes[i] = {
  906. opacity: curCharState.opacity * curCharState.strokes[i].opacity
  907. };
  908. }
  909. return mutationState;
  910. };
  911. const stroke = character.strokes[strokeNum];
  912. return [new Mutation(`character.${charName}`, mutationStateFunc), ...animateStroke(charName, stroke, speed)];
  913. };
  914. const showStroke = (charName, strokeNum, duration) => {
  915. return [new Mutation(`character.${charName}.strokes.${strokeNum}`, {
  916. displayPortion: 1,
  917. opacity: 1
  918. }, {
  919. duration,
  920. force: true
  921. })];
  922. };
  923. const animateCharacter = (charName, character, fadeDuration, speed, delayBetweenStrokes) => {
  924. let mutations = hideCharacter(charName, character, fadeDuration);
  925. mutations = mutations.concat(showStrokes(charName, character, 0));
  926. mutations.push(new Mutation(`character.${charName}`, {
  927. opacity: 1,
  928. strokes: objRepeat({
  929. opacity: 0
  930. }, character.strokes.length)
  931. }, {
  932. force: true
  933. }));
  934. character.strokes.forEach((stroke, i) => {
  935. if (i > 0) mutations.push(new Mutation.Delay(delayBetweenStrokes));
  936. mutations = mutations.concat(animateStroke(charName, stroke, speed));
  937. });
  938. return mutations;
  939. };
  940. const animateCharacterLoop = (charName, character, fadeDuration, speed, delayBetweenStrokes, delayBetweenLoops) => {
  941. const mutations = animateCharacter(charName, character, fadeDuration, speed, delayBetweenStrokes);
  942. mutations.push(new Mutation.Delay(delayBetweenLoops));
  943. return mutations;
  944. };
  945. const startQuiz = (character, fadeDuration, startStrokeNum) => {
  946. return [...hideCharacter('main', character, fadeDuration), new Mutation('character.highlight', {
  947. opacity: 1,
  948. strokes: objRepeat({
  949. opacity: 0
  950. }, character.strokes.length)
  951. }, {
  952. force: true
  953. }), new Mutation('character.main', {
  954. opacity: 1,
  955. strokes: objRepeatCb(character.strokes.length, i => ({
  956. opacity: i < startStrokeNum ? 1 : 0
  957. }))
  958. }, {
  959. force: true
  960. })];
  961. };
  962. const startUserStroke = (id, point) => {
  963. return [new Mutation('quiz.activeUserStrokeId', id, {
  964. force: true
  965. }), new Mutation(`userStrokes.${id}`, {
  966. points: [point],
  967. opacity: 1
  968. }, {
  969. force: true
  970. })];
  971. };
  972. const updateUserStroke = (userStrokeId, points) => {
  973. return [new Mutation(`userStrokes.${userStrokeId}.points`, points, {
  974. force: true
  975. })];
  976. };
  977. const removeUserStroke = (userStrokeId, duration) => {
  978. return [new Mutation(`userStrokes.${userStrokeId}.opacity`, 0, {
  979. duration
  980. }), new Mutation(`userStrokes.${userStrokeId}`, null, {
  981. force: true
  982. })];
  983. };
  984. const highlightCompleteChar = (character, color, duration) => {
  985. return [new Mutation('options.highlightColor', color), ...hideCharacter('highlight', character), ...showCharacter('highlight', character, duration / 2), ...hideCharacter('highlight', character, duration / 2)];
  986. };
  987. const getDrawnPath = userStroke => ({
  988. pathString: getPathString(userStroke.externalPoints),
  989. points: userStroke.points.map(point => round(point))
  990. });
  991. class Quiz {
  992. constructor(character, renderState, positioner) {
  993. this._currentStrokeIndex = 0;
  994. this._mistakesOnStroke = 0;
  995. this._totalMistakes = 0;
  996. this._character = character;
  997. this._renderState = renderState;
  998. this._isActive = false;
  999. this._positioner = positioner;
  1000. }
  1001. startQuiz(options) {
  1002. this._isActive = true;
  1003. this._options = options;
  1004. const startIndex = fixIndex(options.quizStartStrokeNum, this._character.strokes.length);
  1005. this._currentStrokeIndex = Math.min(startIndex, this._character.strokes.length - 1);
  1006. this._mistakesOnStroke = 0;
  1007. this._totalMistakes = 0;
  1008. return this._renderState.run(startQuiz(this._character, options.strokeFadeDuration, this._currentStrokeIndex));
  1009. }
  1010. startUserStroke(externalPoint) {
  1011. if (!this._isActive) {
  1012. return null;
  1013. }
  1014. if (this._userStroke) {
  1015. return this.endUserStroke();
  1016. }
  1017. const point = this._positioner.convertExternalPoint(externalPoint);
  1018. const strokeId = counter();
  1019. this._userStroke = new UserStroke(strokeId, point, externalPoint);
  1020. return this._renderState.run(startUserStroke(strokeId, point));
  1021. }
  1022. continueUserStroke(externalPoint) {
  1023. if (!this._userStroke) {
  1024. return Promise.resolve();
  1025. }
  1026. const point = this._positioner.convertExternalPoint(externalPoint);
  1027. this._userStroke.appendPoint(point, externalPoint);
  1028. const nextPoints = this._userStroke.points.slice(0);
  1029. return this._renderState.run(updateUserStroke(this._userStroke.id, nextPoints));
  1030. }
  1031. setPositioner(positioner) {
  1032. this._positioner = positioner;
  1033. }
  1034. endUserStroke() {
  1035. var _this$_options$drawin;
  1036. if (!this._userStroke) return;
  1037. this._renderState.run(removeUserStroke(this._userStroke.id, (_this$_options$drawin = this._options.drawingFadeDuration) !== null && _this$_options$drawin !== void 0 ? _this$_options$drawin : 300)); // skip single-point strokes
  1038. if (this._userStroke.points.length === 1) {
  1039. this._userStroke = undefined;
  1040. return;
  1041. }
  1042. const {
  1043. acceptBackwardsStrokes,
  1044. markStrokeCorrectAfterMisses
  1045. } = this._options;
  1046. const currentStroke = this._getCurrentStroke();
  1047. const {
  1048. isMatch,
  1049. meta
  1050. } = strokeMatches(this._userStroke, this._character, this._currentStrokeIndex, {
  1051. isOutlineVisible: this._renderState.state.character.outline.opacity > 0,
  1052. leniency: this._options.leniency,
  1053. averageDistanceThreshold: this._options.averageDistanceThreshold
  1054. }); // if markStrokeCorrectAfterMisses is passed, just force the stroke to count as correct after n tries
  1055. const isForceAccepted = markStrokeCorrectAfterMisses && this._mistakesOnStroke + 1 >= markStrokeCorrectAfterMisses;
  1056. const isAccepted = isMatch || isForceAccepted || meta.isStrokeBackwards && acceptBackwardsStrokes;
  1057. if (isAccepted) {
  1058. this._handleSuccess(meta);
  1059. } else {
  1060. this._handleFailure(meta);
  1061. const {
  1062. showHintAfterMisses,
  1063. highlightColor,
  1064. strokeHighlightSpeed
  1065. } = this._options;
  1066. if (showHintAfterMisses !== false && this._mistakesOnStroke >= showHintAfterMisses) {
  1067. this._renderState.run(highlightStroke(currentStroke, colorStringToVals(highlightColor), strokeHighlightSpeed));
  1068. }
  1069. }
  1070. this._userStroke = undefined;
  1071. }
  1072. cancel() {
  1073. this._isActive = false;
  1074. if (this._userStroke) {
  1075. this._renderState.run(removeUserStroke(this._userStroke.id, this._options.drawingFadeDuration));
  1076. }
  1077. }
  1078. _getStrokeData({
  1079. isCorrect,
  1080. meta
  1081. }) {
  1082. return {
  1083. character: this._character.symbol,
  1084. strokeNum: this._currentStrokeIndex,
  1085. mistakesOnStroke: this._mistakesOnStroke,
  1086. totalMistakes: this._totalMistakes,
  1087. strokesRemaining: this._character.strokes.length - this._currentStrokeIndex - (isCorrect ? 1 : 0),
  1088. drawnPath: getDrawnPath(this._userStroke),
  1089. isBackwards: meta.isStrokeBackwards
  1090. };
  1091. }
  1092. _handleSuccess(meta) {
  1093. if (!this._options) return;
  1094. const {
  1095. strokes,
  1096. symbol
  1097. } = this._character;
  1098. const {
  1099. onCorrectStroke,
  1100. onComplete,
  1101. highlightOnComplete,
  1102. strokeFadeDuration,
  1103. highlightCompleteColor,
  1104. highlightColor,
  1105. strokeHighlightDuration
  1106. } = this._options;
  1107. onCorrectStroke === null || onCorrectStroke === void 0 ? void 0 : onCorrectStroke({ ...this._getStrokeData({
  1108. isCorrect: true,
  1109. meta
  1110. })
  1111. });
  1112. let animation = showStroke('main', this._currentStrokeIndex, strokeFadeDuration);
  1113. this._mistakesOnStroke = 0;
  1114. this._currentStrokeIndex += 1;
  1115. const isComplete = this._currentStrokeIndex === strokes.length;
  1116. if (isComplete) {
  1117. this._isActive = false;
  1118. onComplete === null || onComplete === void 0 ? void 0 : onComplete({
  1119. character: symbol,
  1120. totalMistakes: this._totalMistakes
  1121. });
  1122. if (highlightOnComplete) {
  1123. animation = animation.concat(highlightCompleteChar(this._character, colorStringToVals(highlightCompleteColor || highlightColor), (strokeHighlightDuration || 0) * 2));
  1124. }
  1125. }
  1126. this._renderState.run(animation);
  1127. }
  1128. _handleFailure(meta) {
  1129. var _this$_options$onMist, _this$_options;
  1130. this._mistakesOnStroke += 1;
  1131. this._totalMistakes += 1;
  1132. (_this$_options$onMist = (_this$_options = this._options).onMistake) === null || _this$_options$onMist === void 0 ? void 0 : _this$_options$onMist.call(_this$_options, this._getStrokeData({
  1133. isCorrect: false,
  1134. meta
  1135. }));
  1136. }
  1137. _getCurrentStroke() {
  1138. return this._character.strokes[this._currentStrokeIndex];
  1139. }
  1140. }
  1141. function createElm(elmType) {
  1142. return document.createElementNS('http://www.w3.org/2000/svg', elmType);
  1143. }
  1144. function attr(elm, name, value) {
  1145. elm.setAttributeNS(null, name, value);
  1146. }
  1147. function attrs(elm, attrsMap) {
  1148. Object.keys(attrsMap).forEach(attrName => attr(elm, attrName, attrsMap[attrName]));
  1149. } // inspired by https://talk.observablehq.com/t/hanzi-writer-renders-incorrectly-inside-an-observable-notebook-on-a-mobile-browser/1898
  1150. function urlIdRef(id) {
  1151. let prefix = '';
  1152. if (window.location && window.location.href) {
  1153. prefix = window.location.href.replace(/#[^#]*$/, '').replace(/"/gi, '%22');
  1154. }
  1155. return `url("${prefix}#${id}")`;
  1156. }
  1157. function removeElm(elm) {
  1158. var _elm$parentNode;
  1159. elm === null || elm === void 0 ? void 0 : (_elm$parentNode = elm.parentNode) === null || _elm$parentNode === void 0 ? void 0 : _elm$parentNode.removeChild(elm);
  1160. }
  1161. class StrokeRendererBase {
  1162. constructor(stroke) {
  1163. this.stroke = stroke;
  1164. this._pathLength = stroke.getLength() + StrokeRendererBase.STROKE_WIDTH / 2;
  1165. }
  1166. _getStrokeDashoffset(displayPortion) {
  1167. return this._pathLength * 0.999 * (1 - displayPortion);
  1168. }
  1169. _getColor({
  1170. strokeColor,
  1171. radicalColor
  1172. }) {
  1173. return radicalColor && this.stroke.isInRadical ? radicalColor : strokeColor;
  1174. }
  1175. }
  1176. StrokeRendererBase.STROKE_WIDTH = 200;
  1177. const STROKE_WIDTH = 200;
  1178. /** This is a stroke composed of several stroke parts **/
  1179. class StrokeRenderer extends StrokeRendererBase {
  1180. constructor(stroke) {
  1181. super(stroke);
  1182. this._oldProps = undefined;
  1183. }
  1184. mount(target) {
  1185. this._animationPath = createElm('path');
  1186. this._clip = createElm('clipPath');
  1187. this._strokePath = createElm('path');
  1188. const maskId = `mask-${counter()}`;
  1189. attr(this._clip, 'id', maskId);
  1190. attr(this._strokePath, 'd', this.stroke.path);
  1191. this._animationPath.style.opacity = '0';
  1192. attr(this._animationPath, 'clip-path', urlIdRef(maskId));
  1193. const extendedMaskPoints = extendStart(this.stroke.points, STROKE_WIDTH / 2);
  1194. attr(this._animationPath, 'd', getPathString(extendedMaskPoints));
  1195. attrs(this._animationPath, {
  1196. stroke: '#FFFFFF',
  1197. 'stroke-width': STROKE_WIDTH.toString(),
  1198. fill: 'none',
  1199. 'stroke-linecap': 'round',
  1200. 'stroke-linejoin': 'miter',
  1201. 'stroke-dasharray': `${this._pathLength},${this._pathLength}`
  1202. });
  1203. this._clip.appendChild(this._strokePath);
  1204. target.defs.appendChild(this._clip);
  1205. target.svg.appendChild(this._animationPath);
  1206. return this;
  1207. }
  1208. render(props) {
  1209. var _this$_oldProps, _this$_oldProps2;
  1210. if (props === this._oldProps || !this._animationPath) {
  1211. return;
  1212. }
  1213. if (props.displayPortion !== ((_this$_oldProps = this._oldProps) === null || _this$_oldProps === void 0 ? void 0 : _this$_oldProps.displayPortion)) {
  1214. this._animationPath.style.strokeDashoffset = this._getStrokeDashoffset(props.displayPortion).toString();
  1215. }
  1216. const color = this._getColor(props);
  1217. if (!this._oldProps || color !== this._getColor(this._oldProps)) {
  1218. const {
  1219. r,
  1220. g,
  1221. b,
  1222. a
  1223. } = color;
  1224. attrs(this._animationPath, {
  1225. stroke: `rgba(${r},${g},${b},${a})`
  1226. });
  1227. }
  1228. if (props.opacity !== ((_this$_oldProps2 = this._oldProps) === null || _this$_oldProps2 === void 0 ? void 0 : _this$_oldProps2.opacity)) {
  1229. this._animationPath.style.opacity = props.opacity.toString();
  1230. }
  1231. this._oldProps = props;
  1232. }
  1233. }
  1234. class CharacterRenderer {
  1235. constructor(character) {
  1236. this._oldProps = undefined;
  1237. this._strokeRenderers = character.strokes.map(stroke => new StrokeRenderer(stroke));
  1238. }
  1239. mount(target) {
  1240. const subTarget = target.createSubRenderTarget();
  1241. this._group = subTarget.svg;
  1242. this._strokeRenderers.forEach(strokeRenderer => {
  1243. strokeRenderer.mount(subTarget);
  1244. });
  1245. }
  1246. render(props) {
  1247. var _this$_oldProps, _this$_oldProps3;
  1248. if (props === this._oldProps || !this._group) {
  1249. return;
  1250. }
  1251. const {
  1252. opacity,
  1253. strokes,
  1254. strokeColor,
  1255. radicalColor = null
  1256. } = props;
  1257. if (opacity !== ((_this$_oldProps = this._oldProps) === null || _this$_oldProps === void 0 ? void 0 : _this$_oldProps.opacity)) {
  1258. this._group.style.opacity = opacity.toString(); // MS browsers seem to have a bug where if SVG is set to display:none, it sometimes breaks.
  1259. // More info: https://github.com/chanind/hanzi-writer/issues/164
  1260. // this is just a perf improvement, so disable for MS browsers
  1261. if (!isMsBrowser) {
  1262. var _this$_oldProps2;
  1263. if (opacity === 0) {
  1264. this._group.style.display = 'none';
  1265. } else if (((_this$_oldProps2 = this._oldProps) === null || _this$_oldProps2 === void 0 ? void 0 : _this$_oldProps2.opacity) === 0) {
  1266. this._group.style.removeProperty('display');
  1267. }
  1268. }
  1269. }
  1270. const colorsChanged = !this._oldProps || strokeColor !== this._oldProps.strokeColor || radicalColor !== this._oldProps.radicalColor;
  1271. if (colorsChanged || strokes !== ((_this$_oldProps3 = this._oldProps) === null || _this$_oldProps3 === void 0 ? void 0 : _this$_oldProps3.strokes)) {
  1272. for (let i = 0; i < this._strokeRenderers.length; i++) {
  1273. var _this$_oldProps4;
  1274. if (!colorsChanged && (_this$_oldProps4 = this._oldProps) !== null && _this$_oldProps4 !== void 0 && _this$_oldProps4.strokes && strokes[i] === this._oldProps.strokes[i]) {
  1275. continue;
  1276. }
  1277. this._strokeRenderers[i].render({
  1278. strokeColor,
  1279. radicalColor,
  1280. opacity: strokes[i].opacity,
  1281. displayPortion: strokes[i].displayPortion
  1282. });
  1283. }
  1284. }
  1285. this._oldProps = props;
  1286. }
  1287. }
  1288. class UserStrokeRenderer {
  1289. constructor() {
  1290. this._oldProps = undefined;
  1291. }
  1292. mount(target) {
  1293. this._path = createElm('path');
  1294. target.svg.appendChild(this._path);
  1295. }
  1296. render(props) {
  1297. var _this$_oldProps, _this$_oldProps2, _this$_oldProps3, _this$_oldProps4;
  1298. if (!this._path || props === this._oldProps) {
  1299. return;
  1300. }
  1301. if (props.strokeColor !== ((_this$_oldProps = this._oldProps) === null || _this$_oldProps === void 0 ? void 0 : _this$_oldProps.strokeColor) || props.strokeWidth !== ((_this$_oldProps2 = this._oldProps) === null || _this$_oldProps2 === void 0 ? void 0 : _this$_oldProps2.strokeWidth)) {
  1302. const {
  1303. r,
  1304. g,
  1305. b,
  1306. a
  1307. } = props.strokeColor;
  1308. attrs(this._path, {
  1309. fill: 'none',
  1310. stroke: `rgba(${r},${g},${b},${a})`,
  1311. 'stroke-width': props.strokeWidth.toString(),
  1312. 'stroke-linecap': 'round',
  1313. 'stroke-linejoin': 'round'
  1314. });
  1315. }
  1316. if (props.opacity !== ((_this$_oldProps3 = this._oldProps) === null || _this$_oldProps3 === void 0 ? void 0 : _this$_oldProps3.opacity)) {
  1317. attr(this._path, 'opacity', props.opacity.toString());
  1318. }
  1319. if (props.points !== ((_this$_oldProps4 = this._oldProps) === null || _this$_oldProps4 === void 0 ? void 0 : _this$_oldProps4.points)) {
  1320. attr(this._path, 'd', getPathString(props.points));
  1321. }
  1322. this._oldProps = props;
  1323. }
  1324. destroy() {
  1325. removeElm(this._path);
  1326. }
  1327. }
  1328. class HanziWriterRenderer {
  1329. constructor(character, positioner) {
  1330. this._character = character;
  1331. this._positioner = positioner;
  1332. this._mainCharRenderer = new CharacterRenderer(character);
  1333. this._outlineCharRenderer = new CharacterRenderer(character);
  1334. this._highlightCharRenderer = new CharacterRenderer(character);
  1335. this._userStrokeRenderers = {};
  1336. }
  1337. mount(target) {
  1338. const positionedTarget = target.createSubRenderTarget();
  1339. const group = positionedTarget.svg;
  1340. const {
  1341. xOffset,
  1342. yOffset,
  1343. height,
  1344. scale
  1345. } = this._positioner;
  1346. attr(group, 'transform', `translate(${xOffset}, ${height - yOffset}) scale(${scale}, ${-1 * scale})`);
  1347. this._outlineCharRenderer.mount(positionedTarget);
  1348. this._mainCharRenderer.mount(positionedTarget);
  1349. this._highlightCharRenderer.mount(positionedTarget);
  1350. this._positionedTarget = positionedTarget;
  1351. }
  1352. render(props) {
  1353. const {
  1354. main,
  1355. outline,
  1356. highlight
  1357. } = props.character;
  1358. const {
  1359. outlineColor,
  1360. radicalColor,
  1361. highlightColor,
  1362. strokeColor,
  1363. drawingWidth,
  1364. drawingColor
  1365. } = props.options;
  1366. this._outlineCharRenderer.render({
  1367. opacity: outline.opacity,
  1368. strokes: outline.strokes,
  1369. strokeColor: outlineColor
  1370. });
  1371. this._mainCharRenderer.render({
  1372. opacity: main.opacity,
  1373. strokes: main.strokes,
  1374. strokeColor,
  1375. radicalColor: radicalColor
  1376. });
  1377. this._highlightCharRenderer.render({
  1378. opacity: highlight.opacity,
  1379. strokes: highlight.strokes,
  1380. strokeColor: highlightColor
  1381. });
  1382. const userStrokes = props.userStrokes || {};
  1383. for (const userStrokeId in this._userStrokeRenderers) {
  1384. if (!userStrokes[userStrokeId]) {
  1385. var _this$_userStrokeRend;
  1386. (_this$_userStrokeRend = this._userStrokeRenderers[userStrokeId]) === null || _this$_userStrokeRend === void 0 ? void 0 : _this$_userStrokeRend.destroy();
  1387. delete this._userStrokeRenderers[userStrokeId];
  1388. }
  1389. }
  1390. for (const userStrokeId in userStrokes) {
  1391. const stroke = userStrokes[userStrokeId];
  1392. if (!stroke) {
  1393. continue;
  1394. }
  1395. const userStrokeProps = {
  1396. strokeWidth: drawingWidth,
  1397. strokeColor: drawingColor,
  1398. ...stroke
  1399. };
  1400. const strokeRenderer = (() => {
  1401. if (this._userStrokeRenderers[userStrokeId]) {
  1402. return this._userStrokeRenderers[userStrokeId];
  1403. }
  1404. const newStrokeRenderer = new UserStrokeRenderer();
  1405. newStrokeRenderer.mount(this._positionedTarget);
  1406. this._userStrokeRenderers[userStrokeId] = newStrokeRenderer;
  1407. return newStrokeRenderer;
  1408. })();
  1409. strokeRenderer.render(userStrokeProps);
  1410. }
  1411. }
  1412. destroy() {
  1413. removeElm(this._positionedTarget.svg);
  1414. this._positionedTarget.defs.innerHTML = '';
  1415. }
  1416. }
  1417. /** Generic render target */
  1418. class RenderTargetBase {
  1419. constructor(node) {
  1420. this.node = node;
  1421. }
  1422. addPointerStartListener(callback) {
  1423. this.node.addEventListener('mousedown', evt => {
  1424. callback(this._eventify(evt, this._getMousePoint));
  1425. });
  1426. this.node.addEventListener('touchstart', evt => {
  1427. callback(this._eventify(evt, this._getTouchPoint));
  1428. });
  1429. }
  1430. addPointerMoveListener(callback) {
  1431. this.node.addEventListener('mousemove', evt => {
  1432. callback(this._eventify(evt, this._getMousePoint));
  1433. });
  1434. this.node.addEventListener('touchmove', evt => {
  1435. callback(this._eventify(evt, this._getTouchPoint));
  1436. });
  1437. }
  1438. addPointerEndListener(callback) {
  1439. // TODO: find a way to not need global listeners
  1440. document.addEventListener('mouseup', callback);
  1441. document.addEventListener('touchend', callback);
  1442. }
  1443. getBoundingClientRect() {
  1444. return this.node.getBoundingClientRect();
  1445. }
  1446. updateDimensions(width, height) {
  1447. this.node.setAttribute('width', `${width}`);
  1448. this.node.setAttribute('height', `${height}`);
  1449. }
  1450. _eventify(evt, pointFunc) {
  1451. return {
  1452. getPoint: () => pointFunc.call(this, evt),
  1453. preventDefault: () => evt.preventDefault()
  1454. };
  1455. }
  1456. _getMousePoint(evt) {
  1457. const {
  1458. left,
  1459. top
  1460. } = this.getBoundingClientRect();
  1461. const x = evt.clientX - left;
  1462. const y = evt.clientY - top;
  1463. return {
  1464. x,
  1465. y
  1466. };
  1467. }
  1468. _getTouchPoint(evt) {
  1469. const {
  1470. left,
  1471. top
  1472. } = this.getBoundingClientRect();
  1473. const x = evt.touches[0].clientX - left;
  1474. const y = evt.touches[0].clientY - top;
  1475. return {
  1476. x,
  1477. y
  1478. };
  1479. }
  1480. }
  1481. class RenderTarget extends RenderTargetBase {
  1482. constructor(svg, defs) {
  1483. super(svg);
  1484. this.svg = svg;
  1485. this.defs = defs;
  1486. if ('createSVGPoint' in svg) {
  1487. this._pt = svg.createSVGPoint();
  1488. }
  1489. }
  1490. static init(elmOrId, width = '100%', height = '100%') {
  1491. const element = (() => {
  1492. if (typeof elmOrId === 'string') {
  1493. return document.getElementById(elmOrId);
  1494. }
  1495. return elmOrId;
  1496. })();
  1497. if (!element) {
  1498. throw new Error(`HanziWriter target element not found: ${elmOrId}`);
  1499. }
  1500. const nodeType = element.nodeName.toUpperCase();
  1501. const svg = (() => {
  1502. if (nodeType === 'SVG' || nodeType === 'G') {
  1503. return element;
  1504. } else {
  1505. const svg = createElm('svg');
  1506. element.appendChild(svg);
  1507. return svg;
  1508. }
  1509. })();
  1510. attrs(svg, {
  1511. width,
  1512. height
  1513. });
  1514. const defs = createElm('defs');
  1515. svg.appendChild(defs);
  1516. return new RenderTarget(svg, defs);
  1517. }
  1518. createSubRenderTarget() {
  1519. const group = createElm('g');
  1520. this.svg.appendChild(group);
  1521. return new RenderTarget(group, this.defs);
  1522. }
  1523. _getMousePoint(evt) {
  1524. if (this._pt) {
  1525. this._pt.x = evt.clientX;
  1526. this._pt.y = evt.clientY;
  1527. if ('getScreenCTM' in this.node) {
  1528. var _this$node$getScreenC;
  1529. const localPt = this._pt.matrixTransform((_this$node$getScreenC = this.node.getScreenCTM()) === null || _this$node$getScreenC === void 0 ? void 0 : _this$node$getScreenC.inverse());
  1530. return {
  1531. x: localPt.x,
  1532. y: localPt.y
  1533. };
  1534. }
  1535. }
  1536. return super._getMousePoint.call(this, evt);
  1537. }
  1538. _getTouchPoint(evt) {
  1539. if (this._pt) {
  1540. this._pt.x = evt.touches[0].clientX;
  1541. this._pt.y = evt.touches[0].clientY;
  1542. if ('getScreenCTM' in this.node) {
  1543. var _this$node$getScreenC2;
  1544. const localPt = this._pt.matrixTransform((_this$node$getScreenC2 = this.node.getScreenCTM()) === null || _this$node$getScreenC2 === void 0 ? void 0 : _this$node$getScreenC2.inverse());
  1545. return {
  1546. x: localPt.x,
  1547. y: localPt.y
  1548. };
  1549. }
  1550. }
  1551. return super._getTouchPoint(evt);
  1552. }
  1553. }
  1554. var svgRenderer = {
  1555. HanziWriterRenderer,
  1556. createRenderTarget: RenderTarget.init
  1557. };
  1558. const drawPath = (ctx, points) => {
  1559. ctx.beginPath();
  1560. const start = points[0];
  1561. const remainingPoints = points.slice(1);
  1562. ctx.moveTo(start.x, start.y);
  1563. for (const point of remainingPoints) {
  1564. ctx.lineTo(point.x, point.y);
  1565. }
  1566. ctx.stroke();
  1567. };
  1568. /**
  1569. * Break a path string into a series of canvas path commands
  1570. *
  1571. * Note: only works with the subset of SVG paths used by MakeMeAHanzi data
  1572. * @param pathString
  1573. */
  1574. const pathStringToCanvas = pathString => {
  1575. const pathParts = pathString.split(/(^|\s+)(?=[A-Z])/).filter(part => part !== ' ');
  1576. const commands = [ctx => ctx.beginPath()];
  1577. for (const part of pathParts) {
  1578. const [cmd, ...rawParams] = part.split(/\s+/);
  1579. const params = rawParams.map(param => parseFloat(param));
  1580. if (cmd === 'M') {
  1581. commands.push(ctx => ctx.moveTo(...params));
  1582. } else if (cmd === 'L') {
  1583. commands.push(ctx => ctx.lineTo(...params));
  1584. } else if (cmd === 'C') {
  1585. commands.push(ctx => ctx.bezierCurveTo(...params));
  1586. } else if (cmd === 'Q') {
  1587. commands.push(ctx => ctx.quadraticCurveTo(...params));
  1588. } else ;
  1589. }
  1590. return ctx => commands.forEach(cmd => cmd(ctx));
  1591. };
  1592. /** this is a stroke composed of several stroke parts */
  1593. class StrokeRenderer$1 extends StrokeRendererBase {
  1594. constructor(stroke, usePath2D = true) {
  1595. super(stroke);
  1596. if (usePath2D && Path2D) {
  1597. this._path2D = new Path2D(this.stroke.path);
  1598. } else {
  1599. this._pathCmd = pathStringToCanvas(this.stroke.path);
  1600. }
  1601. this._extendedMaskPoints = extendStart(this.stroke.points, StrokeRendererBase.STROKE_WIDTH / 2);
  1602. }
  1603. render(ctx, props) {
  1604. if (props.opacity < 0.05) {
  1605. return;
  1606. }
  1607. ctx.save();
  1608. if (this._path2D) {
  1609. ctx.clip(this._path2D);
  1610. } else {
  1611. var _this$_pathCmd;
  1612. (_this$_pathCmd = this._pathCmd) === null || _this$_pathCmd === void 0 ? void 0 : _this$_pathCmd.call(this, ctx); // wechat bugs out if the clip path isn't stroked or filled
  1613. ctx.globalAlpha = 0;
  1614. ctx.stroke();
  1615. ctx.clip();
  1616. }
  1617. const {
  1618. r,
  1619. g,
  1620. b,
  1621. a
  1622. } = this._getColor(props);
  1623. const color = a === 1 ? `rgb(${r},${g},${b})` : `rgb(${r},${g},${b},${a})`;
  1624. const dashOffset = this._getStrokeDashoffset(props.displayPortion);
  1625. ctx.globalAlpha = props.opacity;
  1626. ctx.strokeStyle = color;
  1627. ctx.fillStyle = color;
  1628. ctx.lineWidth = StrokeRendererBase.STROKE_WIDTH;
  1629. ctx.lineCap = 'round';
  1630. ctx.lineJoin = 'round'; // wechat sets dashOffset as a second param here. Should be harmless for browsers to add here too
  1631. // @ts-ignore
  1632. ctx.setLineDash([this._pathLength, this._pathLength], dashOffset);
  1633. ctx.lineDashOffset = dashOffset;
  1634. drawPath(ctx, this._extendedMaskPoints);
  1635. ctx.restore();
  1636. }
  1637. }
  1638. class CharacterRenderer$1 {
  1639. constructor(character) {
  1640. this._strokeRenderers = character.strokes.map(stroke => new StrokeRenderer$1(stroke));
  1641. }
  1642. render(ctx, props) {
  1643. if (props.opacity < 0.05) return;
  1644. const {
  1645. opacity,
  1646. strokeColor,
  1647. radicalColor,
  1648. strokes
  1649. } = props;
  1650. for (let i = 0; i < this._strokeRenderers.length; i++) {
  1651. this._strokeRenderers[i].render(ctx, {
  1652. strokeColor,
  1653. radicalColor,
  1654. opacity: strokes[i].opacity * opacity,
  1655. displayPortion: strokes[i].displayPortion || 0
  1656. });
  1657. }
  1658. }
  1659. }
  1660. function renderUserStroke(ctx, props) {
  1661. if (props.opacity < 0.05) {
  1662. return;
  1663. }
  1664. const {
  1665. opacity,
  1666. strokeWidth,
  1667. strokeColor,
  1668. points
  1669. } = props;
  1670. const {
  1671. r,
  1672. g,
  1673. b,
  1674. a
  1675. } = strokeColor;
  1676. ctx.save();
  1677. ctx.globalAlpha = opacity;
  1678. ctx.lineWidth = strokeWidth;
  1679. ctx.strokeStyle = `rgba(${r},${g},${b},${a})`;
  1680. ctx.lineCap = 'round';
  1681. ctx.lineJoin = 'round';
  1682. drawPath(ctx, points);
  1683. ctx.restore();
  1684. }
  1685. class HanziWriterRenderer$1 {
  1686. constructor(character, positioner) {
  1687. this.destroy = noop;
  1688. this._character = character;
  1689. this._positioner = positioner;
  1690. this._mainCharRenderer = new CharacterRenderer$1(character);
  1691. this._outlineCharRenderer = new CharacterRenderer$1(character);
  1692. this._highlightCharRenderer = new CharacterRenderer$1(character);
  1693. }
  1694. mount(target) {
  1695. this._target = target;
  1696. }
  1697. _animationFrame(cb) {
  1698. const {
  1699. width,
  1700. height,
  1701. scale,
  1702. xOffset,
  1703. yOffset
  1704. } = this._positioner;
  1705. const ctx = this._target.getContext();
  1706. ctx.clearRect(0, 0, width, height);
  1707. ctx.save();
  1708. ctx.translate(xOffset, height - yOffset);
  1709. ctx.transform(1, 0, 0, -1, 0, 0);
  1710. ctx.scale(scale, scale);
  1711. cb(ctx);
  1712. ctx.restore(); // @ts-expect-error Verify if this is still needed for the "wechat miniprogram".
  1713. if (ctx.draw) {
  1714. // @ts-expect-error
  1715. ctx.draw();
  1716. }
  1717. }
  1718. render(props) {
  1719. const {
  1720. outline,
  1721. main,
  1722. highlight
  1723. } = props.character;
  1724. const {
  1725. outlineColor,
  1726. strokeColor,
  1727. radicalColor,
  1728. highlightColor,
  1729. drawingColor,
  1730. drawingWidth
  1731. } = props.options;
  1732. this._animationFrame(ctx => {
  1733. this._outlineCharRenderer.render(ctx, {
  1734. opacity: outline.opacity,
  1735. strokes: outline.strokes,
  1736. strokeColor: outlineColor
  1737. });
  1738. this._mainCharRenderer.render(ctx, {
  1739. opacity: main.opacity,
  1740. strokes: main.strokes,
  1741. strokeColor: strokeColor,
  1742. radicalColor: radicalColor
  1743. });
  1744. this._highlightCharRenderer.render(ctx, {
  1745. opacity: highlight.opacity,
  1746. strokes: highlight.strokes,
  1747. strokeColor: highlightColor
  1748. });
  1749. const userStrokes = props.userStrokes || {};
  1750. for (const userStrokeId in userStrokes) {
  1751. const userStroke = userStrokes[userStrokeId];
  1752. if (userStroke) {
  1753. const userStrokeProps = {
  1754. strokeWidth: drawingWidth,
  1755. strokeColor: drawingColor,
  1756. ...userStroke
  1757. };
  1758. renderUserStroke(ctx, userStrokeProps);
  1759. }
  1760. }
  1761. });
  1762. }
  1763. }
  1764. class RenderTarget$1 extends RenderTargetBase {
  1765. constructor(canvas) {
  1766. super(canvas);
  1767. }
  1768. static init(elmOrId, width = '100%', height = '100%') {
  1769. const element = (() => {
  1770. if (typeof elmOrId === 'string') {
  1771. return document.getElementById(elmOrId);
  1772. }
  1773. return elmOrId;
  1774. })();
  1775. if (!element) {
  1776. throw new Error(`HanziWriter target element not found: ${elmOrId}`);
  1777. }
  1778. const nodeType = element.nodeName.toUpperCase();
  1779. const canvas = (() => {
  1780. if (nodeType === 'CANVAS') {
  1781. return element;
  1782. }
  1783. const canvas = document.createElement('canvas');
  1784. element.appendChild(canvas);
  1785. return canvas;
  1786. })();
  1787. canvas.setAttribute('width', width);
  1788. canvas.setAttribute('height', height);
  1789. return new RenderTarget$1(canvas);
  1790. }
  1791. getContext() {
  1792. return this.node.getContext('2d');
  1793. }
  1794. }
  1795. var canvasRenderer = {
  1796. HanziWriterRenderer: HanziWriterRenderer$1,
  1797. createRenderTarget: RenderTarget$1.init
  1798. };
  1799. const VERSION = '2.0';
  1800. const getCharDataUrl = char => `https://cdn.jsdelivr.net/npm/hanzi-writer-data@${VERSION}/${char}.json`;
  1801. const defaultCharDataLoader = (char, onLoad, onError) => {
  1802. // load char data from hanziwriter cdn (currently hosted on jsdelivr)
  1803. const xhr = new XMLHttpRequest();
  1804. if (xhr.overrideMimeType) {
  1805. // IE 9 and 10 don't seem to support this...
  1806. xhr.overrideMimeType('application/json');
  1807. }
  1808. xhr.open('GET', getCharDataUrl(char), true);
  1809. xhr.onerror = event => {
  1810. onError(xhr, event);
  1811. };
  1812. xhr.onreadystatechange = () => {
  1813. // TODO: error handling
  1814. if (xhr.readyState !== 4) return;
  1815. if (xhr.status === 200) {
  1816. onLoad(JSON.parse(xhr.responseText));
  1817. } else if (xhr.status !== 0 && onError) {
  1818. onError(xhr);
  1819. }
  1820. };
  1821. xhr.send(null);
  1822. };
  1823. const defaultOptions = {
  1824. charDataLoader: defaultCharDataLoader,
  1825. onLoadCharDataError: null,
  1826. onLoadCharDataSuccess: null,
  1827. showOutline: true,
  1828. showCharacter: true,
  1829. renderer: 'svg',
  1830. // positioning options
  1831. width: 0,
  1832. height: 0,
  1833. padding: 20,
  1834. // animation options
  1835. strokeAnimationSpeed: 1,
  1836. strokeFadeDuration: 400,
  1837. strokeHighlightDuration: 200,
  1838. strokeHighlightSpeed: 2,
  1839. delayBetweenStrokes: 1000,
  1840. delayBetweenLoops: 2000,
  1841. // colors
  1842. strokeColor: '#555',
  1843. radicalColor: null,
  1844. highlightColor: '#AAF',
  1845. outlineColor: '#DDD',
  1846. drawingColor: '#333',
  1847. // quiz options
  1848. leniency: 1,
  1849. showHintAfterMisses: 3,
  1850. highlightOnComplete: true,
  1851. highlightCompleteColor: null,
  1852. markStrokeCorrectAfterMisses: false,
  1853. acceptBackwardsStrokes: false,
  1854. quizStartStrokeNum: 0,
  1855. averageDistanceThreshold: 350,
  1856. // undocumented obscure options
  1857. drawingFadeDuration: 300,
  1858. drawingWidth: 4,
  1859. strokeWidth: 2,
  1860. outlineWidth: 2,
  1861. rendererOverride: {}
  1862. };
  1863. class LoadingManager {
  1864. constructor(options) {
  1865. this._loadCounter = 0;
  1866. this._isLoading = false;
  1867. /** use this to attribute to determine if there was a problem with loading */
  1868. this.loadingFailed = false;
  1869. this._options = options;
  1870. }
  1871. _debouncedLoad(char, count) {
  1872. // these wrappers ignore all responses except the most recent.
  1873. const wrappedResolve = data => {
  1874. if (count === this._loadCounter) {
  1875. var _this$_resolve;
  1876. (_this$_resolve = this._resolve) === null || _this$_resolve === void 0 ? void 0 : _this$_resolve.call(this, data);
  1877. }
  1878. };
  1879. const wrappedReject = reason => {
  1880. if (count === this._loadCounter) {
  1881. var _this$_reject;
  1882. (_this$_reject = this._reject) === null || _this$_reject === void 0 ? void 0 : _this$_reject.call(this, reason);
  1883. }
  1884. };
  1885. const returnedData = this._options.charDataLoader(char, wrappedResolve, wrappedReject);
  1886. if (returnedData) {
  1887. if ('then' in returnedData) {
  1888. returnedData.then(wrappedResolve).catch(wrappedReject);
  1889. } else {
  1890. wrappedResolve(returnedData);
  1891. }
  1892. }
  1893. }
  1894. _setupLoadingPromise() {
  1895. return new Promise((resolve, reject) => {
  1896. this._resolve = resolve;
  1897. this._reject = reject;
  1898. }).then(data => {
  1899. var _this$_options$onLoad, _this$_options;
  1900. this._isLoading = false;
  1901. (_this$_options$onLoad = (_this$_options = this._options).onLoadCharDataSuccess) === null || _this$_options$onLoad === void 0 ? void 0 : _this$_options$onLoad.call(_this$_options, data);
  1902. return data;
  1903. }).catch(reason => {
  1904. this._isLoading = false;
  1905. this.loadingFailed = true; // If the user has provided an "onLoadCharDataError", call this function
  1906. // Otherwise, throw the promise
  1907. if (this._options.onLoadCharDataError) {
  1908. this._options.onLoadCharDataError(reason);
  1909. return;
  1910. } // If error callback wasn't provided, throw an error so the developer will be aware something went wrong
  1911. if (reason instanceof Error) {
  1912. throw reason;
  1913. }
  1914. const err = new Error(`Failed to load char data for ${this._loadingChar}`);
  1915. err.reason = reason;
  1916. throw err;
  1917. });
  1918. }
  1919. loadCharData(char) {
  1920. this._loadingChar = char;
  1921. const promise = this._setupLoadingPromise();
  1922. this.loadingFailed = false;
  1923. this._isLoading = true;
  1924. this._loadCounter++;
  1925. this._debouncedLoad(char, this._loadCounter);
  1926. return promise;
  1927. }
  1928. }
  1929. class HanziWriter {
  1930. constructor(element, options = {}) {
  1931. const {
  1932. HanziWriterRenderer,
  1933. createRenderTarget
  1934. } = options.renderer === 'canvas' ? canvasRenderer : svgRenderer;
  1935. const rendererOverride = options.rendererOverride || {};
  1936. this._renderer = {
  1937. HanziWriterRenderer: rendererOverride.HanziWriterRenderer || HanziWriterRenderer,
  1938. createRenderTarget: rendererOverride.createRenderTarget || createRenderTarget
  1939. }; // wechat miniprogram component needs direct access to the render target, so this is public
  1940. this.target = this._renderer.createRenderTarget(element, options.width, options.height);
  1941. this._options = this._assignOptions(options);
  1942. this._loadingManager = new LoadingManager(this._options);
  1943. this._setupListeners();
  1944. }
  1945. /** Main entry point */
  1946. static create(element, character, options) {
  1947. const writer = new HanziWriter(element, options);
  1948. writer.setCharacter(character);
  1949. return writer;
  1950. }
  1951. static loadCharacterData(character, options = {}) {
  1952. const loadingManager = (() => {
  1953. const {
  1954. _loadingManager,
  1955. _loadingOptions
  1956. } = HanziWriter;
  1957. if ((_loadingManager === null || _loadingManager === void 0 ? void 0 : _loadingManager._loadingChar) === character && _loadingOptions === options) {
  1958. return _loadingManager;
  1959. }
  1960. return new LoadingManager({ ...defaultOptions,
  1961. ...options
  1962. });
  1963. })();
  1964. HanziWriter._loadingManager = loadingManager;
  1965. HanziWriter._loadingOptions = options;
  1966. return loadingManager.loadCharData(character);
  1967. }
  1968. static getScalingTransform(width, height, padding = 0) {
  1969. const positioner = new Positioner({
  1970. width,
  1971. height,
  1972. padding
  1973. });
  1974. return {
  1975. x: positioner.xOffset,
  1976. y: positioner.yOffset,
  1977. scale: positioner.scale,
  1978. transform: trim(`
  1979. translate(${positioner.xOffset}, ${positioner.height - positioner.yOffset})
  1980. scale(${positioner.scale}, ${-1 * positioner.scale})
  1981. `).replace(/\s+/g, ' ')
  1982. };
  1983. }
  1984. showCharacter(options = {}) {
  1985. this._options.showCharacter = true;
  1986. return this._withData(() => {
  1987. var _this$_renderState;
  1988. return (_this$_renderState = this._renderState) === null || _this$_renderState === void 0 ? void 0 : _this$_renderState.run(showCharacter('main', this._character, typeof options.duration === 'number' ? options.duration : this._options.strokeFadeDuration)).then(res => {
  1989. var _options$onComplete;
  1990. (_options$onComplete = options.onComplete) === null || _options$onComplete === void 0 ? void 0 : _options$onComplete.call(options, res);
  1991. return res;
  1992. });
  1993. });
  1994. }
  1995. hideCharacter(options = {}) {
  1996. this._options.showCharacter = false;
  1997. return this._withData(() => {
  1998. var _this$_renderState2;
  1999. return (_this$_renderState2 = this._renderState) === null || _this$_renderState2 === void 0 ? void 0 : _this$_renderState2.run(hideCharacter('main', this._character, typeof options.duration === 'number' ? options.duration : this._options.strokeFadeDuration)).then(res => {
  2000. var _options$onComplete2;
  2001. (_options$onComplete2 = options.onComplete) === null || _options$onComplete2 === void 0 ? void 0 : _options$onComplete2.call(options, res);
  2002. return res;
  2003. });
  2004. });
  2005. }
  2006. animateCharacter(options = {}) {
  2007. this.cancelQuiz();
  2008. return this._withData(() => {
  2009. var _this$_renderState3;
  2010. return (_this$_renderState3 = this._renderState) === null || _this$_renderState3 === void 0 ? void 0 : _this$_renderState3.run(animateCharacter('main', this._character, this._options.strokeFadeDuration, this._options.strokeAnimationSpeed, this._options.delayBetweenStrokes)).then(res => {
  2011. var _options$onComplete3;
  2012. (_options$onComplete3 = options.onComplete) === null || _options$onComplete3 === void 0 ? void 0 : _options$onComplete3.call(options, res);
  2013. return res;
  2014. });
  2015. });
  2016. }
  2017. animateStroke(strokeNum, options = {}) {
  2018. this.cancelQuiz();
  2019. return this._withData(() => {
  2020. var _this$_renderState4;
  2021. return (_this$_renderState4 = this._renderState) === null || _this$_renderState4 === void 0 ? void 0 : _this$_renderState4.run(animateSingleStroke('main', this._character, fixIndex(strokeNum, this._character.strokes.length), this._options.strokeAnimationSpeed)).then(res => {
  2022. var _options$onComplete4;
  2023. (_options$onComplete4 = options.onComplete) === null || _options$onComplete4 === void 0 ? void 0 : _options$onComplete4.call(options, res);
  2024. return res;
  2025. });
  2026. });
  2027. }
  2028. highlightStroke(strokeNum, options = {}) {
  2029. const promise = () => {
  2030. if (!this._character || !this._renderState) {
  2031. return;
  2032. }
  2033. return this._renderState.run(highlightStroke(selectIndex(this._character.strokes, strokeNum), colorStringToVals(this._options.highlightColor), this._options.strokeHighlightSpeed)).then(res => {
  2034. var _options$onComplete5;
  2035. (_options$onComplete5 = options.onComplete) === null || _options$onComplete5 === void 0 ? void 0 : _options$onComplete5.call(options, res);
  2036. return res;
  2037. });
  2038. };
  2039. return this._withData(promise);
  2040. }
  2041. async loopCharacterAnimation() {
  2042. this.cancelQuiz();
  2043. return this._withData(() => this._renderState.run(animateCharacterLoop('main', this._character, this._options.strokeFadeDuration, this._options.strokeAnimationSpeed, this._options.delayBetweenStrokes, this._options.delayBetweenLoops), {
  2044. loop: true
  2045. }));
  2046. }
  2047. pauseAnimation() {
  2048. return this._withData(() => {
  2049. var _this$_renderState5;
  2050. return (_this$_renderState5 = this._renderState) === null || _this$_renderState5 === void 0 ? void 0 : _this$_renderState5.pauseAll();
  2051. });
  2052. }
  2053. resumeAnimation() {
  2054. return this._withData(() => {
  2055. var _this$_renderState6;
  2056. return (_this$_renderState6 = this._renderState) === null || _this$_renderState6 === void 0 ? void 0 : _this$_renderState6.resumeAll();
  2057. });
  2058. }
  2059. showOutline(options = {}) {
  2060. this._options.showOutline = true;
  2061. return this._withData(() => {
  2062. var _this$_renderState7;
  2063. return (_this$_renderState7 = this._renderState) === null || _this$_renderState7 === void 0 ? void 0 : _this$_renderState7.run(showCharacter('outline', this._character, typeof options.duration === 'number' ? options.duration : this._options.strokeFadeDuration)).then(res => {
  2064. var _options$onComplete6;
  2065. (_options$onComplete6 = options.onComplete) === null || _options$onComplete6 === void 0 ? void 0 : _options$onComplete6.call(options, res);
  2066. return res;
  2067. });
  2068. });
  2069. }
  2070. hideOutline(options = {}) {
  2071. this._options.showOutline = false;
  2072. return this._withData(() => {
  2073. var _this$_renderState8;
  2074. return (_this$_renderState8 = this._renderState) === null || _this$_renderState8 === void 0 ? void 0 : _this$_renderState8.run(hideCharacter('outline', this._character, typeof options.duration === 'number' ? options.duration : this._options.strokeFadeDuration)).then(res => {
  2075. var _options$onComplete7;
  2076. (_options$onComplete7 = options.onComplete) === null || _options$onComplete7 === void 0 ? void 0 : _options$onComplete7.call(options, res);
  2077. return res;
  2078. });
  2079. });
  2080. }
  2081. /** Updates the size of the writer instance without resetting render state */
  2082. updateDimensions({
  2083. width,
  2084. height,
  2085. padding
  2086. }) {
  2087. if (width !== undefined) this._options.width = width;
  2088. if (height !== undefined) this._options.height = height;
  2089. if (padding !== undefined) this._options.padding = padding;
  2090. this.target.updateDimensions(this._options.width, this._options.height); // if there's already a character drawn, destroy and recreate the renderer in the same state
  2091. if (this._character && this._renderState && this._hanziWriterRenderer && this._positioner) {
  2092. this._hanziWriterRenderer.destroy();
  2093. const hanziWriterRenderer = this._initAndMountHanziWriterRenderer(this._character); // TODO: this should probably implement EventEmitter instead of manually tracking updates like this
  2094. this._renderState.overwriteOnStateChange(nextState => hanziWriterRenderer.render(nextState));
  2095. hanziWriterRenderer.render(this._renderState.state); // update the current quiz as well, if one is active
  2096. if (this._quiz) {
  2097. this._quiz.setPositioner(this._positioner);
  2098. }
  2099. }
  2100. }
  2101. updateColor(colorName, colorVal, options = {}) {
  2102. var _options$duration;
  2103. let mutations = [];
  2104. const fixedColorVal = (() => {
  2105. // If we're removing radical color, tween it to the stroke color
  2106. if (colorName === 'radicalColor' && !colorVal) {
  2107. return this._options.strokeColor;
  2108. }
  2109. return colorVal;
  2110. })();
  2111. const mappedColor = colorStringToVals(fixedColorVal);
  2112. this._options[colorName] = colorVal;
  2113. const duration = (_options$duration = options.duration) !== null && _options$duration !== void 0 ? _options$duration : this._options.strokeFadeDuration;
  2114. mutations = mutations.concat(updateColor(colorName, mappedColor, duration)); // make sure to set radicalColor back to null after the transition finishes if val == null
  2115. if (colorName === 'radicalColor' && !colorVal) {
  2116. mutations = mutations.concat(updateColor(colorName, null, 0));
  2117. }
  2118. return this._withData(() => {
  2119. var _this$_renderState9;
  2120. return (_this$_renderState9 = this._renderState) === null || _this$_renderState9 === void 0 ? void 0 : _this$_renderState9.run(mutations).then(res => {
  2121. var _options$onComplete8;
  2122. (_options$onComplete8 = options.onComplete) === null || _options$onComplete8 === void 0 ? void 0 : _options$onComplete8.call(options, res);
  2123. return res;
  2124. });
  2125. });
  2126. }
  2127. quiz(quizOptions = {}) {
  2128. return this._withData(async () => {
  2129. if (this._character && this._renderState && this._positioner) {
  2130. this.cancelQuiz();
  2131. this._quiz = new Quiz(this._character, this._renderState, this._positioner);
  2132. this._options = { ...this._options,
  2133. ...quizOptions
  2134. };
  2135. this._quiz.startQuiz(this._options);
  2136. }
  2137. });
  2138. }
  2139. cancelQuiz() {
  2140. if (this._quiz) {
  2141. this._quiz.cancel();
  2142. this._quiz = undefined;
  2143. }
  2144. }
  2145. setCharacter(char) {
  2146. this.cancelQuiz();
  2147. this._char = char;
  2148. if (this._hanziWriterRenderer) {
  2149. this._hanziWriterRenderer.destroy();
  2150. }
  2151. if (this._renderState) {
  2152. this._renderState.cancelAll();
  2153. }
  2154. this._hanziWriterRenderer = null;
  2155. this._withDataPromise = this._loadingManager.loadCharData(char).then(pathStrings => {
  2156. // if "pathStrings" isn't set, ".catch()"" was probably called and loading likely failed
  2157. if (!pathStrings || this._loadingManager.loadingFailed) {
  2158. return;
  2159. }
  2160. this._character = parseCharData(char, pathStrings);
  2161. this._renderState = new RenderState(this._character, this._options, nextState => hanziWriterRenderer.render(nextState));
  2162. const hanziWriterRenderer = this._initAndMountHanziWriterRenderer(this._character);
  2163. hanziWriterRenderer.render(this._renderState.state);
  2164. });
  2165. return this._withDataPromise;
  2166. }
  2167. _initAndMountHanziWriterRenderer(character) {
  2168. const {
  2169. width,
  2170. height,
  2171. padding
  2172. } = this._options;
  2173. this._positioner = new Positioner({
  2174. width,
  2175. height,
  2176. padding
  2177. });
  2178. const hanziWriterRenderer = new this._renderer.HanziWriterRenderer(character, this._positioner);
  2179. hanziWriterRenderer.mount(this.target);
  2180. this._hanziWriterRenderer = hanziWriterRenderer;
  2181. return hanziWriterRenderer;
  2182. }
  2183. async getCharacterData() {
  2184. if (!this._char) {
  2185. throw new Error('setCharacter() must be called before calling getCharacterData()');
  2186. }
  2187. const character = await this._withData(() => this._character);
  2188. return character;
  2189. }
  2190. _assignOptions(options) {
  2191. const mergedOptions = { ...defaultOptions,
  2192. ...options
  2193. }; // backfill strokeAnimationSpeed if deprecated strokeAnimationDuration is provided instead
  2194. if (options.strokeAnimationDuration && !options.strokeAnimationSpeed) {
  2195. mergedOptions.strokeAnimationSpeed = 500 / options.strokeAnimationDuration;
  2196. }
  2197. if (options.strokeHighlightDuration && !options.strokeHighlightSpeed) {
  2198. mergedOptions.strokeHighlightSpeed = 500 / mergedOptions.strokeHighlightDuration;
  2199. }
  2200. if (!options.highlightCompleteColor) {
  2201. mergedOptions.highlightCompleteColor = mergedOptions.highlightColor;
  2202. }
  2203. return this._fillWidthAndHeight(mergedOptions);
  2204. }
  2205. /** returns a new options object with width and height filled in if missing */
  2206. _fillWidthAndHeight(options) {
  2207. const filledOpts = { ...options
  2208. };
  2209. if (filledOpts.width && !filledOpts.height) {
  2210. filledOpts.height = filledOpts.width;
  2211. } else if (filledOpts.height && !filledOpts.width) {
  2212. filledOpts.width = filledOpts.height;
  2213. } else if (!filledOpts.width && !filledOpts.height) {
  2214. const {
  2215. width,
  2216. height
  2217. } = this.target.getBoundingClientRect();
  2218. const minDim = Math.min(width, height);
  2219. filledOpts.width = minDim;
  2220. filledOpts.height = minDim;
  2221. }
  2222. return filledOpts;
  2223. }
  2224. _withData(func) {
  2225. // if this._loadingManager.loadingFailed, then loading failed before this method was called
  2226. if (this._loadingManager.loadingFailed) {
  2227. throw Error('Failed to load character data. Call setCharacter and try again.');
  2228. }
  2229. if (this._withDataPromise) {
  2230. return this._withDataPromise.then(() => {
  2231. if (!this._loadingManager.loadingFailed) {
  2232. return func();
  2233. }
  2234. });
  2235. }
  2236. return Promise.resolve().then(func);
  2237. }
  2238. _setupListeners() {
  2239. this.target.addPointerStartListener(evt => {
  2240. if (this._quiz) {
  2241. evt.preventDefault();
  2242. this._quiz.startUserStroke(evt.getPoint());
  2243. }
  2244. });
  2245. this.target.addPointerMoveListener(evt => {
  2246. if (this._quiz) {
  2247. evt.preventDefault();
  2248. this._quiz.continueUserStroke(evt.getPoint());
  2249. }
  2250. });
  2251. this.target.addPointerEndListener(() => {
  2252. var _this$_quiz;
  2253. (_this$_quiz = this._quiz) === null || _this$_quiz === void 0 ? void 0 : _this$_quiz.endUserStroke();
  2254. });
  2255. }
  2256. }
  2257. /** Singleton instance of LoadingManager. Only set in `loadCharacterData` */
  2258. HanziWriter._loadingManager = null;
  2259. /** Singleton loading options. Only set in `loadCharacterData` */
  2260. HanziWriter._loadingOptions = null;
  2261. export default HanziWriter;
  2262. //# sourceMappingURL=index.esm.js.map