index.cjs.js 78 KB

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