prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { DisassembledInstruction } from "./types"; import { isLetterChar, maskOfSize } from "./util"; export const buildDisassembledInstructionString = ( { instruction, actualWord, address }: DisassembledInstruction, immediateLabel: string | undefined ) => { let instructionString = instruction.originalInstruction; if (instruction.type === "immediate") { const { bitCount, stringIndex, stringLength } = instruction.immediate; const immediatePrefix = instructionString.substring(0, stringIndex); const immediateSuffix = instructionString.substring( stringIndex + stringLength ); let immediate = ""; if (immediateLabel) { immediate = immediateLabel; } else { const argument = maskOfSize(bitCount) & actualWord; if (isLetterChar(immediatePrefix.charAt(immediatePrefix.length - 1))) { // If letter, treat as decimal immediate = argument.toString(); } else { // Otherwise, treat as hex immediate = `0x${argument.toString(16).toUpperCase()}`; } } instructionString = `${immediatePrefix}${immediate}${immediateSuffix}`; } // Separate out instruction so that it formats nicely // Four total columns // Opcode - Source - Dest - Comments const splitInstruction = instructionString.split(/\s+/); let lastPadWidth = 0; for (let i = 2; i >= splitInstruction.length - 1; i--) { lastPadWidth += columnPadWidth(i); } const formattedInstructionString = splitInstruction
.map((s, i) => {
const pad = i === splitInstruction.length - 1 ? lastPadWidth : columnPadWidth(i); return s.padEnd(pad); }) .join(""); const comment = `// 0x${address .toString(16) .toUpperCase() .padEnd(4)} (0x${actualWord.toString(16).toUpperCase()})`; return `${formattedInstructionString.padEnd(81)}${comment}`; }; const columnPadWidth = (column: number) => { switch (column) { case 0: return 6; case 1: return 5; case 2: return 10; } return 0; };
src/lib/display.ts
agg23-tamagotchi-disassembled-421eacb
[ { "filename": "src/lib/bass.ts", "retrieved_chunk": " });\n } else {\n // This is a literal\n const sortableOpcode = buildSortableOpcode(opcodeString, 0);\n config.instructions.push({\n type: \"literal\",\n regex: cleanAndFinishInstructionRegex(originalInstruction),\n opcodeString,\n sortableOpcode,\n originalInstruction: originalInstruction.trim(),", "score": 0.8256341218948364 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " const matchString = numberMatch[0];\n // This is guaranteed to exist due to the regex\n const bitCount = parseNumber(numberMatch[1]!);\n const index = numberMatch.index;\n const instructionLine =\n originalInstruction.substring(0, index) +\n \"(?:(0x[a-f0-9]+|[0-9]+)|([a-z0-9_]+))\" +\n originalInstruction.substring(index + matchString.length);\n const sortableOpcode = buildSortableOpcode(opcodeString, bitCount);\n config.instructions.push({", "score": 0.8203538656234741 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " type: \"immediate\",\n regex: cleanAndFinishInstructionRegex(instructionLine),\n immediate: {\n bitCount,\n stringIndex: index,\n stringLength: matchString.length,\n },\n opcodeString,\n sortableOpcode,\n originalInstruction: originalInstruction.trim(),", "score": 0.8182759284973145 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " // Force nothing but whitespace and a comment from instruction to end of string\n return new RegExp(\n instructionPrefixRegex.source + cleaned + instructionSuffixRegex.source\n );\n};", "score": 0.8077684640884399 }, { "filename": "src/lib/disassembly.ts", "retrieved_chunk": " if (lineLabel) {\n output += `\\n${lineLabel.name}:\\n`;\n }\n output += ` ${buildDisassembledInstructionString(\n instruction,\n immediateLabel\n )}\\n`;\n address += 1;\n }\n return output;", "score": 0.806488037109375 } ]
typescript
.map((s, i) => {
import { log } from "./log"; import { AssembledProgram, Option } from "./types"; import { maskOfSize } from "./util"; /** * Builds the output buffer from the matched instructions * @param program The configured program we have built * @param word16Align If true, align the 12 bit opcodes to 16 bit words. The lowest nibble will be 0 * @returns The output buffer that should be written to the assembled binary */ export const outputInstructions = ( program: AssembledProgram, word16Align: boolean ): Option<Buffer> => { // This buffer stores each nibble of the program separately, and we will combine this later into the output buffer const threeNibbleBuffer: number[] = new Array(8192 * 3); // Fill array with 0xF for (let i = 0; i < threeNibbleBuffer.length; i++) { threeNibbleBuffer[i] = 0xf; } for (const instruction of program.matchedInstructions) { let opcode = 0; switch (instruction.type) { case "literal": { opcode = buildOpcode(instruction.opcodeString, 0, 0); break; } case "immediate": { opcode = buildOpcode( instruction.opcodeString, instruction.bitCount, instruction.immediate ); break; } case "label": { const label =
program.matchedLabels[instruction.label];
if (!label) { log(`Unknown label ${instruction.label}`, instruction.lineNumber); return { type: "none" }; } opcode = buildOpcode( instruction.opcodeString, instruction.bitCount, label.address ); break; } case "constant": { if (instruction.subtype === "literal") { opcode = instruction.value; } else { // Label const label = program.matchedLabels[instruction.label]; if (!label) { log(`Unknown label ${instruction.label}`, instruction.lineNumber); return { type: "none" }; } console.log(`${label.address.toString(16)}`); opcode = label.address; } break; } } const low = opcode & 0xf; const mid = (opcode & 0xf0) >> 4; const high = (opcode & 0xf00) >> 8; const baseAddress = instruction.address * 3; // We use reverse order because that's how the nibbles are in the ROM threeNibbleBuffer[baseAddress] = high; threeNibbleBuffer[baseAddress + 1] = mid; threeNibbleBuffer[baseAddress + 2] = low; } return { type: "some", value: copyToOutputBuffer(threeNibbleBuffer, word16Align), }; }; const copyToOutputBuffer = ( threeNibbleBuffer: number[], word16Align: boolean ): Buffer => { const bufferSize = word16Align ? 8192 * 2 : (8192 * 3) / 2; const buffer = Buffer.alloc(bufferSize); let byteBuffer = 0; let bufferAddress = 0; let lowNibble = false; let evenByte = true; for (let i = 0; i < threeNibbleBuffer.length; i++) { const nibble = threeNibbleBuffer[i]!; const writeSpacerValue = word16Align && !lowNibble && evenByte; if (lowNibble || writeSpacerValue) { // "Second", lower value of byte, or we're writing the spacer now byteBuffer |= nibble; buffer[bufferAddress] = byteBuffer; bufferAddress += 1; byteBuffer = 0; evenByte = !evenByte; } else { // "First", upper value of byte byteBuffer |= nibble << 4; } if (!writeSpacerValue) { // We've moved to the next byte if we wrote a spacer, so stay at !lowNibble lowNibble = !lowNibble; } } return buffer; }; /** * Comsumes the opcode template from the BASS arch file and produces the actual output word * @param template The opcode template from the BASS arch file * @param argSize The number of bits in an argument to the opcode, if any * @param argument The actual data to pass as an argument to the opcode, if any * @returns The output opcode as a 12 bit word */ export const buildOpcode = ( template: string, argSize: number, argument: number ) => { let index = 0; let outputWord = 0; while (index < template.length) { const char = template[index]; if (char === "%") { // Consume chars until whitespace let data = 0; let count = 0; for (let i = 1; i < Math.min(13, template.length - index); i++) { const nextChar = template[index + i]!; if (nextChar !== "1" && nextChar !== "0") { // Stop consuming break; } data <<= 1; data |= nextChar === "1" ? 1 : 0; count += 1; } // Consume the next four chars as bits outputWord <<= count; outputWord |= data; index += count + 1; } else if (char === "=") { if (template[index + 1] !== "a") { console.log( `ERROR: Unexpected char after = in instruction definition "${template}"` ); return 0; } outputWord <<= argSize; outputWord |= maskOfSize(argSize) & argument; index += 2; } else { index += 1; } } return outputWord; };
src/lib/opcodeOutput.ts
agg23-tamagotchi-disassembled-421eacb
[ { "filename": "src/assembler.ts", "retrieved_chunk": " program.matchedInstructions.push({\n type: \"label\",\n line,\n label: matches[2],\n opcodeString: instruction.opcodeString,\n bitCount: instruction.immediate.bitCount,\n lineNumber,\n address,\n });\n } else {", "score": 0.9028606414794922 }, { "filename": "src/assembler.ts", "retrieved_chunk": " return;\n }\n program.matchedInstructions.push({\n type: \"immediate\",\n line,\n immediate: parseNumber(matches[1]),\n opcodeString: instruction.opcodeString,\n bitCount: instruction.immediate.bitCount,\n lineNumber,\n address,", "score": 0.8759524822235107 }, { "filename": "src/lib/types.ts", "retrieved_chunk": " opcodeString: string;\n};\nexport type LabelMatchedInstruction = MatchedInstructionBase & {\n type: \"label\";\n label: string;\n bitCount: number;\n opcodeString: string;\n};\nexport type LiteralMatchedInstruction = MatchedInstructionBase & {\n type: \"literal\";", "score": 0.8666285276412964 }, { "filename": "src/assembler.ts", "retrieved_chunk": " // literal only\n program.matchedInstructions.push({\n type: \"literal\",\n line,\n opcodeString: instruction.opcodeString,\n lineNumber,\n address,\n });\n }\n hasInstruction = true;", "score": 0.8663293123245239 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " const matchString = numberMatch[0];\n // This is guaranteed to exist due to the regex\n const bitCount = parseNumber(numberMatch[1]!);\n const index = numberMatch.index;\n const instructionLine =\n originalInstruction.substring(0, index) +\n \"(?:(0x[a-f0-9]+|[0-9]+)|([a-z0-9_]+))\" +\n originalInstruction.substring(index + matchString.length);\n const sortableOpcode = buildSortableOpcode(opcodeString, bitCount);\n config.instructions.push({", "score": 0.8648136854171753 } ]
typescript
program.matchedLabels[instruction.label];
import { DisassembledInstruction } from "./types"; import { isLetterChar, maskOfSize } from "./util"; export const buildDisassembledInstructionString = ( { instruction, actualWord, address }: DisassembledInstruction, immediateLabel: string | undefined ) => { let instructionString = instruction.originalInstruction; if (instruction.type === "immediate") { const { bitCount, stringIndex, stringLength } = instruction.immediate; const immediatePrefix = instructionString.substring(0, stringIndex); const immediateSuffix = instructionString.substring( stringIndex + stringLength ); let immediate = ""; if (immediateLabel) { immediate = immediateLabel; } else { const argument = maskOfSize(bitCount) & actualWord; if (isLetterChar(immediatePrefix.charAt(immediatePrefix.length - 1))) { // If letter, treat as decimal immediate = argument.toString(); } else { // Otherwise, treat as hex immediate = `0x${argument.toString(16).toUpperCase()}`; } } instructionString = `${immediatePrefix}${immediate}${immediateSuffix}`; } // Separate out instruction so that it formats nicely // Four total columns // Opcode - Source - Dest - Comments const splitInstruction = instructionString.split(/\s+/); let lastPadWidth = 0; for (let i = 2; i >= splitInstruction.length - 1; i--) { lastPadWidth += columnPadWidth(i); } const formattedInstructionString = splitInstruction .map((
s, i) => {
const pad = i === splitInstruction.length - 1 ? lastPadWidth : columnPadWidth(i); return s.padEnd(pad); }) .join(""); const comment = `// 0x${address .toString(16) .toUpperCase() .padEnd(4)} (0x${actualWord.toString(16).toUpperCase()})`; return `${formattedInstructionString.padEnd(81)}${comment}`; }; const columnPadWidth = (column: number) => { switch (column) { case 0: return 6; case 1: return 5; case 2: return 10; } return 0; };
src/lib/display.ts
agg23-tamagotchi-disassembled-421eacb
[ { "filename": "src/lib/bass.ts", "retrieved_chunk": " });\n } else {\n // This is a literal\n const sortableOpcode = buildSortableOpcode(opcodeString, 0);\n config.instructions.push({\n type: \"literal\",\n regex: cleanAndFinishInstructionRegex(originalInstruction),\n opcodeString,\n sortableOpcode,\n originalInstruction: originalInstruction.trim(),", "score": 0.8298588395118713 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " const matchString = numberMatch[0];\n // This is guaranteed to exist due to the regex\n const bitCount = parseNumber(numberMatch[1]!);\n const index = numberMatch.index;\n const instructionLine =\n originalInstruction.substring(0, index) +\n \"(?:(0x[a-f0-9]+|[0-9]+)|([a-z0-9_]+))\" +\n originalInstruction.substring(index + matchString.length);\n const sortableOpcode = buildSortableOpcode(opcodeString, bitCount);\n config.instructions.push({", "score": 0.8282871246337891 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " type: \"immediate\",\n regex: cleanAndFinishInstructionRegex(instructionLine),\n immediate: {\n bitCount,\n stringIndex: index,\n stringLength: matchString.length,\n },\n opcodeString,\n sortableOpcode,\n originalInstruction: originalInstruction.trim(),", "score": 0.8203908801078796 }, { "filename": "src/lib/bass.ts", "retrieved_chunk": " });\n }\n};\nconst buildSortableOpcode = (template: string, bitCount: number) =>\n buildOpcode(template, bitCount, 0);\nconst cleanAndFinishInstructionRegex = (instruction: string): RegExp => {\n const cleaned = instruction\n .trim()\n .replace(whitespaceRegex, whitespaceRegex.source);\n // Force nothing but whitespace from beginning of string to instruction", "score": 0.8124393224716187 }, { "filename": "src/lib/opcodeOutput.ts", "retrieved_chunk": " let opcode = 0;\n switch (instruction.type) {\n case \"literal\": {\n opcode = buildOpcode(instruction.opcodeString, 0, 0);\n break;\n }\n case \"immediate\": {\n opcode = buildOpcode(\n instruction.opcodeString,\n instruction.bitCount,", "score": 0.8083645701408386 } ]
typescript
s, i) => {
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) irotation: f32, @location(4) isize: f32, } struct VertexOutput { @builtin(position) position: vec4<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; fn rotate(rad: f32) -> mat2x2<f32> { var c: f32 = cos(rad); var s: f32 = sin(rad); return mat2x2<f32>(c, s, -s, c); } @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1); return out; } `; const Fragment = /* wgsl */` @fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(vec3(0.125), 1); } `; class Lines { private readonly bindings: GPUBindGroup; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) { this.geometry = Plane(device); this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, { shaderLocation: 3, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 3 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource:
{ buffer: camera.getBuffer() }, }, ], });
this.simulation = simulation; } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const { lines } = simulation.getBuffers(); pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, lines, 16); pass.drawIndirect(lines, 0); } } export default Lines;
src/render/lines.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {", "score": 0.9469263553619385 }, { "filename": "src/render/points.ts", "retrieved_chunk": " size: [512, 512],\n usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,\n });\n this.bindings = device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: camera.getBuffer() },\n },", "score": 0.9453586339950562 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: joints },\n },\n {\n binding: 1,\n resource: { buffer: lines },", "score": 0.9313647747039795 }, { "filename": "src/compute/simulation/constrain.ts", "retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],", "score": 0.9195787310600281 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " binding: 1,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer, i) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,", "score": 0.8930138349533081 } ]
typescript
{ buffer: camera.getBuffer() }, }, ], });
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) irotation: f32, @location(4) isize: f32, } struct VertexOutput { @builtin(position) position: vec4<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; fn rotate(rad: f32) -> mat2x2<f32> { var c: f32 = cos(rad); var s: f32 = sin(rad); return mat2x2<f32>(c, s, -s, c); } @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1); return out; } `; const Fragment = /* wgsl */` @fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(vec3(0.125), 1); } `; class Lines { private readonly bindings: GPUBindGroup; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) { this.
geometry = Plane(device);
this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, { shaderLocation: 3, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 3 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: camera.getBuffer() }, }, ], }); this.simulation = simulation; } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const { lines } = simulation.getBuffers(); pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, lines, 16); pass.drawIndirect(lines, 0); } } export default Lines;
src/render/lines.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/points.ts", "retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {", "score": 0.942392885684967 }, { "filename": "src/render/points.ts", "retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,", "score": 0.8859769105911255 }, { "filename": "src/render/renderer.ts", "retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');", "score": 0.8779411911964417 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " private readonly position: vec2;\n constructor(device: GPUDevice) {\n this.aspect = 1;\n this.near = -100;\n this.far = 100;\n this.zoom = 200;\n this.position = vec2.create();\n this.matrix = mat4.create();\n this.matrixInverse = mat4.create();\n this.device = device;", "score": 0.866797924041748 }, { "filename": "src/render/geometry.ts", "retrieved_chunk": "export const Plane = (device: GPUDevice, width: number = 1, height: number = 1) => {\n const buffer = device.createBuffer({\n mappedAtCreation: true,\n size: 24 * Float32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.VERTEX,\n });\n new Float32Array(buffer.getMappedRange()).set([\n width * -0.5, height * 0.5, 0, 1,\n width * 0.5, height * 0.5, 1, 1,\n width * 0.5, height * -0.5, 1, 0,", "score": 0.861384391784668 } ]
typescript
geometry = Plane(device);
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) irotation: f32, @location(4) isize: f32, } struct VertexOutput { @builtin(position) position: vec4<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; fn rotate(rad: f32) -> mat2x2<f32> { var c: f32 = cos(rad); var s: f32 = sin(rad); return mat2x2<f32>(c, s, -s, c); } @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1); return out; } `; const Fragment = /* wgsl */` @fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(vec3(0.125), 1); } `; class Lines { private readonly bindings: GPUBindGroup; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) { this.geometry = Plane(device); this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, { shaderLocation: 3, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 3 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: camera.getBuffer() }, }, ], }); this.simulation = simulation; } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const {
lines } = simulation.getBuffers();
pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, lines, 16); pass.drawIndirect(lines, 0); } } export default Lines;
src/render/lines.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/points.ts", "retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);", "score": 0.9331257343292236 }, { "filename": "src/render/renderer.ts", "retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');", "score": 0.8513774275779724 }, { "filename": "src/render/points.ts", "retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,", "score": 0.8507723808288574 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default StepSimulation;", "score": 0.8507288098335266 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default ComputeLines;", "score": 0.8435138463973999 } ]
typescript
lines } = simulation.getBuffers();
import { Joint, JointBuffer, Point, PointBuffers } from '../simulation/types'; export default (large: boolean = false, tension: boolean = false) => { const width = large ? 65 : 33; const height = large ? 65 : 33; const gap = 4; const points: Point[] = []; const joints: Joint[] = []; for (let i = 0, y = 0; y < height; y++) { for (let x = 0; x < width; x++, i++) { points.push({ locked: tension ? ( ((y === 0 || y === height - 1) && (x % 8 === 0)) || ((x === 0 || x === width - 1) && (y % 8 === 0)) ) : ( y === height - 1 && (x % 8 === 0) ), position: { x: (x - width * 0.5 + 0.5) * gap * 1.125 + gap * (Math.random() - 0.25) * 0.125, y: (y - height * 0.5 + 0.5) * gap + gap * (Math.random() - 0.5) * 0.125 + height * gap * 0.2, }, size: 1.5 + Math.random() * 0.5, uv: { x: (x + 0.5) / width, y: (y + 0.5) / height, }, }); if (x < width - 1) { joints.push({ enabled: true, a: i, b: i + 1, length: 0, }); } if (y > 0) { joints.push({ enabled: true, a: i, b: i - width, length: 0, }); } } } joints.forEach((joint) => { const a = points
[joint.a].position;
const b = points[joint.b].position; joint.length = Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); }); if (tension || large) { points.forEach(({ position }) => { if (tension) position.x *= 1.25; position.y = (position.y - height * gap * 0.2) * 1.4; }); } return { ...PointBuffers(points), joints: JointBuffer(joints), numJoints: joints.length, numPoints: points.length, }; }
src/compute/generation/cloth.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/generation/ropes.ts", "retrieved_chunk": " });\n if (i >= 3 && i < length - 1) {\n joints.push({\n enabled: true,\n a: o + i,\n b: o + i + 1,\n length: 4,\n });\n }\n }", "score": 0.8779510855674744 }, { "filename": "src/compute/generation/ropes.ts", "retrieved_chunk": " points[o + 2].position.x -= 4;\n points[o + 1].position.x += 4;\n [\n [3, 2],\n [3, 1],\n [2, 1],\n [2, 0],\n [1, 0],\n ].forEach(([a, b]) => joints.push({\n enabled: true,", "score": 0.8701297044754028 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " return;\n }\n }\n var origin = (points[joint.a] + points[joint.b]) * 0.5;\n var line = points[joint.a] - points[joint.b];\n var direction = normalize(line);\n var rotation = atan2(direction.x, direction.y);\n var size = length(line);\n var instance = atomicAdd(&lines.instanceCount, 1);\n lines.data[instance].position = origin;", "score": 0.8645236492156982 }, { "filename": "src/compute/generation/ropes.ts", "retrieved_chunk": " a: o + a,\n b: o + b,\n length: 8,\n }));\n }\n return {\n ...PointBuffers(points),\n joints: JointBuffer(joints),\n numJoints: joints.length,\n numPoints: points.length,", "score": 0.8553808927536011 }, { "filename": "src/compute/generation/ropes.ts", "retrieved_chunk": "import { Joint, JointBuffer, Point, PointBuffers } from '../simulation/types';\nexport default () => {\n const points: Point[] = [];\n const joints: Joint[] = [];\n const length = 33;\n for (let j = 0, i = 0; j < 2; j++) {\n let o = i;\n let x = 64 * (j === 0 ? -1 : 1);\n for (i = 0; i < length; i++) {\n points.push({", "score": 0.8525844812393188 } ]
typescript
[joint.a].position;
import ConstrainSimulation from './constrain'; import ComputeLines from './lines'; import StepSimulation from './step'; import { LineBuffer, UniformsBuffer } from './types'; class Simulation { private buffers?: { data: GPUBuffer; joints: GPUBuffer; lines: GPUBuffer; points: GPUBuffer[]; }; private count: number = 0; private device: GPUDevice; private initial?: { joints: ArrayBuffer; points: ArrayBuffer; }; private pipelines?: { constraint: ConstrainSimulation, lines: ComputeLines, step: StepSimulation, }; private step: number = 0; private readonly uniforms: UniformsBuffer; constructor(device: GPUDevice) { this.device = device; this.uniforms = new UniformsBuffer(device); } compute( command: GPUCommandEncoder, delta: number, pointer: { button: number; position: [number, number] | Float32Array; }, radius: number ) { const { buffers, pipelines, step, uniforms } = this; if (!buffers || !pipelines) { return; } uniforms.delta = delta; uniforms.button = pointer.button; uniforms.pointer = pointer.position; uniforms.radius = radius; uniforms.update(); const pass = command.beginComputePass(); pipelines.
step.compute(pass, step);
this.step = (this.step + 1) % 2; pipelines.constraint.compute(pass, this.step); pipelines.lines.compute(pass, this.step); pass.end(); } getBuffers() { const { buffers, count, step } = this; if (!buffers) { throw new Error("Simulation is not loaded"); } return { count, data: buffers.data, lines: buffers.lines, points: buffers.points[step], }; } load( { data, joints, numJoints, points, numPoints }: { data: ArrayBuffer; joints: ArrayBuffer; numJoints: number; points: ArrayBuffer; numPoints: number; } ) { const { device } = this; const createBuffer = (data: ArrayBuffer, usage: number) => { const buffer = device.createBuffer({ mappedAtCreation: true, size: data.byteLength, usage, }); new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data)); buffer.unmap(); return buffer; }; if (this.buffers) { this.buffers.data.destroy(); this.buffers.joints.destroy(); this.buffers.lines.destroy(); this.buffers.points.forEach((buffer) => buffer.destroy()); } this.buffers = { data: createBuffer( data, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX ), joints: createBuffer( joints, GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE ), lines: LineBuffer(device, numJoints), points: Array.from({ length: 2 }, () => createBuffer( points, GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX )), }; this.count = numPoints; this.initial = { joints, points }; this.pipelines = { constraint: new ConstrainSimulation( device, this.buffers.data, this.buffers.joints, numJoints, this.buffers.lines, this.buffers.points, numPoints ), lines: new ComputeLines( device, this.buffers.joints, numJoints, this.buffers.lines, this.buffers.points, numPoints, this.uniforms.getBuffer() ), step: new StepSimulation( device, this.buffers.data, this.buffers.points, numPoints, this.uniforms.getBuffer() ), }; } reset() { const { buffers, device, initial } = this; if (!buffers || !initial) { return; } device.queue.writeBuffer(buffers.joints, 0, initial.joints); buffers.points.forEach((buffer) => ( device.queue.writeBuffer(buffer, 0, initial.points) )); } } export default Simulation;
src/compute/simulation/index.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/simulation/constrain.ts", "retrieved_chunk": " })),\n };\n }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(1);\n }", "score": 0.8650021553039551 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default ComputeLines;", "score": 0.8604846596717834 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default StepSimulation;", "score": 0.8518841862678528 }, { "filename": "src/compute/simulation/types.ts", "retrieved_chunk": " set delta(value: number) {\n new Float32Array(this.buffers.cpu, 4, 1)[0] = value;\n }\n set pointer(value: [number, number] | Float32Array) {\n new Float32Array(this.buffers.cpu, 8, 2).set(value);\n }\n set radius(value: number) {\n new Float32Array(this.buffers.cpu, 16, 1)[0] = value;\n }\n update() {", "score": 0.8514871597290039 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " let index: u32 = id.x;\n if (index >= ${numPoints}) {\n return;\n }\n var point = input[index];\n if (data[index].locked == 0) {\n point += point - output[index];\n point += vec2<f32>(0, -8) * uniforms.delta;\n if (uniforms.button != 2) {\n var d = point - uniforms.pointer;", "score": 0.8311224579811096 } ]
typescript
step.compute(pass, step);
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) isize: f32, @location(4) iuv: vec2<f32>, } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) size: f32, @location(1) uv: vec2<f32>, @location(2) uv2: vec2<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1); out.size = vertex.isize; out.uv = (vertex.uv - 0.5) * 2; out.uv2 = vertex.iuv; return out; } `; const Fragment = /* wgsl */` struct FragmentInput { @location(0) size: f32, @location(1) uv: vec2<f32>, @location(2) uv2: vec2<f32>, } @group(0) @binding(1) var texture: texture_2d<f32>; @group(0) @binding(2) var textureSampler: sampler; fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> { if (all(linear <= vec3<f32>(0.0031308))) { return linear * 12.92; } return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055); } @fragment fn main(fragment: FragmentInput) -> @location(0) vec4<f32> { let l = min(length(fragment.uv), 1); var uv = fragment.uv2 + (fragment.uv / fragment.size / 33); return vec4<f32>(linearTosRGB( textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1 ), smoothstep(1, 0.8, l)); } `; class Points { private readonly bindings: GPUBindGroup; private readonly device: GPUDevice; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; private readonly texture: GPUTexture; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) { this.device = device;
this.geometry = Plane(device, 2, 2);
this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 1 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add', }, alpha: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add', }, }, }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.texture = device.createTexture({ dimension: '2d', format: 'rgba8unorm-srgb', size: [512, 512], usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: camera.getBuffer() }, }, { binding: 1, resource: this.texture.createView(), }, { binding: 2, resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }), }, ], }); this.simulation = simulation; this.generateDefaultTexture(); } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const { count, data, points } = simulation.getBuffers(); pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, points); pass.setVertexBuffer(2, data); pass.draw(6, count, 0, 0); } setTexture(file: Blob) { const image = new Image(); image.addEventListener('load', () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } let x = 0; let y = 0; let w = canvas.width = 512; let h = canvas.height = 512; if (image.width / image.height > w / h) { w = image.width * canvas.height / image.height; x = (canvas.width - w) * 0.5; } else { h = image.height * canvas.width / image.width; y = (canvas.height - h) * 0.5; } ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h); this.updateTexture(canvas); }); image.src = URL.createObjectURL(file); } private generateDefaultTexture() { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } canvas.width = canvas.height = 512; for (let i = 0; i < 256; i++) { ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`; ctx.beginPath(); ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2); ctx.fill(); } this.updateTexture(canvas); } private async updateTexture(canvas: HTMLCanvasElement) { const { device, texture } = this; const source = await createImageBitmap(canvas) device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]); } } export default Points;
src/render/points.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/lines.ts", "retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.geometry = Plane(device);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {\n buffers: [", "score": 0.9426939487457275 }, { "filename": "src/render/renderer.ts", "retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');", "score": 0.8810195922851562 }, { "filename": "src/render/geometry.ts", "retrieved_chunk": "export const Plane = (device: GPUDevice, width: number = 1, height: number = 1) => {\n const buffer = device.createBuffer({\n mappedAtCreation: true,\n size: 24 * Float32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.VERTEX,\n });\n new Float32Array(buffer.getMappedRange()).set([\n width * -0.5, height * 0.5, 0, 1,\n width * 0.5, height * 0.5, 1, 1,\n width * 0.5, height * -0.5, 1, 0,", "score": 0.8706897497177124 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " private readonly position: vec2;\n constructor(device: GPUDevice) {\n this.aspect = 1;\n this.near = -100;\n this.far = 100;\n this.zoom = 200;\n this.position = vec2.create();\n this.matrix = mat4.create();\n this.matrixInverse = mat4.create();\n this.device = device;", "score": 0.869762122631073 }, { "filename": "src/render/lines.ts", "retrieved_chunk": " return vec4<f32>(vec3(0.125), 1);\n}\n`;\nclass Lines {\n private readonly bindings: GPUBindGroup;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n constructor(\n camera: Camera,", "score": 0.8527339100837708 } ]
typescript
this.geometry = Plane(device, 2, 2);
import { vec2 } from 'gl-matrix'; import Camera from '../render/camera'; class Input { private hotkeys: Record<string, () => void> = {}; private readonly pointer: { id: number; button: number; normalized: vec2; position: vec2; }; constructor(target: HTMLCanvasElement) { this.pointer = { id: -1, button: 0, normalized: vec2.fromValues(-1, -1), position: vec2.create(), }; window.addEventListener('keydown', this.onKeyDown.bind(this)); target.addEventListener('pointerdown', this.onPointerDown.bind(this)); window.addEventListener('pointermove', this.onPointerMove.bind(this)); target.addEventListener('pointerup', this.onPointerUp.bind(this)); { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } canvas.width = 20; canvas.height = 20; ctx.lineWidth = 5; ctx.strokeStyle = '#111'; ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = 3; ctx.strokeStyle = '#eee'; ctx.stroke(); canvas.toBlob((blob) => { if (blob) { document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`; } }); } } getPointer(camera:
Camera) {
const { pointer } = this; vec2.transformMat4( pointer.position, pointer.normalized, camera.getMatrixInverse() ); return pointer; } setHotkeys(hotkeys: Record<string, () => void>) { this.hotkeys = hotkeys; } private onKeyDown({ key, repeat, target }: KeyboardEvent) { const { hotkeys } = this; const handler = hotkeys[key.toLowerCase()]; if ( handler && !repeat && !['input', 'textarea', 'select'].includes( (target as HTMLElement).tagName.toLowerCase() ) ) { handler(); } } private onPointerDown({ buttons, pointerId, target }: PointerEvent) { (target as HTMLCanvasElement).setPointerCapture(pointerId); const { pointer } = this; if (pointer.id !== -1) { return; } pointer.id = pointerId; pointer.button = buttons; } private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) { const { pointer } = this; if (pointer.id !== -1 && pointer.id !== pointerId) { return; } vec2.set( pointer.normalized, (clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1 ); } private onPointerUp({ pointerId, target }: PointerEvent) { (target as HTMLCanvasElement).releasePointerCapture(pointerId); const { pointer } = this; if (pointer.id !== pointerId) { return; } pointer.id = -1; pointer.button = 0; } } export default Input;
src/compute/input.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/points.ts", "retrieved_chunk": " ctx.fill();\n }\n this.updateTexture(canvas);\n }\n private async updateTexture(canvas: HTMLCanvasElement) {\n const { device, texture } = this;\n const source = await createImageBitmap(canvas)\n device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);\n }\n}", "score": 0.8355469703674316 }, { "filename": "src/render/renderer.ts", "retrieved_chunk": " target,\n } = this;\n const pixelRatio = window.devicePixelRatio || 1;\n const size = [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)];\n canvas.width = size[0];\n canvas.height = size[1];\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n camera.setAspect(width / height);\n if (target) {", "score": 0.8263350129127502 }, { "filename": "src/render/points.ts", "retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {", "score": 0.8217974305152893 }, { "filename": "src/main.ts", "retrieved_chunk": " points.setTexture(file);\n }\n });\n window.addEventListener('resize', () => (\n renderer.setSize(window.innerWidth, window.innerHeight)\n ));\n window.addEventListener('wheel', ({ deltaY }) => (\n camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400))\n ));\n};", "score": 0.8206039667129517 }, { "filename": "src/render/points.ts", "retrieved_chunk": " const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = canvas.height = 512;\n for (let i = 0; i < 256; i++) {\n ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;\n ctx.beginPath();\n ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);", "score": 0.8174746632575989 } ]
typescript
Camera) {
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) irotation: f32, @location(4) isize: f32, } struct VertexOutput { @builtin(position) position: vec4<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; fn rotate(rad: f32) -> mat2x2<f32> { var c: f32 = cos(rad); var s: f32 = sin(rad); return mat2x2<f32>(c, s, -s, c); } @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1); return out; } `; const Fragment = /* wgsl */` @fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(vec3(0.125), 1); } `; class Lines { private readonly bindings: GPUBindGroup; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) {
this.geometry = Plane(device);
this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, { shaderLocation: 3, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 3 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: camera.getBuffer() }, }, ], }); this.simulation = simulation; } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const { lines } = simulation.getBuffers(); pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, lines, 16); pass.drawIndirect(lines, 0); } } export default Lines;
src/render/lines.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/points.ts", "retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {", "score": 0.9428656697273254 }, { "filename": "src/render/points.ts", "retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,", "score": 0.8971647024154663 }, { "filename": "src/render/renderer.ts", "retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');", "score": 0.89287930727005 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " private readonly position: vec2;\n constructor(device: GPUDevice) {\n this.aspect = 1;\n this.near = -100;\n this.far = 100;\n this.zoom = 200;\n this.position = vec2.create();\n this.matrix = mat4.create();\n this.matrixInverse = mat4.create();\n this.device = device;", "score": 0.8671592473983765 }, { "filename": "src/render/points.ts", "retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);", "score": 0.8628442287445068 } ]
typescript
this.geometry = Plane(device);
import { vec2 } from 'gl-matrix'; import Camera from '../render/camera'; class Input { private hotkeys: Record<string, () => void> = {}; private readonly pointer: { id: number; button: number; normalized: vec2; position: vec2; }; constructor(target: HTMLCanvasElement) { this.pointer = { id: -1, button: 0, normalized: vec2.fromValues(-1, -1), position: vec2.create(), }; window.addEventListener('keydown', this.onKeyDown.bind(this)); target.addEventListener('pointerdown', this.onPointerDown.bind(this)); window.addEventListener('pointermove', this.onPointerMove.bind(this)); target.addEventListener('pointerup', this.onPointerUp.bind(this)); { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } canvas.width = 20; canvas.height = 20; ctx.lineWidth = 5; ctx.strokeStyle = '#111'; ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = 3; ctx.strokeStyle = '#eee'; ctx.stroke(); canvas.toBlob((blob) => { if (blob) { document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`; } }); } } getPointer(camera: Camera) { const { pointer } = this; vec2.transformMat4( pointer.position, pointer.normalized,
camera.getMatrixInverse() );
return pointer; } setHotkeys(hotkeys: Record<string, () => void>) { this.hotkeys = hotkeys; } private onKeyDown({ key, repeat, target }: KeyboardEvent) { const { hotkeys } = this; const handler = hotkeys[key.toLowerCase()]; if ( handler && !repeat && !['input', 'textarea', 'select'].includes( (target as HTMLElement).tagName.toLowerCase() ) ) { handler(); } } private onPointerDown({ buttons, pointerId, target }: PointerEvent) { (target as HTMLCanvasElement).setPointerCapture(pointerId); const { pointer } = this; if (pointer.id !== -1) { return; } pointer.id = pointerId; pointer.button = buttons; } private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) { const { pointer } = this; if (pointer.id !== -1 && pointer.id !== pointerId) { return; } vec2.set( pointer.normalized, (clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1 ); } private onPointerUp({ pointerId, target }: PointerEvent) { (target as HTMLCanvasElement).releasePointerCapture(pointerId); const { pointer } = this; if (pointer.id !== pointerId) { return; } pointer.id = -1; pointer.button = 0; } } export default Input;
src/compute/input.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/camera.ts", "retrieved_chunk": "import { mat4, vec2 } from 'gl-matrix';\nclass Camera {\n private readonly device: GPUDevice;\n private readonly buffer: GPUBuffer;\n private aspect: number;\n private near: number;\n private far: number;\n private zoom: number;\n private readonly matrix: mat4;\n private readonly matrixInverse: mat4;", "score": 0.8322885036468506 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " this.update();\n }\n private update() {\n const {\n device, buffer,\n matrix, matrixInverse,\n aspect, near, far, zoom, position,\n } = this;\n const x = zoom * aspect * 0.5;\n const y = zoom * 0.5;", "score": 0.820197582244873 }, { "filename": "src/compute/simulation/index.ts", "retrieved_chunk": " delta: number,\n pointer: { button: number; position: [number, number] | Float32Array; },\n radius: number\n ) {\n const { buffers, pipelines, step, uniforms } = this;\n if (!buffers || !pipelines) {\n return;\n }\n uniforms.delta = delta;\n uniforms.button = pointer.button;", "score": 0.8197986483573914 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " private readonly position: vec2;\n constructor(device: GPUDevice) {\n this.aspect = 1;\n this.near = -100;\n this.far = 100;\n this.zoom = 200;\n this.position = vec2.create();\n this.matrix = mat4.create();\n this.matrixInverse = mat4.create();\n this.device = device;", "score": 0.816789984703064 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " mat4.ortho(\n matrix,\n position[0] - x, position[0] + x,\n position[1] - y, position[1] + y,\n near, far\n );\n mat4.invert(matrixInverse, matrix);\n device.queue.writeBuffer(buffer, 0, matrix as Float32Array);\n }\n}", "score": 0.809978723526001 } ]
typescript
camera.getMatrixInverse() );
import ConstrainSimulation from './constrain'; import ComputeLines from './lines'; import StepSimulation from './step'; import { LineBuffer, UniformsBuffer } from './types'; class Simulation { private buffers?: { data: GPUBuffer; joints: GPUBuffer; lines: GPUBuffer; points: GPUBuffer[]; }; private count: number = 0; private device: GPUDevice; private initial?: { joints: ArrayBuffer; points: ArrayBuffer; }; private pipelines?: { constraint: ConstrainSimulation, lines: ComputeLines, step: StepSimulation, }; private step: number = 0; private readonly uniforms: UniformsBuffer; constructor(device: GPUDevice) { this.device = device; this.uniforms = new UniformsBuffer(device); } compute( command: GPUCommandEncoder, delta: number, pointer: { button: number; position: [number, number] | Float32Array; }, radius: number ) { const { buffers, pipelines, step, uniforms } = this; if (!buffers || !pipelines) { return; } uniforms.delta = delta; uniforms.button = pointer.button; uniforms.pointer = pointer.position; uniforms.radius = radius; uniforms.update(); const pass = command.beginComputePass(); pipelines.step.compute(pass, step); this.step = (this.step + 1) % 2;
pipelines.constraint.compute(pass, this.step);
pipelines.lines.compute(pass, this.step); pass.end(); } getBuffers() { const { buffers, count, step } = this; if (!buffers) { throw new Error("Simulation is not loaded"); } return { count, data: buffers.data, lines: buffers.lines, points: buffers.points[step], }; } load( { data, joints, numJoints, points, numPoints }: { data: ArrayBuffer; joints: ArrayBuffer; numJoints: number; points: ArrayBuffer; numPoints: number; } ) { const { device } = this; const createBuffer = (data: ArrayBuffer, usage: number) => { const buffer = device.createBuffer({ mappedAtCreation: true, size: data.byteLength, usage, }); new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data)); buffer.unmap(); return buffer; }; if (this.buffers) { this.buffers.data.destroy(); this.buffers.joints.destroy(); this.buffers.lines.destroy(); this.buffers.points.forEach((buffer) => buffer.destroy()); } this.buffers = { data: createBuffer( data, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX ), joints: createBuffer( joints, GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE ), lines: LineBuffer(device, numJoints), points: Array.from({ length: 2 }, () => createBuffer( points, GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX )), }; this.count = numPoints; this.initial = { joints, points }; this.pipelines = { constraint: new ConstrainSimulation( device, this.buffers.data, this.buffers.joints, numJoints, this.buffers.lines, this.buffers.points, numPoints ), lines: new ComputeLines( device, this.buffers.joints, numJoints, this.buffers.lines, this.buffers.points, numPoints, this.uniforms.getBuffer() ), step: new StepSimulation( device, this.buffers.data, this.buffers.points, numPoints, this.uniforms.getBuffer() ), }; } reset() { const { buffers, device, initial } = this; if (!buffers || !initial) { return; } device.queue.writeBuffer(buffers.joints, 0, initial.joints); buffers.points.forEach((buffer) => ( device.queue.writeBuffer(buffer, 0, initial.points) )); } } export default Simulation;
src/compute/simulation/index.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/simulation/constrain.ts", "retrieved_chunk": " })),\n };\n }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(1);\n }", "score": 0.8682354688644409 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default ComputeLines;", "score": 0.859962522983551 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default StepSimulation;", "score": 0.8576599359512329 }, { "filename": "src/compute/simulation/types.ts", "retrieved_chunk": " set delta(value: number) {\n new Float32Array(this.buffers.cpu, 4, 1)[0] = value;\n }\n set pointer(value: [number, number] | Float32Array) {\n new Float32Array(this.buffers.cpu, 8, 2).set(value);\n }\n set radius(value: number) {\n new Float32Array(this.buffers.cpu, 16, 1)[0] = value;\n }\n update() {", "score": 0.8570863604545593 }, { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " let index: u32 = id.x;\n if (index >= ${numPoints}) {\n return;\n }\n var point = input[index];\n if (data[index].locked == 0) {\n point += point - output[index];\n point += vec2<f32>(0, -8) * uniforms.delta;\n if (uniforms.button != 2) {\n var d = point - uniforms.pointer;", "score": 0.8373245596885681 } ]
typescript
pipelines.constraint.compute(pass, this.step);
import Camera from './camera'; class Renderer { private readonly animation: { clock: number; loop: (command: GPUCommandEncoder, delta: number, time: number) => void; request: number; }; private readonly camera: Camera; private readonly canvas: HTMLCanvasElement; private readonly context: GPUCanvasContext; private readonly descriptor: GPURenderPassDescriptor; private readonly device: GPUDevice; private readonly format: GPUTextureFormat; private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[]; private readonly samples: number = 4; private target: GPUTexture = undefined as unknown as GPUTexture; constructor(camera: Camera, device: GPUDevice) { this.camera = camera; this.canvas = document.createElement('canvas'); const context = this.canvas.getContext('webgpu'); if (!context) { throw new Error("Couldn't get GPUCanvasContext"); } this.context = context; this.format = navigator.gpu.getPreferredCanvasFormat(); this.context.configure({ alphaMode: 'opaque', device, format: this.format }); this.descriptor = { colorAttachments: [ { clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: 'clear', storeOp: 'store', view: undefined as unknown as GPUTextureView, }, ], }; this.device = device; this.objects = []; this.animate = this.animate.bind(this); this.animation = { clock: performance.now() / 1000, loop: () => {}, request: requestAnimationFrame(this.animate), }; this.visibilitychange = this.visibilitychange.bind(this); document.addEventListener('visibilitychange', this.visibilitychange); } add(object: { render: (pass: GPURenderPassEncoder) => void }) { this.objects.push(object); } getCanvas() { return this.canvas; } getFormat() { return this.format; } getSamples() { return this.samples; } setAnimationLoop(loop: (command: GPUCommandEncoder, delta: number, time: number) => void) { this.animation.loop = loop; } setSize(width: number, height: number) { const { camera, canvas, descriptor: { colorAttachments: [color] }, device, format, samples, target, } = this; const pixelRatio = window.devicePixelRatio || 1; const size = [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)]; canvas.width = size[0]; canvas.height = size[1]; canvas.style.width = `${width}px`; canvas.style.height = `${height}px`;
camera.setAspect(width / height);
if (target) { target.destroy(); } this.target = device.createTexture({ format, sampleCount: samples, size, usage: GPUTextureUsage.RENDER_ATTACHMENT, }); color!.view = this.target.createView(); } private animate() { const { animation, device } = this; const time = performance.now() / 1000; const delta = Math.min(time - animation.clock, 0.1); animation.clock = time; animation.request = requestAnimationFrame(this.animate); const command = device.createCommandEncoder(); animation.loop(command, delta, time); this.render(command); device.queue.submit([command.finish()]); } private render(command: GPUCommandEncoder) { const { context, descriptor, objects, } = this; const { colorAttachments: [color] } = descriptor; color!.resolveTarget = context.getCurrentTexture().createView(); const pass = command.beginRenderPass(descriptor); objects.forEach((object) => object.render(pass)); pass.end(); } private visibilitychange() { const { animation } = this; cancelAnimationFrame(animation.request); if (document.visibilityState === 'visible') { animation.clock = performance.now() / 1000; animation.request = requestAnimationFrame(this.animate); } } } export default Renderer;
src/render/renderer.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/render/points.ts", "retrieved_chunk": " }\n let x = 0;\n let y = 0;\n let w = canvas.width = 512;\n let h = canvas.height = 512;\n if (image.width / image.height > w / h) {\n w = image.width * canvas.height / image.height;\n x = (canvas.width - w) * 0.5;\n } else {\n h = image.height * canvas.width / image.width;", "score": 0.8612279295921326 }, { "filename": "src/render/camera.ts", "retrieved_chunk": " this.update();\n }\n private update() {\n const {\n device, buffer,\n matrix, matrixInverse,\n aspect, near, far, zoom, position,\n } = this;\n const x = zoom * aspect * 0.5;\n const y = zoom * 0.5;", "score": 0.850365936756134 }, { "filename": "src/main.ts", "retrieved_chunk": " points.setTexture(file);\n }\n });\n window.addEventListener('resize', () => (\n renderer.setSize(window.innerWidth, window.innerHeight)\n ));\n window.addEventListener('wheel', ({ deltaY }) => (\n camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400))\n ));\n};", "score": 0.8439004421234131 }, { "filename": "src/render/points.ts", "retrieved_chunk": " const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = canvas.height = 512;\n for (let i = 0; i < 256; i++) {\n ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;\n ctx.beginPath();\n ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);", "score": 0.8392263650894165 }, { "filename": "src/render/points.ts", "retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {", "score": 0.8345401883125305 } ]
typescript
camera.setAspect(width / height);
import './main.css'; import Camera from './render/camera'; import Input from './compute/input'; import Lines from './render/lines'; import Points from './render/points'; import Renderer from './render/renderer'; import Simulation from './compute/simulation'; import { Cloth, Ropes } from './compute/generation'; const Main = (device: GPUDevice) => { const dom = document.getElementById('app'); if (!dom) { throw new Error("Couldn't get app DOM node"); } const camera = new Camera(device); const renderer = new Renderer(camera, device); const input = new Input(renderer.getCanvas()); const simulation = new Simulation(device); dom.appendChild(renderer.getCanvas()); renderer.setAnimationLoop((command, delta) => ( simulation.compute(command, delta, input.getPointer(camera), camera.getZoom() * 0.02) )); renderer.setSize(window.innerWidth, window.innerHeight); simulation.load(Cloth()); const lines = new Lines(camera, device, renderer.getFormat(), renderer.getSamples(), simulation); renderer.add(lines); const points = new Points(camera, device, renderer.getFormat(), renderer.getSamples(), simulation); renderer.add(points); input.setHotkeys({ 1: () => simulation.load(Cloth()), 2: () => simulation.load(Cloth(false, true)), 3: () => simulation.load(Ropes()), 4: () => simulation.load(Cloth(true, false)), 5: () => simulation.load(Cloth(true, true)), escape: () => simulation.reset(), '?': () => document.getElementById('help')?.classList.toggle('hidden'), }); window.addEventListener('drop', (e) => { e.preventDefault(); const [file] = e.dataTransfer?.files || []; if (file && file.type.indexOf('image/') === 0) { points
.setTexture(file);
} }); window.addEventListener('resize', () => ( renderer.setSize(window.innerWidth, window.innerHeight) )); window.addEventListener('wheel', ({ deltaY }) => ( camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400)) )); }; const GPU = async () => { if (!navigator.gpu) { throw new Error("Couldn't load WebGPU"); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw new Error("Couldn't load WebGPU adapter"); } const device = await adapter.requestDevice(); if (!device) { throw new Error("Couldn't load WebGPU device"); } return device; }; const prevent = (e: DragEvent | MouseEvent | TouchEvent) => e.preventDefault(); window.addEventListener('contextmenu', prevent); window.addEventListener('dragenter', prevent); window.addEventListener('dragover', prevent); window.addEventListener('touchstart', prevent); GPU() .then(Main) .catch((e) => { document.getElementById('error')!.innerText = e.message; document.getElementById('support')!.classList.remove('hidden'); }) .finally(() => document.getElementById('loading')!.classList.add('hidden'));
src/main.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/input.ts", "retrieved_chunk": " ctx.strokeStyle = '#111';\n ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);\n ctx.stroke();\n ctx.lineWidth = 3;\n ctx.strokeStyle = '#eee';\n ctx.stroke();\n canvas.toBlob((blob) => {\n if (blob) {\n document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;\n }", "score": 0.8029736876487732 }, { "filename": "src/render/points.ts", "retrieved_chunk": " pass.setVertexBuffer(2, data);\n pass.draw(6, count, 0, 0);\n }\n setTexture(file: Blob) {\n const image = new Image();\n image.addEventListener('load', () => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");", "score": 0.8026083707809448 }, { "filename": "src/compute/input.ts", "retrieved_chunk": " target.addEventListener('pointerup', this.onPointerUp.bind(this));\n {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = 20;\n canvas.height = 20;\n ctx.lineWidth = 5;", "score": 0.8021779656410217 }, { "filename": "src/compute/simulation/index.ts", "retrieved_chunk": " };\n }\n load(\n { data, joints, numJoints, points, numPoints }: {\n data: ArrayBuffer;\n joints: ArrayBuffer;\n numJoints: number;\n points: ArrayBuffer;\n numPoints: number;\n }", "score": 0.7980535626411438 }, { "filename": "src/compute/input.ts", "retrieved_chunk": " return;\n }\n vec2.set(\n pointer.normalized,\n (clientX / window.innerWidth) * 2 - 1,\n -(clientY / window.innerHeight) * 2 + 1\n );\n }\n private onPointerUp({ pointerId, target }: PointerEvent) {\n (target as HTMLCanvasElement).releasePointerCapture(pointerId);", "score": 0.7949607372283936 } ]
typescript
.setTexture(file);
import Camera from './camera'; import { Plane } from './geometry'; import Simulation from '../compute/simulation'; const Vertex = /* wgsl */` struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) iposition: vec2<f32>, @location(3) isize: f32, @location(4) iuv: vec2<f32>, } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) size: f32, @location(1) uv: vec2<f32>, @location(2) uv2: vec2<f32>, } @group(0) @binding(0) var<uniform> camera: mat4x4<f32>; @vertex fn main(vertex: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1); out.size = vertex.isize; out.uv = (vertex.uv - 0.5) * 2; out.uv2 = vertex.iuv; return out; } `; const Fragment = /* wgsl */` struct FragmentInput { @location(0) size: f32, @location(1) uv: vec2<f32>, @location(2) uv2: vec2<f32>, } @group(0) @binding(1) var texture: texture_2d<f32>; @group(0) @binding(2) var textureSampler: sampler; fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> { if (all(linear <= vec3<f32>(0.0031308))) { return linear * 12.92; } return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055); } @fragment fn main(fragment: FragmentInput) -> @location(0) vec4<f32> { let l = min(length(fragment.uv), 1); var uv = fragment.uv2 + (fragment.uv / fragment.size / 33); return vec4<f32>(linearTosRGB( textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1 ), smoothstep(1, 0.8, l)); } `; class Points { private readonly bindings: GPUBindGroup; private readonly device: GPUDevice; private readonly geometry: GPUBuffer; private readonly pipeline: GPURenderPipeline; private readonly simulation: Simulation; private readonly texture: GPUTexture; constructor( camera: Camera, device: GPUDevice, format: GPUTextureFormat, samples: number, simulation: Simulation, ) { this.device = device; this.geometry = Plane(device, 2, 2); this.pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { buffers: [ { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x2', }, { shaderLocation: 1, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, { arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float32x2', }, ], }, { arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 1 * Float32Array.BYTES_PER_ELEMENT, format: 'float32', }, { shaderLocation: 4, offset: 2 * Float32Array.BYTES_PER_ELEMENT, format: 'float32x2', }, ], }, ], entryPoint: 'main', module: device.createShaderModule({ code: Vertex, }), }, fragment: { entryPoint: 'main', module: device.createShaderModule({ code: Fragment, }), targets: [{ format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add', }, alpha: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add', }, }, }], }, primitive: { topology: 'triangle-list', }, multisample: { count: samples, }, }); this.texture = device.createTexture({ dimension: '2d', format: 'rgba8unorm-srgb', size: [512, 512], usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING, }); this.bindings = device.createBindGroup({ layout: this.pipeline.getBindGroupLayout(0), entries: [ { binding: 0,
resource: { buffer: camera.getBuffer() }, }, {
binding: 1, resource: this.texture.createView(), }, { binding: 2, resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }), }, ], }); this.simulation = simulation; this.generateDefaultTexture(); } render(pass: GPURenderPassEncoder) { const { bindings, geometry, pipeline, simulation } = this; const { count, data, points } = simulation.getBuffers(); pass.setPipeline(pipeline); pass.setBindGroup(0, bindings); pass.setVertexBuffer(0, geometry); pass.setVertexBuffer(1, points); pass.setVertexBuffer(2, data); pass.draw(6, count, 0, 0); } setTexture(file: Blob) { const image = new Image(); image.addEventListener('load', () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } let x = 0; let y = 0; let w = canvas.width = 512; let h = canvas.height = 512; if (image.width / image.height > w / h) { w = image.width * canvas.height / image.height; x = (canvas.width - w) * 0.5; } else { h = image.height * canvas.width / image.width; y = (canvas.height - h) * 0.5; } ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h); this.updateTexture(canvas); }); image.src = URL.createObjectURL(file); } private generateDefaultTexture() { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error("Couldn't get 2d context"); } canvas.width = canvas.height = 512; for (let i = 0; i < 256; i++) { ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`; ctx.beginPath(); ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2); ctx.fill(); } this.updateTexture(canvas); } private async updateTexture(canvas: HTMLCanvasElement) { const { device, texture } = this; const source = await createImageBitmap(canvas) device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]); } } export default Points;
src/render/points.ts
danielesteban-gpucloth-b0d861b
[ { "filename": "src/compute/simulation/step.ts", "retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {", "score": 0.8820552825927734 }, { "filename": "src/compute/simulation/lines.ts", "retrieved_chunk": " data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: joints },\n },\n {\n binding: 1,\n resource: { buffer: lines },", "score": 0.8674578666687012 }, { "filename": "src/render/lines.ts", "retrieved_chunk": " topology: 'triangle-list',\n },\n multisample: {\n count: samples,\n },\n });\n this.bindings = device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {", "score": 0.8660348653793335 }, { "filename": "src/compute/simulation/constrain.ts", "retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],", "score": 0.8607368469238281 }, { "filename": "src/compute/simulation/types.ts", "retrieved_chunk": " gpu: GPUBuffer,\n };\n private readonly device: GPUDevice;\n constructor(device: GPUDevice) {\n const buffer = new ArrayBuffer(24);\n this.buffers = {\n cpu: buffer,\n gpu: device.createBuffer({\n size: buffer.byteLength,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM,", "score": 0.8542414903640747 } ]
typescript
resource: { buffer: camera.getBuffer() }, }, {
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) } markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.9086710810661316 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8890332579612732 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.869652271270752 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.8601080179214478 }, { "filename": "src/index.ts", "retrieved_chunk": " PageRichText,\n PageSelect,\n Cover,\n RouteObject,\n Plugin,\n PluginPassthrough,\n} from './types'\nexport type { BlockRenderers } from './notion-blocks-parser'\nexport { default as NotionBlocksParser } from './notion-blocks-parser'\nexport { default } from './notion-cms'", "score": 0.8298481106758118 } ]
typescript
htmlParser: NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
import fs from 'node:fs' import { Buffer } from 'node:buffer' import { fileTypeFromBuffer } from 'file-type' import { nanoid } from 'nanoid' import sharp from 'sharp' import type { Content, PageContent, PluginExecOptions } from '../types' interface ImageCacheEntry { filename?: string location?: string url?: string } interface ImageCache { [key: string]: Array<ImageCacheEntry> } const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json' const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig function multiStringMatch(stringA: unknown, stringB: unknown): Boolean { if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB) return false const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX) const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX) return Boolean(matchA && matchB && (matchA[0] === matchB[0])) } export default function ({ globalExtension = 'webp', compression = 80, imageCacheDirectory = './public', customMatchers = [], }: { globalExtension?: 'webp' | 'png' | 'jpeg' compression?: number imageCacheDirectory?: string customMatchers?: RegExp[] } = {}) { let imageCache: ImageCache try { // Pull existing imageCache if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) { imageCache = JSON.parse( fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache } else { imageCache = {} } } catch (e) { console.warn(e, 'ncms-plugin-images: error attempting to read image cache.') imageCache = {} } async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> { let filename = '' if (existingImageFile) return existingImageFile.filename as string const response = await fetch(imageUrl) const arrayBuffer = await response.arrayBuffer() const buffer = Buffer.from(arrayBuffer) const fileType = await fileTypeFromBuffer(buffer) if (fileType?.ext) { const id = nanoid(6) filename = `${id}.remote.${globalExtension}` const outputFilePath = `${imageCacheDirectory}/remote/${filename}` const imageBuffer = sharp(buffer) const webPBuffer = await imageBuffer[globalExtension]({ quality: compression, nearLossless: true, effort: 6, }).toBuffer() const writeStream = fs.createWriteStream(outputFilePath) // eslint-disable-next-line @typescript-eslint/restrict-template-expressions writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`)) writeStream.write(webPBuffer) } return filename } function detectExisting(path: string, imageUrl: string): ImageCacheEntry { const entries = imageCache[path] return entries.filter((entry) => { return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl) })[0] } async function processImage( path: string, imageUrl: string, updator: { update: Content | string }, debug?: boolean): Promise<void> { if (imageUrl && path) { let filename = '' try { filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl)) } catch (e) { if (debug) console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!') return } if (filename) { imageCache[path].push({ filename, location: `/remote/${filename}`, url: imageUrl, }) // if we don't do this, the replaceall cant find the proper url below if (typeof updator.update !== 'string') { if (updator.update?.html.includes('amazonaws')) updator.update.html = updator.update.html.replaceAll('&amp;', '&') updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`) } else { // This replaces the coverImage updator.update = updator.update.replace(imageUrl, `/remote/${filename}`) } if (debug) console.log('ncms-plugin-images: rewriting', path, 'at', filename) } } } return { name: 'ncms-plugin-images', hook: 'during-tree', core: true, exec
: async (context: PageContent, options: PluginExecOptions) => {
const copyOfContext = structuredClone(context) if (!copyOfContext.path) return const matchables = [ GENERIC_MATCH, IMAGE_SOURCE_MATCH, ...customMatchers, ] if (!imageCache[copyOfContext.path]) imageCache[copyOfContext.path] = [] as ImageCacheEntry[] const contents = { update: copyOfContext.content as Content, } const coverImage = { update: copyOfContext.coverImage as string, } // Must run all async in series so that we don't end up with duplicates for (const match of matchables) { if (!copyOfContext.path) return const path = copyOfContext.path const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || [] const matchedCoverImages = (coverImage.update && [coverImage.update]) || [] for (const imageUrl of matched) await processImage(path, imageUrl, contents, options.debug) for (const imageUrl of matchedCoverImages) await processImage(path, imageUrl, coverImage, options.debug) } copyOfContext.content = contents.update copyOfContext.coverImage = coverImage.update try { if (!fs.existsSync(`${imageCacheDirectory}/remote`)) fs.mkdirSync(`${imageCacheDirectory}/remote`) fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache)) if (options.debug) fs.writeFileSync('debug/images.json', JSON.stringify(imageCache)) } catch (e) { if (options.debug) console.warn(e, 'ncms-plugin-images: error writing to image cache.') } return copyOfContext }, } }
src/plugins/images.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/linker.ts", "retrieved_chunk": " exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context)\n if (copyOfContext._notion?.id && copyOfContext.path)\n links.set(copyOfContext._notion?.id, copyOfContext.path)\n return copyOfContext\n },\n },\n {\n name: 'ncms-plugin-linker',\n hook: 'post-tree',", "score": 0.8564703464508057 }, { "filename": "src/plugins/head.ts", "retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',", "score": 0.8418070077896118 }, { "filename": "src/plugins/linker.ts", "retrieved_chunk": " core: true,\n exec: (context: CMS) => {\n const copyOfContext = structuredClone(context)\n const cmsWalker = NotionCMS._createCMSWalker((node: PageContent) => {\n let html: string | undefined = node.content?.html\n let md: string | undefined = node.content?.markdown\n let plaintext: string | undefined = node.content?.plaintext\n if (html) {\n const pathsToReplace = [...html.matchAll(ESCAPED_HREF_REGEX)]\n pathsToReplace.forEach((path) => {", "score": 0.8385836482048035 }, { "filename": "src/plugins/linker.ts", "retrieved_chunk": "import { idToUuid } from 'notion-utils'\nimport type { CMS, PageContent } from '../types'\nimport NotionCMS from '../notion-cms'\nconst links: Map<string, string> = new Map()\nconst ESCAPED_HREF_REGEX = /<a\\s+(?:[^>]*?\\s+)?href=([\"'])\\/([0-9a-f]{8}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{12})\\1/g\nexport default function () {\n return [{\n name: 'ncms-plugin-linker',\n hook: 'during-tree',\n core: true,", "score": 0.8258610963821411 }, { "filename": "src/notion-cms.ts", "retrieved_chunk": " // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n clackSpinner.stop(kleur.blue(`[ncms]: updated@ ${pageContent.path}`))\n },\n })\n .withRootObjectCallbacks(false)\n .withParallelizeAsyncCallbacks(true)\n .walk(stateWithContent.siteData)\n stateWithContent.stages.push('content')\n stateWithContent = await this._runPlugins(stateWithContent, 'post-tree') as CMS\n return stateWithContent", "score": 0.8231878280639648 } ]
typescript
: async (context: PageContent, options: PluginExecOptions) => {
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser: NotionBlocksHtmlParser plainTextParser
: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) } markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.9080055952072144 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8887186050415039 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.8765798211097717 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.8582326173782349 }, { "filename": "src/index.ts", "retrieved_chunk": " PageRichText,\n PageSelect,\n Cover,\n RouteObject,\n Plugin,\n PluginPassthrough,\n} from './types'\nexport type { BlockRenderers } from './notion-blocks-parser'\nexport { default as NotionBlocksParser } from './notion-blocks-parser'\nexport { default } from './notion-cms'", "score": 0.8271937370300293 } ]
typescript
: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) } markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.9086710810661316 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8890332579612732 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.869652271270752 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.8601080179214478 }, { "filename": "src/index.ts", "retrieved_chunk": " PageRichText,\n PageSelect,\n Cover,\n RouteObject,\n Plugin,\n PluginPassthrough,\n} from './types'\nexport type { BlockRenderers } from './notion-blocks-parser'\nexport { default as NotionBlocksParser } from './notion-blocks-parser'\nexport { default } from './notion-cms'", "score": 0.8298481106758118 } ]
typescript
plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser:
NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) } markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.9073804020881653 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8912950754165649 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.8698052167892456 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.8591712713241577 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n constructor() {\n this.renderer = {\n // Block elements\n code: escapeBlock,\n blockquote: block,\n html: empty,\n heading: block,\n hr: newline,", "score": 0.8285681009292603 } ]
typescript
NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser: NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser
= new NotionBlocksHtmlParser(this.mdParser, this.debug) }
markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.8885486125946045 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.8729972839355469 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8727931380271912 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " parseLinkPreview(linkPreviewBlock: LinkPreviewBlock): string {\n return `<div notion-link-preview>\n <a href=\"${linkPreviewBlock.link_preview.url}\">${linkPreviewBlock.link_preview.url}</a>\n </div>\\n\\n`\n }\n parseParagraph(paragraphBlock: ParagraphBlock): string {\n const text: string = this.parseRichTexts(paragraphBlock.paragraph.rich_text)\n return EOL_MD.concat(text, EOL_MD)\n }\n parseCodeBlock(codeBlock: CodeBlock): string {", "score": 0.8681182265281677 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.8633060455322266 } ]
typescript
= new NotionBlocksHtmlParser(this.mdParser, this.debug) }
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser: NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) }
markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string { return this.mdParser.parse(blocks, depth) } blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/render.ts", "retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })", "score": 0.873469889163971 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,", "score": 0.8733842968940735 }, { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport hljs from 'highlight.js'\nimport type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\n// @ts-expect-error module\nimport { gfmHeadingId } from 'marked-gfm-heading-id'\nimport type NotionBlocksMarkdownParser from './notion-blocks-md-parser'\nexport default class NotionBlocksHtmlParser {\n markdownParser: NotionBlocksMarkdownParser", "score": 0.863371729850769 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " parseLinkPreview(linkPreviewBlock: LinkPreviewBlock): string {\n return `<div notion-link-preview>\n <a href=\"${linkPreviewBlock.link_preview.url}\">${linkPreviewBlock.link_preview.url}</a>\n </div>\\n\\n`\n }\n parseParagraph(paragraphBlock: ParagraphBlock): string {\n const text: string = this.parseRichTexts(paragraphBlock.paragraph.rich_text)\n return EOL_MD.concat(text, EOL_MD)\n }\n parseCodeBlock(codeBlock: CodeBlock): string {", "score": 0.8562849760055542 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.8456987738609314 } ]
typescript
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) }
import dotenv from 'dotenv' import { suite } from 'uvu' import * as assert from 'uvu/assert' import nock from 'nock' import NotionCMS from '../index' import type { CMS, PluginPassthrough } from '../types' dotenv.config() export const TestNotionCMSCache = suite('TestNotionCMSCache') const cachingDatabaseId = '1234' // this does not exist in notion const baseUrl = 'https://api.notion.com/v1' const cachingTestCMS: NotionCMS = new NotionCMS({ databaseId: cachingDatabaseId, notionAPIKey: process.env.NOTION as string, draftMode: true, }) cachingTestCMS.purgeCache() const topLevelPageId = '456' const topLevelPageId2 = '789' TestNotionCMSCache('Unchanged since last edit time uses cache', async () => { nock(baseUrl) .post(`/databases/${cachingDatabaseId}/query`) .query(true) .reply(200, { object: 'list', results: [ { object: 'page', id: topLevelPageId, created_time: '2023-04-09T06:03:00.000Z', last_edited_time: '2023-04-09T06:03:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, properties: { name: { id: 'title', type: 'title', title: [ { type: 'text', text: { content: 'Page 1', link: null, }, annotations: {}, plain_text: 'Page 1', href: null, }, ], }, Author: { id: 'SQeZ', type: 'people', people: [ { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', name: 'Jacob', avatar_url: null, type: 'person', person: { email: 'jacob@agencykit.so', }, }, ], }, Tags: { id: 'NNmP', type: 'multi_select', multi_select: [ { id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18', name: 'programming', color: 'default', }, ], }, }, cover: null, icon: null, archived: false, url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d', }, { object: 'page', id: topLevelPageId2, created_time: '2023-04-09T06:03:00.000Z', last_edited_time: '2023-04-09T06:03:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, properties: { name: { id: 'title', type: 'title', title: [ { type: 'text', text: { content: 'Page 2', link: null, }, annotations: {}, plain_text: 'Page 2', href: null, }, ], }, Author: { id: 'SQeZ', type: 'people', people: [ { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', name: 'Jacob', avatar_url: null, type: 'person', person: { email: 'jacob@agencykit.so', }, }, ], }, Tags: { id: 'NNmP', type: 'multi_select', multi_select: [ { id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18', name: 'programming', color: 'default', }, ], }, }, cover: null, icon: null, archived: false, url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d', }, ], next_cursor: null, has_more: false, type: 'page', page: {}, }) nock(baseUrl) .get(`/blocks/${topLevelPageId}/children`) .query(true) .reply(200, { object: 'list', results: [ { object: 'block', id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad', parent: { type: 'page_id', page_id: topLevelPageId, }, created_time: '2023-04-22T04:34:00.000Z', last_edited_time: '2023-04-22T04:34:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, has_children: false, archived: false, type: 'heading_1', heading_1: { rich_text: [ { type: 'text', text: { content: 'Block 1: Has not changed.', link: null, }, annotations: {}, plain_text: 'Block 1: Has not changed.', href: null, }, ], is_toggleable: false, color: 'default', }, }, ], }) nock(baseUrl) .get(`/blocks/${topLevelPageId2}/children`) .query(true) .reply(200, { object: 'list', results: [ { object: 'block', id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad', parent: { type: 'page_id', page_id: topLevelPageId2, }, created_time: '2023-04-22T04:34:00.000Z', last_edited_time: '2023-04-22T04:34:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, has_children: false, archived: false, type: 'heading_1', heading_1: { rich_text: [ { type: 'text', text: { content: 'Block 2: Has not changed.', link: null, }, annotations: {}, plain_text: 'Block 2: Has not changed.', href: null, }, ], is_toggleable: false, color: 'default', }, }, ], }) // Build the cache const cms: CMS = await cachingTestCMS.pull() assert.ok(cms.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.') assert.ok(cms.siteData['/page-2'].content?.plaintext === 'Block 2: Has not changed.') // Change some data in only page 2 nock(baseUrl) .post(`/databases/${cachingDatabaseId}/query`) .query(true) .reply(200, { object: 'list', results: [ { object: 'page', id: topLevelPageId, created_time: '2023-04-09T06:03:00.000Z', last_edited_time: '2023-04-09T06:03:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, properties: { name: { id: 'title', type: 'title', title: [ { type: 'text', text: { content: 'Page 1', link: null, }, annotations: {}, plain_text: 'Page 1', href: null, }, ], }, Author: { id: 'SQeZ', type: 'people', people: [ { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', name: 'Jacob', avatar_url: null, type: 'person', person: { email: 'jacob@agencykit.so', }, }, ], }, Tags: { id: 'NNmP', type: 'multi_select', multi_select: [ { id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18', name: 'programming', color: 'default', }, ], }, }, cover: null, icon: null, archived: false, url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d', }, { object: 'page', id: topLevelPageId2, created_time: '2023-04-09T06:03:00.000Z', last_edited_time: '2023-04-09T06:16:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, properties: { name: { id: 'title', type: 'title', title: [ { type: 'text', text: { content: 'Page 2', link: null, }, annotations: {}, plain_text: 'Page 2', href: null, }, ], }, Author: { id: 'SQeZ', type: 'people', people: [ { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', name: 'Jacob', avatar_url: null, type: 'person', person: { email: 'jacob@agencykit.so', }, }, ], }, Tags: { id: 'NNmP', type: 'multi_select', multi_select: [ { id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18', name: 'programming', color: 'default', }, ], }, }, cover: null, icon: null, archived: false, url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d', }, ], next_cursor: null, has_more: false, type: 'page', page: {}, }) nock(baseUrl) .get(`/blocks/${topLevelPageId2}/children`) .query(true) .reply(200, { object: 'list', results: [ { object: 'block', id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad', parent: { type: 'page_id', page_id: topLevelPageId2, }, created_time: '2023-04-22T04:34:00.000Z', last_edited_time: '2023-04-22T04:34:00.000Z', created_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, last_edited_by: { object: 'user', id: '4e38fa57-609c-4beb-8e28-271b11cc81a3', }, has_children: false, archived: false, type: 'heading_1', heading_1: { rich_text: [ { type: 'text', text: { content: 'Block 2: Has changed.', link: null, }, annotations: {}, plain_text: 'Block 2: Has changed.', href: null, }, ], is_toggleable: false, color: 'default', }, }, ], }) const cms2: CMS = await cachingTestCMS.pull() assert.ok(cms2.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.') assert.ok(cms2.siteData['/page-2'].content?.plaintext === 'Block 2: Has changed.') }) TestNotionCMSCache('Plugins run even when using cached state.', async () => { const databaseId = '610627a9-28b1-4477-b660-c00c5364435b' let counter = 0 const testCMS: NotionCMS = new NotionCMS({ databaseId, notionAPIKey: process.env.NOTION as string, draftMode: true, refreshTimeout: '1 minute', plugins: [ { name: 'counter-plugin', hook: '*', // this will run every hook
exec: (ctx: PluginPassthrough) => {
counter++ return ctx }, }, ], }) console.log('caching test: purging cache') testCMS.purgeCache() await testCMS.pull() assert.equal(counter, 22) })
src/tests/notion-cms-caching.spec.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/tests/limiter.spec.ts", "retrieved_chunk": "const limiter = new Bottleneck({\n maxConcurrent: 1,\n minTime: 333,\n})\nconst testCMS = new NotionCMS({\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n limiter,\n})", "score": 0.9019831418991089 }, { "filename": "src/tests/custom-render.spec.ts", "retrieved_chunk": " PluginsCustomCMS = new NotionCMS({\n // Kitchen sink DB in community/tests\n databaseId,\n notionAPIKey,\n // Should work with other plugin too\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n }),", "score": 0.8946294784545898 }, { "filename": "src/tests/notion-cms.spec.ts", "retrieved_chunk": " }\n})\nTestNotionCMS('Options have changed', () => {\n const options = {\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n plugins: [() => 'test plugin'],\n }\n const otherOptions = {", "score": 0.8796320557594299 }, { "filename": "src/tests/notion-cms.spec.ts", "retrieved_chunk": " expectedRoutes,\n expectedSiteData,\n expectedTagGroups,\n expectedTaggedCollection,\n expectedTags,\n} from './notion-api-mock.spec'\ndotenv.config()\nexport const TestNotionCMS = suite('TestNotionCMS')\nconst databaseId = '610627a9-28b1-4477-b660-c00c5364435b'\nconst testCMS: NotionCMS = new NotionCMS({", "score": 0.8694669008255005 }, { "filename": "src/tests/custom-render.spec.ts", "retrieved_chunk": " expectedRoutes,\n expectedSiteData,\n expectedTags,\n} from './notion-api-mock.spec'\ndotenv.config()\n// Kitchen sink database\nconst databaseId = '21608fc7-c1c5-40a1-908f-9ade89585111'\nconst notionAPIKey = process.env.NOTION\nlet PluginsDefaultCMS: NotionCMS,\n PluginsDefaultOtherCMS: NotionCMS,", "score": 0.8682204484939575 } ]
typescript
exec: (ctx: PluginPassthrough) => {
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils"; import type { MarkdownCodeBlockTimelineProcessingContext, CompleteCardContext, } from "~/types"; import { parse } from "yaml"; import { getAbstractDateFromMetadata, getBodyFromContextOrDocument, getImageUrlFromContextOrDocument, getTagsFromMetadataOrTagObject, } from "./cardDataExtraction"; /** * A un-changeable key used to check if a note is eligeable for render. */ const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"]; /** * Provides additional context for the creation cards in the DOM. * * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteMetadata( context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ) { const { cachedMetadata, settings } = context; const { frontmatter: metaData, tags } = cachedMetadata; if (!metaData) return undefined; if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true)) return undefined; const timelineTags = getTagsFromMetadataOrTagObject( settings, metaData, tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined; return { cardData: await extractCardData(context), context, } as const; } /** * Provides additional context for the creation cards in the DOM but reads it from the body * * @param body - The extracted body for a single event card. * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteBody( body: string | undefined | null, context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ): Promise<CompleteCardContext[]> { const { settings } = context; if (!body) return []; const inlineEventBlockRegExp = new RegExp( `%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`, "gi" ); const originalFrontmatter = context.cachedMetadata.frontmatter; const matches = body.match(inlineEventBlockRegExp); if (!matches) return []; matches.unshift(); const output: CompleteCardContext[] = []; for (const block of matches) { const sanitizedBlock = block.split("\n"); sanitizedBlock.shift(); sanitizedBlock.pop(); const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao // Replace frontmatter with newly built fake one. Just to re-use all the existing code. context.cachedMetadata.frontmatter = fakeFrontmatter; if (!
isDefinedAsObject(fakeFrontmatter)) continue;
const timelineTags = getTagsFromMetadataOrTagObject( settings, fakeFrontmatter, context.cachedMetadata.tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue; const matchPositionInBody = body.indexOf(block); output.push({ cardData: await extractCardData( context, matchPositionInBody !== -1 ? body.slice(matchPositionInBody + block.length) : undefined ), context, }); } context.cachedMetadata.frontmatter = originalFrontmatter; return output; } /** * Checks if the extracted tags match at least one of the tags to find. * * @param timelineTags - The extracted tags from the note. * @param tagsToFind - The tags to find. * @returns `true` if valid. */ function extractedTagsAreValid( timelineTags: string[], tagsToFind: string[] ): boolean { return timelineTags.some((tag) => tagsToFind.includes(tag)); } /** * Get the content of a card from a note. This function will parse the raw text content of a note and format it. * * @param context - Timeline generic context. * @param rawFileContent - If you already have it, will avoid reading the file again. * @returns The extracted data to create a card from a note. */ export async function extractCardData( context: MarkdownCodeBlockTimelineProcessingContext, rawFileContent?: string ) { const { file, cachedMetadata: c, settings } = context; const fileTitle = c.frontmatter?.[settings.metadataKeyEventTitleOverride] || file.basename; rawFileContent = rawFileContent || (await file.vault.cachedRead(file)); return { title: fileTitle as string, body: getBodyFromContextOrDocument(rawFileContent, context), imageURL: getImageUrlFromContextOrDocument(rawFileContent, context), startDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventStartDate ), endDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventEndDate ) ?? (isDefined( getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean") ) ? true : undefined), } as const; } export type FnExtractCardData = typeof extractCardData;
src/cardData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.8315643072128296 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.8124748468399048 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\t\t\tconst score = compareAbstractDates(a, b);\n\t\t\t\tif (score) return score;\n\t\t\t\treturn compareAbstractDates(aE, bE);\n\t\t\t}\n\t\t);\n\t\tcardDataTime();\n\t\tconst cardRenderTime = measureTime(\"Card Render\");\n\t\tevents.forEach(({ context, cardData }) =>\n\t\t\tcreateCardFromBuiltContext(context, cardData)\n\t\t);", "score": 0.8005071878433228 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())", "score": 0.7943146824836731 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\t\t\tawait getDataFromNoteBody(body, context, tagsToFind)\n\t\t\t).filter(isDefined);\n\t\t\tif (!inlineEvents.length) continue;\n\t\t\tevents.push(...inlineEvents);\n\t\t}\n\t\tevents.sort(\n\t\t\t(\n\t\t\t\t{ cardData: { startDate: a, endDate: aE } },\n\t\t\t\t{ cardData: { startDate: b, endDate: bE } }\n\t\t\t) => {", "score": 0.7937442064285278 } ]
typescript
isDefinedAsObject(fakeFrontmatter)) continue;
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined);
if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.891127347946167 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8550456166267395 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.8536219596862793 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8358235359191895 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8325172066688538 } ]
typescript
await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined);
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian"; import { isDefined, createElementShort } from "~/utils"; import type { MarkdownCodeBlockTimelineProcessingContext, CardContent, AutoTimelineSettings, } from "~/types"; import { formatAbstractDate } from "./abstractDateFormatting"; /** * Generates a card in the DOM based on given ccontext. * * @param param0 - The context built for this timeline. * @param param0.elements - The HTMLElements exposed for this context. * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned. * @param param0.file - The target note file. * @param param0.settings - The plugin's settings. * @param cardContent - The content of a single timeline card. */ export function createCardFromBuiltContext( { elements: { cardListRootElement }, file, settings, }: MarkdownCodeBlockTimelineProcessingContext, cardContent: CardContent ): void { const { body, title, imageURL } = cardContent; const cardBaseDiv = createElementShort(cardListRootElement, "a", [ "internal-link", "aat-card", ]); cardBaseDiv.setAttribute("href", file.path); if (imageURL) { createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute( "src", imageURL ); cardBaseDiv.addClass("aat-card-has-image"); } const cardTextWraper = createElementShort( cardBaseDiv, "div", "aat-card-text-wraper" ); const titleWrap = createElementShort( cardTextWraper, "header", "aat-card-head-wrap" ); createElementShort(titleWrap, "h2", "aat-card-title", title); createElementShort( titleWrap, "h4", "aat-card-start-date", getDateText(cardContent, settings).trim() ); const markdownTextWrapper = createElementShort( cardTextWraper, "div", "aat-card-body" ); const rendered = new MarkdownRenderChild(markdownTextWrapper); rendered.containerEl = markdownTextWrapper; MarkdownRenderer.renderMarkdown( formatBodyForCard(body), markdownTextWrapper, file.path, rendered ); } /** * Format the body string of the note data for a single card. * * @param body - The body string parsed earlier. * @returns The formated string ready to be displayed. */ export function formatBodyForCard(body?: string | null): string { if (!body) return "No body for this note :("; // Remove external image links return ( body .replace(/!\[.*\]\(.*\)/gi, "") // Remove tags .replace(/#[a-zA-Z\d-_]*/gi, "") // Remove internal images ![[Pasted image 20230418232101.png]] .replace(/!\[\[.*\]\]/gi, "") // Remove other timelines to avoid circular dependencies! .replace(/```aat-vertical\n.*\n```/gi, "") // Trim the text .trim() ); } /** * Get the text displayed in the card where the date should be. * * @param param0 - The context for a single card. * @param param0.startDate - the start date of an event. * @param param0.endDate - the end date of an event. * @param settings - The settings of the plugin. * @returns a formated string representation of the dates included in the card content based off the settings. */ export function getDateText( { startDate, endDate }: Pick<CardContent, "startDate" | "endDate">, settings: AutoTimelineSettings ): string { if (!isDefined(startDate)) return "Start date missing";
const formatedStart = formatAbstractDate(startDate, settings);
if (!isDefined(endDate)) return formatedStart; return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`; }
src/cardMarkup.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\tsettings.metadataKeyEventStartDate\n\t\t),\n\t\tendDate:\n\t\t\tgetAbstractDateFromMetadata(\n\t\t\t\tcontext,\n\t\t\t\tsettings.metadataKeyEventEndDate\n\t\t\t) ??\n\t\t\t(isDefined(\n\t\t\t\tgetMetadataKey(c, settings.metadataKeyEventEndDate, \"boolean\")\n\t\t\t)", "score": 0.807152509689331 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string", "score": 0.7756978273391724 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.7753103971481323 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "export function applyConditionBasedFormatting(\n\tformatedDate: string,\n\tdate: number,\n\t{ formatting }: DateTokenConfiguration,\n\tapplyAdditonalConditionFormatting: AutoTimelineSettings[\"applyAdditonalConditionFormatting\"]\n): string {\n\tif (!applyAdditonalConditionFormatting) return formatedDate;\n\treturn formatting.reduce(\n\t\t(output, { format, conditionsAreExclusive, evaluations }) => {\n\t\t\tconst evaluationRestult = (", "score": 0.7661771774291992 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tcompareAbstractDates(startDate, date) !== 0;\n\treturn {\n\t\tstart: {\n\t\t\ttop:\n\t\t\t\tstartElement.offsetTop +\n\t\t\t\t(shouldOffsetStartToBottomOfCard\n\t\t\t\t\t? startElement.innerHeight\n\t\t\t\t\t: 0),\n\t\t\tdate: startDate,\n\t\t},", "score": 0.7636881470680237 } ]
typescript
const formatedStart = formatAbstractDate(startDate, settings);
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian"; import { isDefined, createElementShort } from "~/utils"; import type { MarkdownCodeBlockTimelineProcessingContext, CardContent, AutoTimelineSettings, } from "~/types"; import { formatAbstractDate } from "./abstractDateFormatting"; /** * Generates a card in the DOM based on given ccontext. * * @param param0 - The context built for this timeline. * @param param0.elements - The HTMLElements exposed for this context. * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned. * @param param0.file - The target note file. * @param param0.settings - The plugin's settings. * @param cardContent - The content of a single timeline card. */ export function createCardFromBuiltContext( { elements: { cardListRootElement }, file, settings, }: MarkdownCodeBlockTimelineProcessingContext, cardContent: CardContent ): void { const { body, title, imageURL } = cardContent; const cardBaseDiv = createElementShort(cardListRootElement, "a", [ "internal-link", "aat-card", ]); cardBaseDiv.setAttribute("href", file.path); if (imageURL) { createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute( "src", imageURL ); cardBaseDiv.addClass("aat-card-has-image"); } const cardTextWraper = createElementShort( cardBaseDiv, "div", "aat-card-text-wraper" ); const titleWrap = createElementShort( cardTextWraper, "header", "aat-card-head-wrap" ); createElementShort(titleWrap, "h2", "aat-card-title", title); createElementShort( titleWrap, "h4", "aat-card-start-date", getDateText(cardContent, settings).trim() ); const markdownTextWrapper = createElementShort( cardTextWraper, "div", "aat-card-body" ); const rendered = new MarkdownRenderChild(markdownTextWrapper); rendered.containerEl = markdownTextWrapper; MarkdownRenderer.renderMarkdown( formatBodyForCard(body), markdownTextWrapper, file.path, rendered ); } /** * Format the body string of the note data for a single card. * * @param body - The body string parsed earlier. * @returns The formated string ready to be displayed. */ export function formatBodyForCard(body?: string | null): string { if (!body) return "No body for this note :("; // Remove external image links return ( body .replace(/!\[.*\]\(.*\)/gi, "") // Remove tags .replace(/#[a-zA-Z\d-_]*/gi, "") // Remove internal images ![[Pasted image 20230418232101.png]] .replace(/!\[\[.*\]\]/gi, "") // Remove other timelines to avoid circular dependencies! .replace(/```aat-vertical\n.*\n```/gi, "") // Trim the text .trim() ); } /** * Get the text displayed in the card where the date should be. * * @param param0 - The context for a single card. * @param param0.startDate - the start date of an event. * @param param0.endDate - the end date of an event. * @param settings - The settings of the plugin. * @returns a formated string representation of the dates included in the card content based off the settings. */ export function getDateText( { startDate, endDate }: Pick<CardContent, "startDate" | "endDate">, settings: AutoTimelineSettings ): string {
if (!isDefined(startDate)) return "Start date missing";
const formatedStart = formatAbstractDate(startDate, settings); if (!isDefined(endDate)) return formatedStart; return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`; }
src/cardMarkup.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\tsettings.metadataKeyEventStartDate\n\t\t),\n\t\tendDate:\n\t\t\tgetAbstractDateFromMetadata(\n\t\t\t\tcontext,\n\t\t\t\tsettings.metadataKeyEventEndDate\n\t\t\t) ??\n\t\t\t(isDefined(\n\t\t\t\tgetMetadataKey(c, settings.metadataKeyEventEndDate, \"boolean\")\n\t\t\t)", "score": 0.7969769835472107 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string", "score": 0.7700929045677185 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.7638511061668396 }, { "filename": "src/rangeMarkup.ts", "retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||", "score": 0.7523484826087952 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": " */\nexport function getTagsFromMetadataOrTagObject(\n\tsettings: AutoTimelineSettings,\n\tmetaData: Omit<FrontMatterCache, \"position\">,\n\ttags?: TagCache[]\n): string[] {\n\tlet output = [] as string[];\n\tconst timelineArray = metaData[settings.metadataKeyEventTimelineTag];\n\tif (isDefinedAsArray(timelineArray))\n\t\toutput = timelineArray.filter(isDefinedAsString);", "score": 0.7509846687316895 } ]
typescript
if (!isDefined(startDate)) return "Start date missing";
import fs from 'node:fs' import { Buffer } from 'node:buffer' import { fileTypeFromBuffer } from 'file-type' import { nanoid } from 'nanoid' import sharp from 'sharp' import type { Content, PageContent, PluginExecOptions } from '../types' interface ImageCacheEntry { filename?: string location?: string url?: string } interface ImageCache { [key: string]: Array<ImageCacheEntry> } const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json' const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig function multiStringMatch(stringA: unknown, stringB: unknown): Boolean { if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB) return false const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX) const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX) return Boolean(matchA && matchB && (matchA[0] === matchB[0])) } export default function ({ globalExtension = 'webp', compression = 80, imageCacheDirectory = './public', customMatchers = [], }: { globalExtension?: 'webp' | 'png' | 'jpeg' compression?: number imageCacheDirectory?: string customMatchers?: RegExp[] } = {}) { let imageCache: ImageCache try { // Pull existing imageCache if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) { imageCache = JSON.parse( fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache } else { imageCache = {} } } catch (e) { console.warn(e, 'ncms-plugin-images: error attempting to read image cache.') imageCache = {} } async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> { let filename = '' if (existingImageFile) return existingImageFile.filename as string const response = await fetch(imageUrl) const arrayBuffer = await response.arrayBuffer() const buffer = Buffer.from(arrayBuffer) const fileType = await fileTypeFromBuffer(buffer) if (fileType?.ext) { const id = nanoid(6) filename = `${id}.remote.${globalExtension}` const outputFilePath = `${imageCacheDirectory}/remote/${filename}` const imageBuffer = sharp(buffer) const webPBuffer = await imageBuffer[globalExtension]({ quality: compression, nearLossless: true, effort: 6, }).toBuffer() const writeStream = fs.createWriteStream(outputFilePath) // eslint-disable-next-line @typescript-eslint/restrict-template-expressions writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`)) writeStream.write(webPBuffer) } return filename } function detectExisting(path: string, imageUrl: string): ImageCacheEntry { const entries = imageCache[path] return entries.filter((entry) => { return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl) })[0] } async function processImage( path: string, imageUrl: string,
updator: { update: Content | string }, debug?: boolean): Promise<void> {
if (imageUrl && path) { let filename = '' try { filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl)) } catch (e) { if (debug) console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!') return } if (filename) { imageCache[path].push({ filename, location: `/remote/${filename}`, url: imageUrl, }) // if we don't do this, the replaceall cant find the proper url below if (typeof updator.update !== 'string') { if (updator.update?.html.includes('amazonaws')) updator.update.html = updator.update.html.replaceAll('&amp;', '&') updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`) } else { // This replaces the coverImage updator.update = updator.update.replace(imageUrl, `/remote/${filename}`) } if (debug) console.log('ncms-plugin-images: rewriting', path, 'at', filename) } } } return { name: 'ncms-plugin-images', hook: 'during-tree', core: true, exec: async (context: PageContent, options: PluginExecOptions) => { const copyOfContext = structuredClone(context) if (!copyOfContext.path) return const matchables = [ GENERIC_MATCH, IMAGE_SOURCE_MATCH, ...customMatchers, ] if (!imageCache[copyOfContext.path]) imageCache[copyOfContext.path] = [] as ImageCacheEntry[] const contents = { update: copyOfContext.content as Content, } const coverImage = { update: copyOfContext.coverImage as string, } // Must run all async in series so that we don't end up with duplicates for (const match of matchables) { if (!copyOfContext.path) return const path = copyOfContext.path const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || [] const matchedCoverImages = (coverImage.update && [coverImage.update]) || [] for (const imageUrl of matched) await processImage(path, imageUrl, contents, options.debug) for (const imageUrl of matchedCoverImages) await processImage(path, imageUrl, coverImage, options.debug) } copyOfContext.content = contents.update copyOfContext.coverImage = coverImage.update try { if (!fs.existsSync(`${imageCacheDirectory}/remote`)) fs.mkdirSync(`${imageCacheDirectory}/remote`) fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache)) if (options.debug) fs.writeFileSync('debug/images.json', JSON.stringify(imageCache)) } catch (e) { if (options.debug) console.warn(e, 'ncms-plugin-images: error writing to image cache.') } return copyOfContext }, } }
src/plugins/images.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " return `\\`${originalContent}\\``\n case 'color':\n if (color !== 'default')\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `<span notion-color='${color}'>${originalContent}</span>`\n return originalContent\n }\n }\n}\nfunction processExternalVideoUrl(url: string): [boolean, string] {", "score": 0.7902483940124512 }, { "filename": "src/notion-cms.ts", "retrieved_chunk": " const content = await this._parsePageContent(blocks)\n _.assign(pageContent, {\n content,\n ...(!pageContent.coverImage && { coverImage: content.html.match(COVER_IMAGE_REGEX)?.[1] }),\n _ancestors: this._gatherNodeAncestors(node),\n })\n }\n else if (cachedState && pageContent.path) {\n const cachedPage = this._queryByPath(pageContent.path, cachedState?.siteData)\n if (cachedPage) {", "score": 0.7865012288093567 }, { "filename": "src/notion-cms.ts", "retrieved_chunk": " url: (stateWithDb.metadata.rootUrl && pageContent.path)\n ? (`${stateWithDb.metadata.rootUrl as string}${pageContent.path}`)\n : '',\n })\n if (cachedState && pageContent.path && !this.withinRefreshTimeout) {\n const cachedPage = this._queryByPath(pageContent.path, cachedState?.siteData)\n pageContent._updateNeeded = this.autoUpdate\n && (update._notion?.last_edited_time !== cachedPage?._notion?.last_edited_time)\n }\n if (node.key && typeof node.key === 'string' && pageContent.tags && pageContent.path)", "score": 0.7837158441543579 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " if (url.includes('youtu'))\n return processYoutubeUrl(url)\n return [false, url]\n}\nfunction processYoutubeUrl(youtubeUrl: string): [boolean, string] {\n const lastPart = youtubeUrl.split('/').pop()\n const youtubeIframe = '<iframe width=\\'560\\' height=\\'315\\' src=\\'https://www.youtube-nocookie.com/embed/{{videoId}}\\' title=\\'YouTube video player\\' frameborder=\\'0\\' allow=\\'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\\' allowfullscreen></iframe>'\n if (!lastPart)\n return [true, youtubeIframe]\n if (lastPart.includes('watch')) {", "score": 0.7771082520484924 }, { "filename": "src/notion-cms.ts", "retrieved_chunk": " _.assign(pageContent, {\n content: cachedPage.content,\n ...(!cachedPage.coverImage && { coverImage: cachedPage.content?.html.match(COVER_IMAGE_REGEX)?.[1] }),\n _ancestors: this._gatherNodeAncestors(node),\n })\n if (!this.quietMode && pageContent.path)\n clackSpinner.start(kleur.yellow(`[ncms][using cache]: ${pageContent.path}`))\n }\n }\n else {", "score": 0.7720642685890198 } ]
typescript
updator: { update: Content | string }, debug?: boolean): Promise<void> {
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(
new TimelineSettingTab(this.app, this));
} /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/settings.ts", "retrieved_chunk": "\t\tcreateNumberDateTokenConfiguration({ name: \"day\" }),\n\t] as DateTokenConfiguration[],\n};\nexport const __VUE_PROD_DEVTOOLS__ = true;\n/**\n * Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.\n */\nexport class TimelineSettingTab extends PluginSettingTab {\n\tplugin: AprilsAutomaticTimelinesPlugin;\n\tvueApp: VueApp<Element> | null;", "score": 0.8627059459686279 }, { "filename": "src/settings.ts", "retrieved_chunk": "import { PluginSettingTab } from \"obsidian\";\nimport { createApp, ref } from \"vue\";\nimport createVueI18nConfig from \"~/i18n.config\";\nimport VApp from \"~/views/App.vue\";\nimport type { App as ObsidianApp } from \"obsidian\";\nimport type AprilsAutomaticTimelinesPlugin from \"~/main\";\nimport type { AutoTimelineSettings, DateTokenConfiguration } from \"./types\";\nimport type { App as VueApp } from \"vue\";\nimport { createNumberDateTokenConfiguration } from \"./utils\";\n/**", "score": 0.8287216424942017 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.8166559338569641 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(", "score": 0.81363844871521 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "import {\n\tdateTokenConfigurationIsTypeNumber,\n\tdateTokenConfigurationIsTypeString,\n\tevalNumericalCondition,\n} from \"~/utils\";\nimport type {\n\tAutoTimelineSettings,\n\tAbstractDate,\n\tDateTokenConfiguration,\n\tDateTokenType,", "score": 0.8094145059585571 } ]
typescript
new TimelineSettingTab(this.app, this));
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score =
compareAbstractDates(a, b);
if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.8370809555053711 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.8345003128051758 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tcompareAbstractDates(startDate, date) !== 0;\n\treturn {\n\t\tstart: {\n\t\t\ttop:\n\t\t\t\tstartElement.offsetTop +\n\t\t\t\t(shouldOffsetStartToBottomOfCard\n\t\t\t\t\t? startElement.innerHeight\n\t\t\t\t\t: 0),\n\t\t\tdate: startDate,\n\t\t},", "score": 0.8247859477996826 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)", "score": 0.820376992225647 }, { "filename": "src/rangeMarkup.ts", "retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||", "score": 0.811904788017273 } ]
typescript
compareAbstractDates(a, b);
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const
baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.8438391089439392 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8419438004493713 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8327869176864624 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8268729448318481 }, { "filename": "src/types.ts", "retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined", "score": 0.8205568790435791 } ]
typescript
baseData = await getDataFromNoteMetadata(context, tagsToFind);
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find( ({ name }) => name === token ); if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8137847781181335 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.8103455901145935 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.8010818958282471 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7809976935386658 }, { "filename": "src/utils.ts", "retrieved_chunk": "): DateTokenConfiguration<DateTokenType.number> {\n\treturn {\n\t\tminLeght: 2,\n\t\tname: \"\",\n\t\ttype: DateTokenType.number,\n\t\tdisplayWhenZero: true,\n\t\tformatting: [],\n\t\thideSign: false,\n\t\t...defaultValue,\n\t};", "score": 0.7720714807510376 } ]
typescript
prioArray.forEach((token, index) => {
import fs from 'node:fs' import { Buffer } from 'node:buffer' import { fileTypeFromBuffer } from 'file-type' import { nanoid } from 'nanoid' import sharp from 'sharp' import type { Content, PageContent, PluginExecOptions } from '../types' interface ImageCacheEntry { filename?: string location?: string url?: string } interface ImageCache { [key: string]: Array<ImageCacheEntry> } const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json' const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig function multiStringMatch(stringA: unknown, stringB: unknown): Boolean { if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB) return false const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX) const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX) return Boolean(matchA && matchB && (matchA[0] === matchB[0])) } export default function ({ globalExtension = 'webp', compression = 80, imageCacheDirectory = './public', customMatchers = [], }: { globalExtension?: 'webp' | 'png' | 'jpeg' compression?: number imageCacheDirectory?: string customMatchers?: RegExp[] } = {}) { let imageCache: ImageCache try { // Pull existing imageCache if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) { imageCache = JSON.parse( fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache } else { imageCache = {} } } catch (e) { console.warn(e, 'ncms-plugin-images: error attempting to read image cache.') imageCache = {} } async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> { let filename = '' if (existingImageFile) return existingImageFile.filename as string const response = await fetch(imageUrl) const arrayBuffer = await response.arrayBuffer() const buffer = Buffer.from(arrayBuffer) const fileType = await fileTypeFromBuffer(buffer) if (fileType?.ext) { const id = nanoid(6) filename = `${id}.remote.${globalExtension}` const outputFilePath = `${imageCacheDirectory}/remote/${filename}` const imageBuffer = sharp(buffer) const webPBuffer = await imageBuffer[globalExtension]({ quality: compression, nearLossless: true, effort: 6, }).toBuffer() const writeStream = fs.createWriteStream(outputFilePath) // eslint-disable-next-line @typescript-eslint/restrict-template-expressions writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`)) writeStream.write(webPBuffer) } return filename } function detectExisting(path: string, imageUrl: string): ImageCacheEntry { const entries = imageCache[path] return entries.filter((entry) => { return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl) })[0] } async function processImage( path: string, imageUrl: string, updator: { update: Content | string }, debug?: boolean): Promise<void> { if (imageUrl && path) { let filename = '' try { filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl)) } catch (e) { if (debug) console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!') return } if (filename) { imageCache[path].push({ filename, location: `/remote/${filename}`, url: imageUrl, }) // if we don't do this, the replaceall cant find the proper url below if (typeof updator.update !== 'string') { if (updator.update?.html.includes('amazonaws')) updator.update.html = updator.update.html.replaceAll('&amp;', '&') updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`) } else { // This replaces the coverImage updator.update = updator.update.replace(imageUrl, `/remote/${filename}`) } if (debug) console.log('ncms-plugin-images: rewriting', path, 'at', filename) } } } return { name: 'ncms-plugin-images', hook: 'during-tree', core: true, exec: async (
context: PageContent, options: PluginExecOptions) => {
const copyOfContext = structuredClone(context) if (!copyOfContext.path) return const matchables = [ GENERIC_MATCH, IMAGE_SOURCE_MATCH, ...customMatchers, ] if (!imageCache[copyOfContext.path]) imageCache[copyOfContext.path] = [] as ImageCacheEntry[] const contents = { update: copyOfContext.content as Content, } const coverImage = { update: copyOfContext.coverImage as string, } // Must run all async in series so that we don't end up with duplicates for (const match of matchables) { if (!copyOfContext.path) return const path = copyOfContext.path const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || [] const matchedCoverImages = (coverImage.update && [coverImage.update]) || [] for (const imageUrl of matched) await processImage(path, imageUrl, contents, options.debug) for (const imageUrl of matchedCoverImages) await processImage(path, imageUrl, coverImage, options.debug) } copyOfContext.content = contents.update copyOfContext.coverImage = coverImage.update try { if (!fs.existsSync(`${imageCacheDirectory}/remote`)) fs.mkdirSync(`${imageCacheDirectory}/remote`) fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache)) if (options.debug) fs.writeFileSync('debug/images.json', JSON.stringify(imageCache)) } catch (e) { if (options.debug) console.warn(e, 'ncms-plugin-images: error writing to image cache.') } return copyOfContext }, } }
src/plugins/images.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/plugins/linker.ts", "retrieved_chunk": " exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context)\n if (copyOfContext._notion?.id && copyOfContext.path)\n links.set(copyOfContext._notion?.id, copyOfContext.path)\n return copyOfContext\n },\n },\n {\n name: 'ncms-plugin-linker',\n hook: 'post-tree',", "score": 0.8536784648895264 }, { "filename": "src/plugins/head.ts", "retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',", "score": 0.8438869118690491 }, { "filename": "src/plugins/linker.ts", "retrieved_chunk": " core: true,\n exec: (context: CMS) => {\n const copyOfContext = structuredClone(context)\n const cmsWalker = NotionCMS._createCMSWalker((node: PageContent) => {\n let html: string | undefined = node.content?.html\n let md: string | undefined = node.content?.markdown\n let plaintext: string | undefined = node.content?.plaintext\n if (html) {\n const pathsToReplace = [...html.matchAll(ESCAPED_HREF_REGEX)]\n pathsToReplace.forEach((path) => {", "score": 0.8356519937515259 }, { "filename": "src/plugins/linker.ts", "retrieved_chunk": "import { idToUuid } from 'notion-utils'\nimport type { CMS, PageContent } from '../types'\nimport NotionCMS from '../notion-cms'\nconst links: Map<string, string> = new Map()\nconst ESCAPED_HREF_REGEX = /<a\\s+(?:[^>]*?\\s+)?href=([\"'])\\/([0-9a-f]{8}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{12})\\1/g\nexport default function () {\n return [{\n name: 'ncms-plugin-linker',\n hook: 'during-tree',\n core: true,", "score": 0.8339943289756775 }, { "filename": "src/notion-cms.ts", "retrieved_chunk": " // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n clackSpinner.stop(kleur.blue(`[ncms]: updated@ ${pageContent.path}`))\n },\n })\n .withRootObjectCallbacks(false)\n .withParallelizeAsyncCallbacks(true)\n .walk(stateWithContent.siteData)\n stateWithContent.stages.push('content')\n stateWithContent = await this._runPlugins(stateWithContent, 'post-tree') as CMS\n return stateWithContent", "score": 0.8324393630027771 } ]
typescript
context: PageContent, options: PluginExecOptions) => {
import { SETTINGS_DEFAULT } from "~/settings"; import { AutoTimelineSettings } from "./types"; import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils"; /** * Fetches the tags to find and timeline specific settings override. * * @param source - The markdown code block source, a.k.a. the content inside the code block. * @returns Partial settings to override the global ones. */ export function parseMarkdownBlockSource(source: string): { readonly tagsToFind: string[]; readonly settingsOverride: Partial<AutoTimelineSettings>; } { const sourceEntries = source.split("\n"); if (!source.length) return { tagsToFind: [] as string[], settingsOverride: {} } as const; const tagsToFind = sourceEntries[0] .split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator) .map((e) => e.trim()); sourceEntries.shift(); return { tagsToFind, settingsOverride: sourceEntries.reduce((accumulator, element) => { return { ...accumulator, ...parseSingleLine(element), }; }, {} as Partial<AutoTimelineSettings>), } as const; } type OverridableSettingKey = (typeof acceptedSettingsOverride)[number]; const acceptedSettingsOverride = [ "dateDisplayFormat", "applyAdditonalConditionFormatting", ] as const; /** * Checks if a given string is part of the settings keys that can be overriden. * * @param value - A given settings key. * @returns the typeguard boolean `true` if the key is indeed overridable. */ function isOverridableSettingsKey( value: string ): value is OverridableSettingKey { // @ts-expect-error return acceptedSettingsOverride.includes(value); } /** * Will apply the needed formatting to a setting value based of it's key. * * @param key - The settings key. * @param value - The value associated to this value. * @returns Undefined if unvalid or the actual expected value. */ function formatValueFromKey( key: string, value: string ): AutoTimelineSettings[OverridableSettingKey] | undefined { if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { const validBooleanStrings = ["true", "false"]; if (!validBooleanStrings.includes(value.toLocaleLowerCase())) throw new Error(`${value} is supposed to be a boolean`); return value.toLocaleLowerCase() === "true" ? true : false; } return undefined; } /** * Parse a single line of the timeline markdown block content. * * @param line - The line to parse. * @returns A potencialy partial settings object. */ function parseSingleLine(line: string): Partial<AutoTimelineSettings> { const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i; const matches = line.match(reg); if ( !matches || !matches.groups || !isDefinedAsString(matches.groups.key) || !isDefined(matches.groups.value) ) return {}; const key = matches.groups.key.trim(); const value = formatValueFromKey(key, matches.groups.value.trim()); if (!isDefined(value)) return {}; return { [key]: value }; }
src/markdownBlockData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/utils.ts", "retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {", "score": 0.8076854944229126 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.7845255136489868 }, { "filename": "src/utils.ts", "retrieved_chunk": "\treturn 0;\n}\n/**\n * Typeguard to check if a value is an array of unknowed sub type.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an array, `false` if not.\n */\nexport function isDefinedAsArray(value: unknown): value is unknown[] {\n\treturn isDefined(value) && value instanceof Array;", "score": 0.7789604067802429 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.", "score": 0.7702955007553101 }, { "filename": "src/settings.ts", "retrieved_chunk": " * Default key value relation for obsidian settings object\n */\nexport const SETTINGS_DEFAULT = {\n\tmetadataKeyEventStartDate: \"aat-event-start-date\",\n\tmetadataKeyEventEndDate: \"aat-event-end-date\",\n\tmetadataKeyEventTitleOverride: \"aat-event-title\",\n\tmetadataKeyEventBodyOverride: \"aat-event-body\",\n\tmetadataKeyEventPictureOverride: \"aat-event-picture\",\n\tmetadataKeyEventTimelineTag: \"timelines\",\n\tnoteInlineEventKey: \"aat-inline-event\",", "score": 0.7621468305587769 } ]
typescript
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString(); prioArray.
forEach((token, index) => {
const configuration = dateTokenConfiguration.find( ({ name }) => name === token ); if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8110610246658325 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.8061815500259399 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7972186803817749 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7819868922233582 }, { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.768772542476654 } ]
typescript
forEach((token, index) => {
import { PluginSettingTab } from "obsidian"; import { createApp, ref } from "vue"; import createVueI18nConfig from "~/i18n.config"; import VApp from "~/views/App.vue"; import type { App as ObsidianApp } from "obsidian"; import type AprilsAutomaticTimelinesPlugin from "~/main"; import type { AutoTimelineSettings, DateTokenConfiguration } from "./types"; import type { App as VueApp } from "vue"; import { createNumberDateTokenConfiguration } from "./utils"; /** * Default key value relation for obsidian settings object */ export const SETTINGS_DEFAULT = { metadataKeyEventStartDate: "aat-event-start-date", metadataKeyEventEndDate: "aat-event-end-date", metadataKeyEventTitleOverride: "aat-event-title", metadataKeyEventBodyOverride: "aat-event-body", metadataKeyEventPictureOverride: "aat-event-picture", metadataKeyEventTimelineTag: "timelines", noteInlineEventKey: "aat-inline-event", markdownBlockTagsToFindSeparator: ",", dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)", dateParserGroupPriority: "year,month,day", dateDisplayFormat: "{day}/{month}/{year}", lookForTagsForTimeline: false, lookForInlineEventsInNotes: true, applyAdditonalConditionFormatting: true, dateTokenConfiguration: [ createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }), createNumberDateTokenConfiguration({ name: "month" }), createNumberDateTokenConfiguration({ name: "day" }), ] as DateTokenConfiguration[], }; export const __VUE_PROD_DEVTOOLS__ = true; /** * Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note. */ export class TimelineSettingTab extends PluginSettingTab { plugin: AprilsAutomaticTimelinesPlugin; vueApp: VueApp<Element> | null; constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) { super(app, plugin); this.plugin = plugin; this.vueApp = null; } display(): void { this.containerEl.empty(); // TODO Read locale off obsidian. const i18n = createVueI18nConfig(); this.vueApp = createApp({ components: { VApp }, template: "<VApp :value='value' @update:value='save' />", setup: () => { const value = ref(this.plugin.settings); return { value,
save: async (payload: Partial<AutoTimelineSettings>) => {
this.plugin.settings = { ...this.plugin.settings, ...payload, }; value.value = this.plugin.settings; await this.plugin.saveSettings(); }, }; }, methods: {}, }); this.vueApp.use(i18n).mount(this.containerEl); } hide() { if (!this.vueApp) return; this.vueApp.unmount(); this.vueApp = null; } }
src/settings.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",", "score": 0.8141860365867615 }, { "filename": "src/types.ts", "retrieved_chunk": "};\nexport type AutoTimelineSettings = typeof SETTINGS_DEFAULT;\n/**\n * The main bundle of data needed to build a timeline.\n */\nexport interface MarkdownCodeBlockTimelineProcessingContext {\n\t/**\n\t * Obsidian application context.\n\t */\n\tapp: App;", "score": 0.8073461055755615 }, { "filename": "src/i18n.config.ts", "retrieved_chunk": "import { createI18n } from \"vue-i18n\";\nimport en from \"~/locales/en.json\";\nexport default () =>\n\tcreateI18n({\n\t\tlocale: \"en\",\n\t\tfallbackLocale: \"en\",\n\t\tmessages: {\n\t\t\ten,\n\t\t},\n\t\tallowComposition: true,", "score": 0.806962251663208 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.7968810796737671 }, { "filename": "src/timelineMarkup.ts", "retrieved_chunk": "\tconst { vault, metadataCache } = app;\n\tconst fileArray = vault.getMarkdownFiles();\n\tconst root = element.createDiv();\n\tconst cardListRootElement = root.createDiv();\n\tconst timelineRootElement = root.createDiv();\n\telement.classList.add(\"aat-root-container\");\n\troot.classList.add(\"aat-vertical-timeline\");\n\tcardListRootElement.classList.add(\"aat-card-list-root\");\n\ttimelineRootElement.classList.add(\"aat-timeline-root\");\n\tconst dataBundleArray = fileArray.reduce((accumulator, file) => {", "score": 0.7910130023956299 } ]
typescript
save: async (payload: Partial<AutoTimelineSettings>) => {
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (
isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8530809283256531 }, { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.8524672985076904 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8422019481658936 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8351073265075684 }, { "filename": "src/types.ts", "retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined", "score": 0.819185733795166 } ]
typescript
isDefined(baseData)) events.push(baseData);
import type { AudioBlock, Block, Blocks, BulletedListItemBlock, CalloutBlock, CodeBlock, EmbedBlock, FileBlock, HeadingBlock, ImageBlock, LinkPreviewBlock, LinkToPageBlock, NumberedListItemBlock, PDFBlock, ParagraphBlock, QuoteBlock, RichText, ToDoBlock, VideoBlock, } from '@notion-stuff/v4-types' import { z } from 'zod' import NotionBlocksMarkdownParser from './notion-blocks-md-parser' import NotionBlocksHtmlParser from './notion-blocks-html-parser' import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser' const blockRenderers = z.object({ AudioBlock: z.function().returns(z.string()), BulletedListItemBlock: z.function().returns(z.string()), CalloutBlock: z.function().returns(z.string()), CodeBlock: z.function().returns(z.string()), EmbedBlock: z.function().returns(z.string()), FileBlock: z.function().returns(z.string()), HeadingBlock: z.function().returns(z.string()), ImageBlock: z.function().returns(z.string()), LinkToPageBlock: z.function().returns(z.string()), NumberedListItemBlock: z.function().returns(z.string()), ParagraphBlock: z.function().returns(z.string()), PDFBlock: z.function().returns(z.string()), QuoteBlock: z.function().returns(z.string()), RichText: z.function().returns(z.string()), RichTextEquation: z.function().returns(z.string()), RichTextMention: z.function().returns(z.string()), RichTextText: z.function().returns(z.string()), ToDoBlock: z.function().returns(z.string()), ToggleBlock: z.function().returns(z.string()), VideoBlock: z.function().returns(z.string()), LinkPreviewBlock: z.function().returns(z.string()), }).partial() export type BlockRenderers = z.infer<typeof blockRenderers> type Renderer = (block: Block | RichText[], ...args: unknown[]) => string type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null function modularize( custom: CustomRenderer | undefined, def: Renderer): Renderer { return function render(block: Block | RichText[], ...args: unknown[]) { if (custom) { const customRender = custom(block, ...args) if (customRender !== null) return customRender } return def(block, ...args) } } export default class NotionBlocksParser { mdParser: NotionBlocksMarkdownParser htmlParser: NotionBlocksHtmlParser plainTextParser: NotionBlocksPlaintextParser debug: boolean constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { this.mdParser = new NotionBlocksMarkdownParser() this.plainTextParser = new NotionBlocksPlaintextParser() this.debug = debug || false this.mdParser.parseParagraph = modularize( blockRenderers?.ParagraphBlock, this.mdParser.parseParagraph.bind(this.mdParser) as Renderer, ) as (block: ParagraphBlock) => string this.mdParser.parseCodeBlock = modularize( blockRenderers?.CodeBlock, this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer, ) as (block: CodeBlock) => string this.mdParser.parseQuoteBlock = modularize( blockRenderers?.QuoteBlock, this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer, ) as (block: QuoteBlock) => string this.mdParser.parseCalloutBlock = modularize( blockRenderers?.CalloutBlock, this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer, ) as (block: CalloutBlock) => string this.mdParser.parseHeading = modularize( blockRenderers?.HeadingBlock, this.mdParser.parseHeading.bind(this.mdParser) as Renderer, ) as (block: HeadingBlock) => string this.mdParser.parseBulletedListItems = modularize( blockRenderers?.BulletedListItemBlock, this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer, ) as (block: BulletedListItemBlock) => string this.mdParser.parseLinkToPageBlock = modularize( blockRenderers?.LinkToPageBlock, this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer, ) as (block: LinkToPageBlock) => string this.mdParser.parseNumberedListItems = modularize( blockRenderers?.NumberedListItemBlock, this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer, ) as (block: NumberedListItemBlock) => string this.mdParser.parseTodoBlock = modularize( blockRenderers?.ToDoBlock, this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer, ) as (block: ToDoBlock) => string this.mdParser.parseImageBlock = modularize( blockRenderers?.ImageBlock, this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer, ) as (block: ImageBlock) => string this.mdParser.parseEmbedBlock = modularize( blockRenderers?.EmbedBlock, this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer, ) as (block: EmbedBlock) => string this.mdParser.parseAudioBlock = modularize( blockRenderers?.AudioBlock, this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer, ) as (block: AudioBlock) => string this.mdParser.parseVideoBlock = modularize( blockRenderers?.VideoBlock, this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer, ) as (block: VideoBlock) => string this.mdParser.parseFileBlock = modularize( blockRenderers?.FileBlock, this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer, ) as (block: FileBlock) => string this.mdParser.parsePdfBlock = modularize( blockRenderers?.PDFBlock, this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer, ) as (block: PDFBlock) => string this.mdParser.parseLinkPreview = modularize( blockRenderers?.LinkPreviewBlock, this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer, ) as (block: LinkPreviewBlock) => string // Warning: this parser is used in many of the other parsers internally. // Modding it could affect the others unexpectedly. this.mdParser.parseRichTexts = modularize( blockRenderers?.RichText, this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer, ) as (block: RichText[]) => string this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug) } markdownToPlainText(markdown: string): string { return this.plainTextParser.parse(markdown) } blocksToPlainText(blocks: Blocks, depth?: number): string { return this.plainTextParser.parse( this.blocksToMarkdown(blocks, depth)) } blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth) }
blocksToHtml(blocks: Blocks): string { return this.htmlParser.parse(blocks) } static parseRichText(richTexts: RichText[]) { const tempParser = new NotionBlocksMarkdownParser() return tempParser.parseRichTexts(richTexts) } }
src/notion-blocks-parser.ts
agency-kit-notion-cms-dfe1751
[ { "filename": "src/notion-blocks-html-parser.ts", "retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)", "score": 0.8762625455856323 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": "import { uuidToId } from 'notion-utils'\nconst EOL_MD = '\\n'\nexport default class NotionBlocksMarkdownParser {\n parse(blocks: Blocks, depth = 0): string {\n return blocks\n .reduce((markdown, childBlock) => {\n let childBlockString = ''\n // @ts-expect-error children\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (childBlock.has_children && childBlock[childBlock.type].children) {", "score": 0.8518797159194946 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " if (childBlock.type === 'link_to_page')\n markdown += this.parseLinkToPageBlock(childBlock).concat(childBlockString)\n if (childBlock.type === 'divider')\n markdown += EOL_MD.concat('---', EOL_MD, childBlockString)\n if (childBlock.type === 'link_preview')\n markdown += this.parseLinkPreview(childBlock).concat(childBlockString)\n return markdown\n }, '')\n .concat(EOL_MD)\n }", "score": 0.8476052284240723 }, { "filename": "src/notion-blocks-md-parser.ts", "retrieved_chunk": " parseLinkPreview(linkPreviewBlock: LinkPreviewBlock): string {\n return `<div notion-link-preview>\n <a href=\"${linkPreviewBlock.link_preview.url}\">${linkPreviewBlock.link_preview.url}</a>\n </div>\\n\\n`\n }\n parseParagraph(paragraphBlock: ParagraphBlock): string {\n const text: string = this.parseRichTexts(paragraphBlock.paragraph.rich_text)\n return EOL_MD.concat(text, EOL_MD)\n }\n parseCodeBlock(codeBlock: CodeBlock): string {", "score": 0.8444037437438965 }, { "filename": "src/notion-blocks-plaintext-parser.ts", "retrieved_chunk": "import type { Renderer as MarkedRenderer } from 'marked'\nimport { marked } from 'marked'\nimport _ from 'lodash'\nconst block = (text: string) => `${text}\\n\\n`\nconst escapeBlock = (text: string) => `${_.escape(text)}\\n\\n`\nconst line = (text: string) => `${text}\\n`\nconst inline = (text: string) => text\nconst newline = () => '\\n'\nconst empty = () => ''\nexport default class NotionBlocksPlaintextParser {", "score": 0.8401568531990051 } ]
typescript
return this.mdParser.parse(blocks, depth) }
import { SETTINGS_DEFAULT } from "~/settings"; import { FnGetRangeData } from "./rangeData"; import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData"; import type { App, CachedMetadata, TFile } from "obsidian"; import type { Merge } from "ts-essentials"; /** * @author https://stackoverflow.com/a/69756175 */ export type PickByType<T, Value> = { [P in keyof T as T[P] extends Value | undefined ? P : never]: T[P]; }; export type AutoTimelineSettings = typeof SETTINGS_DEFAULT; /** * The main bundle of data needed to build a timeline. */ export interface MarkdownCodeBlockTimelineProcessingContext { /** * Obsidian application context. */ app: App; /** * The plugins settings */ settings: AutoTimelineSettings; /** * The formatted metadata of a single note. */ cachedMetadata: CachedMetadata; /** * The file data of a single note. */ file: TFile; /** * The filepath of a single timeline. */ timelineFile: string; /** * Shorthand access to HTMLElements for the range timelines and the card list. */ elements: { timelineRootElement: HTMLElement; cardListRootElement: HTMLElement; }; } /** * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context. */ export type CompleteCardContext = Exclude< Awaited<ReturnType<typeof getDataFromNoteMetadata>>, undefined >; /** * The context extracted from a single note to create a single card in the timeline. */
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
/** * The needed data to compute a range in a single timeline. */ export type Range = ReturnType<FnGetRangeData>[number]; /** * An abstract representation of a fantasy date. * Given the fickle nature of story telling and how people will literally almost never stick to standard date formats * We'll organise the dates in segments, let's take for example our human callendar * The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to * `[year, month, day]` * Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates. * The only major limitation to this system is that all the dates must respect the same system. */ export type AbstractDate = number[]; /** * Before formatting an abstract date, the end user can configure it's output display * This DateToken type helps to determine what's the nature of a given token * E.g. should it be displayed as a number or as a string ? */ export enum DateTokenType { number = "NUMBER", string = "STRING", } export const availableDateTokenTypeArray = Object.values(DateTokenType); export enum Condition { Greater = "GREATER", Less = "LESS", Equal = "EQUAL", NotEqual = "NOTEQUAL", GreaterOrEqual = "GREATEROREQUAL", LessOrEqual = "LESSOREQUAL", } export const availableConditionArray = Object.values(Condition); export type Evaluation<T extends number = number> = { condition: Condition; value: T; }; export type AdditionalDateFormatting<T extends number = number> = { evaluations: Evaluation<T>[]; /** * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked. */ conditionsAreExclusive: boolean; /** * Use `{value}` to include the pre-formated output of the numerical value held. */ format: string; }; /** * The data used to compute the output of an abstract date based on it's type */ type CommonValues<T extends DateTokenType> = { name: string; type: T; formatting: AdditionalDateFormatting[]; }; export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> = T extends DateTokenType.number ? NumberSpecific : T extends DateTokenType.string ? StringSpecific : StringSpecific | NumberSpecific; /** * Number typed date token. */ type NumberSpecific = Merge< CommonValues<DateTokenType.number>, { /** * The minimum ammount of digits when displaying the date */ minLeght: number; displayWhenZero: boolean; hideSign: boolean; } >; /** * String typed date token. */ type StringSpecific = Merge< CommonValues<DateTokenType.string>, { /** * The dictionary reference for the token */ dictionary: string[]; } >;
src/types.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.825899600982666 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.8241854310035706 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};", "score": 0.8193052411079407 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.8165643215179443 }, { "filename": "src/cardData.ts", "retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;", "score": 0.8160060048103333 } ]
typescript
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
import PROP_PREFIX from './prefix'; // part and slotted not currently supported by quarks const PSEUDO_ELEMENTS = [ // '::part()', // '::slotted()', '::after', '::backdrop', '::before', '::cue', '::cue-region', '::first-letter', '::first-line', '::file-selector-button', '::grammar-error', '::marker', '::placeholder', '::selection', '::spelling-error', '::target-text', '::-moz-placeholder', '::-moz-progress-bar', '::-moz-range-progress', '::-moz-range-thumb', '::-moz-range-track', '::-moz-selection', '::-ms-backdrop', '::-ms-browse', '::-ms-check', '::-ms-clear', '::-ms-expand', '::-ms-fill', '::-ms-fill-lower', '::-ms-fill-upper', '::-ms-input-placeholder', '::-ms-reveal', '::-ms-thumb', '::-ms-ticks-after', '::-ms-ticks-before', '::-ms-tooltip', '::-ms-track', '::-ms-value', '::-webkit-backdrop', '::-webkit-input-placeholder', '::-webkit-progress-bar', '::-webkit-progress-inner-value', '::-webkit-progress-value', '::-webkit-slider-runnable-track', '::-webkit-slider-thumb', ];
export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX));
export default PSEUDO_ELEMENTS;
src/constants/pseudoElements.ts
quarks-css-quarks-2822055
[ { "filename": "src/types/pseudos.ts", "retrieved_chunk": "import type { PropPrefix } from '../constants/prefix';\nimport type { Replace } from '../utils/typeUtils';\nimport type { Pseudos } from 'csstype';\ntype FilterPseudoTypes<T extends string, U extends string> = T extends `${U}${string}` ? T : never;\ntype PseudoElements = FilterPseudoTypes<Pseudos, '::'>;\ntype PseudoClasses = Exclude<Pseudos, PseudoElements>;\nexport type PseudoClassProps = Replace<PseudoClasses, ':', PropPrefix>;\nexport type PseudoElementProps = Exclude<Replace<PseudoElements, '::', PropPrefix>, '$slotted' | '$part'>;", "score": 0.8513625264167786 }, { "filename": "src/utils/propChecks.ts", "retrieved_chunk": "export const isPseudo = (value: unknown): value is Record<string, unknown> => typeof value === 'object';\nexport const isPseudoElement = (propName: string) => prefixedPseudoElements.includes(propName);", "score": 0.8396684527397156 }, { "filename": "src/utils/propChecks.ts", "retrieved_chunk": "import { prefixedPseudoElements } from '../constants/pseudoElements';\nimport media from '../theme/breakpoints';\nimport { customOverwrites } from '../theme/customOverwrites';\nimport type { valueof } from './typeUtils';\ntype customOverWriteValues = Parameters<valueof<typeof customOverwrites>>[number];\nexport const isCustomOverwrite = (\n prop: [string, unknown],\n): prop is [keyof typeof customOverwrites, customOverWriteValues] => prop[0] in customOverwrites;\nexport const isMediaQuery = (prop: [string, unknown]): prop is [keyof typeof media, Record<string, unknown>] =>\n prop[0] in media;", "score": 0.826177716255188 }, { "filename": "src/types/quarkProps.ts", "retrieved_chunk": "import type { PseudoClassProps, PseudoElementProps } from './pseudos';\nimport type media from '../theme/breakpoints';\nimport type { OverwriteValues } from '../theme/customOverwrites';\nimport type { OverwriteProperties, Prefix } from '../utils/typeUtils';\nimport type { Properties } from 'csstype';\nimport type { DefaultTheme, Theme } from 'goober';\ntype PrefixedProperties = Prefix<Properties, '$'>;\ntype DirectStyleProps = OverwriteProperties<PrefixedProperties, OverwriteValues>;\nexport type StyleProps = DirectStyleProps & {\n [P in keyof typeof media]?: StyleProps;", "score": 0.8155877590179443 }, { "filename": "src/createStylesFromProps.ts", "retrieved_chunk": "import PROP_PREFIX from './constants/prefix';\nimport { validateProp } from './setup';\nimport media from './theme/breakpoints';\nimport { customOverwrites } from './theme/customOverwrites';\nimport { camelToKebabCase } from './utils/functions';\nimport { isCustomOverwrite, isMediaQuery, isPseudo, isPseudoElement } from './utils/propChecks';\nimport { objectEntries } from './utils/typeUtils';\nimport type { CSSAttribute } from 'goober';\nconst createStylesFromProps = (props: Record<string, unknown>): CSSAttribute =>\n objectEntries(props).reduce((prevValue, prop) => {", "score": 0.8155117630958557 } ]
typescript
export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX));
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString(); prioArray.forEach((token, index) => { const configuration = dateTokenConfiguration.find( (
{ name }) => name === token );
if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8117526769638062 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.7961183786392212 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7815698981285095 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7750324606895447 }, { "filename": "src/types.ts", "retrieved_chunk": "};\nexport type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =\n\tT extends DateTokenType.number\n\t\t? NumberSpecific\n\t\t: T extends DateTokenType.string\n\t\t? StringSpecific\n\t\t: StringSpecific | NumberSpecific;\n/**\n * Number typed date token.\n */", "score": 0.7630138993263245 } ]
typescript
{ name }) => name === token );
import { PluginSettingTab } from "obsidian"; import { createApp, ref } from "vue"; import createVueI18nConfig from "~/i18n.config"; import VApp from "~/views/App.vue"; import type { App as ObsidianApp } from "obsidian"; import type AprilsAutomaticTimelinesPlugin from "~/main"; import type { AutoTimelineSettings, DateTokenConfiguration } from "./types"; import type { App as VueApp } from "vue"; import { createNumberDateTokenConfiguration } from "./utils"; /** * Default key value relation for obsidian settings object */ export const SETTINGS_DEFAULT = { metadataKeyEventStartDate: "aat-event-start-date", metadataKeyEventEndDate: "aat-event-end-date", metadataKeyEventTitleOverride: "aat-event-title", metadataKeyEventBodyOverride: "aat-event-body", metadataKeyEventPictureOverride: "aat-event-picture", metadataKeyEventTimelineTag: "timelines", noteInlineEventKey: "aat-inline-event", markdownBlockTagsToFindSeparator: ",", dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)", dateParserGroupPriority: "year,month,day", dateDisplayFormat: "{day}/{month}/{year}", lookForTagsForTimeline: false, lookForInlineEventsInNotes: true, applyAdditonalConditionFormatting: true, dateTokenConfiguration: [ createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }), createNumberDateTokenConfiguration({ name: "month" }), createNumberDateTokenConfiguration({ name: "day" }), ] as DateTokenConfiguration[], }; export const __VUE_PROD_DEVTOOLS__ = true; /** * Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note. */ export class TimelineSettingTab extends PluginSettingTab { plugin: AprilsAutomaticTimelinesPlugin; vueApp: VueApp<Element> | null; constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) { super(app, plugin); this.plugin = plugin; this.vueApp = null; } display(): void { this.containerEl.empty(); // TODO Read locale off obsidian.
const i18n = createVueI18nConfig();
this.vueApp = createApp({ components: { VApp }, template: "<VApp :value='value' @update:value='save' />", setup: () => { const value = ref(this.plugin.settings); return { value, save: async (payload: Partial<AutoTimelineSettings>) => { this.plugin.settings = { ...this.plugin.settings, ...payload, }; value.value = this.plugin.settings; await this.plugin.saveSettings(); }, }; }, methods: {}, }); this.vueApp.use(i18n).mount(this.containerEl); } hide() { if (!this.vueApp) return; this.vueApp.unmount(); this.vueApp = null; } }
src/settings.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",", "score": 0.8287190794944763 }, { "filename": "src/timelineMarkup.ts", "retrieved_chunk": "\tconst { vault, metadataCache } = app;\n\tconst fileArray = vault.getMarkdownFiles();\n\tconst root = element.createDiv();\n\tconst cardListRootElement = root.createDiv();\n\tconst timelineRootElement = root.createDiv();\n\telement.classList.add(\"aat-root-container\");\n\troot.classList.add(\"aat-vertical-timeline\");\n\tcardListRootElement.classList.add(\"aat-card-list-root\");\n\ttimelineRootElement.classList.add(\"aat-timeline-root\");\n\tconst dataBundleArray = fileArray.reduce((accumulator, file) => {", "score": 0.8034178614616394 }, { "filename": "src/types.ts", "retrieved_chunk": "};\nexport type AutoTimelineSettings = typeof SETTINGS_DEFAULT;\n/**\n * The main bundle of data needed to build a timeline.\n */\nexport interface MarkdownCodeBlockTimelineProcessingContext {\n\t/**\n\t * Obsidian application context.\n\t */\n\tapp: App;", "score": 0.7816901206970215 }, { "filename": "src/i18n.config.ts", "retrieved_chunk": "import { createI18n } from \"vue-i18n\";\nimport en from \"~/locales/en.json\";\nexport default () =>\n\tcreateI18n({\n\t\tlocale: \"en\",\n\t\tfallbackLocale: \"en\",\n\t\tmessages: {\n\t\t\ten,\n\t\t},\n\t\tallowComposition: true,", "score": 0.778369665145874 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.7666734457015991 } ]
typescript
const i18n = createVueI18nConfig();
import { SETTINGS_DEFAULT } from "~/settings"; import { AutoTimelineSettings } from "./types"; import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils"; /** * Fetches the tags to find and timeline specific settings override. * * @param source - The markdown code block source, a.k.a. the content inside the code block. * @returns Partial settings to override the global ones. */ export function parseMarkdownBlockSource(source: string): { readonly tagsToFind: string[]; readonly settingsOverride: Partial<AutoTimelineSettings>; } { const sourceEntries = source.split("\n"); if (!source.length) return { tagsToFind: [] as string[], settingsOverride: {} } as const; const tagsToFind = sourceEntries[0] .split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator) .map((e) => e.trim()); sourceEntries.shift(); return { tagsToFind, settingsOverride: sourceEntries.reduce((accumulator, element) => { return { ...accumulator, ...parseSingleLine(element), }; }, {} as Partial<AutoTimelineSettings>), } as const; } type OverridableSettingKey = (typeof acceptedSettingsOverride)[number]; const acceptedSettingsOverride = [ "dateDisplayFormat", "applyAdditonalConditionFormatting", ] as const; /** * Checks if a given string is part of the settings keys that can be overriden. * * @param value - A given settings key. * @returns the typeguard boolean `true` if the key is indeed overridable. */ function isOverridableSettingsKey( value: string ): value is OverridableSettingKey { // @ts-expect-error return acceptedSettingsOverride.includes(value); } /** * Will apply the needed formatting to a setting value based of it's key. * * @param key - The settings key. * @param value - The value associated to this value. * @returns Undefined if unvalid or the actual expected value. */ function formatValueFromKey( key: string, value: string ): AutoTimelineSettings[OverridableSettingKey] | undefined { if (!isOverridableSettingsKey(key)) return undefined; if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; if
(isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"]; if (!validBooleanStrings.includes(value.toLocaleLowerCase())) throw new Error(`${value} is supposed to be a boolean`); return value.toLocaleLowerCase() === "true" ? true : false; } return undefined; } /** * Parse a single line of the timeline markdown block content. * * @param line - The line to parse. * @returns A potencialy partial settings object. */ function parseSingleLine(line: string): Partial<AutoTimelineSettings> { const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i; const matches = line.match(reg); if ( !matches || !matches.groups || !isDefinedAsString(matches.groups.key) || !isDefined(matches.groups.value) ) return {}; const key = matches.groups.key.trim(); const value = formatValueFromKey(key, matches.groups.value.trim()); if (!isDefined(value)) return {}; return { [key]: value }; }
src/markdownBlockData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/utils.ts", "retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {", "score": 0.8089927434921265 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8058614730834961 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.", "score": 0.793164074420929 }, { "filename": "src/utils.ts", "retrieved_chunk": "\treturn 0;\n}\n/**\n * Typeguard to check if a value is an array of unknowed sub type.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an array, `false` if not.\n */\nexport function isDefinedAsArray(value: unknown): value is unknown[] {\n\treturn isDefined(value) && value instanceof Array;", "score": 0.7820466160774231 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "\t}: Pick<\n\t\tAutoTimelineSettings,\n\t\t| \"dateDisplayFormat\"\n\t\t| \"dateParserGroupPriority\"\n\t\t| \"dateTokenConfiguration\"\n\t\t| \"applyAdditonalConditionFormatting\"\n\t>\n): string {\n\tif (typeof date === \"boolean\") return \"now\";\n\tconst prioArray = dateParserGroupPriority.split(\",\");", "score": 0.7789130210876465 } ]
typescript
(isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output
= dateDisplayFormat.toString();
prioArray.forEach((token, index) => { const configuration = dateTokenConfiguration.find( ({ name }) => name === token ); if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8252766728401184 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.8032549619674683 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7940285205841064 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7915412187576294 }, { "filename": "src/utils.ts", "retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);", "score": 0.7680331468582153 } ]
typescript
= dateDisplayFormat.toString();
import { SETTINGS_DEFAULT } from "~/settings"; import { FnGetRangeData } from "./rangeData"; import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData"; import type { App, CachedMetadata, TFile } from "obsidian"; import type { Merge } from "ts-essentials"; /** * @author https://stackoverflow.com/a/69756175 */ export type PickByType<T, Value> = { [P in keyof T as T[P] extends Value | undefined ? P : never]: T[P]; }; export type AutoTimelineSettings = typeof SETTINGS_DEFAULT; /** * The main bundle of data needed to build a timeline. */ export interface MarkdownCodeBlockTimelineProcessingContext { /** * Obsidian application context. */ app: App; /** * The plugins settings */ settings: AutoTimelineSettings; /** * The formatted metadata of a single note. */ cachedMetadata: CachedMetadata; /** * The file data of a single note. */ file: TFile; /** * The filepath of a single timeline. */ timelineFile: string; /** * Shorthand access to HTMLElements for the range timelines and the card list. */ elements: { timelineRootElement: HTMLElement; cardListRootElement: HTMLElement; }; } /** * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context. */ export type CompleteCardContext = Exclude< Awaited<ReturnType<typeof getDataFromNoteMetadata>>, undefined >; /** * The context extracted from a single note to create a single card in the timeline. */ export type CardContent = Awaited<ReturnType<FnExtractCardData>>; /** * The needed data to compute a range in a single timeline. */ export type
Range = ReturnType<FnGetRangeData>[number];
/** * An abstract representation of a fantasy date. * Given the fickle nature of story telling and how people will literally almost never stick to standard date formats * We'll organise the dates in segments, let's take for example our human callendar * The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to * `[year, month, day]` * Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates. * The only major limitation to this system is that all the dates must respect the same system. */ export type AbstractDate = number[]; /** * Before formatting an abstract date, the end user can configure it's output display * This DateToken type helps to determine what's the nature of a given token * E.g. should it be displayed as a number or as a string ? */ export enum DateTokenType { number = "NUMBER", string = "STRING", } export const availableDateTokenTypeArray = Object.values(DateTokenType); export enum Condition { Greater = "GREATER", Less = "LESS", Equal = "EQUAL", NotEqual = "NOTEQUAL", GreaterOrEqual = "GREATEROREQUAL", LessOrEqual = "LESSOREQUAL", } export const availableConditionArray = Object.values(Condition); export type Evaluation<T extends number = number> = { condition: Condition; value: T; }; export type AdditionalDateFormatting<T extends number = number> = { evaluations: Evaluation<T>[]; /** * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked. */ conditionsAreExclusive: boolean; /** * Use `{value}` to include the pre-formated output of the numerical value held. */ format: string; }; /** * The data used to compute the output of an abstract date based on it's type */ type CommonValues<T extends DateTokenType> = { name: string; type: T; formatting: AdditionalDateFormatting[]; }; export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> = T extends DateTokenType.number ? NumberSpecific : T extends DateTokenType.string ? StringSpecific : StringSpecific | NumberSpecific; /** * Number typed date token. */ type NumberSpecific = Merge< CommonValues<DateTokenType.number>, { /** * The minimum ammount of digits when displaying the date */ minLeght: number; displayWhenZero: boolean; hideSign: boolean; } >; /** * String typed date token. */ type StringSpecific = Merge< CommonValues<DateTokenType.string>, { /** * The dictionary reference for the token */ dictionary: string[]; } >;
src/types.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.8190391063690186 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\t\t? true\n\t\t\t\t: undefined),\n\t} as const;\n}\nexport type FnExtractCardData = typeof extractCardData;", "score": 0.8115149736404419 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.8103598356246948 }, { "filename": "src/cardData.ts", "retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;", "score": 0.8096693754196167 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.8050939440727234 } ]
typescript
Range = ReturnType<FnGetRangeData>[number];
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString(); prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find( ({ name }) => name === token );
if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.8154218196868896 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8152629137039185 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7975974082946777 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7881563901901245 }, { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.7839699983596802 } ]
typescript
const configuration = dateTokenConfiguration.find( ({ name }) => name === token );
import { isDefined, findLastIndex, lerp, inLerp, getChildAtIndexInHTMLElement, compareAbstractDates, } from "~/utils"; import type { CompleteCardContext, AbstractDate } from "~/types"; /** * Will compute all the data needed to build ranges in the timeline. * * @param collection - The complete collection of relevant data gathered from notes. * @returns the needed data to build ranges in the timeline. */ export function getAllRangeData(collection: CompleteCardContext[]) { if (!collection.length) return []; return collection.reduce( (accumulator, relatedCardData, index) => { const { context: { elements: { timelineRootElement, cardListRootElement }, }, cardData: { startDate, endDate }, } = relatedCardData; if (!isDefined(startDate) || !isDefined(endDate)) return accumulator; if ( endDate !== true && compareAbstractDates(endDate, startDate) < 0 ) return accumulator; const timelineLength = timelineRootElement.offsetHeight; const targetCard = cardListRootElement.children.item( index ) as HTMLElement | null; // Error handling but should not happen if (!targetCard) return accumulator; const cardRelativeTopPosition = targetCard.offsetTop; let targetPosition: number; if (endDate === true) targetPosition = timelineLength; else targetPosition = findEndPositionForDate( endDate, collection.slice(index), timelineLength, cardListRootElement, index ); accumulator.push({ relatedCardData: { ...relatedCardData, cardData: { ...relatedCardData.cardData, endDate, startDate, }, }, targetPosition, cardRelativeTopPosition, index, } as const); return accumulator; }, [] as { readonly relatedCardData: CompleteCardContext & { cardData: CompleteCardContext["cardData"] & {
startDate: AbstractDate;
endDate: AbstractDate | true; }; }; readonly index: number; readonly targetPosition: number; readonly cardRelativeTopPosition: number; }[] ); } export type FnGetRangeData = typeof getAllRangeData; /** * Finds the end position in pixel relative to the top of the timeline root element for the give endDate of a range. * * @param date - The target endDate to position on the timeline. * @param collection - The collection of cards part of the same timeline. * @param timelineLength - The length in pixel of the timeline. * @param rootElement - The root HTMLElement of the cardList. * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before. * @returns The expected position relative to the top of the timeline container for this date range. */ export function findEndPositionForDate( date: AbstractDate, collection: CompleteCardContext[], timelineLength: number, rootElement: HTMLElement, indexOffset: number ): number { if (collection.length <= 1) return timelineLength; try { const { start, end } = findBoundaries( date, collection, rootElement, indexOffset ); const [inLerpStart, inLerpEnd, targetInLerpDate] = getInLerpValues( start.date, end.date, date ); const t = inLerp(inLerpStart, inLerpEnd, targetInLerpDate); return lerp(start.top, end.top, t); } catch (_) { return timelineLength; } } /** * Gets the values to compute the inlerp needed for range gutter renders. * * @param a - The start date * @param b - The end date * @param c - The date in between * @returns the first non equal member of a - b when compared from left to right, also returns the same member from c. */ export function getInLerpValues( a: AbstractDate, b: AbstractDate, c: AbstractDate ): [number, number, number] { for (let index = 0; index < a.length; index++) { if (a[index] === b[index]) continue; return [a[index], b[index], c[index]]; } return [0, 1, 1]; } type Boundary = { date: AbstractDate; top: number }; /** * Find the position of the last card having a lower start date and the first card with a higher start date relative to the endDate of the evaluated range. * * @param date - The target endDate to position on the timeline. * @param collection - The collection of cards part of the same timeline. * @param rootElement - The root HTMLElement of the cardList. * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before. * @returns The start and end boundaries of the target end date. */ export function findBoundaries( date: AbstractDate, collection: CompleteCardContext[], rootElement: HTMLElement, indexOffset: number ): { start: Boundary; end: Boundary } { const firstOverIndex = collection.findIndex(({ cardData: { startDate } }) => isDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false ); if (firstOverIndex === -1) throw new Error( "No first over found - Can't draw range since there are no other two start date to referrence it's position" ); const firstLastUnderIndex = findLastIndex( collection, ({ cardData: { startDate } }) => isDefined(startDate) ? compareAbstractDates(startDate, date) <= 0 : false ); if (firstLastUnderIndex === -1) throw new Error( "Could not find a firstLastUnderIndex, this means this function was called with un rangeable members" ); const lastUnderIndex = collection.findIndex( ({ cardData: { startDate } }, index) => { return ( compareAbstractDates( startDate, collection[firstLastUnderIndex].cardData.startDate ) === 0 ); } ); if (lastUnderIndex === -1) throw new Error( "No last under found - Can't draw range since there are no other two start date to referrence it's position" ); const startElement = getChildAtIndexInHTMLElement( rootElement, lastUnderIndex + indexOffset ); const startDate = collection[lastUnderIndex].cardData .startDate as AbstractDate; const startIsMoreThanOneCardAway = lastUnderIndex > 1; const shouldOffsetStartToBottomOfCard = startIsMoreThanOneCardAway && compareAbstractDates(startDate, date) !== 0; return { start: { top: startElement.offsetTop + (shouldOffsetStartToBottomOfCard ? startElement.innerHeight : 0), date: startDate, }, end: { top: getChildAtIndexInHTMLElement( rootElement, firstOverIndex + indexOffset ).offsetTop, date: collection[firstOverIndex].cardData.startDate as AbstractDate, }, }; }
src/rangeData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/types.ts", "retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined", "score": 0.8206149339675903 }, { "filename": "src/rangeMarkup.ts", "retrieved_chunk": "\t\t\t},\n\t\t},\n\t\ttargetPosition,\n\t\tcardRelativeTopPosition,\n\t\tindex,\n\t}: Range,\n\toffset: number,\n\trootElelement: HTMLElement\n) {\n\tconst el = createElementShort(", "score": 0.8100652098655701 }, { "filename": "src/timelineMarkup.ts", "retrieved_chunk": "\t\t\t\t\tcardListRootElement,\n\t\t\t\t},\n\t\t\t});\n\t\treturn accumulator;\n\t}, [] as MarkdownCodeBlockTimelineProcessingContext[]);\n\treturn dataBundleArray;\n}", "score": 0.7953791618347168 }, { "filename": "src/types.ts", "retrieved_chunk": ">;\n/**\n * The context extracted from a single note to create a single card in the timeline.\n */\nexport type CardContent = Awaited<ReturnType<FnExtractCardData>>;\n/**\n * The needed data to compute a range in a single timeline.\n */\nexport type Range = ReturnType<FnGetRangeData>[number];\n/**", "score": 0.7895713448524475 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\t\t\tconst score = compareAbstractDates(a, b);\n\t\t\t\tif (score) return score;\n\t\t\t\treturn compareAbstractDates(aE, bE);\n\t\t\t}\n\t\t);\n\t\tcardDataTime();\n\t\tconst cardRenderTime = measureTime(\"Card Render\");\n\t\tevents.forEach(({ context, cardData }) =>\n\t\t\tcreateCardFromBuiltContext(context, cardData)\n\t\t);", "score": 0.7882733345031738 } ]
typescript
startDate: AbstractDate;
import { SETTINGS_DEFAULT } from "~/settings"; import { AutoTimelineSettings } from "./types"; import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils"; /** * Fetches the tags to find and timeline specific settings override. * * @param source - The markdown code block source, a.k.a. the content inside the code block. * @returns Partial settings to override the global ones. */ export function parseMarkdownBlockSource(source: string): { readonly tagsToFind: string[]; readonly settingsOverride: Partial<AutoTimelineSettings>; } { const sourceEntries = source.split("\n"); if (!source.length) return { tagsToFind: [] as string[], settingsOverride: {} } as const; const tagsToFind = sourceEntries[0] .split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator) .map((e) => e.trim()); sourceEntries.shift(); return { tagsToFind, settingsOverride: sourceEntries.reduce((accumulator, element) => { return { ...accumulator, ...parseSingleLine(element), }; }, {} as Partial<AutoTimelineSettings>), } as const; } type OverridableSettingKey = (typeof acceptedSettingsOverride)[number]; const acceptedSettingsOverride = [ "dateDisplayFormat", "applyAdditonalConditionFormatting", ] as const; /** * Checks if a given string is part of the settings keys that can be overriden. * * @param value - A given settings key. * @returns the typeguard boolean `true` if the key is indeed overridable. */ function isOverridableSettingsKey( value: string ): value is OverridableSettingKey { // @ts-expect-error return acceptedSettingsOverride.includes(value); } /** * Will apply the needed formatting to a setting value based of it's key. * * @param key - The settings key. * @param value - The value associated to this value. * @returns Undefined if unvalid or the actual expected value. */ function formatValueFromKey( key: string, value: string ): AutoTimelineSettings[OverridableSettingKey] | undefined { if (!isOverridableSettingsKey(key)) return undefined; if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { const validBooleanStrings = ["true", "false"]; if (!validBooleanStrings.includes(value.toLocaleLowerCase())) throw new Error(`${value} is supposed to be a boolean`); return value.toLocaleLowerCase() === "true" ? true : false; } return undefined; } /** * Parse a single line of the timeline markdown block content. * * @param line - The line to parse. * @returns A potencialy partial settings object. */ function parseSingleLine(line: string): Partial<AutoTimelineSettings> { const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i; const matches = line.match(reg); if ( !matches || !matches.groups || !isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value) ) return {};
const key = matches.groups.key.trim(); const value = formatValueFromKey(key, matches.groups.value.trim()); if (!isDefined(value)) return {}; return { [key]: value }; }
src/markdownBlockData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7891091108322144 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.7841635942459106 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "import {\n\tisDefinedAsString,\n\tisDefined,\n\tisDefinedAsArray,\n\tgetMetadataKey,\n\tparseAbstractDate,\n} from \"~/utils\";\nimport { FrontMatterCache, TagCache, TFile } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,", "score": 0.7838301062583923 }, { "filename": "src/utils.ts", "retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);", "score": 0.7838176488876343 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.7802542448043823 } ]
typescript
!isDefined(matches.groups.value) ) return {};
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString(); prioArray.forEach((token, index) => { const configuration = dateTokenConfiguration.find( ({ name }) => name === token ); if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8248920440673828 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7955734729766846 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7896453738212585 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.78301602602005 }, { "filename": "src/cardMarkup.ts", "retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}", "score": 0.7801997661590576 } ]
typescript
const prioArray = dateParserGroupPriority.split(",");
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString(); prioArray.forEach((token, index) => { const configuration = dateTokenConfiguration.find( ({ name }) => name === token ); if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string {
if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.7985379695892334 }, { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.7941575646400452 }, { "filename": "src/types.ts", "retrieved_chunk": "\t */\n\tformat: string;\n};\n/**\n * The data used to compute the output of an abstract date based on it's type\n */\ntype CommonValues<T extends DateTokenType> = {\n\tname: string;\n\ttype: T;\n\tformatting: AdditionalDateFormatting[];", "score": 0.780910849571228 }, { "filename": "src/types.ts", "retrieved_chunk": "};\nexport type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =\n\tT extends DateTokenType.number\n\t\t? NumberSpecific\n\t\t: T extends DateTokenType.string\n\t\t? StringSpecific\n\t\t: StringSpecific | NumberSpecific;\n/**\n * Number typed date token.\n */", "score": 0.7638307809829712 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7587178945541382 } ]
typescript
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string {
import { dateTokenConfigurationIsTypeNumber, dateTokenConfigurationIsTypeString, evalNumericalCondition, } from "~/utils"; import type { AutoTimelineSettings, AbstractDate, DateTokenConfiguration, DateTokenType, AdditionalDateFormatting, } from "~/types"; /** * Handy function to format an abstract date based on the current settings. * * @param date - Target date to format. * @param param1 - The settings of the plugin. * @param param1.dateDisplayFormat - The target format to displat the date in. * @param param1.dateParserGroupPriority - The token priority list for the date format. * @param param1.dateTokenConfiguration - The configuration for the given date format. * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the formated representation of a given date based off the plugins settings. */ export function formatAbstractDate( date: AbstractDate | boolean, { dateDisplayFormat, dateParserGroupPriority, dateTokenConfiguration, applyAdditonalConditionFormatting, }: Pick< AutoTimelineSettings, | "dateDisplayFormat" | "dateParserGroupPriority" | "dateTokenConfiguration" | "applyAdditonalConditionFormatting" > ): string { if (typeof date === "boolean") return "now"; const prioArray = dateParserGroupPriority.split(","); let output = dateDisplayFormat.toString(); prioArray.forEach((token, index) => { const configuration = dateTokenConfiguration.find(
({ name }) => name === token );
if (!configuration) throw new Error( `[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly` ); output = output.replace( `{${token}}`, applyConditionBasedFormatting( formatDateToken(date[index], configuration), date[index], configuration, applyAdditonalConditionFormatting ) ); }); return output; } /** * Shorthand to format a part of an abstract date. * * @param datePart - fragment of an abstract date. * @param configuration - the configuration bound to that date token. * @returns the formated token. */ export function formatDateToken( datePart: number, configuration: DateTokenConfiguration ): string { if (dateTokenConfigurationIsTypeNumber(configuration)) return formatNumberDateToken(datePart, configuration); if (dateTokenConfigurationIsTypeString(configuration)) return formatStringDateToken(datePart, configuration); throw new Error( `[April's not so automatic timelines] - Corrupted date token configuration, please reset settings` ); } /** * This functions processes each tokens additional conditional formatting. * * @param formatedDate - The previously processed date token. * @param date - The numerical value of the token. * @param configuration - The configuration of the token. * @param configuration.formatting - The formatting array bound to a token configuration. * @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings. * @returns the fully formated token ready to be inserted in the output string. */ export function applyConditionBasedFormatting( formatedDate: string, date: number, { formatting }: DateTokenConfiguration, applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"] ): string { if (!applyAdditonalConditionFormatting) return formatedDate; return formatting.reduce( (output, { format, conditionsAreExclusive, evaluations }) => { const evaluationRestult = ( conditionsAreExclusive ? evaluations.some : evaluations.every ).bind(evaluations)( ({ condition, value, }: AdditionalDateFormatting["evaluations"][number]) => evalNumericalCondition(condition, date, value) ); if (evaluationRestult) return format.replace("{value}", output); return output; }, formatedDate ); } /** * Used to quickly format a fragment of an abstract date based off a number typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A numerical date token configuration to apply. * @param param1.minLeght - the minimal length of a numerical date input. * @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting. * @returns the formated token. */ function formatNumberDateToken( datePart: number, { minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number> ): string { let stringifiedToken = Math.abs(datePart).toString(); if (minLeght < 0) return stringifiedToken; while (stringifiedToken.length < minLeght) stringifiedToken = "0" + stringifiedToken; if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`; return stringifiedToken; } /** * Used to quickly format a fragment of an abstract date based off a string typed date token configuration. * * @param datePart - fragment of an abstract date. * @param param1 - A string typed date token configuration to apply. * @param param1.dictionary - the relation dictionary for a date string typed token. * @returns the formated token. */ function formatStringDateToken( datePart: number, { dictionary }: DateTokenConfiguration<DateTokenType.string> ): string { return dictionary[datePart]; }
src/abstractDateFormatting.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/types.ts", "retrieved_chunk": " * Before formatting an abstract date, the end user can configure it's output display\n * This DateToken type helps to determine what's the nature of a given token\n * E.g. should it be displayed as a number or as a string ?\n */\nexport enum DateTokenType {\n\tnumber = \"NUMBER\",\n\tstring = \"STRING\",\n}\nexport const availableDateTokenTypeArray = Object.values(DateTokenType);\nexport enum Condition {", "score": 0.815454363822937 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.8152152299880981 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.7975360155105591 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}", "score": 0.7881374359130859 }, { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.7838358879089355 } ]
typescript
({ name }) => name === token );
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils"; import type { MarkdownCodeBlockTimelineProcessingContext, CompleteCardContext, } from "~/types"; import { parse } from "yaml"; import { getAbstractDateFromMetadata, getBodyFromContextOrDocument, getImageUrlFromContextOrDocument, getTagsFromMetadataOrTagObject, } from "./cardDataExtraction"; /** * A un-changeable key used to check if a note is eligeable for render. */ const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"]; /** * Provides additional context for the creation cards in the DOM. * * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteMetadata( context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ) { const { cachedMetadata, settings } = context; const { frontmatter: metaData, tags } = cachedMetadata; if (!metaData) return undefined; if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true)) return undefined; const timelineTags = getTagsFromMetadataOrTagObject( settings, metaData, tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined; return { cardData: await extractCardData(context), context, } as const; } /** * Provides additional context for the creation cards in the DOM but reads it from the body * * @param body - The extracted body for a single event card. * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteBody( body: string | undefined | null, context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ): Promise<CompleteCardContext[]> { const { settings } = context; if (!body) return []; const inlineEventBlockRegExp = new RegExp( `%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`, "gi" ); const originalFrontmatter = context.cachedMetadata.frontmatter; const matches = body.match(inlineEventBlockRegExp); if (!matches) return []; matches.unshift(); const output: CompleteCardContext[] = []; for (const block of matches) { const sanitizedBlock = block.split("\n"); sanitizedBlock.shift(); sanitizedBlock.pop(); const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao // Replace frontmatter with newly built fake one. Just to re-use all the existing code. context.cachedMetadata.frontmatter = fakeFrontmatter;
if (!isDefinedAsObject(fakeFrontmatter)) continue;
const timelineTags = getTagsFromMetadataOrTagObject( settings, fakeFrontmatter, context.cachedMetadata.tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue; const matchPositionInBody = body.indexOf(block); output.push({ cardData: await extractCardData( context, matchPositionInBody !== -1 ? body.slice(matchPositionInBody + block.length) : undefined ), context, }); } context.cachedMetadata.frontmatter = originalFrontmatter; return output; } /** * Checks if the extracted tags match at least one of the tags to find. * * @param timelineTags - The extracted tags from the note. * @param tagsToFind - The tags to find. * @returns `true` if valid. */ function extractedTagsAreValid( timelineTags: string[], tagsToFind: string[] ): boolean { return timelineTags.some((tag) => tagsToFind.includes(tag)); } /** * Get the content of a card from a note. This function will parse the raw text content of a note and format it. * * @param context - Timeline generic context. * @param rawFileContent - If you already have it, will avoid reading the file again. * @returns The extracted data to create a card from a note. */ export async function extractCardData( context: MarkdownCodeBlockTimelineProcessingContext, rawFileContent?: string ) { const { file, cachedMetadata: c, settings } = context; const fileTitle = c.frontmatter?.[settings.metadataKeyEventTitleOverride] || file.basename; rawFileContent = rawFileContent || (await file.vault.cachedRead(file)); return { title: fileTitle as string, body: getBodyFromContextOrDocument(rawFileContent, context), imageURL: getImageUrlFromContextOrDocument(rawFileContent, context), startDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventStartDate ), endDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventEndDate ) ?? (isDefined( getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean") ) ? true : undefined), } as const; } export type FnExtractCardData = typeof extractCardData;
src/cardData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.8219727277755737 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.802711009979248 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\t\t\tconst score = compareAbstractDates(a, b);\n\t\t\t\tif (score) return score;\n\t\t\t\treturn compareAbstractDates(aE, bE);\n\t\t\t}\n\t\t);\n\t\tcardDataTime();\n\t\tconst cardRenderTime = measureTime(\"Card Render\");\n\t\tevents.forEach(({ context, cardData }) =>\n\t\t\tcreateCardFromBuiltContext(context, cardData)\n\t\t);", "score": 0.7974877953529358 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\t\t\tawait getDataFromNoteBody(body, context, tagsToFind)\n\t\t\t).filter(isDefined);\n\t\t\tif (!inlineEvents.length) continue;\n\t\t\tevents.push(...inlineEvents);\n\t\t}\n\t\tevents.sort(\n\t\t\t(\n\t\t\t\t{ cardData: { startDate: a, endDate: aE } },\n\t\t\t\t{ cardData: { startDate: b, endDate: bE } }\n\t\t\t) => {", "score": 0.79662024974823 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);", "score": 0.7920382618904114 } ]
typescript
if (!isDefinedAsObject(fakeFrontmatter)) continue;
import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; import { getClientIp } from "./utils"; import { NextRequest } from "next/server"; import { upstashToken, upstashUrl, enableUpstash, upstashBanEnabled, upstashBanDuration, maxRequests, requestsWindow, } from "@/configs/upstash"; const isValidUpstash = () => { if (!upstashUrl) { console.error("UPSTASH_URL is missing from your environment variables."); } if (!upstashToken) { console.error("UPSTASH_TOKEN is missing from your environment variables."); } return upstashUrl !== "" && upstashToken != ""; }; export const redisClient = new Redis({ url: upstashUrl, token: upstashToken, }); export const ratelimit = new Ratelimit({ redis: redisClient, limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow), }); export const isRatelimited = async (request: NextRequest) => { if (!enableUpstash) return false; // Check if upstash variables are set correctly const validUpstash = isValidUpstash(); if (!validUpstash) return false; try { const
identifier = getClientIp(request);
if (!identifier) return false; const result = await ratelimit.limit(identifier); if (result.success) return false; // Ban user if ratelimit exceeded if (upstashBanEnabled) { await redisClient.setex( `ban:${identifier}`, upstashBanDuration, "banned" ); } return true; } catch (error: any) { console.error(error.message); return false; } };
src/lib/rate-limiter.ts
riad-azz-instagram-video-downloader-78513ff
[ { "filename": "src/middleware.ts", "retrieved_chunk": " }\n if (requestPath.startsWith(\"/api\") && enableServerAPI) {\n const isLimited = await isRatelimited(request);\n if (isLimited) {\n const banDuration = Math.floor(upstashBanDuration / 60 / 60); // Ban duration in hours\n return NextResponse.json(\n {\n error: `Too many requests, you have been banned for ${banDuration} hours.`,\n },\n { status: 429 }", "score": 0.8472142219543457 }, { "filename": "src/lib/utils.ts", "retrieved_chunk": "};\nexport const isJsonResponse = (response: Response) => {\n const contentType = response.headers.get(\"content-type\");\n return contentType && contentType.includes(\"application/json\");\n};\nexport const getClientIp = (request: NextRequest) => {\n let ip = request.ip ?? request.headers.get(\"x-real-ip\");\n const forwardedFor = request.headers.get(\"x-forwarded-for\");\n if (!ip && forwardedFor) {\n ip = forwardedFor.split(\",\").at(0) ?? null;", "score": 0.8309530019760132 }, { "filename": "src/middleware.ts", "retrieved_chunk": "import { NextRequest, NextResponse } from \"next/server\";\nimport { upstashBanDuration } from \"./configs/upstash\";\nimport { enableServerAPI } from \"./configs/instagram\";\nimport { getClientIp } from \"@/lib/utils\";\nimport { isRatelimited } from \"./lib/rate-limiter\";\nconst isStaticPath = (path: string) => {\n return (\n path.startsWith(\"/_next\") ||\n path.startsWith(\"/images\") ||\n path.startsWith(\"/favicon.ico\") ||", "score": 0.8281300067901611 }, { "filename": "src/configs/upstash.ts", "retrieved_chunk": "// Upstash configs\nexport const upstashUrl = process.env.UPSTASH_REDIS_REST_URL ?? \"\";\nexport const upstashToken = process.env.UPSTASH_REDIS_REST_TOKEN ?? \"\";\nconst isUsingUpstash = process.env.USE_UPSTASH ?? \"\";\nexport const enableUpstash = isUsingUpstash === \"true\";\n// Ratelimit configs\nexport const maxRequests = 5; // Max requests every requests window\nexport const requestsWindow = \"1 m\"; // 5 requests allowed every 1 min\n// Ban configs\nexport const upstashBanEnabled = true; // Ban user by ip in case of spam", "score": 0.7992974519729614 }, { "filename": "src/middleware.ts", "retrieved_chunk": " path.startsWith(\"/og.png\") ||\n path.startsWith(\"/robot.txt\") ||\n path.startsWith(\"/site.webmanifest\")\n );\n};\nexport async function middleware(request: NextRequest) {\n const requestPath = request.nextUrl.pathname;\n const country = request.geo?.country ?? \"Country\";\n if (isStaticPath(requestPath)) {\n return NextResponse.next();", "score": 0.7895575761795044 } ]
typescript
identifier = getClientIp(request);
"use client"; import { useState, FormEvent } from "react"; import { DownloadButton } from "./DownloadButton"; import { Exception, ClientException } from "@/exceptions"; import { fetchVideoInfoAction } from "@/lib/instagram/actions"; import { APIResponse, VideoInfo } from "@/types"; const validateInput = (postUrl: string) => { if (!postUrl) { throw new ClientException("Instagram URL was not provided"); } if (!postUrl.includes("instagram.com/")) { throw new ClientException("Invalid URL does not contain Instagram domain"); } if (!postUrl.startsWith("https://")) { throw new ClientException( 'Invalid URL it should start with "https://www.instagram.com..."' ); } const postRegex = /^https:\/\/(?:www\.)?instagram\.com\/p\/([a-zA-Z0-9_-]+)\/?/; const reelRegex = /^https:\/\/(?:www\.)?instagram\.com\/reels?\/([a-zA-Z0-9_-]+)\/?/; if (!postRegex.test(postUrl) && !reelRegex.test(postUrl)) { throw new ClientException("URL does not match Instagram post or reel"); } }; const downloadVideo = async (filename: string, downloadUrl: any) => { try { await fetch(downloadUrl) .then((response) => response.blob()) .then((blob) => { const blobUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.target = "_blank"; a.href = blobUrl; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); }); } catch (error) { const a = document.createElement("a"); a.target = "_blank"; a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); console.log(error); } }; const fetchVideo = async (postUrl: string) => { const response: APIResponse<VideoInfo> = await fetchVideoInfoAction(postUrl); if (response.status === "error") { throw new ClientException(response.message); } const { filename, videoUrl } = response.data; await downloadVideo(filename, videoUrl); return true; }; export default function InstagramForm() { const [postUrl, setPostUrl] = useState(""); const [errorMsg, setErrorMsg] = useState(""); const [isLoading, setIsLoading] = useState(false); function handleError(error: any) { if (error instanceof Exception) { setErrorMsg(error.message); } else { console.error(error); setErrorMsg( "Something went wrong, if this problem persists contact the developer." ); } setIsLoading(false); } async function handleSubmit(e: FormEvent) { e.preventDefault(); setIsLoading(true); setErrorMsg(""); try { validateInput(postUrl); } catch (error: any) { return handleError(error); } try { const isSuccess = await fetchVideo(postUrl); if (isSuccess) setErrorMsg(""); } catch (error: any) { return handleError(error); } setIsLoading(false); } return ( <> {errorMsg !== "" && ( <div className="mb-1 text-sm text-red-500 md:text-base">{errorMsg}</div> )} <form className="flex flex-col items-center gap-4 motion-safe:animate-[animate-up_1.5s_ease-in-out_1] md:flex-row md:gap-2" onSubmit={handleSubmit} > <label htmlFor="url-input" className="sr-only"> instagram URL input </label> <input id="url-input" type="url" value={postUrl} autoFocus={true} onChange={(e) => setPostUrl(e.target.value)} placeholder="e.g. https://www.instagram.com/p/CGh4a0iASGS" aria-label="Instagram video download URL input" title="Instagram video download URL input" className="w-full rounded border border-slate-100 px-2 py-3 placeholder-gray-400/80 drop-shadow-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-none dark:bg-gray-700 dark:text-white dark:placeholder-gray-400" /> <
DownloadButton isLoading={isLoading} /> </form> </> );
}
src/components/instagram/InstagramForm.tsx
riad-azz-instagram-video-downloader-78513ff
[ { "filename": "src/components/instagram/DownloadButton.tsx", "retrieved_chunk": "import { Icons } from \"@/components/Icons\";\nexport interface IDownloadButton {\n isLoading: boolean;\n}\nexport const DownloadButton: React.FC<IDownloadButton> = ({ isLoading }) => {\n return (\n <>\n <button\n aria-label=\"Download Instagram video button\"\n title=\"Download Instagram video button\"", "score": 0.8694800138473511 }, { "filename": "src/components/instagram/DownloadButton.tsx", "retrieved_chunk": " {!isLoading && (\n <>\n <Icons.download />\n <span>Download</span>\n </>\n )}\n </button>\n </>\n );\n};", "score": 0.8688136339187622 }, { "filename": "src/components/instagram/DownloadButton.tsx", "retrieved_chunk": " type=\"submit\"\n className=\"inline-flex items-center gap-2 rounded border border-slate-100 bg-white px-5 py-3.5 text-sm tracking-wide drop-shadow-lg transition-transform focus:outline-none focus:ring-2 focus:ring-blue-500 active:scale-95 dark:border-none dark:bg-gray-700 max-md:w-full max-md:justify-center\"\n disabled={isLoading}\n >\n {isLoading && (\n <>\n <Icons.loading />\n <span>Fetching</span>\n </>\n )}", "score": 0.8412783145904541 }, { "filename": "src/app/page.tsx", "retrieved_chunk": " Instagram content for free. No registration or account required. You\n can save videos and reels by copying and pasting the Instagram URL.\n </p>\n </section>\n <section>\n <InstagramForm />\n <p className=\"my-4 text-center text-sm text-gray-500 motion-safe:animate-[animate-late-fade-in_2s_ease-in-out_1] dark:text-gray-400\">\n If the download opens a new page, just right click the video and then\n click `Save as video`\n </p>", "score": 0.8394955396652222 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "};\nconst Download: React.FC<IconProps> = ({ size = 16 }) => {\n return (\n <svg\n aria-hidden=\"true\"\n width={size}\n height={size}\n aria-label=\"download icon\"\n className=\"fill-current\"\n xmlns=\"http://www.w3.org/2000/svg\"", "score": 0.821863055229187 } ]
typescript
DownloadButton isLoading={isLoading} /> </form> </> );
import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; import { getClientIp } from "./utils"; import { NextRequest } from "next/server"; import { upstashToken, upstashUrl, enableUpstash, upstashBanEnabled, upstashBanDuration, maxRequests, requestsWindow, } from "@/configs/upstash"; const isValidUpstash = () => { if (!upstashUrl) { console.error("UPSTASH_URL is missing from your environment variables."); } if (!upstashToken) { console.error("UPSTASH_TOKEN is missing from your environment variables."); } return upstashUrl !== "" && upstashToken != ""; }; export const redisClient = new Redis({ url: upstashUrl, token: upstashToken, }); export const ratelimit = new Ratelimit({ redis: redisClient, limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow), }); export const isRatelimited = async (request: NextRequest) => { if (!enableUpstash) return false; // Check if upstash variables are set correctly const validUpstash = isValidUpstash(); if (!validUpstash) return false; try {
const identifier = getClientIp(request);
if (!identifier) return false; const result = await ratelimit.limit(identifier); if (result.success) return false; // Ban user if ratelimit exceeded if (upstashBanEnabled) { await redisClient.setex( `ban:${identifier}`, upstashBanDuration, "banned" ); } return true; } catch (error: any) { console.error(error.message); return false; } };
src/lib/rate-limiter.ts
riad-azz-instagram-video-downloader-78513ff
[ { "filename": "src/middleware.ts", "retrieved_chunk": " }\n if (requestPath.startsWith(\"/api\") && enableServerAPI) {\n const isLimited = await isRatelimited(request);\n if (isLimited) {\n const banDuration = Math.floor(upstashBanDuration / 60 / 60); // Ban duration in hours\n return NextResponse.json(\n {\n error: `Too many requests, you have been banned for ${banDuration} hours.`,\n },\n { status: 429 }", "score": 0.8519333600997925 }, { "filename": "src/middleware.ts", "retrieved_chunk": "import { NextRequest, NextResponse } from \"next/server\";\nimport { upstashBanDuration } from \"./configs/upstash\";\nimport { enableServerAPI } from \"./configs/instagram\";\nimport { getClientIp } from \"@/lib/utils\";\nimport { isRatelimited } from \"./lib/rate-limiter\";\nconst isStaticPath = (path: string) => {\n return (\n path.startsWith(\"/_next\") ||\n path.startsWith(\"/images\") ||\n path.startsWith(\"/favicon.ico\") ||", "score": 0.8346713185310364 }, { "filename": "src/lib/utils.ts", "retrieved_chunk": "};\nexport const isJsonResponse = (response: Response) => {\n const contentType = response.headers.get(\"content-type\");\n return contentType && contentType.includes(\"application/json\");\n};\nexport const getClientIp = (request: NextRequest) => {\n let ip = request.ip ?? request.headers.get(\"x-real-ip\");\n const forwardedFor = request.headers.get(\"x-forwarded-for\");\n if (!ip && forwardedFor) {\n ip = forwardedFor.split(\",\").at(0) ?? null;", "score": 0.8307325839996338 }, { "filename": "src/configs/upstash.ts", "retrieved_chunk": "// Upstash configs\nexport const upstashUrl = process.env.UPSTASH_REDIS_REST_URL ?? \"\";\nexport const upstashToken = process.env.UPSTASH_REDIS_REST_TOKEN ?? \"\";\nconst isUsingUpstash = process.env.USE_UPSTASH ?? \"\";\nexport const enableUpstash = isUsingUpstash === \"true\";\n// Ratelimit configs\nexport const maxRequests = 5; // Max requests every requests window\nexport const requestsWindow = \"1 m\"; // 5 requests allowed every 1 min\n// Ban configs\nexport const upstashBanEnabled = true; // Ban user by ip in case of spam", "score": 0.8179468512535095 }, { "filename": "src/middleware.ts", "retrieved_chunk": " path.startsWith(\"/og.png\") ||\n path.startsWith(\"/robot.txt\") ||\n path.startsWith(\"/site.webmanifest\")\n );\n};\nexport async function middleware(request: NextRequest) {\n const requestPath = request.nextUrl.pathname;\n const country = request.geo?.country ?? \"Country\";\n if (isStaticPath(requestPath)) {\n return NextResponse.next();", "score": 0.7898679971694946 } ]
typescript
const identifier = getClientIp(request);
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client"; import { prisma } from "../../../prisma/client"; export class GetPedidoPorCpfUseCase { async getPedidoPorCpf(numero: string): Promise<any | null> { if (numero.length === 11) { const clienteCpf = await prisma.cliente.findFirst({ where: { cpf: numero } }); if (clienteCpf) { const pedido = await prisma.pedido.findMany({ where: { id_cliente: clienteCpf.id_cliente }, include: { cliente: { select: { nome_completo: true, cpf: true } }, pedido_status: { select: { status_pedido: true, status_erro: true } }, nota_fiscal: { select: { numero_nota: true } }, pagamento: { select: { tipo_pagamento: true, parcela: true } }, produto: { select: { nome_produto: true, quantidade: true } } } }); if (!pedido) { return null; } const pedidosFormatados = pedido.map((
pedido) => ({
numero: pedido.numero, status_pedido: pedido.pedido_status.status_pedido, status_erro: pedido.pedido_status.status_erro, numero_nota_fiscal: pedido.nota_fiscal.numero_nota, data_pedido_realizado: pedido.data_pedido_realizado, nome_cliente: pedido.cliente.nome_completo, cpf_cliente: pedido.cliente.cpf, tipo_pagamento: pedido.pagamento.tipo_pagamento, })); return pedidosFormatados; } } } }
src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts
Iguu42-node-project-FC-0cd6618
[ { "filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts", "retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {", "score": 0.9211585521697998 }, { "filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts", "retrieved_chunk": " })\n if (!pedidos) {\n return null\n }\n const pedidosFormatados = pedidos.map(pedido => ({\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n pedido: pedido.cliente.cpf,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,", "score": 0.9138096570968628 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,", "score": 0.9067886471748352 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,", "score": 0.8954660296440125 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " quantidade: produto.quantidade,\n valor_produto: produto.valor,\n valor_total_produto: produto.valor * produto.quantidade\n };\n produtosFormatados.push(produtoFormatado);\n });\n const moment = require('moment');\n const pedidoFormatado = {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,", "score": 0.8941174149513245 } ]
typescript
pedido) => ({
import { isDefinedAsString, isDefined, isDefinedAsArray, getMetadataKey, parseAbstractDate, } from "~/utils"; import { FrontMatterCache, TagCache, TFile } from "obsidian"; import type { AutoTimelineSettings, AbstractDate, MarkdownCodeBlockTimelineProcessingContext, } from "~/types"; /** * Returns a list of tags based off plugin settings, note frontmatter and note tags. * * @param settings - The plugins settings. * @param metaData - The frontematter cache. * @param tags - Potencial tags. * @returns A list of tags to look for in a note. */ export function getTagsFromMetadataOrTagObject( settings: AutoTimelineSettings, metaData: Omit<FrontMatterCache, "position">, tags?: TagCache[] ): string[] { let output = [] as string[]; const timelineArray = metaData[settings.metadataKeyEventTimelineTag]; if (isDefinedAsArray(timelineArray)) output = timelineArray.filter(isDefinedAsString); // Breakout earlier if we don't check the tags if (!settings.lookForTagsForTimeline) return output; if (isDefinedAsArray(tags)) output = output.concat(tags.map(({ tag }) => tag.substring(1))); // Tags in the frontmatter const metadataInlineTags = metaData.tags; if (!isDefined(metadataInlineTags)) return output; if (isDefinedAsString(metadataInlineTags)) output = output.concat( metadataInlineTags.split(",").map((e) => e.trim()) ); if (isDefinedAsArray(metadataInlineTags)) output = output.concat(metadataInlineTags.filter(isDefinedAsString)); // .substring called to remove the initial `#` in the notes tags return output; } /** * Extract the body from the raw text of a note. * After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the body of a given card or null if none was found. */ export function getBodyFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, settings: {
metadataKeyEventBodyOverride }, } = context;
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null; if (!rawFileText.length || overrideBody) return overrideBody; const rawTextArray = rawFileText.split("\n"); rawTextArray.shift(); const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1); const finalString = processedArray.join("\n").trim(); return finalString; } /** * Extract the first image from the raw markdown in a note. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the URL of the image to be displayed in a card or null if none where found. */ export function getImageUrlFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, file: currentFile, app, settings: { metadataKeyEventPictureOverride }, } = context; const { vault, metadataCache: { getFirstLinkpathDest }, } = app; const override = metadata?.[metadataKeyEventPictureOverride]; if (override) return override; const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/); const matchs = internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/); if (!matchs || !matchs.groups || !matchs.groups.src) return null; if (internalLinkMatch) { // https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295 const file = getFirstLinkpathDest.bind(app.metadataCache)( matchs.groups.src, currentFile.path ) satisfies TFile | null; if (file instanceof TFile) return vault.getResourcePath(file); // Thanks https://github.com/joethei return null; } else return encodeURI(matchs.groups.src); } /** * Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it * * @param param0 - Timeline generic context. * @param param0.cachedMetadata - The cached metadata from a note. * @param param0.settings - the plugin's settings. * @param key - The target lookup key in the notes metadata object. * @returns the abstract date representation or undefined. */ export function getAbstractDateFromMetadata( { cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext, key: string ): AbstractDate | undefined { const groupsToCheck = settings.dateParserGroupPriority.split(","); const numberValue = getMetadataKey(cachedMetadata, key, "number"); if (isDefined(numberValue)) { const additionalContentForNumberOnlydate = [ ...Array(Math.max(0, groupsToCheck.length - 1)), ].map(() => 0); return [numberValue, ...additionalContentForNumberOnlydate]; } const stringValue = getMetadataKey(cachedMetadata, key, "string"); if (!stringValue) return undefined; return parseAbstractDate( groupsToCheck, stringValue, settings.dateParserRegex ); }
src/cardDataExtraction.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,", "score": 0.8750216364860535 }, { "filename": "src/cardData.ts", "retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;", "score": 0.8570582866668701 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.8505414724349976 }, { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.8291113972663879 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8188409805297852 } ]
typescript
metadataKeyEventBodyOverride }, } = context;
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from '@prisma/client' import { prisma } from '../../../prisma/client' export class GetPedidosDataUseCase { async allPedidosData(data: String): Promise<any[] | null> { const pedidos = await prisma.pedido.findMany({ where: { data_pedido_realizado: { gte: new Date(`${data}`), lt: new Date(`${data}T23:59:59Z`) } }, include: { cliente: { select: { nome_completo: true, cpf: true } }, pedido_status: { select: { status_pedido: true, status_erro: true } }, nota_fiscal: { select: { numero_nota: true } }, pagamento: { select: { tipo_pagamento: true, parcela: true } }, produto: { select: { nome_produto: true, quantidade: true, valor: true } } } }) if (!pedidos) { return null }
const pedidosFormatados = pedidos.map(pedido => ({
status_pedido: pedido.pedido_status.status_pedido, status_erro: pedido.pedido_status.status_erro, pedido: pedido.cliente.cpf, numero_nota_fiscal: pedido.nota_fiscal.numero_nota, data_pedido_realizado: pedido.data_pedido_realizado, nome_cliente: pedido.cliente.nome_completo, tipo_pagamento: pedido.pagamento.tipo_pagamento, // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`, // nome_produto: pedido.produto.nome_produto, // quantidade_produto: pedido.produto.quantidade })) return pedidosFormatados } }
src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts
Iguu42-node-project-FC-0cd6618
[ { "filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts", "retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {", "score": 0.9236745834350586 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,", "score": 0.9131588339805603 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,", "score": 0.906703770160675 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " status_erro: pedido.pedido_status.status_erro,\n valorTotal: valorTotal,\n dataDaCompra: moment(pedido.data_pedido_realizado).format('DD/MM/YYYY'),\n status_pedido: pedido.pedido_status.status_pedido,\n };\n });\n return pedidosFormatados;\n }\n}", "score": 0.9003593921661377 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " quantidade: produto.quantidade,\n valor_produto: produto.valor,\n valor_total_produto: produto.valor * produto.quantidade\n };\n produtosFormatados.push(produtoFormatado);\n });\n const moment = require('moment');\n const pedidoFormatado = {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,", "score": 0.8983275294303894 } ]
typescript
const pedidosFormatados = pedidos.map(pedido => ({
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from '@prisma/client' import { prisma } from '../../../prisma/client' export class GetPedidosDataUseCase { async allPedidosData(data: String): Promise<any[] | null> { const pedidos = await prisma.pedido.findMany({ where: { data_pedido_realizado: { gte: new Date(`${data}`), lt: new Date(`${data}T23:59:59Z`) } }, include: { cliente: { select: { nome_completo: true, cpf: true } }, pedido_status: { select: { status_pedido: true, status_erro: true } }, nota_fiscal: { select: { numero_nota: true } }, pagamento: { select: { tipo_pagamento: true, parcela: true } }, produto: { select: { nome_produto: true, quantidade: true, valor: true } } } }) if (!pedidos) { return null } const pedidosFormatados = pedidos.map
(pedido => ({
status_pedido: pedido.pedido_status.status_pedido, status_erro: pedido.pedido_status.status_erro, pedido: pedido.cliente.cpf, numero_nota_fiscal: pedido.nota_fiscal.numero_nota, data_pedido_realizado: pedido.data_pedido_realizado, nome_cliente: pedido.cliente.nome_completo, tipo_pagamento: pedido.pagamento.tipo_pagamento, // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`, // nome_produto: pedido.produto.nome_produto, // quantidade_produto: pedido.produto.quantidade })) return pedidosFormatados } }
src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts
Iguu42-node-project-FC-0cd6618
[ { "filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts", "retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {", "score": 0.9234495162963867 }, { "filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts", "retrieved_chunk": " const pedidosFormatados = pedido.map((pedido) => ({\n numero: pedido.numero,\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,\n nome_cliente: pedido.cliente.nome_completo,\n cpf_cliente: pedido.cliente.cpf,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n }));", "score": 0.915831446647644 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " status_erro: pedido.pedido_status.status_erro,\n valorTotal: valorTotal,\n dataDaCompra: moment(pedido.data_pedido_realizado).format('DD/MM/YYYY'),\n status_pedido: pedido.pedido_status.status_pedido,\n };\n });\n return pedidosFormatados;\n }\n}", "score": 0.914667010307312 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,", "score": 0.9124717116355896 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,", "score": 0.9116930961608887 } ]
typescript
(pedido => ({
import { isDefinedAsString, isDefined, isDefinedAsArray, getMetadataKey, parseAbstractDate, } from "~/utils"; import { FrontMatterCache, TagCache, TFile } from "obsidian"; import type { AutoTimelineSettings, AbstractDate, MarkdownCodeBlockTimelineProcessingContext, } from "~/types"; /** * Returns a list of tags based off plugin settings, note frontmatter and note tags. * * @param settings - The plugins settings. * @param metaData - The frontematter cache. * @param tags - Potencial tags. * @returns A list of tags to look for in a note. */ export function getTagsFromMetadataOrTagObject( settings: AutoTimelineSettings, metaData: Omit<FrontMatterCache, "position">, tags?: TagCache[] ): string[] { let output = [] as string[]; const timelineArray = metaData[settings.metadataKeyEventTimelineTag]; if (isDefinedAsArray(timelineArray)) output = timelineArray.filter(isDefinedAsString); // Breakout earlier if we don't check the tags if (!settings.lookForTagsForTimeline) return output; if (isDefinedAsArray(tags)) output = output.concat(tags.map(({ tag }) => tag.substring(1))); // Tags in the frontmatter const metadataInlineTags = metaData.tags; if (!isDefined(metadataInlineTags)) return output; if (isDefinedAsString(metadataInlineTags)) output = output.concat( metadataInlineTags.split(",").map((e) => e.trim()) ); if (isDefinedAsArray(metadataInlineTags)) output = output.concat(metadataInlineTags.filter(isDefinedAsString)); // .substring called to remove the initial `#` in the notes tags return output; } /** * Extract the body from the raw text of a note. * After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the body of a given card or null if none was found. */ export function getBodyFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, settings: { metadataKeyEventBodyOverride }, } = context; const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null; if (!rawFileText.length || overrideBody) return overrideBody; const rawTextArray = rawFileText.split("\n"); rawTextArray.shift(); const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1); const finalString = processedArray.join("\n").trim(); return finalString; } /** * Extract the first image from the raw markdown in a note. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the URL of the image to be displayed in a card or null if none where found. */ export function getImageUrlFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, file: currentFile, app, settings: {
metadataKeyEventPictureOverride }, } = context;
const { vault, metadataCache: { getFirstLinkpathDest }, } = app; const override = metadata?.[metadataKeyEventPictureOverride]; if (override) return override; const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/); const matchs = internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/); if (!matchs || !matchs.groups || !matchs.groups.src) return null; if (internalLinkMatch) { // https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295 const file = getFirstLinkpathDest.bind(app.metadataCache)( matchs.groups.src, currentFile.path ) satisfies TFile | null; if (file instanceof TFile) return vault.getResourcePath(file); // Thanks https://github.com/joethei return null; } else return encodeURI(matchs.groups.src); } /** * Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it * * @param param0 - Timeline generic context. * @param param0.cachedMetadata - The cached metadata from a note. * @param param0.settings - the plugin's settings. * @param key - The target lookup key in the notes metadata object. * @returns the abstract date representation or undefined. */ export function getAbstractDateFromMetadata( { cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext, key: string ): AbstractDate | undefined { const groupsToCheck = settings.dateParserGroupPriority.split(","); const numberValue = getMetadataKey(cachedMetadata, key, "number"); if (isDefined(numberValue)) { const additionalContentForNumberOnlydate = [ ...Array(Math.max(0, groupsToCheck.length - 1)), ].map(() => 0); return [numberValue, ...additionalContentForNumberOnlydate]; } const stringValue = getMetadataKey(cachedMetadata, key, "string"); if (!stringValue) return undefined; return parseAbstractDate( groupsToCheck, stringValue, settings.dateParserRegex ); }
src/cardDataExtraction.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,", "score": 0.872836709022522 }, { "filename": "src/cardData.ts", "retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;", "score": 0.842812180519104 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.8316328525543213 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8240300416946411 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tsanitizedBlock.pop();\n\t\tconst fakeFrontmatter = parse(sanitizedBlock.join(\"\\n\")); // this actually works lmao\n\t\t// Replace frontmatter with newly built fake one. Just to re-use all the existing code.\n\t\tcontext.cachedMetadata.frontmatter = fakeFrontmatter;\n\t\tif (!isDefinedAsObject(fakeFrontmatter)) continue;\n\t\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\t\tsettings,\n\t\t\tfakeFrontmatter,\n\t\t\tcontext.cachedMetadata.tags\n\t\t);", "score": 0.8156390190124512 } ]
typescript
metadataKeyEventPictureOverride }, } = context;
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils"; import type { MarkdownCodeBlockTimelineProcessingContext, CompleteCardContext, } from "~/types"; import { parse } from "yaml"; import { getAbstractDateFromMetadata, getBodyFromContextOrDocument, getImageUrlFromContextOrDocument, getTagsFromMetadataOrTagObject, } from "./cardDataExtraction"; /** * A un-changeable key used to check if a note is eligeable for render. */ const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"]; /** * Provides additional context for the creation cards in the DOM. * * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteMetadata( context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ) { const { cachedMetadata, settings } = context; const { frontmatter: metaData, tags } = cachedMetadata; if (!metaData) return undefined; if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true)) return undefined; const timelineTags = getTagsFromMetadataOrTagObject( settings, metaData, tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined; return { cardData: await extractCardData(context), context, } as const; } /** * Provides additional context for the creation cards in the DOM but reads it from the body * * @param body - The extracted body for a single event card. * @param context - Timeline generic context. * @param tagsToFind - The tags to find in a note to match the current timeline. * @returns the context or underfined if it could not build it. */ export async function getDataFromNoteBody( body: string | undefined | null, context: MarkdownCodeBlockTimelineProcessingContext, tagsToFind: string[] ): Promise<CompleteCardContext[]> { const { settings } = context; if (!body) return []; const inlineEventBlockRegExp = new RegExp( `%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`, "gi" ); const originalFrontmatter = context.cachedMetadata.frontmatter; const matches = body.match(inlineEventBlockRegExp); if (!matches) return []; matches.unshift(); const output: CompleteCardContext[] = []; for (const block of matches) { const sanitizedBlock = block.split("\n"); sanitizedBlock.shift(); sanitizedBlock.pop(); const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao // Replace frontmatter with newly built fake one. Just to re-use all the existing code. context.cachedMetadata.frontmatter = fakeFrontmatter; if (!isDefinedAsObject(fakeFrontmatter)) continue; const timelineTags = getTagsFromMetadataOrTagObject( settings, fakeFrontmatter, context.cachedMetadata.tags ); if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue; const matchPositionInBody = body.indexOf(block); output.push({ cardData: await extractCardData( context, matchPositionInBody !== -1 ? body.slice(matchPositionInBody + block.length) : undefined ), context, }); } context.cachedMetadata.frontmatter = originalFrontmatter; return output; } /** * Checks if the extracted tags match at least one of the tags to find. * * @param timelineTags - The extracted tags from the note. * @param tagsToFind - The tags to find. * @returns `true` if valid. */ function extractedTagsAreValid( timelineTags: string[], tagsToFind: string[] ): boolean { return timelineTags.some((tag) => tagsToFind.includes(tag)); } /** * Get the content of a card from a note. This function will parse the raw text content of a note and format it. * * @param context - Timeline generic context. * @param rawFileContent - If you already have it, will avoid reading the file again. * @returns The extracted data to create a card from a note. */ export async function extractCardData( context: MarkdownCodeBlockTimelineProcessingContext, rawFileContent?: string ) { const { file, cachedMetadata: c, settings } = context; const fileTitle =
c.frontmatter?.[settings.metadataKeyEventTitleOverride] || file.basename;
rawFileContent = rawFileContent || (await file.vault.cachedRead(file)); return { title: fileTitle as string, body: getBodyFromContextOrDocument(rawFileContent, context), imageURL: getImageUrlFromContextOrDocument(rawFileContent, context), startDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventStartDate ), endDate: getAbstractDateFromMetadata( context, settings.metadataKeyEventEndDate ) ?? (isDefined( getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean") ) ? true : undefined), } as const; } export type FnExtractCardData = typeof extractCardData;
src/cardData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": " * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the body of a given card or null if none was found.\n */\nexport function getBodyFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext\n): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },", "score": 0.8853700160980225 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}", "score": 0.8383365869522095 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },", "score": 0.8284529447555542 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.8199927806854248 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "/**\n * Extract the first image from the raw markdown in a note.\n *\n * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the URL of the image to be displayed in a card or null if none where found.\n */\nexport function getImageUrlFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext", "score": 0.8191213607788086 } ]
typescript
c.frontmatter?.[settings.metadataKeyEventTitleOverride] || file.basename;
import { isDefinedAsString, isDefined, isDefinedAsArray, getMetadataKey, parseAbstractDate, } from "~/utils"; import { FrontMatterCache, TagCache, TFile } from "obsidian"; import type { AutoTimelineSettings, AbstractDate, MarkdownCodeBlockTimelineProcessingContext, } from "~/types"; /** * Returns a list of tags based off plugin settings, note frontmatter and note tags. * * @param settings - The plugins settings. * @param metaData - The frontematter cache. * @param tags - Potencial tags. * @returns A list of tags to look for in a note. */ export function getTagsFromMetadataOrTagObject( settings: AutoTimelineSettings, metaData: Omit<FrontMatterCache, "position">, tags?: TagCache[] ): string[] { let output = [] as string[]; const timelineArray = metaData[settings.metadataKeyEventTimelineTag]; if (isDefinedAsArray(timelineArray)) output = timelineArray.filter(isDefinedAsString); // Breakout earlier if we don't check the tags if (!settings.lookForTagsForTimeline) return output; if (isDefinedAsArray(tags)) output = output.concat(tags.map(({ tag }) => tag.substring(1))); // Tags in the frontmatter const metadataInlineTags = metaData.tags; if (!isDefined(metadataInlineTags)) return output; if (isDefinedAsString(metadataInlineTags)) output = output.concat( metadataInlineTags.split(",").map((e) => e.trim()) ); if (isDefinedAsArray(metadataInlineTags)) output = output.concat(metadataInlineTags.filter(isDefinedAsString)); // .substring called to remove the initial `#` in the notes tags return output; } /** * Extract the body from the raw text of a note. * After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the body of a given card or null if none was found. */ export function getBodyFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, settings: { metadataKeyEventBodyOverride }, } = context; const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null; if (!rawFileText.length || overrideBody) return overrideBody; const rawTextArray = rawFileText.split("\n"); rawTextArray.shift(); const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1); const finalString = processedArray.join("\n").trim(); return finalString; } /** * Extract the first image from the raw markdown in a note. * * @param rawFileText - The text content of a obsidian note. * @param context - Timeline generic context. * @returns the URL of the image to be displayed in a card or null if none where found. */ export function getImageUrlFromContextOrDocument( rawFileText: string, context: MarkdownCodeBlockTimelineProcessingContext ): string | null { const { cachedMetadata: { frontmatter: metadata }, file: currentFile, app, settings: { metadataKeyEventPictureOverride }, } = context; const { vault, metadataCache: { getFirstLinkpathDest }, } = app; const override = metadata?.[metadataKeyEventPictureOverride]; if (override) return override; const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/); const matchs = internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/); if (!matchs || !matchs.groups || !matchs.groups.src) return null; if (internalLinkMatch) { // https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295 const file = getFirstLinkpathDest.bind(app.metadataCache)( matchs.groups.src, currentFile.path ) satisfies TFile | null; if (file instanceof TFile) return vault.getResourcePath(file); // Thanks https://github.com/joethei return null; } else return encodeURI(matchs.groups.src); } /** * Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it * * @param param0 - Timeline generic context. * @param param0.cachedMetadata - The cached metadata from a note. * @param param0.settings - the plugin's settings. * @param key - The target lookup key in the notes metadata object. * @returns the abstract date representation or undefined. */ export function getAbstractDateFromMetadata( { cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext, key: string ): AbstractDate | undefined { const groupsToCheck =
settings.dateParserGroupPriority.split(",");
const numberValue = getMetadataKey(cachedMetadata, key, "number"); if (isDefined(numberValue)) { const additionalContentForNumberOnlydate = [ ...Array(Math.max(0, groupsToCheck.length - 1)), ].map(() => 0); return [numberValue, ...additionalContentForNumberOnlydate]; } const stringValue = getMetadataKey(cachedMetadata, key, "string"); if (!stringValue) return undefined; return parseAbstractDate( groupsToCheck, stringValue, settings.dateParserRegex ); }
src/cardDataExtraction.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/utils.ts", "retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);", "score": 0.8049790263175964 }, { "filename": "src/utils.ts", "retrieved_chunk": "/**\n * Parse a string based off user date extract settings.\n *\n * @param groupsToCheck - The token names to check.\n * @param metadataString - The actual extracted data from the frontmatter.\n * @param reg - The user defined regex to apply.\n * @returns The parsed abstract date or nothing.\n */\nexport function parseAbstractDate(\n\tgroupsToCheck: string[],", "score": 0.7979308366775513 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.7884938716888428 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\tsettings.metadataKeyEventStartDate\n\t\t),\n\t\tendDate:\n\t\t\tgetAbstractDateFromMetadata(\n\t\t\t\tcontext,\n\t\t\t\tsettings.metadataKeyEventEndDate\n\t\t\t) ??\n\t\t\t(isDefined(\n\t\t\t\tgetMetadataKey(c, settings.metadataKeyEventEndDate, \"boolean\")\n\t\t\t)", "score": 0.7839270234107971 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.7755957841873169 } ]
typescript
settings.dateParserGroupPriority.split(",");
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await
getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.8429664373397827 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8411498665809631 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8308472037315369 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8284330368041992 }, { "filename": "src/types.ts", "retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined", "score": 0.8153628706932068 } ]
typescript
getDataFromNoteMetadata(context, tagsToFind);
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client"; import { prisma } from "../../../prisma/client"; export class GetPedidoPorNumeroUseCase { async getPedidoPorNumero(numero: string): Promise<any | null> { const pedido = await prisma.pedido.findFirst({ where: { numero }, include: { cliente: { select: { nome_completo: true, cpf: true, telefone: true, email: true, endereco: true } }, produto: { select: { nome_produto: true, referencia: true, descricao: true, quantidade: true, valor: true, } }, pagamento: { select: { tipo_pagamento: true, parcela: true, id_transacao: true } }, pedido_status: { select: { status_pedido: true, status_erro: true } } } }); if (!pedido) { return null; } const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = []; pedido.produto
.forEach((produto) => {
const produtoFormatado = { nome: produto.nome_produto, referencia: produto.referencia, descricao: produto.descricao, quantidade: produto.quantidade, valor_produto: produto.valor, valor_total_produto: produto.valor * produto.quantidade }; produtosFormatados.push(produtoFormatado); }); const moment = require('moment'); const pedidoFormatado = { cpf: pedido.cliente.cpf, nome: pedido.cliente.nome_completo, contato: pedido.cliente.telefone, email: pedido.cliente.email, endereco: pedido.cliente.endereco, numeroDoPedido: pedido.numero, produtos: produtosFormatados, tipo_pagamento: pedido.pagamento.tipo_pagamento, parcelas: pedido.pagamento.parcela, id_transacao: pedido.pagamento.id_transacao, dataDaCompra: moment(pedido.data_pedido_realizado).format('DD/MM/YYYY'), status_pedido: pedido.pedido_status.status_pedido, status_erro: pedido.pedido_status.status_erro }; return pedidoFormatado; } }
src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts
Iguu42-node-project-FC-0cd6618
[ { "filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts", "retrieved_chunk": " })\n if (!pedidos) {\n return null\n }\n const pedidosFormatados = pedidos.map(pedido => ({\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n pedido: pedido.cliente.cpf,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,", "score": 0.9073168635368347 }, { "filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts", "retrieved_chunk": " nome_cliente: pedido.cliente.nome_completo,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,\n // nome_produto: pedido.produto.nome_produto,\n // quantidade_produto: pedido.produto.quantidade\n }))\n return pedidosFormatados\n }\n}", "score": 0.9020191431045532 }, { "filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts", "retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {", "score": 0.900510311126709 }, { "filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts", "retrieved_chunk": " const pedidosFormatados = pedido.map((pedido) => ({\n numero: pedido.numero,\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,\n nome_cliente: pedido.cliente.nome_completo,\n cpf_cliente: pedido.cliente.cpf,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n }));", "score": 0.8978395462036133 }, { "filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts", "retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,", "score": 0.896796703338623 } ]
typescript
.forEach((produto) => {
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => {
const score = compareAbstractDates(a, b);
if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.8390841484069824 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.8365968465805054 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)", "score": 0.8321726322174072 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tcompareAbstractDates(startDate, date) !== 0;\n\treturn {\n\t\tstart: {\n\t\t\ttop:\n\t\t\t\tstartElement.offsetTop +\n\t\t\t\t(shouldOffsetStartToBottomOfCard\n\t\t\t\t\t? startElement.innerHeight\n\t\t\t\t\t: 0),\n\t\t\tdate: startDate,\n\t\t},", "score": 0.8247506618499756 }, { "filename": "src/rangeMarkup.ts", "retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||", "score": 0.8236017823219299 } ]
typescript
const score = compareAbstractDates(a, b);
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.8502305746078491 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8481544256210327 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8384066820144653 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8299669027328491 }, { "filename": "src/types.ts", "retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined", "score": 0.8212161064147949 } ]
typescript
if (isDefined(baseData)) events.push(baseData);
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client"; import { prisma } from "../../../prisma/client"; export class GetPedidoPorCpfUseCase { async getPedidoPorCpf(numero: string): Promise<any | null> { if (numero.length === 11) { const clienteCpf = await prisma.cliente.findFirst({ where: { cpf: numero } }); if (clienteCpf) { const pedido = await prisma.pedido.findMany({ where: { id_cliente: clienteCpf.id_cliente }, include: { cliente: { select: { nome_completo: true, cpf: true } }, pedido_status: { select: { status_pedido: true, status_erro: true } }, nota_fiscal: { select: { numero_nota: true } }, pagamento: { select: { tipo_pagamento: true, parcela: true } }, produto: { select: { nome_produto: true, quantidade: true } } } }); if (!pedido) { return null; }
const pedidosFormatados = pedido.map((pedido) => ({
numero: pedido.numero, status_pedido: pedido.pedido_status.status_pedido, status_erro: pedido.pedido_status.status_erro, numero_nota_fiscal: pedido.nota_fiscal.numero_nota, data_pedido_realizado: pedido.data_pedido_realizado, nome_cliente: pedido.cliente.nome_completo, cpf_cliente: pedido.cliente.cpf, tipo_pagamento: pedido.pagamento.tipo_pagamento, })); return pedidosFormatados; } } } }
src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts
Iguu42-node-project-FC-0cd6618
[ { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,", "score": 0.9315840005874634 }, { "filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts", "retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {", "score": 0.9265934228897095 }, { "filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts", "retrieved_chunk": " })\n if (!pedidos) {\n return null\n }\n const pedidosFormatados = pedidos.map(pedido => ({\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n pedido: pedido.cliente.cpf,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,", "score": 0.9213918447494507 }, { "filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts", "retrieved_chunk": " quantidade: produto.quantidade,\n valor_produto: produto.valor,\n valor_total_produto: produto.valor * produto.quantidade\n };\n produtosFormatados.push(produtoFormatado);\n });\n const moment = require('moment');\n const pedidoFormatado = {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,", "score": 0.9146153330802917 }, { "filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts", "retrieved_chunk": " nome_cliente: pedido.cliente.nome_completo,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,\n // nome_produto: pedido.produto.nome_produto,\n // quantidade_produto: pedido.produto.quantidade\n }))\n return pedidosFormatados\n }\n}", "score": 0.9066673517227173 } ]
typescript
const pedidosFormatados = pedido.map((pedido) => ({
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) );
cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.8493819832801819 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "import {\n\tisDefined,\n\tfindLastIndex,\n\tlerp,\n\tinLerp,\n\tgetChildAtIndexInHTMLElement,\n\tcompareAbstractDates,\n} from \"~/utils\";\nimport type { CompleteCardContext, AbstractDate } from \"~/types\";\n/**", "score": 0.8383328318595886 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tcompareAbstractDates(startDate, date) !== 0;\n\treturn {\n\t\tstart: {\n\t\t\ttop:\n\t\t\t\tstartElement.offsetTop +\n\t\t\t\t(shouldOffsetStartToBottomOfCard\n\t\t\t\t\t? startElement.innerHeight\n\t\t\t\t\t: 0),\n\t\t\tdate: startDate,\n\t\t},", "score": 0.8145343065261841 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)", "score": 0.8139110803604126 }, { "filename": "src/cardMarkup.ts", "retrieved_chunk": "\tcreateElementShort(\n\t\ttitleWrap,\n\t\t\"h4\",\n\t\t\"aat-card-start-date\",\n\t\tgetDateText(cardContent, settings).trim()\n\t);\n\tconst markdownTextWrapper = createElementShort(\n\t\tcardTextWraper,\n\t\t\"div\",\n\t\t\"aat-card-body\"", "score": 0.810665488243103 } ]
typescript
events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) );
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( (
{ cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } }
) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.9058982729911804 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8724019527435303 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.8719052076339722 }, { "filename": "src/rangeData.ts", "retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0", "score": 0.8196878433227539 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8144544959068298 } ]
typescript
{ cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } }
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const
runtimeTime = measureTime("Run time");
const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardMarkup.ts", "retrieved_chunk": " *\n * @param param0 - The context built for this timeline.\n * @param param0.elements - The HTMLElements exposed for this context.\n * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.\n * @param param0.file - The target note file.\n * @param param0.settings - The plugin's settings.\n * @param cardContent - The content of a single timeline card.\n */\nexport function createCardFromBuiltContext(\n\t{", "score": 0.7475443482398987 }, { "filename": "src/markdownBlockData.ts", "retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();", "score": 0.7276361584663391 }, { "filename": "src/cardMarkup.ts", "retrieved_chunk": "\t\telements: { cardListRootElement },\n\t\tfile,\n\t\tsettings,\n\t}: MarkdownCodeBlockTimelineProcessingContext,\n\tcardContent: CardContent\n): void {\n\tconst { body, title, imageURL } = cardContent;\n\tconst cardBaseDiv = createElementShort(cardListRootElement, \"a\", [\n\t\t\"internal-link\",\n\t\t\"aat-card\",", "score": 0.719179093837738 }, { "filename": "src/markdownBlockData.ts", "retrieved_chunk": "import { SETTINGS_DEFAULT } from \"~/settings\";\nimport { AutoTimelineSettings } from \"./types\";\nimport { isDefined, isDefinedAsBoolean, isDefinedAsString } from \"./utils\";\n/**\n * Fetches the tags to find and timeline specific settings override.\n *\n * @param source - The markdown code block source, a.k.a. the content inside the code block.\n * @returns Partial settings to override the global ones.\n */\nexport function parseMarkdownBlockSource(source: string): {", "score": 0.7179466485977173 }, { "filename": "src/timelineMarkup.ts", "retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {", "score": 0.7159642577171326 } ]
typescript
runtimeTime = measureTime("Run time");
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await
getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined);
if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,", "score": 0.9018354415893555 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,", "score": 0.8598383665084839 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();", "score": 0.8545619249343872 }, { "filename": "src/cardData.ts", "retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;", "score": 0.8395326733589172 }, { "filename": "src/cardData.ts", "retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),", "score": 0.8371604084968567 } ]
typescript
getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined);
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0; index < this.settings.dateTokenConfiguration.length; index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; }
this.addSettingTab(new TimelineSettingTab(this.app, this));
} /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/settings.ts", "retrieved_chunk": "\t\tcreateNumberDateTokenConfiguration({ name: \"day\" }),\n\t] as DateTokenConfiguration[],\n};\nexport const __VUE_PROD_DEVTOOLS__ = true;\n/**\n * Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.\n */\nexport class TimelineSettingTab extends PluginSettingTab {\n\tplugin: AprilsAutomaticTimelinesPlugin;\n\tvueApp: VueApp<Element> | null;", "score": 0.8669183254241943 }, { "filename": "src/settings.ts", "retrieved_chunk": "import { PluginSettingTab } from \"obsidian\";\nimport { createApp, ref } from \"vue\";\nimport createVueI18nConfig from \"~/i18n.config\";\nimport VApp from \"~/views/App.vue\";\nimport type { App as ObsidianApp } from \"obsidian\";\nimport type AprilsAutomaticTimelinesPlugin from \"~/main\";\nimport type { AutoTimelineSettings, DateTokenConfiguration } from \"./types\";\nimport type { App as VueApp } from \"vue\";\nimport { createNumberDateTokenConfiguration } from \"./utils\";\n/**", "score": 0.8318579196929932 }, { "filename": "src/settings.ts", "retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),", "score": 0.8099823594093323 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "import {\n\tdateTokenConfigurationIsTypeNumber,\n\tdateTokenConfigurationIsTypeString,\n\tevalNumericalCondition,\n} from \"~/utils\";\nimport type {\n\tAutoTimelineSettings,\n\tAbstractDate,\n\tDateTokenConfiguration,\n\tDateTokenType,", "score": 0.8033332824707031 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(", "score": 0.8031778335571289 } ]
typescript
this.addSettingTab(new TimelineSettingTab(this.app, this));
import { SETTINGS_DEFAULT } from "~/settings"; import { FnGetRangeData } from "./rangeData"; import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData"; import type { App, CachedMetadata, TFile } from "obsidian"; import type { Merge } from "ts-essentials"; /** * @author https://stackoverflow.com/a/69756175 */ export type PickByType<T, Value> = { [P in keyof T as T[P] extends Value | undefined ? P : never]: T[P]; }; export type AutoTimelineSettings = typeof SETTINGS_DEFAULT; /** * The main bundle of data needed to build a timeline. */ export interface MarkdownCodeBlockTimelineProcessingContext { /** * Obsidian application context. */ app: App; /** * The plugins settings */ settings: AutoTimelineSettings; /** * The formatted metadata of a single note. */ cachedMetadata: CachedMetadata; /** * The file data of a single note. */ file: TFile; /** * The filepath of a single timeline. */ timelineFile: string; /** * Shorthand access to HTMLElements for the range timelines and the card list. */ elements: { timelineRootElement: HTMLElement; cardListRootElement: HTMLElement; }; } /** * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context. */ export type CompleteCardContext = Exclude< Awaited<ReturnType<typeof getDataFromNoteMetadata>>, undefined >; /** * The context extracted from a single note to create a single card in the timeline. */ export type CardContent = Awaited<ReturnType<FnExtractCardData>>; /** * The needed data to compute a range in a single timeline. */
export type Range = ReturnType<FnGetRangeData>[number];
/** * An abstract representation of a fantasy date. * Given the fickle nature of story telling and how people will literally almost never stick to standard date formats * We'll organise the dates in segments, let's take for example our human callendar * The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to * `[year, month, day]` * Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates. * The only major limitation to this system is that all the dates must respect the same system. */ export type AbstractDate = number[]; /** * Before formatting an abstract date, the end user can configure it's output display * This DateToken type helps to determine what's the nature of a given token * E.g. should it be displayed as a number or as a string ? */ export enum DateTokenType { number = "NUMBER", string = "STRING", } export const availableDateTokenTypeArray = Object.values(DateTokenType); export enum Condition { Greater = "GREATER", Less = "LESS", Equal = "EQUAL", NotEqual = "NOTEQUAL", GreaterOrEqual = "GREATEROREQUAL", LessOrEqual = "LESSOREQUAL", } export const availableConditionArray = Object.values(Condition); export type Evaluation<T extends number = number> = { condition: Condition; value: T; }; export type AdditionalDateFormatting<T extends number = number> = { evaluations: Evaluation<T>[]; /** * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked. */ conditionsAreExclusive: boolean; /** * Use `{value}` to include the pre-formated output of the numerical value held. */ format: string; }; /** * The data used to compute the output of an abstract date based on it's type */ type CommonValues<T extends DateTokenType> = { name: string; type: T; formatting: AdditionalDateFormatting[]; }; export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> = T extends DateTokenType.number ? NumberSpecific : T extends DateTokenType.string ? StringSpecific : StringSpecific | NumberSpecific; /** * Number typed date token. */ type NumberSpecific = Merge< CommonValues<DateTokenType.number>, { /** * The minimum ammount of digits when displaying the date */ minLeght: number; displayWhenZero: boolean; hideSign: boolean; } >; /** * String typed date token. */ type StringSpecific = Merge< CommonValues<DateTokenType.string>, { /** * The dictionary reference for the token */ dictionary: string[]; } >;
src/types.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/cardData.ts", "retrieved_chunk": "\t\t\t\t? true\n\t\t\t\t: undefined),\n\t} as const;\n}\nexport type FnExtractCardData = typeof extractCardData;", "score": 0.8391566276550293 }, { "filename": "src/main.ts", "retrieved_chunk": "import { MarkdownPostProcessorContext, Plugin } from \"obsidian\";\nimport type { AutoTimelineSettings, CompleteCardContext } from \"~/types\";\nimport { compareAbstractDates, isDefined, measureTime } from \"~/utils\";\nimport { getDataFromNoteMetadata, getDataFromNoteBody } from \"~/cardData\";\nimport { setupTimelineCreation } from \"~/timelineMarkup\";\nimport { createCardFromBuiltContext } from \"~/cardMarkup\";\nimport { getAllRangeData } from \"~/rangeData\";\nimport { renderRanges } from \"~/rangeMarkup\";\nimport { SETTINGS_DEFAULT, TimelineSettingTab } from \"~/settings\";\nimport { parseMarkdownBlockSource } from \"./markdownBlockData\";", "score": 0.8213231563568115 }, { "filename": "src/main.ts", "retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (", "score": 0.8160637021064758 }, { "filename": "src/cardData.ts", "retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;", "score": 0.8117481470108032 }, { "filename": "src/cardData.ts", "retrieved_chunk": "import { getMetadataKey, isDefined, isDefinedAsObject } from \"~/utils\";\nimport type {\n\tMarkdownCodeBlockTimelineProcessingContext,\n\tCompleteCardContext,\n} from \"~/types\";\nimport { parse } from \"yaml\";\nimport {\n\tgetAbstractDateFromMetadata,\n\tgetBodyFromContextOrDocument,\n\tgetImageUrlFromContextOrDocument,", "score": 0.8098846673965454 } ]
typescript
export type Range = ReturnType<FnGetRangeData>[number];
import { SETTINGS_DEFAULT } from "~/settings"; import { AutoTimelineSettings } from "./types"; import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils"; /** * Fetches the tags to find and timeline specific settings override. * * @param source - The markdown code block source, a.k.a. the content inside the code block. * @returns Partial settings to override the global ones. */ export function parseMarkdownBlockSource(source: string): { readonly tagsToFind: string[]; readonly settingsOverride: Partial<AutoTimelineSettings>; } { const sourceEntries = source.split("\n"); if (!source.length) return { tagsToFind: [] as string[], settingsOverride: {} } as const; const tagsToFind = sourceEntries[0] .split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator) .map((e) => e.trim()); sourceEntries.shift(); return { tagsToFind, settingsOverride: sourceEntries.reduce((accumulator, element) => { return { ...accumulator, ...parseSingleLine(element), }; }, {} as Partial<AutoTimelineSettings>), } as const; } type OverridableSettingKey = (typeof acceptedSettingsOverride)[number]; const acceptedSettingsOverride = [ "dateDisplayFormat", "applyAdditonalConditionFormatting", ] as const; /** * Checks if a given string is part of the settings keys that can be overriden. * * @param value - A given settings key. * @returns the typeguard boolean `true` if the key is indeed overridable. */ function isOverridableSettingsKey( value: string ): value is OverridableSettingKey { // @ts-expect-error return acceptedSettingsOverride.includes(value); } /** * Will apply the needed formatting to a setting value based of it's key. * * @param key - The settings key. * @param value - The value associated to this value. * @returns Undefined if unvalid or the actual expected value. */ function formatValueFromKey( key: string, value: string ): AutoTimelineSettings[OverridableSettingKey] | undefined { if (!isOverridableSettingsKey(key)) return undefined; if
(isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { const validBooleanStrings = ["true", "false"]; if (!validBooleanStrings.includes(value.toLocaleLowerCase())) throw new Error(`${value} is supposed to be a boolean`); return value.toLocaleLowerCase() === "true" ? true : false; } return undefined; } /** * Parse a single line of the timeline markdown block content. * * @param line - The line to parse. * @returns A potencialy partial settings object. */ function parseSingleLine(line: string): Partial<AutoTimelineSettings> { const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i; const matches = line.match(reg); if ( !matches || !matches.groups || !isDefinedAsString(matches.groups.key) || !isDefined(matches.groups.value) ) return {}; const key = matches.groups.key.trim(); const value = formatValueFromKey(key, matches.groups.value.trim()); if (!isDefined(value)) return {}; return { [key]: value }; }
src/markdownBlockData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/utils.ts", "retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {", "score": 0.8136589527130127 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.7875051498413086 }, { "filename": "src/utils.ts", "retrieved_chunk": "\treturn 0;\n}\n/**\n * Typeguard to check if a value is an array of unknowed sub type.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an array, `false` if not.\n */\nexport function isDefinedAsArray(value: unknown): value is unknown[] {\n\treturn isDefined(value) && value instanceof Array;", "score": 0.7861531972885132 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.", "score": 0.7730415463447571 }, { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.7690455913543701 } ]
typescript
(isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
import { SETTINGS_DEFAULT } from "~/settings"; import { AutoTimelineSettings } from "./types"; import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils"; /** * Fetches the tags to find and timeline specific settings override. * * @param source - The markdown code block source, a.k.a. the content inside the code block. * @returns Partial settings to override the global ones. */ export function parseMarkdownBlockSource(source: string): { readonly tagsToFind: string[]; readonly settingsOverride: Partial<AutoTimelineSettings>; } { const sourceEntries = source.split("\n"); if (!source.length) return { tagsToFind: [] as string[], settingsOverride: {} } as const; const tagsToFind = sourceEntries[0] .split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator) .map((e) => e.trim()); sourceEntries.shift(); return { tagsToFind, settingsOverride: sourceEntries.reduce((accumulator, element) => { return { ...accumulator, ...parseSingleLine(element), }; }, {} as Partial<AutoTimelineSettings>), } as const; } type OverridableSettingKey = (typeof acceptedSettingsOverride)[number]; const acceptedSettingsOverride = [ "dateDisplayFormat", "applyAdditonalConditionFormatting", ] as const; /** * Checks if a given string is part of the settings keys that can be overriden. * * @param value - A given settings key. * @returns the typeguard boolean `true` if the key is indeed overridable. */ function isOverridableSettingsKey( value: string ): value is OverridableSettingKey { // @ts-expect-error return acceptedSettingsOverride.includes(value); } /** * Will apply the needed formatting to a setting value based of it's key. * * @param key - The settings key. * @param value - The value associated to this value. * @returns Undefined if unvalid or the actual expected value. */ function formatValueFromKey( key: string, value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined; if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { const validBooleanStrings = ["true", "false"]; if (!validBooleanStrings.includes(value.toLocaleLowerCase())) throw new Error(`${value} is supposed to be a boolean`); return value.toLocaleLowerCase() === "true" ? true : false; } return undefined; } /** * Parse a single line of the timeline markdown block content. * * @param line - The line to parse. * @returns A potencialy partial settings object. */ function parseSingleLine(line: string): Partial<AutoTimelineSettings> { const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i; const matches = line.match(reg); if ( !matches || !matches.groups || !isDefinedAsString(matches.groups.key) || !isDefined(matches.groups.value) ) return {}; const key = matches.groups.key.trim(); const value = formatValueFromKey(key, matches.groups.value.trim()); if (!isDefined(value)) return {}; return { [key]: value }; }
src/markdownBlockData.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/utils.ts", "retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {", "score": 0.7833453416824341 }, { "filename": "src/cardDataExtraction.ts", "retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");", "score": 0.7626240253448486 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.", "score": 0.7541797161102295 }, { "filename": "src/types.ts", "retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.", "score": 0.7504202723503113 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "export function applyConditionBasedFormatting(\n\tformatedDate: string,\n\tdate: number,\n\t{ formatting }: DateTokenConfiguration,\n\tapplyAdditonalConditionFormatting: AutoTimelineSettings[\"applyAdditonalConditionFormatting\"]\n): string {\n\tif (!applyAdditonalConditionFormatting) return formatedDate;\n\treturn formatting.reduce(\n\t\t(output, { format, conditionsAreExclusive, evaluations }) => {\n\t\t\tconst evaluationRestult = (", "score": 0.7417144179344177 } ]
typescript
): AutoTimelineSettings[OverridableSettingKey] | undefined {
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did> public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) { this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller: string | Did, asArray = true ): ReturnBuilderWithController<this> { const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addService(service: ServiceOptions): ReturnBuilderWithService<this> { const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public
findServiceByType(type: string): Service {
const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered( id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " service: z.optional(uniqueServicesSchema),\n })\n .transform((didDocument) => ({\n ...didDocument,\n service: didDocument.service?.map((s) => new Service(s)),\n verificationMethod: didDocument.verificationMethod?.map(\n (v) => new VerificationMethod(v)\n ),\n }))", "score": 0.8324593305587769 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": "import { z } from 'zod'\nimport { stringOrDid } from './didSchema'\nimport {\n uniqueStringOrVerificationMethodsSchema,\n verificationMethodSchema,\n} from './verificationMethodSchema'\nimport { uniqueServicesSchema } from './serviceSchema'\nimport { Service } from '../service'\nimport { VerificationMethod } from '../verificationMethod'\nexport const didDocumentSchema = z", "score": 0.8096315264701843 }, { "filename": "src/schemas/verificationMethodSchema.ts", "retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {", "score": 0.8095040321350098 }, { "filename": "src/service.ts", "retrieved_chunk": " public constructor(options: ServiceOptions) {\n this.fullService = options\n const { id, type, serviceEndpoint } = serviceSchema.parse(options)\n this.id = id\n this.type = type\n this.serviceEndpoint = serviceEndpoint\n }\n /**\n * Checks whether the service type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#service-types | service types}\n *", "score": 0.7918027639389038 }, { "filename": "src/schemas/verificationMethodSchema.ts", "retrieved_chunk": " z.object({\n id: stringOrDidUrl,\n controller: stringOrDid,\n type: z.string(),\n publicKeyJwk: z.optional(publicKeyJwkSchema),\n publicKeyMultibase: z.optional(publicKeyMultibaseSchema),\n }),\n z.custom<VerificationMethod>(\n (verificationMethod) => verificationMethod instanceof VerificationMethod\n ),", "score": 0.784528374671936 } ]
typescript
findServiceByType(type: string): Service {
import { MarkdownPostProcessorContext, Plugin } from "obsidian"; import type { AutoTimelineSettings, CompleteCardContext } from "~/types"; import { compareAbstractDates, isDefined, measureTime } from "~/utils"; import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData"; import { setupTimelineCreation } from "~/timelineMarkup"; import { createCardFromBuiltContext } from "~/cardMarkup"; import { getAllRangeData } from "~/rangeData"; import { renderRanges } from "~/rangeMarkup"; import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings"; import { parseMarkdownBlockSource } from "./markdownBlockData"; export default class AprilsAutomaticTimelinesPlugin extends Plugin { settings: AutoTimelineSettings; /** * The default onload method of a obsidian plugin * See the official documentation for more details */ async onload() { await this.loadSettings(); this.registerMarkdownCodeBlockProcessor( "aat-vertical", (source, element, context) => { this.run(source, element, context); } ); } onunload() {} /** * Main runtime function to process a single timeline. * * @param source - The content found in the markdown block. * @param element - The root element of all the timeline. * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method. * @param param2.sourcePath - A string representing the fs path of a note. */ async run( source: string, element: HTMLElement, { sourcePath }: MarkdownPostProcessorContext ) { const runtimeTime = measureTime("Run time"); const { app } = this; const { tagsToFind, settingsOverride } = parseMarkdownBlockSource(source); const finalSettings = { ...this.settings, ...settingsOverride }; const creationContext = setupTimelineCreation( app, element, sourcePath, finalSettings ); const cardDataTime = measureTime("Data fetch"); const events: CompleteCardContext[] = []; for (const context of creationContext) { const baseData = await getDataFromNoteMetadata(context, tagsToFind); if (isDefined(baseData)) events.push(baseData); if (!finalSettings.lookForInlineEventsInNotes) continue; const body = baseData?.cardData.body || (await context.file.vault.cachedRead(context.file)); const inlineEvents = ( await getDataFromNoteBody(body, context, tagsToFind) ).filter(isDefined); if (!inlineEvents.length) continue; events.push(...inlineEvents); } events.sort( ( { cardData: { startDate: a, endDate: aE } }, { cardData: { startDate: b, endDate: bE } } ) => { const score = compareAbstractDates(a, b); if (score) return score; return compareAbstractDates(aE, bE); } ); cardDataTime(); const cardRenderTime = measureTime("Card Render"); events.forEach(({ context, cardData }) => createCardFromBuiltContext(context, cardData) ); cardRenderTime(); const rangeDataFecthTime = measureTime("Range Data"); const ranges = getAllRangeData(events); rangeDataFecthTime(); const rangeRenderTime = measureTime("Range Render"); renderRanges(ranges, element); rangeRenderTime(); runtimeTime(); } /** * Loads the saved settings from the local device and sets up the setting tabs in the plugin options. */ async loadSettings() { this.settings = Object.assign( {}, SETTINGS_DEFAULT, await this.loadData() ); for ( let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++ ) { this.settings.dateTokenConfiguration[index].formatting = this.settings.dateTokenConfiguration[index].formatting || []; } this.addSettingTab(new TimelineSettingTab(this.app, this)); } /** * Saves the settings in obsidian. */ async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
April-Gras-obsidian-auto-timelines-047d836
[ { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "import {\n\tdateTokenConfigurationIsTypeNumber,\n\tdateTokenConfigurationIsTypeString,\n\tevalNumericalCondition,\n} from \"~/utils\";\nimport type {\n\tAutoTimelineSettings,\n\tAbstractDate,\n\tDateTokenConfiguration,\n\tDateTokenType,", "score": 0.8055092692375183 }, { "filename": "src/utils.ts", "retrieved_chunk": "): DateTokenConfiguration<DateTokenType.number> {\n\treturn {\n\t\tminLeght: 2,\n\t\tname: \"\",\n\t\ttype: DateTokenType.number,\n\t\tdisplayWhenZero: true,\n\t\tformatting: [],\n\t\thideSign: false,\n\t\t...defaultValue,\n\t};", "score": 0.7972285747528076 }, { "filename": "src/settings.ts", "retrieved_chunk": " * Default key value relation for obsidian settings object\n */\nexport const SETTINGS_DEFAULT = {\n\tmetadataKeyEventStartDate: \"aat-event-start-date\",\n\tmetadataKeyEventEndDate: \"aat-event-end-date\",\n\tmetadataKeyEventTitleOverride: \"aat-event-title\",\n\tmetadataKeyEventBodyOverride: \"aat-event-body\",\n\tmetadataKeyEventPictureOverride: \"aat-event-picture\",\n\tmetadataKeyEventTimelineTag: \"timelines\",\n\tnoteInlineEventKey: \"aat-inline-event\",", "score": 0.7916930913925171 }, { "filename": "src/abstractDateFormatting.ts", "retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(", "score": 0.7887911200523376 }, { "filename": "src/settings.ts", "retrieved_chunk": "\t\tcreateNumberDateTokenConfiguration({ name: \"day\" }),\n\t] as DateTokenConfiguration[],\n};\nexport const __VUE_PROD_DEVTOOLS__ = true;\n/**\n * Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.\n */\nexport class TimelineSettingTab extends PluginSettingTab {\n\tplugin: AprilsAutomaticTimelinesPlugin;\n\tvueApp: VueApp<Element> | null;", "score": 0.78803950548172 } ]
typescript
index < this.settings.dateTokenConfiguration.length;
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did> public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) { this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller:
string | Did, asArray = true ): ReturnBuilderWithController<this> {
const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addService(service: ServiceOptions): ReturnBuilderWithService<this> { const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public findServiceByType(type: string): Service { const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered( id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " .object({\n id: stringOrDid,\n alsoKnownAs: z.optional(z.array(z.string().url())),\n controller: z.optional(z.union([stringOrDid, z.array(stringOrDid)])),\n verificationMethod: z.optional(z.array(verificationMethodSchema)),\n authentication: z.optional(\n uniqueStringOrVerificationMethodsSchema('authentication')\n ),\n assertionMethod: z.optional(\n uniqueStringOrVerificationMethodsSchema('assertionMethod')", "score": 0.7484328150749207 }, { "filename": "src/did.ts", "retrieved_chunk": " }\n return `${p}${s}`\n }\n public addParameterKey(key: string | Array<string>): this {\n if (typeof key === 'string') {\n this.parameterKeys.push(key)\n } else if (Array.isArray(key)) {\n this.parameterKeys.push(...key)\n }\n return this", "score": 0.7431460618972778 }, { "filename": "src/did.ts", "retrieved_chunk": " return this\n }\n public addPath(path: string): this {\n if (this.path) {\n this.path = this.path + this.addPrefixIfNotSupplied(path, PREFIX_PATH)\n } else {\n return this.withPath(path)\n }\n return this\n }", "score": 0.7415411472320557 }, { "filename": "src/verificationMethod.ts", "retrieved_chunk": " this.controller = controller\n this.type = type\n this.publicKeyJwk = publicKeyJwk\n this.publicKeyMultibase = publicKeyMultibase\n }\n /**\n * Checks whether the verification method type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#verification-method-types | verification method types}\n *\n */\n public isTypeInDidSpecRegistry(", "score": 0.7389959096908569 }, { "filename": "src/did.ts", "retrieved_chunk": " public removePath(): this {\n this.path = undefined\n return this\n }\n public withQuery(query: Record<string, string>): this {\n this.query = query\n return this\n }\n public addQuery(query: Record<string, string>): this {\n if (this.query) {", "score": 0.7277308702468872 } ]
typescript
string | Did, asArray = true ): ReturnBuilderWithController<this> {
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did> public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) { this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller: string | Did, asArray = true ): ReturnBuilderWithController<this> { const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addService(service: ServiceOptions): ReturnBuilderWithService<this> { const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public findServiceByType(type: string): Service { const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered(
id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean {
const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/verificationMethod.ts", "retrieved_chunk": " additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (\n Object.values(VerificationMethodTypes) as Array<string>\n ).concat(additionalAcceptedTypesArray)\n return allTypes.includes(this.type)", "score": 0.8728107213973999 }, { "filename": "src/service.ts", "retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray", "score": 0.8388878107070923 }, { "filename": "src/verificationMethod.ts", "retrieved_chunk": " this.controller = controller\n this.type = type\n this.publicKeyJwk = publicKeyJwk\n this.publicKeyMultibase = publicKeyMultibase\n }\n /**\n * Checks whether the verification method type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#verification-method-types | verification method types}\n *\n */\n public isTypeInDidSpecRegistry(", "score": 0.8269964456558228 }, { "filename": "src/schemas/verificationMethodSchema.ts", "retrieved_chunk": " for (const obj of verificationMethods) {\n if (idSet.has(obj.id)) {\n return false\n }\n idSet.add(obj.id)\n }\n return true\n }, `Duplicate verificationMethod.id found. They must be unique`)\nexport const stringOrVerificationMethod = z\n .union([stringOrDidUrl, verificationMethodSchema])", "score": 0.8257825374603271 }, { "filename": "src/schemas/verificationMethodSchema.ts", "retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {", "score": 0.8080253601074219 } ]
typescript
id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean {
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) {
this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller: string | Did, asArray = true ): ReturnBuilderWithController<this> { const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addService(service: ServiceOptions): ReturnBuilderWithService<this> { const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public findServiceByType(type: string): Service { const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered( id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/verificationMethod.ts", "retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id", "score": 0.8866515159606934 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " .object({\n id: stringOrDid,\n alsoKnownAs: z.optional(z.array(z.string().url())),\n controller: z.optional(z.union([stringOrDid, z.array(stringOrDid)])),\n verificationMethod: z.optional(z.array(verificationMethodSchema)),\n authentication: z.optional(\n uniqueStringOrVerificationMethodsSchema('authentication')\n ),\n assertionMethod: z.optional(\n uniqueStringOrVerificationMethodsSchema('assertionMethod')", "score": 0.8385926485061646 }, { "filename": "src/did.ts", "retrieved_chunk": " 'service',\n 'relativeRef',\n 'versionId',\n 'versionTime',\n 'hl',\n]\nexport type DidParts = {\n scheme: string\n method: string\n namespaces?: Array<string>", "score": 0.8325380682945251 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " service: z.optional(uniqueServicesSchema),\n })\n .transform((didDocument) => ({\n ...didDocument,\n service: didDocument.service?.map((s) => new Service(s)),\n verificationMethod: didDocument.verificationMethod?.map(\n (v) => new VerificationMethod(v)\n ),\n }))", "score": 0.8289445638656616 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": "import { z } from 'zod'\nimport { stringOrDid } from './didSchema'\nimport {\n uniqueStringOrVerificationMethodsSchema,\n verificationMethodSchema,\n} from './verificationMethodSchema'\nimport { uniqueServicesSchema } from './serviceSchema'\nimport { Service } from '../service'\nimport { VerificationMethod } from '../verificationMethod'\nexport const didDocumentSchema = z", "score": 0.8266024589538574 } ]
typescript
public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) {
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did> public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service> public constructor(options: DidDocumentOptions) {
this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller: string | Did, asArray = true ): ReturnBuilderWithController<this> { const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addService(service: ServiceOptions): ReturnBuilderWithService<this> { const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public findServiceByType(type: string): Service { const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered( id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/verificationMethod.ts", "retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id", "score": 0.8865695595741272 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " .object({\n id: stringOrDid,\n alsoKnownAs: z.optional(z.array(z.string().url())),\n controller: z.optional(z.union([stringOrDid, z.array(stringOrDid)])),\n verificationMethod: z.optional(z.array(verificationMethodSchema)),\n authentication: z.optional(\n uniqueStringOrVerificationMethodsSchema('authentication')\n ),\n assertionMethod: z.optional(\n uniqueStringOrVerificationMethodsSchema('assertionMethod')", "score": 0.8385428190231323 }, { "filename": "src/did.ts", "retrieved_chunk": " 'service',\n 'relativeRef',\n 'versionId',\n 'versionTime',\n 'hl',\n]\nexport type DidParts = {\n scheme: string\n method: string\n namespaces?: Array<string>", "score": 0.8325067758560181 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " service: z.optional(uniqueServicesSchema),\n })\n .transform((didDocument) => ({\n ...didDocument,\n service: didDocument.service?.map((s) => new Service(s)),\n verificationMethod: didDocument.verificationMethod?.map(\n (v) => new VerificationMethod(v)\n ),\n }))", "score": 0.8289432525634766 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": "import { z } from 'zod'\nimport { stringOrDid } from './didSchema'\nimport {\n uniqueStringOrVerificationMethodsSchema,\n verificationMethodSchema,\n} from './verificationMethodSchema'\nimport { uniqueServicesSchema } from './serviceSchema'\nimport { Service } from '../service'\nimport { VerificationMethod } from '../verificationMethod'\nexport const didDocumentSchema = z", "score": 0.8266110420227051 } ]
typescript
public service?: Array<Service> public constructor(options: DidDocumentOptions) {
import { z } from 'zod' import { Did } from './did' import { Service, ServiceOptions } from './service' import { VerificationMethod, VerificationMethodOptions, } from './verificationMethod' import { didDocumentSchema, stringOrDid, uniqueServicesSchema, uniqueStringOrVerificationMethodsSchema, uniqueVerificationMethodsSchema, } from './schemas' import { DidDocumentError } from './error' import { MakePropertyRequired, Modify } from './types' type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString> type VerificationMethodOrDidOrString = | VerificationMethod | VerificationMethodOptions | Did | string export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify< z.input<typeof didDocumentSchema>, { verificationMethod?: Array<VerificationMethodOptions> authentication?: DidOrVerificationMethodArray assertionMethod?: DidOrVerificationMethodArray keyAgreement?: DidOrVerificationMethodArray capabilityInvocation?: DidOrVerificationMethodArray capabilityDelegation?: DidOrVerificationMethodArray service?: Array<ServiceOptions | Service> } > & Record<string, unknown> & T type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired< T, 'alsoKnownAs' > type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired< T, 'controller' > type ReturnBuilderWithVerificationMethod<T extends DidDocument> = MakePropertyRequired<T, 'verificationMethod'> type ReturnBuilderWithAuthentication<T extends DidDocument> = MakePropertyRequired<T, 'authentication'> type ReturnBuilderWithAssertionMethod<T extends DidDocument> = MakePropertyRequired<T, 'assertionMethod'> type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> = MakePropertyRequired<T, 'keyAgreement'> type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityInvocation'> type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> = MakePropertyRequired<T, 'capabilityDelegation'> type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired< T, 'service' > export class DidDocument { public fullDocument: DidDocumentOptions public id: Did public alsoKnownAs?: Array<string> public controller?: Did | Array<Did> public verificationMethod?: Array<VerificationMethod> public authentication?: Array<VerificationMethod | Did> public assertionMethod?: Array<VerificationMethod | Did> public keyAgreement?: Array<VerificationMethod | Did> public capabilityInvocation?: Array<VerificationMethod | Did> public capabilityDelegation?: Array<VerificationMethod | Did> public service?: Array<Service> public constructor(options: DidDocumentOptions) { this.fullDocument = options const parsed = didDocumentSchema.parse(options) this.id = parsed.id this.alsoKnownAs = parsed.alsoKnownAs this.controller = parsed.controller this.verificationMethod = parsed.verificationMethod this.authentication = parsed.authentication this.assertionMethod = parsed.assertionMethod this.keyAgreement = parsed.keyAgreement this.capabilityDelegation = parsed.capabilityDelegation this.capabilityInvocation = parsed.capabilityInvocation this.service = parsed.service } public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) { const did = stringOrDid.parse(didUrl) const verificationMethod = this.verificationMethod?.find( (verificationMethod) => verificationMethod.id.toUrl() === did.toUrl() ) if (!verificationMethod) { throw new DidDocumentError( `Verification method for did '${did.toString()}' not found` ) } return verificationMethod } public safeFindToVerificationMethodByDidUrl( didUrl: z.input<typeof stringOrDid> ) { try { return this.findVerificationMethodByDidUrl(didUrl) } catch { return undefined } } public addAlsoKnownAs( alsoKnownAs: string ): ReturnBuilderWithAlsoKnownAs<this> { if (this.alsoKnownAs) { this.alsoKnownAs.push(alsoKnownAs) } else { this.alsoKnownAs = [alsoKnownAs] } return this as ReturnBuilderWithAlsoKnownAs<this> } public addController( controller: string | Did, asArray = true ): ReturnBuilderWithController<this> { const instancedController = typeof controller === 'string' ? new Did(controller) : controller if (this.controller) { if (Array.isArray(this.controller)) { this.controller.push(instancedController) } else { this.controller = [this.controller, instancedController] } } else { this.controller = asArray ? [instancedController] : instancedController } return this as ReturnBuilderWithController<this> } public addVerificationMethod( verificationMethod: VerificationMethodOptions ): ReturnBuilderWithVerificationMethod<this> { if (this.verificationMethod) { this.verificationMethod.push(new VerificationMethod(verificationMethod)) } else { this.verificationMethod = [new VerificationMethod(verificationMethod)] } uniqueVerificationMethodsSchema.parse(this.verificationMethod) return this as ReturnBuilderWithVerificationMethod<this> } public addAuthentication( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString ) return this as ReturnBuilderWithAuthentication<this> } public addAuthenticationUnsafe( verificationMethodOrDidOrString: VerificationMethodOrDidOrString ): ReturnBuilderWithAuthentication<this> { this.authentication = this.addVerificationMethodOrDidOrString( 'authentication', this.authentication, verificationMethodOrDidOrString, true ) return this as ReturnBuilderWithAuthentication<this> } public addKeyAgreement( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addKeyAgreementUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithKeyAgreementMethod<this> { this.keyAgreement = this.addVerificationMethodOrDidOrString( 'keyAgreement', this.keyAgreement, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithKeyAgreementMethod<this> } public addAssertionMethod( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithAssertionMethod<this> } public addAssertionMethodUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithAssertionMethod<this> { this.assertionMethod = this.addVerificationMethodOrDidOrString( 'assertionMethod', this.assertionMethod, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithAssertionMethod<this> } public addCapabilityDelegation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityDelegationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityDelegation<this> { this.capabilityDelegation = this.addVerificationMethodOrDidOrString( 'capabilityDelegation', this.capabilityDelegation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityDelegation<this> } public addCapabilityInvocation( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid ) return this as ReturnBuilderWithCapabilityInvocation<this> } public addCapabilityInvocationUnsafe( verificationMethodOrStringOrDid: VerificationMethodOrDidOrString ): ReturnBuilderWithCapabilityInvocation<this> { this.capabilityInvocation = this.addVerificationMethodOrDidOrString( 'capabilityInvocation', this.capabilityInvocation, verificationMethodOrStringOrDid, true ) return this as ReturnBuilderWithCapabilityInvocation<this> } public
addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service) if (this.service) { this.service.push(instanceService) } else { this.service = [instanceService] } uniqueServicesSchema.parse(this.service) return this as ReturnBuilderWithService<this> } private addVerificationMethodOrDidOrString( fieldName: string, previousItem: Array<VerificationMethod | Did> | undefined, verificationMethodOrDidOrString: VerificationMethodOrDidOrString, unsafe = false ) { let newItem = previousItem const id = verificationMethodOrDidOrString instanceof Did ? verificationMethodOrDidOrString : typeof verificationMethodOrDidOrString === 'string' ? new Did(verificationMethodOrDidOrString) : undefined if (id && !unsafe) { const verificationMethodIds = this.verificationMethod?.map((vm) => vm.id.toUrl() ) if ( verificationMethodIds === undefined || !verificationMethodIds.includes(id.toUrl()) ) { throw new DidDocumentError( `Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${ fieldName.charAt(0).toUpperCase() + fieldName.slice(1) }Unsafe(...)'` ) } } const vm = id === undefined ? verificationMethodOrDidOrString instanceof VerificationMethod ? verificationMethodOrDidOrString : new VerificationMethod( verificationMethodOrDidOrString as VerificationMethodOptions ) : undefined const item = id ?? vm if (item) { if (newItem) { newItem.push(item) } else { newItem = [item] } } else { throw new DidDocumentError( `Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}` ) } uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem) return newItem } public findServiceByType(type: string): Service { const service = this.service?.find((s) => (typeof s.type === 'string' ? [s.type] : s.type).includes(type) ) if (!service) { throw new DidDocumentError(`Service not found for type '${type}'`) } return service } public safeFindServiceByType(type: string): Service | undefined { try { return this.findServiceByType(type) } catch { return undefined } } public findServiceById(id: string): Service { const service = this.service?.find((s) => s.id === id) if (!service) { throw new DidDocumentError(`Service not found with id '${id}'`) } return service } public safeFindServiceById(id: string): Service | undefined { try { return this.findServiceById(id) } catch { return undefined } } public findVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod { const field = purpose === 'authentication' ? this.authentication : purpose === 'keyAgreement' ? this.keyAgreement : purpose === 'assertionMethod' ? this.assertionMethod : purpose === 'capabilityInvocation' ? this.capabilityInvocation : purpose === 'capabilityDelegation' ? this.capabilityInvocation : this.verificationMethod if (!field) { throw new DidDocumentError( `Purpose '${purpose}' does not exist inside the did document` ) } const vm = field .map((f) => f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f ) .find((vm) => vm?.type === type) if (!vm) { throw new DidDocumentError( `Purpose '${purpose}' does not have a field with type '${type}'` ) } return vm } public safeFindVerificationMethodByTypeAndPurpose( type: string, purpose: | 'authentication' | 'keyAgreement' | 'assertionMethod' | 'capabilityInvocation' | 'capabilityDelegation' | 'verificationMethod' = 'verificationMethod' ): VerificationMethod | undefined { try { return this.findVerificationMethodByTypeAndPurpose(type, purpose) } catch { return undefined } } public isVerificationMethodTypeRegistered( id: Did | string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const vm = this.findVerificationMethodByDidUrl(id) return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public isServiceTypeRegistered( id: string, additionalAcceptedTypes: string | Array<string> = [] ): boolean { const service = this.findServiceById(id) return service.isTypeInDidSpecRegistry(additionalAcceptedTypes) } public toJSON(omitKeys?: Array<string>): Record<string, unknown> { const mapStringOrVerificationMethod = (i: Did | VerificationMethod) => i.toJSON() const omitBase = ['fullDocument'] const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase const mappedRest = { ...this.fullDocument, id: this.id.did, alsoKnownAs: this.alsoKnownAs, controller: this.controller && this.controller instanceof Did ? this.controller?.did : this.controller?.map((c) => c.did), verificationMethod: this.verificationMethod?.map((v) => v.toJSON()), service: this.service?.map((s) => s.toJSON()), assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod), keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod), capabilityInvocation: this.capabilityInvocation?.map( mapStringOrVerificationMethod ), capabilityDelegation: this.capabilityDelegation?.map( mapStringOrVerificationMethod ), authentication: this.authentication?.map(mapStringOrVerificationMethod), } const cleanedRest = Object.fromEntries( Object.entries(mappedRest) .filter(([_, value]) => value !== undefined) .filter(([key]) => !omitKeysWithBase.includes(key)) ) return cleanedRest } }
src/didDocument.ts
berendsliedrecht-did-core-1d5b3ba
[ { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " service: z.optional(uniqueServicesSchema),\n })\n .transform((didDocument) => ({\n ...didDocument,\n service: didDocument.service?.map((s) => new Service(s)),\n verificationMethod: didDocument.verificationMethod?.map(\n (v) => new VerificationMethod(v)\n ),\n }))", "score": 0.7948167324066162 }, { "filename": "src/service.ts", "retrieved_chunk": "import { z } from 'zod'\nimport { serviceSchema } from './schemas'\nimport { ServiceTypes } from './serviceTypes'\nexport type ServiceOptions = z.input<typeof serviceSchema> &\n Record<string, unknown>\nexport class Service {\n public fullService: ServiceOptions\n public id: string\n public type: ServiceTypes | string | Array<ServiceTypes | string>\n public serviceEndpoint: string | Array<string> | Record<string, string>", "score": 0.7795419096946716 }, { "filename": "src/schemas/didDocumentSchema.ts", "retrieved_chunk": " ),\n keyAgreement: z.optional(\n uniqueStringOrVerificationMethodsSchema('keyAgreement')\n ),\n capabilityInvocation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),\n capabilityDelegation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),", "score": 0.7690833806991577 }, { "filename": "src/verificationMethod.ts", "retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id", "score": 0.765235185623169 }, { "filename": "src/service.ts", "retrieved_chunk": " public constructor(options: ServiceOptions) {\n this.fullService = options\n const { id, type, serviceEndpoint } = serviceSchema.parse(options)\n this.id = id\n this.type = type\n this.serviceEndpoint = serviceEndpoint\n }\n /**\n * Checks whether the service type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#service-types | service types}\n *", "score": 0.7641839981079102 } ]
typescript
addService(service: ServiceOptions): ReturnBuilderWithService<this> {
import { useEffect, useLayoutEffect, useRef } from 'react'; import { PlayIcon } from '@heroicons/react/24/outline'; import MonacoEditor from '@monaco-editor/react'; import { editor } from 'monaco-editor'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import K from './Hotkey'; interface EditorProps { onRunCode?: (code: string) => void; showRunButton?: boolean; } interface CoreEditorProps extends EditorProps { onSave: (content: string) => void; onChange: (value: string) => void; value: string; } const CoreEditor = (props: CoreEditorProps): JSX.Element => { const ref = useRef<editor.IStandaloneCodeEditor>(); const handleShortcut = (e: KeyboardEvent) => { const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey; if (isMod && e.key === 's') { e.preventDefault(); const content = ref.current?.getValue(); if (content !== undefined) props.onSave(content); } if (e.key === 'F5') { e.preventDefault(); saveThenRunCode(); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); const saveThenRunCode = () => { const content = ref.current?.getValue() ?? ''; props.onSave(content); props.onRunCode?.(content); }; return ( <section className="windowed h-full w-full"> <MonacoEditor defaultLanguage="python" onChange={(value) => value !== undefined ? props.onChange(value) : null } onMount={(editor) => (ref.current = editor)} options={{ fontSize: 14, fontFamily: 'monospace', smoothScrolling: true, cursorSmoothCaretAnimation: 'on', minimap: { enabled: false }, }} theme="vs-dark" value={props.value} /> {props.showRunButton && ( <div className="absolute bottom-3 right-3 space-x-2"> <Button icon={PlayIcon} onClick={saveThenRunCode}> Run <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )} </section> ); }; const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, content } = useFile.Selected(); useLayoutEffect(() => { document.title = `${name ? `${name} | ` : ''}Glide`; }, [name]); if (name === undefined || content === undefined) return null; return ( <CoreEditor {...props} onChange={update} onSave={(newContent) => save(name, newContent)} value={content} /> ); }; export default Editor;
src/components/Editor.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileName.tsx", "retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();", "score": 0.8496330380439758 }, { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": "import { ComponentRef, useRef, useState } from 'react';\nimport Between from '../components/Between';\nimport Editor from '../components/Editor';\nimport Navigator from '../components/Navigator';\nimport Terminal from '../components/Terminal';\nimport useFile from '../hooks/useFile';\nimport useInterpreter from '../hooks/useInterpreter';\nconst IDEPage = (): JSX.Element => {\n const consoleRef = useRef<ComponentRef<typeof Terminal>>(null);\n const [running, setRunning] = useState(false);", "score": 0.8460238575935364 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;", "score": 0.8426978588104248 }, { "filename": "src/components/Library.tsx", "retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}", "score": 0.8391138315200806 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>", "score": 0.8390620946884155 } ]
typescript
const { update, save } = useFilesMutations();
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2"> {files.map(({ name, unsaved }) => ( <
FileItem key={name}
name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <FileUploader icon={ArrowUpTrayIcon} onUpload={(name, content) => { if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8556739091873169 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}", "score": 0.8337529897689819 }, { "filename": "src/components/Navigator.tsx", "retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"", "score": 0.8326929807662964 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>", "score": 0.8298754096031189 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();", "score": 0.8287760019302368 } ]
typescript
FileItem key={name}
import { useState } from 'react'; import { Transition } from '@headlessui/react'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import UnsavedBadge from './UnsavedBadge'; interface RenamableInputProps { initialValue: string; onConfirm: (value: string) => void; } const RenamableInput = (props: RenamableInputProps): JSX.Element => { const [newFileName, setNewFileName] = useState<string>(); const [editing, setEditing] = useState(false); return !editing ? ( <div className="min-w-0 rounded-lg p-2 hover:bg-slate-800" onClick={() => setEditing(true)} > <p className="text-md overflow-hidden overflow-ellipsis whitespace-nowrap"> {props.initialValue} </p> </div> ) : ( <input autoFocus className="w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600" onBlur={() => { let newName = newFileName?.trim(); setEditing(false); setNewFileName(undefined); if ( !newName || newName === props.initialValue || newName.startsWith('.') || newName.endsWith('.') ) return; /** * @see https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words */ newName = newName.replace(/[/\\?%*:|"<>]/g, '_'); props.onConfirm(newName); }} onChange={(e) => setNewFileName(e.target.value)} onFocus={(e) => { const name = e.target.value; const extensionLength = name.split('.').pop()?.length ?? 0; e.target.setSelectionRange(0, name.length - extensionLength - 1); }} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); } if (e.key === 'Escape') { e.preventDefault(); setEditing(false); setNewFileName(undefined); } }} placeholder={props.initialValue} type="text" value={newFileName ?? props.initialValue} /> ); }; const FileName = (): JSX.Element => { const name = useFile.SelectedName(); const unsaved = useFile.IsUnsavedOf(name); const existingNames = useFile.NamesSet();
const { rename } = useFilesMutations();
return ( <div className="flex min-w-0 items-center space-x-3"> {name && ( <RenamableInput initialValue={name} onConfirm={(newName) => { if (!name) return; if (existingNames.has(newName)) return; rename(name, newName); }} /> )} <Transition enter="transition-transform origin-left duration-75" enterFrom="scale-0" enterTo="scale-100" leave="transition-transform origin-left duration-150" leaveFrom="scale-100" leaveTo="scale-0" show={Boolean(name && unsaved)} > <UnsavedBadge /> </Transition> </div> ); }; export default FileName;
src/components/FileName.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8866292238235474 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;", "score": 0.8706169128417969 }, { "filename": "src/hooks/useFile.ts", "retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {", "score": 0.8646780848503113 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}", "score": 0.8508984446525574 }, { "filename": "src/components/Editor.tsx", "retrieved_chunk": " const { update, save } = useFilesMutations();\n const { name, content } = useFile.Selected();\n useLayoutEffect(() => {\n document.title = `${name ? `${name} | ` : ''}Glide`;\n }, [name]);\n if (name === undefined || content === undefined) return null;\n return (\n <CoreEditor\n {...props}\n onChange={update}", "score": 0.8494522571563721 } ]
typescript
const { rename } = useFilesMutations();
import { useEffect, useLayoutEffect, useRef } from 'react'; import { PlayIcon } from '@heroicons/react/24/outline'; import MonacoEditor from '@monaco-editor/react'; import { editor } from 'monaco-editor'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import K from './Hotkey'; interface EditorProps { onRunCode?: (code: string) => void; showRunButton?: boolean; } interface CoreEditorProps extends EditorProps { onSave: (content: string) => void; onChange: (value: string) => void; value: string; } const CoreEditor = (props: CoreEditorProps): JSX.Element => { const ref = useRef<editor.IStandaloneCodeEditor>(); const handleShortcut = (e: KeyboardEvent) => { const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey; if (isMod && e.key === 's') { e.preventDefault(); const content = ref.current?.getValue(); if (content !== undefined) props.onSave(content); } if (e.key === 'F5') { e.preventDefault(); saveThenRunCode(); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); const saveThenRunCode = () => { const content = ref.current?.getValue() ?? ''; props.onSave(content); props.onRunCode?.(content); }; return ( <section className="windowed h-full w-full"> <MonacoEditor defaultLanguage="python" onChange={(value) => value !== undefined ? props.onChange(value) : null } onMount={(editor) => (ref.current = editor)} options={{ fontSize: 14, fontFamily: 'monospace', smoothScrolling: true, cursorSmoothCaretAnimation: 'on', minimap: { enabled: false }, }} theme="vs-dark" value={props.value} /> {props.showRunButton && ( <div className="absolute bottom-3 right-3 space-x-2"> <Button icon={PlayIcon} onClick={saveThenRunCode}> Run <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )} </section> ); }; const Editor = (props: EditorProps): JSX.Element | null => { const { update, save } = useFilesMutations(); const { name,
content } = useFile.Selected();
useLayoutEffect(() => { document.title = `${name ? `${name} | ` : ''}Glide`; }, [name]); if (name === undefined || content === undefined) return null; return ( <CoreEditor {...props} onChange={update} onSave={(newContent) => save(name, newContent)} value={content} /> ); }; export default Editor;
src/components/Editor.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileName.tsx", "retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();", "score": 0.8663884401321411 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;", "score": 0.8553194403648376 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8499678373336792 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>", "score": 0.8468621969223022 }, { "filename": "src/hooks/useFilesMutations.ts", "retrieved_chunk": " save: (name: string, content: string) => void;\n destroy: (name: string) => void;\n draft: (autoSelect?: boolean) => void;\n select: (name: string) => void;\n update: (content: string) => void;\n create: (name: string, content: string) => void;\n}\nconst useFilesMutations = (): UseFilesMutationsHook => {\n const dispatch = useAppDispatch();\n return {", "score": 0.8393043875694275 } ]
typescript
content } = useFile.Selected();
import { ComponentRef, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, } from 'react'; import { StopIcon } from '@heroicons/react/24/outline'; import { slate, yellow } from 'tailwindcss/colors'; import { Terminal as Xterm } from 'xterm'; import { CanvasAddon } from 'xterm-addon-canvas'; import { FitAddon } from 'xterm-addon-fit'; import { WebglAddon } from 'xterm-addon-webgl'; import Button from './Button'; import Prompt from './Prompt'; import TerminalMenu from './TerminalMenu'; import 'xterm/css/xterm.css'; interface TerminalRef { append: (result?: string) => void; write: (result?: string) => void; error: (result?: string) => void; system: (result?: string) => void; } interface TerminalProps { onStop?: () => void; onReturn?: (line: string) => void; onRestart?: () => void; showStopButton?: boolean; } const isASCIIPrintable = (character: string): boolean => character >= String.fromCharCode(32) && character <= String.fromCharCode(126); const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); /** * @see https://github.com/xtermjs/xterm.js/pull/4255 */ const getSafariVersion = (): number => { if (!isSafari) return 0; const majorVersion = navigator.userAgent.match(/Version\/(\d+)/); if (majorVersion === null || majorVersion.length < 2) return 0; return parseInt(majorVersion[1]); }; const isWebGL2Compatible = (): boolean => { const context = document.createElement('canvas').getContext('webgl2'); const isWebGL2Available = Boolean(context); return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true); }; const Terminal = forwardRef<TerminalRef, TerminalProps>( (props, ref): JSX.Element => { const xtermRef = useRef<Xterm>(); const fitAddonRef = useRef<FitAddon>(); const terminalRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null); const promptRef = useRef<ComponentRef<typeof Prompt>>(null); useLayoutEffect(() => { const container = containerRef.current; if (!container) return; const resizeObserver = new ResizeObserver(() => fitAddonRef.current?.fit(), ); resizeObserver.observe(container); return () => resizeObserver.disconnect(); }, []); useEffect(() => { const terminal = terminalRef.current; if (!terminal) return; const xterm = new Xterm({ cursorBlink: false, cursorStyle: 'underline', fontFamily: 'monospace', fontSize: 14, theme: { background: slate[900], cursor: yellow[400] }, disableStdin: true, }); const fitAddon = new FitAddon(); xterm.loadAddon(fitAddon); if (isWebGL2Compatible()) { xterm.loadAddon(new WebglAddon()); } else { xterm.loadAddon(new CanvasAddon()); } xterm.onKey(({ key }) => { if (!(isASCIIPrintable(key) || key >= '\u00a0')) return; promptRef.current?.focusWith(key); }); xterm.open(terminal); fitAddon.fit(); xtermRef.current = xterm; fitAddonRef.current = fitAddon; return () => xterm.dispose(); }, []); const write = (text: string, line = true) => { const trimmed = text.replace(/\n/g, '\r\n'); const xterm = xtermRef.current; if (!xterm) return; const writer = (text: string) => line ? xterm.writeln(text) : xterm.write(text); try { writer(trimmed); } catch (error) { if (!(error instanceof Error)) throw error; console.log('oops', error.message); xterm.clear(); writer(trimmed); } }; useImperativeHandle(ref, () => ({ append: (result?: string) => write(result ?? ''), write: (result?: string) => write(result ?? '', false), error: (result?: string) => write('\u001b[31m' + (result ?? '') + '\u001b[0m'), system: (result?: string) => write('\u001b[33m' + (result ?? '') + '\u001b[0m'), })); return ( <section ref={containerRef} className="relative h-full w-full"> <div ref={terminalRef} className="windowed h-full" /> <div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2"> <Prompt ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input); xtermRef.current?.scrollToBottom(); }} /> <TerminalMenu onClickClearConsole={() => xtermRef.current?.clear()} onClickForceStop={() => { props.onStop?.(); xtermRef.current?.scrollToBottom(); }} onClickRestart={props.onRestart} /> </div> {props.showStopButton && ( <div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100"> <Button icon={StopIcon} onClick={props.onStop}> Stop </Button> </div> )} </section> ); }, ); Terminal.displayName = 'Terminal'; export default Terminal;
src/components/Terminal.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": " <Terminal\n ref={consoleRef}\n onRestart={interpreter.restart}\n onReturn={interpreter.execute}\n onStop={interpreter.stop}\n showStopButton={running}\n />\n }\n />\n </main>", "score": 0.860791027545929 }, { "filename": "src/components/Prompt.tsx", "retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)", "score": 0.8571817874908447 }, { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (", "score": 0.8518701195716858 }, { "filename": "src/components/Prompt.tsx", "retrieved_chunk": "import { forwardRef, useImperativeHandle, useRef, useState } from 'react';\nimport { ChevronRightIcon } from '@heroicons/react/24/outline';\nimport produce from 'immer';\nimport useCommandHistory from '../hooks/useCommandHistory';\ninterface PromptRef {\n focusWith: (key?: string) => void;\n}\ninterface PromptProps {\n onReturn?: (command: string) => void;\n}", "score": 0.8515599966049194 }, { "filename": "src/components/Editor.tsx", "retrieved_chunk": " return (\n <section className=\"windowed h-full w-full\">\n <MonacoEditor\n defaultLanguage=\"python\"\n onChange={(value) =>\n value !== undefined ? props.onChange(value) : null\n }\n onMount={(editor) => (ref.current = editor)}\n options={{\n fontSize: 14,", "score": 0.8459218144416809 } ]
typescript
onReturn={(input) => {
import { useEffect, useLayoutEffect, useRef } from 'react'; import { PlayIcon } from '@heroicons/react/24/outline'; import MonacoEditor from '@monaco-editor/react'; import { editor } from 'monaco-editor'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import K from './Hotkey'; interface EditorProps { onRunCode?: (code: string) => void; showRunButton?: boolean; } interface CoreEditorProps extends EditorProps { onSave: (content: string) => void; onChange: (value: string) => void; value: string; } const CoreEditor = (props: CoreEditorProps): JSX.Element => { const ref = useRef<editor.IStandaloneCodeEditor>(); const handleShortcut = (e: KeyboardEvent) => { const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey; if (isMod && e.key === 's') { e.preventDefault(); const content = ref.current?.getValue(); if (content !== undefined) props.onSave(content); } if (e.key === 'F5') { e.preventDefault(); saveThenRunCode(); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); const saveThenRunCode = () => { const content = ref.current?.getValue() ?? ''; props.onSave(content); props.onRunCode?.(content); }; return ( <section className="windowed h-full w-full"> <MonacoEditor defaultLanguage="python" onChange={(value) => value !== undefined ? props.onChange(value) : null } onMount={(editor) => (ref.current = editor)} options={{ fontSize: 14, fontFamily: 'monospace', smoothScrolling: true, cursorSmoothCaretAnimation: 'on', minimap: { enabled: false }, }} theme="vs-dark" value={props.value} /> {props.showRunButton && ( <div className="absolute bottom-3 right-3 space-x-2"> <Button icon={PlayIcon} onClick={saveThenRunCode}> Run <
K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )}
</section> ); }; const Editor = (props: EditorProps): JSX.Element | null => { const { update, save } = useFilesMutations(); const { name, content } = useFile.Selected(); useLayoutEffect(() => { document.title = `${name ? `${name} | ` : ''}Glide`; }, [name]); if (name === undefined || content === undefined) return null; return ( <CoreEditor {...props} onChange={update} onSave={(newContent) => save(name, newContent)} value={content} /> ); }; export default Editor;
src/components/Editor.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/Terminal.tsx", "retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>", "score": 0.8849835395812988 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>", "score": 0.8589751124382019 }, { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>", "score": 0.8405442237854004 }, { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={", "score": 0.8377954959869385 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " {...buttonProps}\n className={`relative cursor-pointer ${props.className ?? ''}`}\n >\n {props.children}\n <input\n accept=\"text/csv, text/x-python-script, text/x-python, .py, .csv, text/plain\"\n className=\"absolute bottom-0 left-0 right-0 top-0 cursor-pointer opacity-0\"\n onChange={handleUpload}\n type=\"file\"\n />", "score": 0.833218514919281 } ]
typescript
K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )}
import { ComponentRef, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, } from 'react'; import { StopIcon } from '@heroicons/react/24/outline'; import { slate, yellow } from 'tailwindcss/colors'; import { Terminal as Xterm } from 'xterm'; import { CanvasAddon } from 'xterm-addon-canvas'; import { FitAddon } from 'xterm-addon-fit'; import { WebglAddon } from 'xterm-addon-webgl'; import Button from './Button'; import Prompt from './Prompt'; import TerminalMenu from './TerminalMenu'; import 'xterm/css/xterm.css'; interface TerminalRef { append: (result?: string) => void; write: (result?: string) => void; error: (result?: string) => void; system: (result?: string) => void; } interface TerminalProps { onStop?: () => void; onReturn?: (line: string) => void; onRestart?: () => void; showStopButton?: boolean; } const isASCIIPrintable = (character: string): boolean => character >= String.fromCharCode(32) && character <= String.fromCharCode(126); const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); /** * @see https://github.com/xtermjs/xterm.js/pull/4255 */ const getSafariVersion = (): number => { if (!isSafari) return 0; const majorVersion = navigator.userAgent.match(/Version\/(\d+)/); if (majorVersion === null || majorVersion.length < 2) return 0; return parseInt(majorVersion[1]); }; const isWebGL2Compatible = (): boolean => { const context = document.createElement('canvas').getContext('webgl2'); const isWebGL2Available = Boolean(context); return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true); }; const Terminal = forwardRef<TerminalRef, TerminalProps>( (props, ref): JSX.Element => { const xtermRef = useRef<Xterm>(); const fitAddonRef = useRef<FitAddon>(); const terminalRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null); const promptRef = useRef<ComponentRef<typeof Prompt>>(null); useLayoutEffect(() => { const container = containerRef.current; if (!container) return; const resizeObserver = new ResizeObserver(() => fitAddonRef.current?.fit(), ); resizeObserver.observe(container); return () => resizeObserver.disconnect(); }, []); useEffect(() => { const terminal = terminalRef.current; if (!terminal) return; const xterm = new Xterm({ cursorBlink: false, cursorStyle: 'underline', fontFamily: 'monospace', fontSize: 14, theme: { background: slate[900], cursor: yellow[400] }, disableStdin: true, }); const fitAddon = new FitAddon(); xterm.loadAddon(fitAddon); if (isWebGL2Compatible()) { xterm.loadAddon(new WebglAddon()); } else { xterm.loadAddon(new CanvasAddon()); } xterm.onKey(({ key }) => { if (!(isASCIIPrintable(key) || key >= '\u00a0')) return; promptRef.current?.focusWith(key); }); xterm.open(terminal); fitAddon.fit(); xtermRef.current = xterm; fitAddonRef.current = fitAddon; return () => xterm.dispose(); }, []); const write = (text: string, line = true) => { const trimmed = text.replace(/\n/g, '\r\n'); const xterm = xtermRef.current; if (!xterm) return; const writer = (text: string) => line ? xterm.writeln(text) : xterm.write(text); try { writer(trimmed); } catch (error) { if (!(error instanceof Error)) throw error; console.log('oops', error.message); xterm.clear(); writer(trimmed); } }; useImperativeHandle(ref, () => ({ append: (result?: string) => write(result ?? ''), write: (result?: string) => write(result ?? '', false), error: (result?: string) => write('\u001b[31m' + (result ?? '') + '\u001b[0m'), system: (result?: string) => write('\u001b[33m' + (result ?? '') + '\u001b[0m'), })); return ( <section ref={containerRef} className="relative h-full w-full"> <div ref={terminalRef} className="windowed h-full" /> <div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2"> <Prompt ref={promptRef} onReturn={(input) => { props.onReturn?.(input); xtermRef.current?.scrollToBottom(); }} />
<TerminalMenu onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => { props.onStop?.(); xtermRef.current?.scrollToBottom(); }} onClickRestart={props.onRestart} /> </div> {props.showStopButton && ( <div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100"> <Button icon={StopIcon} onClick={props.onStop}> Stop </Button> </div> )} </section> ); }, ); Terminal.displayName = 'Terminal'; export default Terminal;
src/components/Terminal.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;", "score": 0.8796051740646362 }, { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition", "score": 0.874311089515686 }, { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>", "score": 0.8733795881271362 }, { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": " <Terminal\n ref={consoleRef}\n onRestart={interpreter.restart}\n onReturn={interpreter.execute}\n onStop={interpreter.stop}\n showStopButton={running}\n />\n }\n />\n </main>", "score": 0.8700170516967773 }, { "filename": "src/components/Prompt.tsx", "retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)", "score": 0.8637628555297852 } ]
typescript
<TerminalMenu onClickClearConsole={() => xtermRef.current?.clear()}
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => ( <FileItem key={name}
name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <FileUploader icon={ArrowUpTrayIcon} onUpload={(name, content) => { if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8507908582687378 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}", "score": 0.8302541971206665 }, { "filename": "src/components/Navigator.tsx", "retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>", "score": 0.8254913091659546 }, { "filename": "src/hooks/useFile.ts", "retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {", "score": 0.8215560913085938 }, { "filename": "src/components/Navigator.tsx", "retrieved_chunk": "import { useEffect, useState } from 'react';\nimport { BuildingLibraryIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport FileName from './FileName';\nimport K from './Hotkey';\nimport Item from './Item';\nimport Library from './Library';\nconst isMac = navigator.platform.startsWith('Mac');\nconst Navigator = (): JSX.Element => {\n const [openLibrary, setOpenLibrary] = useState(true);", "score": 0.8205934762954712 } ]
typescript
{files.map(({ name, unsaved }) => ( <FileItem key={name}
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2"> {files.map(({ name, unsaved }) => ( <FileItem key={name} name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <
FileUploader icon={ArrowUpTrayIcon}
onUpload={(name, content) => { if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileName.tsx", "retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>", "score": 0.8542168140411377 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8469011783599854 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " {...buttonProps}\n className={`relative cursor-pointer ${props.className ?? ''}`}\n >\n {props.children}\n <input\n accept=\"text/csv, text/x-python-script, text/x-python, .py, .csv, text/plain\"\n className=\"absolute bottom-0 left-0 right-0 top-0 cursor-pointer opacity-0\"\n onChange={handleUpload}\n type=\"file\"\n />", "score": 0.8466286659240723 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;", "score": 0.846489667892456 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>", "score": 0.845230758190155 } ]
typescript
FileUploader icon={ArrowUpTrayIcon}
import { loadPyodide, PyodideInterface, PyProxy, PyProxyAwaitable, PyProxyCallable, PyProxyDict, } from 'pyodide'; import consoleScript from '../assets/console.py'; /** * @see https://pyodide.org/en/stable/usage/api/python-api/console.html#pyodide.console.ConsoleFuture.syntax_check */ type SyntaxCheck = 'syntax-error' | 'incomplete' | 'complete'; interface Message<T extends Record<string, unknown>> { type: keyof T; payload: any; } interface RunExportableData { code: string; exports?: { name: string; content: string }[]; } let pyodide: PyodideInterface; let interruptBuffer: Uint8Array | null; let await_fut: PyProxyCallable; let repr_shorten: PyProxyCallable; let pyconsole: PyProxy; let clear_console: PyProxyCallable; let create_console: PyProxyCallable; const PS1 = '\u001b[32;1m>>> \u001b[0m' as const; const PS2 = '\u001b[32m... \u001b[0m' as const; const RUN_CODE = '\u001b[3m\u001b[32m<run code>\u001b[0m' as const; const post = { write: (text: string) => postMessage({ type: 'write', payload: text }), writeln: (line: string) => postMessage({ type: 'writeln', payload: line }), error: (message: string) => postMessage({ type: 'error', payload: message }), system: (message: string) => postMessage({ type: 'system', payload: message }), lock: () => postMessage({ type: 'lock' }), unlock: () => postMessage({ type: 'unlock' }), prompt: (newLine = true) => post.write(`${newLine ? '\n' : ''}${PS1}`), promptPending: () => post.write(PS2), }; const setUpConsole = (globals?: PyProxyDict) => { pyconsole?.destroy(); pyconsole = create_console(globals); }; const setUpREPLEnvironment = () => { const globals = pyodide.globals.get('dict')(); pyodide
.runPython(consoleScript, { globals });
repr_shorten = globals.get('repr_shorten'); await_fut = globals.get('await_fut'); create_console = globals.get('create_console'); clear_console = globals.get('clear_console'); setUpConsole(); return globals.get('BANNER') as string; }; const preparePyodide = async () => { const newPyodide = await loadPyodide(); newPyodide.setStdout({ batched: post.writeln }); newPyodide.setStderr({ batched: post.error }); pyodide = newPyodide; if (interruptBuffer) pyodide.setInterruptBuffer(interruptBuffer); /** * Replaces Pyodide's `js` import with a stub `object`. This must also be * paired with some `del sys.modules['js']` in Pyodide's initialisation. */ pyodide.registerJsModule('js', {}); const banner = setUpREPLEnvironment(); post.writeln(banner); post.prompt(false); post.unlock(); return newPyodide; }; const prepareExports = (exports?: { name: string; content: string }[]) => { let newExports = new Set<string>(); exports?.forEach(({ name, content }) => { pyodide.FS.writeFile(name, content, { encoding: 'utf-8' }); newExports.add(name); }); const oldExports = pyodide.FS.readdir('.') as string[]; oldExports.forEach((name) => { if (name === '.' || name === '..' || newExports.has(name)) return; pyodide.FS.unlink(name); }); }; /** * Pyodide may sometimes not catch `RecursionError`s and excessively * recursive code spills as JavaScript `RangeError`, causing Pyodide to * fatally crash. We need to restart Pyodide in this case. * @see https://github.com/pyodide/pyodide/issues/951 */ const handleRangeErrorAndRestartPyodide = async (error: unknown) => { if (!(error instanceof RangeError)) return; post.system( '\nOops, something happened and we have to restart the interpreter. ' + "Don't worry, it's not your fault. " + 'You may continue once you see the prompt again.\n', ); await preparePyodide(); }; const listeners = { initialize: async (newInterruptBuffer?: Uint8Array) => { pyodide ??= await preparePyodide(); if (!newInterruptBuffer) return; pyodide.setInterruptBuffer(newInterruptBuffer); interruptBuffer = newInterruptBuffer; }, run: async ({ code, exports }: RunExportableData) => { pyodide ??= await preparePyodide(); post.writeln(RUN_CODE); try { post.lock(); prepareExports(exports); await pyodide.loadPackagesFromImports(code); const globals = pyodide.globals.get('dict')(); /** * `await pyodide.runPythonAsync(code)` is not used because it raises * an uncatchable `PythonError` when Pyodide emits a `KeyboardInterrupt`. * @see https://github.com/pyodide/pyodide/issues/2141 */ const result = pyodide.runPython(code, { globals }); setUpConsole(globals); post.writeln(result?.toString()); } catch (error) { if (!(error instanceof Error)) throw error; post.error(error.message); handleRangeErrorAndRestartPyodide(error); } finally { post.prompt(); post.unlock(); } }, replClear: async () => { try { clear_console(pyconsole); await await_fut(pyconsole.push('')); } finally { post.error('\nKeyboardInterrupt'); post.prompt(); } }, replInput: async ({ code, exports }: RunExportableData) => { post.writeln(code); const future = pyconsole.push(code) as PyProxy; const status = future.syntax_check as SyntaxCheck; switch (status) { case 'syntax-error': post.error(future.formatted_error.trimEnd()); post.prompt(); return; case 'incomplete': post.promptPending(); return; case 'complete': break; default: throw new Error(`Unexpected type: ${status}`); } prepareExports(exports); const wrapped = await_fut(future) as PyProxyAwaitable; try { const [value] = await wrapped; if (value !== undefined) { const repr = repr_shorten.callKwargs(value, { separator: '\n<long output truncated>\n', }) as string; post.writeln(repr); } if (pyodide.isPyProxy(value)) value.destroy(); } catch (error) { if (!(error instanceof Error)) throw error; const message = future.formatted_error || error.message; post.error(message.trimEnd()); handleRangeErrorAndRestartPyodide(error); } finally { post.prompt(); future.destroy(); wrapped.destroy(); } }, }; onmessage = async (event: MessageEvent<Message<typeof listeners>>) => { listeners[event.data.type]?.(event.data.payload); };
src/workers/interpreter.worker.ts
NUSSOC-glide-3ab6925
[ { "filename": "src/hooks/useInterpreter.ts", "retrieved_chunk": " resetInterruptBuffer();\n workerRef.current?.postMessage({\n type: 'replInput',\n payload: { code, exports: callbacks.exports?.() },\n });\n },\n restart: () => {\n callbacks.system('\\nOkies! Restarting interpreter...\\n');\n restartInterpreter();\n },", "score": 0.8056826591491699 }, { "filename": "src/hooks/useInterpreter.ts", "retrieved_chunk": "import { useEffect, useRef } from 'react';\ninterface Interpreter {\n run: (code: string) => void;\n stop: () => void;\n execute: (command: string) => void;\n restart: () => void;\n}\ninterface Callbacks {\n write: (text: string) => void;\n writeln: (text: string) => void;", "score": 0.787940263748169 }, { "filename": "src/hooks/useInterpreter.ts", "retrieved_chunk": " interruptBufferRef.current[0] = 2;\n workerRef.current?.postMessage({ type: 'replClear' });\n } else {\n callbacks.system(\n \"\\nDue to browser incompatibility, we can't stop your code execution gracefully. Instead, we'll restart the interpreter for you. Hold on yah...\\n\",\n );\n restartInterpreter();\n }\n },\n execute: (code) => {", "score": 0.78694748878479 }, { "filename": "src/pages/IDEPage.tsx", "retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (", "score": 0.7860040664672852 }, { "filename": "src/components/Terminal.tsx", "retrieved_chunk": " write: (result?: string) => void;\n error: (result?: string) => void;\n system: (result?: string) => void;\n}\ninterface TerminalProps {\n onStop?: () => void;\n onReturn?: (line: string) => void;\n onRestart?: () => void;\n showStopButton?: boolean;\n}", "score": 0.7777590751647949 } ]
typescript
.runPython(consoleScript, { globals });
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2"> {files.map(({ name, unsaved }) => ( <FileItem key={name} name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <FileUploader icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileName.tsx", "retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>", "score": 0.8521597981452942 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " e.preventDefault();\n e.currentTarget.blur();\n }\n if (e.key === 'Escape') {\n e.preventDefault();\n setEditing(false);\n setNewFileName(undefined);\n }\n }}\n placeholder={props.initialValue}", "score": 0.848274290561676 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8463090062141418 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " {...buttonProps}\n className={`relative cursor-pointer ${props.className ?? ''}`}\n >\n {props.children}\n <input\n accept=\"text/csv, text/x-python-script, text/x-python, .py, .csv, text/plain\"\n className=\"absolute bottom-0 left-0 right-0 top-0 cursor-pointer opacity-0\"\n onChange={handleUpload}\n type=\"file\"\n />", "score": 0.8439249992370605 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " props.onConfirm(newName);\n }}\n onChange={(e) => setNewFileName(e.target.value)}\n onFocus={(e) => {\n const name = e.target.value;\n const extensionLength = name.split('.').pop()?.length ?? 0;\n e.target.setSelectionRange(0, name.length - extensionLength - 1);\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {", "score": 0.8429646492004395 } ]
typescript
onUpload={(name, content) => {
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2"> {files.map(({ name,
unsaved }) => ( <FileItem key={name}
name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <FileUploader icon={ArrowUpTrayIcon} onUpload={(name, content) => { if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8568251132965088 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}", "score": 0.8356035947799683 }, { "filename": "src/components/Navigator.tsx", "retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"", "score": 0.8280643224716187 }, { "filename": "src/hooks/useFile.ts", "retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {", "score": 0.8229402303695679 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "export default FileItem;", "score": 0.8225198984146118 } ]
typescript
unsaved }) => ( <FileItem key={name}
import { useEffect, useLayoutEffect, useRef } from 'react'; import { PlayIcon } from '@heroicons/react/24/outline'; import MonacoEditor from '@monaco-editor/react'; import { editor } from 'monaco-editor'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import K from './Hotkey'; interface EditorProps { onRunCode?: (code: string) => void; showRunButton?: boolean; } interface CoreEditorProps extends EditorProps { onSave: (content: string) => void; onChange: (value: string) => void; value: string; } const CoreEditor = (props: CoreEditorProps): JSX.Element => { const ref = useRef<editor.IStandaloneCodeEditor>(); const handleShortcut = (e: KeyboardEvent) => { const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey; if (isMod && e.key === 's') { e.preventDefault(); const content = ref.current?.getValue(); if (content !== undefined) props.onSave(content); } if (e.key === 'F5') { e.preventDefault(); saveThenRunCode(); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); const saveThenRunCode = () => { const content = ref.current?.getValue() ?? ''; props.onSave(content); props.onRunCode?.(content); }; return ( <section className="windowed h-full w-full"> <MonacoEditor defaultLanguage="python" onChange={(value) => value !== undefined ? props.onChange(value) : null } onMount={(editor) => (ref.current = editor)} options={{ fontSize: 14, fontFamily: 'monospace', smoothScrolling: true, cursorSmoothCaretAnimation: 'on', minimap: { enabled: false }, }} theme="vs-dark" value={props.value} /> {props.showRunButton && ( <div className="absolute bottom-3 right-3 space-x-2"> <Button icon={PlayIcon} onClick={saveThenRunCode}> Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )}
</section> ); }; const Editor = (props: EditorProps): JSX.Element | null => { const { update, save } = useFilesMutations(); const { name, content } = useFile.Selected(); useLayoutEffect(() => { document.title = `${name ? `${name} | ` : ''}Glide`; }, [name]); if (name === undefined || content === undefined) return null; return ( <CoreEditor {...props} onChange={update} onSave={(newContent) => save(name, newContent)} value={content} /> ); }; export default Editor;
src/components/Editor.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/Terminal.tsx", "retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>", "score": 0.8790332078933716 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>", "score": 0.8626438975334167 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " {...buttonProps}\n className={`relative cursor-pointer ${props.className ?? ''}`}\n >\n {props.children}\n <input\n accept=\"text/csv, text/x-python-script, text/x-python, .py, .csv, text/plain\"\n className=\"absolute bottom-0 left-0 right-0 top-0 cursor-pointer opacity-0\"\n onChange={handleUpload}\n type=\"file\"\n />", "score": 0.8432183265686035 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>", "score": 0.8385701775550842 }, { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>", "score": 0.8385395407676697 } ]
typescript
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" /> </Button> </div> )}
import { useEffect, useState } from 'react'; import { BuildingLibraryIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import FileName from './FileName'; import K from './Hotkey'; import Item from './Item'; import Library from './Library'; const isMac = navigator.platform.startsWith('Mac'); const Navigator = (): JSX.Element => { const [openLibrary, setOpenLibrary] = useState(true); const name = useFile.SelectedName(); const handleShortcut = (e: KeyboardEvent) => { const isMod = isMac ? e.metaKey : e.ctrlKey; if (isMod && e.key === 'o') { e.preventDefault(); setOpenLibrary(true); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); return ( <> <nav className="flex items-center justify-between space-x-2"> <FileName /> <div className="flex flex-row items-center space-x-2"> {name && ( <Item className="text-slate-400" onClick={() => { window.dispatchEvent( new KeyboardEvent('keydown', { key: 's', metaKey: isMac, ctrlKey: !isMac, }), ); }} > Save <
K of="Mod+S" /> </Item> )}
<Item className="text-slate-400" icon={BuildingLibraryIcon} onClick={() => setOpenLibrary(true)} > Library <K of="Mod+O" /> </Item> </div> </nav> <Library onClose={() => setOpenLibrary(false)} open={openLibrary} /> </> ); }; export default Navigator;
src/components/Navigator.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/Editor.tsx", "retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }", "score": 0.8254271149635315 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',", "score": 0.7972863912582397 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": "const convert = (key: string): string =>\n key in CONVERTED_KEYS ? CONVERTED_KEYS[key as ConvertibleKeys] : key;\nconst Hotkey = (props: HotkeyProps): JSX.Element => {\n const { of: hotkey } = props;\n const keys = hotkey.split(SEPARATOR);\n if (isMac)\n return <kbd className={props.className}>{keys.map(convert).join('')}</kbd>;\n return (\n <>\n {keys", "score": 0.7861407995223999 }, { "filename": "src/components/Editor.tsx", "retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {", "score": 0.7837196588516235 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": " Ctrl: '⌃',\n }\n : {\n Mod: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Ctrl: 'Ctrl',\n };\ntype ConvertibleKeys = keyof typeof CONVERTED_KEYS;\nconst SEPARATOR = '+' as const;", "score": 0.7791030406951904 } ]
typescript
K of="Mod+S" /> </Item> )}
import { ComponentRef, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, } from 'react'; import { StopIcon } from '@heroicons/react/24/outline'; import { slate, yellow } from 'tailwindcss/colors'; import { Terminal as Xterm } from 'xterm'; import { CanvasAddon } from 'xterm-addon-canvas'; import { FitAddon } from 'xterm-addon-fit'; import { WebglAddon } from 'xterm-addon-webgl'; import Button from './Button'; import Prompt from './Prompt'; import TerminalMenu from './TerminalMenu'; import 'xterm/css/xterm.css'; interface TerminalRef { append: (result?: string) => void; write: (result?: string) => void; error: (result?: string) => void; system: (result?: string) => void; } interface TerminalProps { onStop?: () => void; onReturn?: (line: string) => void; onRestart?: () => void; showStopButton?: boolean; } const isASCIIPrintable = (character: string): boolean => character >= String.fromCharCode(32) && character <= String.fromCharCode(126); const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); /** * @see https://github.com/xtermjs/xterm.js/pull/4255 */ const getSafariVersion = (): number => { if (!isSafari) return 0; const majorVersion = navigator.userAgent.match(/Version\/(\d+)/); if (majorVersion === null || majorVersion.length < 2) return 0; return parseInt(majorVersion[1]); }; const isWebGL2Compatible = (): boolean => { const context = document.createElement('canvas').getContext('webgl2'); const isWebGL2Available = Boolean(context); return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true); }; const Terminal = forwardRef<TerminalRef, TerminalProps>( (props, ref): JSX.Element => { const xtermRef = useRef<Xterm>(); const fitAddonRef = useRef<FitAddon>(); const terminalRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null); const promptRef = useRef<ComponentRef<typeof Prompt>>(null); useLayoutEffect(() => { const container = containerRef.current; if (!container) return; const resizeObserver = new ResizeObserver(() => fitAddonRef.current?.fit(), ); resizeObserver.observe(container); return () => resizeObserver.disconnect(); }, []); useEffect(() => { const terminal = terminalRef.current; if (!terminal) return; const xterm = new Xterm({ cursorBlink: false, cursorStyle: 'underline', fontFamily: 'monospace', fontSize: 14, theme: { background: slate[900], cursor: yellow[400] }, disableStdin: true, }); const fitAddon = new FitAddon(); xterm.loadAddon(fitAddon); if (isWebGL2Compatible()) { xterm.loadAddon(new WebglAddon()); } else { xterm.loadAddon(new CanvasAddon()); } xterm.onKey(({ key }) => { if (!(isASCIIPrintable(key) || key >= '\u00a0')) return; promptRef.current?.focusWith(key); }); xterm.open(terminal); fitAddon.fit(); xtermRef.current = xterm; fitAddonRef.current = fitAddon; return () => xterm.dispose(); }, []); const write = (text: string, line = true) => { const trimmed = text.replace(/\n/g, '\r\n'); const xterm = xtermRef.current; if (!xterm) return; const writer = (text: string) => line ? xterm.writeln(text) : xterm.write(text); try { writer(trimmed); } catch (error) { if (!(error instanceof Error)) throw error; console.log('oops', error.message); xterm.clear(); writer(trimmed); } }; useImperativeHandle(ref, () => ({ append: (result?: string) => write(result ?? ''), write: (result?: string) => write(result ?? '', false), error: (result?: string) => write('\u001b[31m' + (result ?? '') + '\u001b[0m'), system: (result?: string) => write('\u001b[33m' + (result ?? '') + '\u001b[0m'), })); return ( <section ref={containerRef} className="relative h-full w-full"> <div ref={terminalRef} className="windowed h-full" /> <div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2"> <Prompt ref={promptRef} onReturn={(input) => { props.onReturn?.(input); xtermRef.current?.scrollToBottom(); }} /> <TerminalMenu onClickClearConsole={() => xtermRef.current?.clear()} onClickForceStop={() => { props.onStop?.(); xtermRef.current?.scrollToBottom(); }} onClickRestart={props.onRestart} /> </div> {props.showStopButton && ( <div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}> Stop </Button> </div> )}
</section> ); }, ); Terminal.displayName = 'Terminal'; export default Terminal;
src/components/Terminal.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>", "score": 0.9002158641815186 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>", "score": 0.8705176115036011 }, { "filename": "src/components/Editor.tsx", "retrieved_chunk": " fontFamily: 'monospace',\n smoothScrolling: true,\n cursorSmoothCaretAnimation: 'on',\n minimap: { enabled: false },\n }}\n theme=\"vs-dark\"\n value={props.value}\n />\n {props.showRunButton && (\n <div className=\"absolute bottom-3 right-3 space-x-2\">", "score": 0.8523690700531006 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": " <div\n className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-red-600/20 text-red-400 transition-transform hover:scale-110 active:scale-95\"\n onClick={() => destroy(props.name)}\n role=\"button\"\n >\n <TrashIcon className=\"h-5\" />\n </div>\n </div>\n );\n};", "score": 0.8508638143539429 }, { "filename": "src/components/TerminalMenu.tsx", "retrieved_chunk": " Bars3Icon,\n StopIcon,\n TrashIcon,\n} from '@heroicons/react/24/outline';\ninterface TerminalMenuProps {\n onClickRestart?: MouseEventHandler<HTMLButtonElement>;\n onClickForceStop?: MouseEventHandler<HTMLButtonElement>;\n onClickClearConsole?: MouseEventHandler<HTMLButtonElement>;\n}\ninterface MenuItemProps {", "score": 0.8445971012115479 } ]
typescript
<Button icon={StopIcon} onClick={props.onStop}> Stop </Button> </div> )}
import { useEffect, useState } from 'react'; import { BuildingLibraryIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import FileName from './FileName'; import K from './Hotkey'; import Item from './Item'; import Library from './Library'; const isMac = navigator.platform.startsWith('Mac'); const Navigator = (): JSX.Element => { const [openLibrary, setOpenLibrary] = useState(true); const name = useFile.SelectedName(); const handleShortcut = (e: KeyboardEvent) => { const isMod = isMac ? e.metaKey : e.ctrlKey; if (isMod && e.key === 'o') { e.preventDefault(); setOpenLibrary(true); } }; useEffect(() => { window.addEventListener('keydown', handleShortcut); return () => window.removeEventListener('keydown', handleShortcut); }, [handleShortcut]); return ( <> <nav className="flex items-center justify-between space-x-2"> <FileName /> <div className="flex flex-row items-center space-x-2"> {name && ( <Item className="text-slate-400" onClick={() => { window.dispatchEvent( new KeyboardEvent('keydown', { key: 's', metaKey: isMac, ctrlKey: !isMac, }), ); }} >
Save <K of="Mod+S" /> </Item> )}
<Item className="text-slate-400" icon={BuildingLibraryIcon} onClick={() => setOpenLibrary(true)} > Library <K of="Mod+O" /> </Item> </div> </nav> <Library onClose={() => setOpenLibrary(false)} open={openLibrary} /> </> ); }; export default Navigator;
src/components/Navigator.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/Editor.tsx", "retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }", "score": 0.8330772519111633 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',", "score": 0.8022722601890564 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": "const convert = (key: string): string =>\n key in CONVERTED_KEYS ? CONVERTED_KEYS[key as ConvertibleKeys] : key;\nconst Hotkey = (props: HotkeyProps): JSX.Element => {\n const { of: hotkey } = props;\n const keys = hotkey.split(SEPARATOR);\n if (isMac)\n return <kbd className={props.className}>{keys.map(convert).join('')}</kbd>;\n return (\n <>\n {keys", "score": 0.795219361782074 }, { "filename": "src/components/Hotkey.tsx", "retrieved_chunk": " Ctrl: '⌃',\n }\n : {\n Mod: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Ctrl: 'Ctrl',\n };\ntype ConvertibleKeys = keyof typeof CONVERTED_KEYS;\nconst SEPARATOR = '+' as const;", "score": 0.7899424433708191 }, { "filename": "src/components/Prompt.tsx", "retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">", "score": 0.7816531658172607 } ]
typescript
Save <K of="Mod+S" /> </Item> )}
import { Fragment } from 'react'; import { Dialog, Transition } from '@headlessui/react'; import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline'; import useFile from '../hooks/useFile'; import useFilesMutations from '../hooks/useFilesMutations'; import Button from './Button'; import FileItem from './FileItem'; import FileUploader from './FileUploader'; interface LibraryProps { open: boolean; onClose: () => void; } const Library = (props: LibraryProps): JSX.Element => { const files = useFile.NamesWithUnsaved(); const { draft, create } = useFilesMutations(); return ( <Transition appear as={Fragment} show={props.open}> <Dialog className="relative z-40" onClose={props.onClose}> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-start justify-center px-4 py-10 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-100" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all"> <div className="flex justify-between"> <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-white" > Library </Dialog.Title> <p className="select-none text-sm text-slate-600"> {__VERSION__} </p> </div> <div className="mt-6 flex flex-col space-y-2"> {files.map(({ name, unsaved }) => ( <FileItem key={name} name={name} onClick={props.onClose} unsaved={unsaved} /> ))} </div> <div className="mt-10 space-x-2"> <Button icon={PlusIcon} onClick={() => { draft(true); props.onClose(); }} > New File </Button> <FileUploader icon={ArrowUpTrayIcon} onUpload=
{(name, content) => {
if (content === null) return; create(name, content); props.onClose(); }} > Upload </FileUploader> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Library;
src/components/Library.tsx
NUSSOC-glide-3ab6925
[ { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " if (!files?.length) return;\n const file = Array.from(files)[0];\n const reader = new FileReader();\n reader.onload = ({ target }) =>\n props.onUpload?.(file.name, target?.result as string);\n reader.readAsText(file);\n e.target.value = '';\n };\n return (\n <Button", "score": 0.8558894395828247 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;", "score": 0.8521519899368286 }, { "filename": "src/components/FileUploader.tsx", "retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;", "score": 0.8481658697128296 }, { "filename": "src/components/FileItem.tsx", "retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">", "score": 0.8471112847328186 }, { "filename": "src/components/FileName.tsx", "retrieved_chunk": " props.onConfirm(newName);\n }}\n onChange={(e) => setNewFileName(e.target.value)}\n onFocus={(e) => {\n const name = e.target.value;\n const extensionLength = name.split('.').pop()?.length ?? 0;\n e.target.setSelectionRange(0, name.length - extensionLength - 1);\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {", "score": 0.8466151356697083 } ]
typescript
{(name, content) => {